Esempio n. 1
0
char *gld_loadHndl::start_element_load(char *buffer, size_t len, const Attributes& attributes){
	static wchar_t wcs_type[5], wcs_minor[6], wcs_major[6];
	static size_t wcs_type_len = mbstowcs(wcs_type, "type", 5);
	static size_t wcs_major_len = mbstowcs(wcs_major, "major", 6);
	static size_t wcs_minor_len = mbstowcs(wcs_minor, "minor", 6);
	XMLCh *_major = NULL, *_minor = NULL;
	int32 major = 0, minor = 0;
	if(strcmp(buffer, "global") == 0){
		stack_state = GLOBAL_STATE;
	} else if(strcmp(buffer, "module") == 0){	//	LOAD THE MODULE
		wcstombs(module_name, (const wchar_t *)attributes.getValue((const XMLCh *)wcs_type), 1024);
		_major = (XMLCh *)attributes.getValue((const XMLCh *)wcs_major);
		_minor = (XMLCh *)attributes.getValue((const XMLCh *)wcs_minor);
		if(_major != NULL)
			major = wcstol((const wchar_t *)_major, NULL, 10);
		if(_minor != NULL)
			minor = wcstol((const wchar_t *)_minor, NULL, 10);
		
		if((module = module_load(module_name, 0, NULL)) == NULL){
			sprintf(errmsg, "Unable to load module \"%s\" in start_element_load()", module_name);
			return errmsg;
		} else {
			strcpy(module_name, buffer);
			stack_state = MODULE_STATE;
			if(major != 0){
				char temp[8];
				module_getvar(this->module, "major", temp, 8);
				int major_in = atoi(temp);
				module_getvar(this->module, "minor", temp, 8);
				int minor_in = atoi(temp);
				if(major < major_in){
					output_warning("XML::read_module_prop(): The input file was built using an older major version of the module.");
					return NULL; /* avoid minor var complaints */
				}
				if(minor == minor_in){			//	current version, continue
					return NULL;
				} else if(minor > minor_in){	//	old version
					output_warning("XML::read_module_prop(): The input file was built using an older minor version of the module.");
				} else if(minor < minor_in){	//	new version
					output_warning("XML::read_module_prop(): The file was built using a newer minor version of the module loading it!");
				}
			}
		}
	} else if(strcmp(buffer, "clock") == 0){
		stack_state = CLOCK_STATE;
	} else {
		sprintf(errmsg, "Unrecognized keyword in start_element_load(%s)", buffer);
		return errmsg;
	}
	return NULL;
}
Esempio n. 2
0
void locale_push(void)
{
	char *tz = timestamp_current_timezone();
	LOCALE *locale = (LOCALE*)malloc(sizeof(LOCALE));
	if (locale==NULL)
	{
		output_error("locale push failed; no memory");
		return;
	}
	else
	{
		locale->next=stack;
		stack=locale;
		if (tz==NULL)
			output_warning("locale TZ is empty");
			/* TROUBLESHOOT
				This warning indicates that the TZ environment variable has not be set.  
				This variable is used to specify the default timezone to use while
				GridLAB-D is running.  Supported timezones are listed in the 
				<a href="http://gridlab-d.svn.sourceforge.net/viewvc/gridlab-d/trunk/core/tzinfo.txt?view=markup">tzinfo.txt</a>
				file.
			 */
		strncpy(locale->tz,tz?tz:"",sizeof(locale->tz));
		return;
	}
}
Esempio n. 3
0
/** randwarn checks to see if non-determinism warning is necessary **/
int randwarn(unsigned int *state)
{
	static int warned=0;
	if (global_nondeterminism_warning && !warned)
	{
		warned=1;
		output_warning("non-deterministic behavior probable--rand was called while running multiple threads");
	}
	
	if ( global_randomnumbergenerator==RNG2 )
	{
		/* use the stdc (RNG2) rand functions */
		if ( state!=NULL )
			srand(*state);
		return rand();
		/* note that RNG2 does not write back the state */
	}
	else if ( global_randomnumbergenerator==RNG3 )
	{
		/* Park-Miller LCG allows very large modulus - this one is use in Cray RANF */
#define MODULUS 281474976710656ULL (2^48)
#define MULTIPLIER 44485709377909ULL
		if ( state==NULL ){
			if(ur_state != NULL){
				state = ur_state;
				*ur_state = (unsigned int)((MULTIPLIER*(unsigned int64)(*ur_state))&0xffffffffffffULL);
				return ((*state)>>16)&0x7fff;
			} else {
				/* stateless - use the OS rng, which keeps its own internal state */
				return rand();
			}
		}
HTTPRESULT *http_read(char *url)
{
	HTTPRESULT *result = http_new_result();
	
	if ( strncmp(url,"http://",7)==0 )
	{
		output_warning("http_read('%s'): http access not implemented", url);
	}

	else if ( strncmp(url,"file://",7)==0 )
	{
		FILE *fp = fopen(url+7,"rt");
		if ( fp==NULL )
		{
			output_error("http_read('%s'): unable to access file", url);
		}
		else
		{
			result->body.size = filelength(fileno(fp))+1;
			result->body.data = malloc(result->body.size);
			memset(result->body.data,0,result->body.size);
			if ( fread(result->body.data,1,result->body.size,fp)<=0 )
			{
				output_error("http_read('%s'): unable to read file", url);
				result->status = errno;
			}
			else
				result->status = 0;
		}
	}
	return result;
}
Esempio n. 5
0
int stream_warning(char *format, ...)
{
	char buffer[1024];
	va_list ptr;
	va_start(ptr,format);
	vsprintf(buffer,format,ptr);
	va_end(ptr);
	output_warning("- stream(%d:%d) - %s", b,t,buffer);
	return -1;
}
Esempio n. 6
0
char *gld_loadHndl::read_module_prop(char *buffer, size_t len){
	//printf("read_module_prop (%s)\n", buffer);
	if(strcmp(propname, "major") == 0){
		char temp[8];
		int major_in = atoi(buffer);
		int major = 0;
		module_getvar(this->module, "major", temp, 8);
		major = atoi(temp);
		if(major == 0)					//	don't care if major = 0
			return NULL;
		if(major == major_in){			//	current version, continue
			return NULL;
		} else if(major > major_in){	//	old version
			output_warning("The input file was built using an older major version of the module.");
			return NULL;
		} else if(major < major_in){	//	newer version
			output_warning("The file was built using a newer major version of the module loading it!");
			return NULL;
		}
	} else if(strcmp(propname, "minor") == 0){
		char temp[8];
		int minor_in = atoi(buffer);
		int minor = 0;
		int major = 0;
		module_getvar(this->module, "major", temp, 8);
		major = atoi(temp);
		module_getvar(this->module, "minor", temp, 8);
		minor = atoi(temp);
		if(major == 0)	//	don't care if major = 0
			return NULL;
		if(minor == minor_in){			//	current version, continue
			return NULL;
		} else if(minor > minor_in){	//	old version
			output_warning("XML::read_module_prop(): The input file was built using an older minor version of the module.");
		} else if(minor < minor_in){	//	new version
			output_warning("XML::read_module_prop(): The file was built using a newer minor version of the module loading it!");
		}
	} else {
		global_setvar(propname, buffer);
	}
	return NULL;
}
Esempio n. 7
0
char *gld_loadHndl::start_element_module_prop(char *buffer, size_t len, const Attributes& attributes){
	char pname[323];
	sprintf(pname, "%s::%s", this->module->name, buffer);
	if(global_find(pname)){
		strcpy(propname, pname);
	} else {
		output_warning("XML: start_element_module_prop: property \"\" not found, initializing");
		strcpy(propname, pname);
	}
	return NULL;
}
Esempio n. 8
0
/**	endDocument() is called when the end of the file is reached.  Any post-processing within the parser should occur here.
*/
void gld_loadHndl::endDocument(){
	OBJECT *tempobj = object_get_first();

	/* resolve_list(); */
	if(load_resolve_all() == FAILED){
		output_error("XML_Load: unable to resolve object linkings!");
		load_state = false;
	}
	/* "establish ranks" */

	for (; obj!=NULL; obj=obj->next)
		object_set_parent(obj,obj->parent);
	output_verbose("XML_Load: %d object%s loaded.", object_get_count(), object_get_count() > 0 ? "s" : "");
	if(object_count > 0)
		if(object_get_count() != this->object_count)
			output_warning("XML_Load: we expected %i objects instead!", this->object_count);
	output_verbose("XML_Load: %d class%s loaded.", class_get_count(), class_get_count() > 0 ? "es" : "");
	if(class_count > 0)
		if(class_get_count() != this->class_count)
			output_warning("XML_Load: we expected %i classes instead!", this->class_count);
}
Esempio n. 9
0
snd_seq_t     *create_aseqh(char *name)
{
  snd_seq_t     *handle = NULL;
  int         err = 0;

  err = snd_seq_open(&handle, "default", SND_SEQ_OPEN_DUPLEX, SND_SEQ_NONBLOCK);
  if (0 > err)
    {
      output_error("Problem while creating alsa handler:\n%s",
                   snd_strerror(err));
      output_warning("(Is snd_seq module unabled ?)");
      return NULL;
    }
  snd_seq_set_client_name(handle, name);
  return handle;
}
Esempio n. 10
0
/** Copy the content of a file to the client
	@returns the number of bytes sent
 **/
int http_copy(HTTP *http, char *context, char *source)
{
	char *buffer;
	size_t len;
	FILE *fp = fopen(source,"rb");
	if (fp==NULL)
	{
		output_error("unable to find %s output '%s': %s", context, source, strerror(errno));
		return 0;
	}
	len = filelength(fileno(fp));
	if (len<0)
	{
		output_error("%s output '%s' not accessible", context, source);
		fclose(fp);
		return 0;
	}
	if (len==0)
	{
		output_warning("%s output '%s' is empty", context, source);
		fclose(fp);
		return 1;
	}
	buffer = (char*)malloc(len);
	if (buffer==NULL)
	{
		output_error("%s output buffer for '%s' not available", context, source);
		fclose(fp);
		return 0;
	}
	if (fread(buffer,1,len,fp)<=0)
	{
		output_error("%s output '%s' read failed", context, source);
		free(buffer);
		fclose(fp);
		return 0;
	}
	http_write(http,buffer,len);
	http_mime(http,source);
	free(buffer);
	fclose(fp);
	return 1;
}
Esempio n. 11
0
static int compare_string(char *a, FINDOP op, char *b)
{
	switch (op) {
	case SAME: op=EQ; goto CompareInt;
	case BEFORE: op=LT; goto CompareInt;
	case AFTER: op=GT; goto CompareInt;
	case DIFF: op=NE; goto CompareInt;
	case LIKE: return match(a, b);
	case EQ:
	case LT:
	case GT:
	case LE:
	case GE:
	case NE:
		if (!(isdigit(a[0])||a[0]=='+'||a[0]=='-')&&!(isdigit(b[0])||b[0]=='+'||b[0]=='-'))
			output_warning("compare of strings using numeric op usually does not work");
			/* TROUBLESHOOT
				An attempt to compare two numbers using a string comparison operation is not generally going to work as expected.
				Check that this is truly the desired comparison and correct it if not.  If so and the warning error is not desired
				you may suppress warnings using <code>#set warning=0</code> in the model file.
			 */
		return compare_double(atof(a),op,atof(b));
	default:
		output_error("compare op %d not supported on strings", op);
		/* TROUBLESHOOT
			This error is caused when an object find procedure uses a comparison operator
			that isn't allowed on a that type of property.  Make sure the property type
			and the comparison operator are compatible and try again.  If your GLM file
			isn't the cause of the problem, try reducing the complexity of the GLM file 
			you are using to isolate which module is causing the error and file a report 
			with the GLM file attached.
		 */
		return 0;
	}
CompareInt:
	return compare_int((int64)strcmp(a,b),op,0);

}
Esempio n. 12
0
void locale_pop(void)
{
	if (stack==NULL)
	{
		output_error("locale pop failed; stack empty");
		return;
	}
	else
	{
		LOCALE *next = stack;
		char tz[32];
		stack = stack->next;
		sprintf(tz,"TZ=%s",next->tz);
		if (putenv(tz)!=0)
			output_warning("locale pop failed");
			/* TROUBLESHOOT
				This is an internal error causes by a corrupt locale stack.  
			 */
		else
			tzset();
		free(next);
	}
}
Esempio n. 13
0
/** Set the response MIME type **/
static void http_mime(HTTP *http, char *path)
{
	size_t len = strlen(path);
	static struct s_map {
		char *ext;
		char *mime;
	} map[] = {
		{".png","image/png"},
		{".js","text/javascript"},
	};
	int n;
	for ( n=0 ; n<sizeof(map)/sizeof(map[0]) ; n++ )
	{
		if (strcmp(path+len-strlen(map[n].ext),map[n].ext)==0)
		{
			http->type = map[n].mime;
			return;
		}
	}
	output_warning("mime type for '%s' is not known", path);
	http->type = NULL;
	return;
}
Esempio n. 14
0
/* initialize modules */
int link_initall(void)
{
	output_debug("link_initall(): link startup in progress...");
	glxlink *mod;
	for ( mod=glxlink::get_first() ; mod!=NULL ; mod=mod->get_next() )
	{
		LINKLIST *item;

		output_debug("link_initall(): setting up %s link", mod->get_target());

		// set default global list (if needed)
		if ( mod->get_globals()==NULL )
		{
			GLOBALVAR *var = NULL;
			while ( (var=global_getnext(var))!=NULL )
			{
				if ( var->prop!=NULL && var->prop->name!=NULL )
				{
					LINKLIST *item = mod->add_global(var->prop->name);
					if ( item!=NULL )
						item->data = (void*)var;
					else
						output_error("link_initall(): unable to link %s", var->prop->name);
				}
				else
					output_warning("link_initall(): a variable property definition is null"); 
			}
		}
		else 
		{
			// link global variables
			for ( item=mod->get_globals() ; item!=NULL ; item=mod->get_next(item) )
			{
				if ( strcmp(item->name,"")==0 ) continue;
				item->data = (void*)global_find(item->name);
				if ( item->data==NULL )
					output_error("link_initall(target='%s'): global '%s' is not found", mod->get_target(), item->name);
			}
		}

		// link objects
		if ( mod->get_objects()==NULL )
		{
			// set default object list
			OBJECT *obj = NULL;
			for ( obj=object_get_first() ; obj!=NULL ; obj=object_get_next(obj) )
			{
				// add named objects
				LINKLIST *item = NULL;
				if ( obj->name!=NULL )
					item = mod->add_object(obj->name);
				else
				{
					char id[256];
					sprintf(id,"%s:%d",obj->oclass->name,obj->id);
					item = mod->add_object(id);
				}
				item->data = (void*)obj;
			}
		}
		else
		{
			LINKLIST *item;

			// link global variables
			for ( item=mod->get_objects() ; item!=NULL ; item=mod->get_next(item) )
			{
				if ( strcmp(item->name,"")==0 ) continue;
				OBJECT *obj = NULL;
				item->data = (void*)object_find_name(item->name);
				if ( item->data==NULL)
					output_error("link_initall(target='%s'): object '%s' is not found", mod->get_target(), item->name);
			}
		}

		// link exports
		for ( item=mod->get_exports() ; item!=NULL ; item=mod->get_next(item) )
		{
			char objname[64], propname[64], varname[64];
			if ( sscanf(item->name,"%[^.].%s %s",objname,propname,varname)==3 )
			{
				OBJECTPROPERTY *objprop = (OBJECTPROPERTY*)malloc(sizeof(OBJECTPROPERTY));
				objprop->obj = object_find_name(objname);
				if ( objprop->obj )
				{
					objprop->prop = class_find_property(objprop->obj->oclass,propname);
					if ( objprop->prop==NULL )
						output_error("link_initall(target='%s'): export '%s' property not found", mod->get_target(), item->name);
					else
					{
						item->data = objprop;
						strcpy(item->name,varname);
					}
				}
				else
					output_error("link_initall(target='%s'): export '%s' object not found", mod->get_target(), item->name);
			}
			else
				output_error("link_initall(target='%s'): '%s' is not a valid export specification", mod->get_target(), item->name);
		}

		// link imports
		for ( item=mod->get_imports() ; item!=NULL ; item=mod->get_next(item) )
		{
			char objname[64], propname[64], varname[64];
			if ( sscanf(item->name,"%[^.].%s %s",objname,propname,varname)==3 )
			{
				OBJECTPROPERTY *objprop = (OBJECTPROPERTY*)malloc(sizeof(OBJECTPROPERTY));
				objprop->obj = object_find_name(objname);
				if ( objprop->obj )
				{
					objprop->prop = class_find_property(objprop->obj->oclass,propname);
					if ( objprop->prop==NULL )
						output_error("link_initall(target='%s'): import '%s' property not found", mod->get_target(), item->name);
					else
					{
						item->data = objprop;
						strcpy(item->name,varname);
					}
				}
				else
					output_error("link_initall(target='%s'): import '%s' object not found", mod->get_target(), item->name);
			}
			else
				output_error("link_initall(target='%s'): '%s' is not a valid import specification", mod->get_target(), item->name);
		}

		// initialize link module
		if ( !mod->do_init() )
		{
			output_error("link_initall(): link startup failed");
			link_termall();
			return 0;
		}
	}
	output_debug("link_initall(): link startup done ok");
	atexit((void(*)(void))link_termall);
	return 1;
}
Esempio n. 15
0
/** Process an incoming request
	@returns nothing
 **/
void http_response(SOCKET fd)
{
	HTTP *http = http_create(fd);
	size_t len;
	int content_length = 0;
	char *user_agent = NULL;
	char *host = NULL;
	int keep_alive = 0;
	char *connection = NULL;
	char *accept = NULL;
	struct s_map {
		char *name;
		enum {INTEGER,STRING} type;
		void *value;
		size_t sz;
	} map[] = {
		{"Content-Length", INTEGER, (void*)&content_length, 0},
		{"Host", STRING, (void*)&host, 0},
		{"Keep-Alive", INTEGER, (void*)&keep_alive, 0},
		{"Connection", STRING, (void*)&connection, 0},
		{"Accept", STRING, (void*)&accept, 0},
	};

	while ( (int)(len=recv_data(fd,http->query,sizeof(http->query)))>0 )
	{
		/* first term is always the request */
		char *request = http->query;
		char method[32];
		char uri[1024];
		char version[32];
		char *p = strchr(http->query,'\r');
		int v;
		
		/* initialize the response */
		http_reset(http);

		/* read the request string */
		if (sscanf(request,"%s %s %s",method,uri,version)!=3)
		{
			http_status(http,HTTP_BADREQUEST);
			http_format(http,HTTP_BADREQUEST);
			http_type(http,"text/html");
			http_send(http);
			break;
		}

		/* read the rest of the header */
		while (p!=NULL && (p=strchr(p,'\r'))!=NULL) 
		{
 			*p = '\0';
			p+=2;
			for ( v=0 ; v<sizeof(map)/sizeof(map[0]) ; v++ )
			{
				if (map[v].sz==0) map[v].sz = strlen(map[v].name);
				if (strnicmp(map[v].name,p,map[v].sz)==0 && strncmp(p+map[v].sz,": ",2)==0)
				{
					if (map[v].type==INTEGER) { *(int*)(map[v].value) = atoi(p+map[v].sz+2); break; }
					else if (map[v].type==STRING) { *(char**)map[v].value = p+map[v].sz+2; break; }
				}
			}
		}
		output_verbose("%s (host='%s', len=%d)",http->query,host?host:"???",content_length);

		/* reject anything but a GET */
		if (stricmp(method,"GET")!=0)
		{
			http_status(http,HTTP_METHODNOTALLOWED);
			http_format(http,HTTP_METHODNOTALLOWED);
			http_type(http,"text/html");
			/* technically, we should add an Allow entry to the response header */
			http_send(http);
			break;
		}

		/* handle request */
		if ( strcmp(uri,"/favicon.ico")==0 )
		{
			if ( http_favicon(http) )
				http_status(http,HTTP_OK);
			else
				http_status(http,HTTP_NOTFOUND);
			http_send(http);
		}
		else {
			static struct s_map {
				char *path;
				int (*request)(HTTP*,char*);
				char *success;
				char *failure;
			} map[] = {
				/* this is the map of recognize request types */
				{"/xml/",		http_xml_request,		HTTP_OK, HTTP_NOTFOUND},
				{"/gui/",		http_gui_request,		HTTP_OK, HTTP_NOTFOUND},
				{"/output/",	http_output_request,	HTTP_OK, HTTP_NOTFOUND},
				{"/action/",	http_action_request,	HTTP_ACCEPTED,HTTP_NOTFOUND},
				{"/rt/",		http_get_rt,			HTTP_OK, HTTP_NOTFOUND},
				{"/perl/",		http_run_perl,			HTTP_OK, HTTP_NOTFOUND},
				{"/gnuplot/",	http_run_gnuplot,		HTTP_OK, HTTP_NOTFOUND},
				{"/java/",		http_run_java,			HTTP_OK, HTTP_NOTFOUND},
				{"/python/",	http_run_python,		HTTP_OK, HTTP_NOTFOUND},
				{"/r/",			http_run_r,				HTTP_OK, HTTP_NOTFOUND},
				{"/scilab/",	http_run_scilab,		HTTP_OK, HTTP_NOTFOUND},
				{"/octave/",	http_run_octave,		HTTP_OK, HTTP_NOTFOUND},
			};
			int n;
			for ( n=0 ; n<sizeof(map)/sizeof(map[0]) ; n++ )
			{
				size_t len = strlen(map[n].path);
				if (strncmp(uri,map[n].path,len)==0)
				{
					if ( map[n].request(http,uri+len) )
						http_status(http,map[n].success);
					else
						http_status(http,map[n].failure);
					http_send(http);
					goto Next;
				}
			}
		}
		/* deprecated XML usage */
		if (strncmp(uri,"/",1)==0 )
		{
			if ( http_xml_request(http,uri+1) )
			{	
				output_warning("deprecate XML usage in request '%s'", uri);
				http_status(http,HTTP_OK);
			}
			else
				http_status(http,HTTP_NOTFOUND);
			http_send(http);
		}
		else 
		{
			http_status(http,HTTP_NOTFOUND);
			http_format(http,HTTP_NOTFOUND);
			http_type(http,"text/html");
			http_send(http);
		}

		/* keep-alive not desired*/
Next:
		if (connection && stricmp(connection,"close")==0)
			break;
	}
	http_close(http);
	output_verbose("socket %d closed",http->s);
}
Esempio n. 16
0
STATUS server_startup(int argc, char *argv[])
{
	static int started = 0;
	int portNumber = global_server_portnum;
	SOCKET sockfd;
	struct sockaddr_in serv_addr;
#ifdef WIN32
	WSADATA wsaData;
#endif

	if (started)
		return SUCCESS;

#ifdef WIN32
	if (WSAStartup(MAKEWORD(2,0),&wsaData)!=0)
	{
		output_error("socket library initialization failed: %s",strerror(GetLastError()));
		return FAILED;	
	}
#endif

	/* create a new socket */
	if ((sockfd = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP)) == INVALID_SOCKET)
	{
		output_error("can't create stream socket: %s",strerror(GetLastError()));
		return FAILED;
	}
	atexit(shutdown_now);

	memset(&serv_addr,0,sizeof(serv_addr));

Retry:
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	serv_addr.sin_port = htons(portNumber);

	/* bind socket to server address */
	if (bind(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
	{
		if (portNumber<global_server_portnum+1000)
		{
			portNumber++;
			output_warning("server port not available, trying port %d...", portNumber);
			goto Retry;
		}
#ifdef WIN32
		output_error("can't bind to %d.%d.%d.%d",serv_addr.sin_addr.S_un.S_un_b.s_b1,serv_addr.sin_addr.S_un.S_un_b.s_b2,serv_addr.sin_addr.S_un.S_un_b.s_b3,serv_addr.sin_addr.S_un.S_un_b.s_b4);
#else
		output_error("can't bind address: %s",strerror(GetLastError()));
#endif
		return FAILED;
	}
#ifdef WIN32
	output_verbose("bind ok to %d.%d.%d.%d",serv_addr.sin_addr.S_un.S_un_b.s_b1,serv_addr.sin_addr.S_un.S_un_b.s_b2,serv_addr.sin_addr.S_un.S_un_b.s_b3,serv_addr.sin_addr.S_un.S_un_b.s_b4);
#else
	output_verbose("bind ok to address");
#endif	
	/* listen for connection */
	listen(sockfd,5);
	output_verbose("server listening to port %d", portNumber);
	global_server_portnum = portNumber;

	/* start the server thread */
	if (pthread_create(&thread,NULL,server_routine,(void*)sockfd))
	{
		output_error("server thread startup failed: %s",strerror(GetLastError()));
		return FAILED;
	}

	started = 1;
	return SUCCESS;
}
Esempio n. 17
0
/** Load a timezone from the timezone info file
 **/
void load_tzspecs(char *tz){
	char filepath[1024];
	char *pTzname = 0;
	FILE *fp = NULL;
	char buffer[1024];
	int linenum = 0;
	int year = YEAR0;
	int y;
	int found;

	found = 0;
	tzvalid = 0;
	pTzname = tz_name(tz);

	if(pTzname == 0){
		THROW("timezone '%s' was not understood by tz_name.", tz);
		/* TROUBLESHOOT
			The specific timezone is not valid.
			Try using a valid timezone or add the desired timezone to the timezone file <code>.../etc/tzinfo.txt</code> and try again.
		 */
	}

	strncpy(current_tzname, pTzname, sizeof(current_tzname));
	tzoffset = tz_offset(current_tzname);
	strncpy(tzstd, tz_std(current_tzname), sizeof(tzstd));
	strncpy(tzdst, tz_dst(current_tzname), sizeof(tzdst));

	if(find_file(TZFILE, NULL, R_OK,filepath,sizeof(filepath)) == NULL){
		THROW("timezone specification file %s not found in GLPATH=%s: %s", TZFILE, getenv("GLPATH"), strerror(errno));
		/* TROUBLESHOOT
			The system could not locate the timezone file <code>tzinfo.txt</code>.
			Check that the <code>etc</code> folder is included in the '''GLPATH''' environment variable and try again.
		 */
	}

	fp = fopen(filepath,"r");

	if(fp == NULL){
		THROW("%s: access denied: %s", filepath, strerror(errno));
		/* TROUBLESHOOT
			The system was unable to read the timezone file.  Check that the file has the correct permissions and try again.
		 */
	}

	// zero previous DST start/end times
	for (y = 0; y < sizeof(tszero) / sizeof(tszero[0]); y++){
		dststart[y] = dstend[y] = -1;
	}

	while(fgets(buffer,sizeof(buffer),fp)){
		char *p = NULL;
		char tzname[32];
		SPEC start, end;
		int form = -1;

		linenum++;

		/* wipe comments */
		p = strchr(buffer,';');

		if(p != NULL){
			*p = '\0';
		}

		/* remove trailing whitespace */
		p = buffer + strlen(buffer) - 1;

		while (iswspace(*p) && p > buffer){
			*p-- = '\0';
		}

		/* ignore blank lines or lines starting with white space*/
		if (buffer[0] == '\0' || iswspace(buffer[0])){
			continue;
		}

		/* year section */
		if(sscanf(buffer, "[%d]", &year) == 1){
			continue;
		}

		/* TZ spec */
		form = sscanf(buffer, "%[^,],M%d.%d.%d/%d:%d,M%d.%d.%d/%d:%d", tzname,
			&start.month, &start.nth, &start.day, &start.hour, &start.minute,
			&end.month, &end.nth, &end.day, &end.hour, &end.minute);

		/* load only TZ requested */
		pTzname = tz_name(tzname);

		if (tz != NULL && pTzname != NULL && strcmp(pTzname,current_tzname) != 0){
			continue;
		}

		if(form == 1){ /* no DST */
			set_tzspec(year, current_tzname, NULL, NULL);
			found = 1;
		} else if(form == 11) { /* full DST spec */
			set_tzspec(year, current_tzname, &start, &end);
			found = 1;
		} else {
			THROW("%s(%d): %s is not a valid timezone spec", filepath, linenum, buffer);
			/* TROUBLESHOOT
				The timezone specification is not valid.  Verify the syntax of the timezone spec and that it is defined in the timezone file
				<code>.../etc/tzinfo.txt</code> or add it, and try again.
			 */
		}
	}

	if(found == 0){
		output_warning("%s(%d): timezone spec '%s' not found in 'tzinfo.txt', will include no DST information", filepath, linenum, current_tzname);
	}

	if(ferror(fp)){
		output_error("%s(%d): %s", filepath, linenum, strerror(errno));
	} else {
		output_verbose("%s loaded ok", filepath);
	}

	fclose(fp);
	tzvalid = 1;
}
Esempio n. 18
0
void gld_loadHndl::warning(const SAXParseException& e){
	output_warning("XML_Load: %ls(%i:char %i)\n Message: %ls", (char *)e.getSystemId(), e.getLineNumber(), e.getColumnNumber(), (char *)e.getMessage());
	//load_state = false;
}
Esempio n. 19
0
void *check_version_proc(void *ptr)
{
	int patch, build;
	char *url = "http://gridlab-d.svn.sourceforge.net/viewvc/gridlab-d/trunk/core/versions.txt";
	HTTPRESULT *result = http_read(url,0x1000);
	char target[32];
	char *pv = NULL, *nv = NULL;
	int rc = 0;
	int mypatch = REV_PATCH;
	int mybuild = atoi(BUILDNUM);

	/* if result not found */
	if ( result==NULL || result->body.size==0 )
	{
		output_warning("check_version: unable to read %s", url);
		rc=CV_NOINFO;
		goto Done;
	}

	/** @todo check the version against latest available **/
	if ( result->status>0 && result->status<400 )
	{
		output_warning("check_version: '%s' error %d", url, result->status);
		rc=CV_BADURL;
		goto Done;
	}

	/* read version data */
	sprintf(target,"%d.%d:",REV_MAJOR,REV_MINOR);
	pv = strstr(result->body.data,target);
	if ( pv==NULL )
	{
		output_warning("check_version: '%s' has no entry for version %d.%d", url, REV_MAJOR, REV_MINOR);
		rc=CV_NODATA;
		goto Done;
	}
	if ( sscanf(pv,"%*d.%*d:%d:%d", &patch, &build)!=2 )
	{
		output_warning("check_version: '%s' entry for version %d.%d is bad", url, REV_MAJOR, REV_MINOR);
		rc=CV_NODATA;
		goto Done;
	}

	nv = strchr(pv,'\n');
	if ( nv!=NULL )
	{
		while ( *nv!='\0' && isspace(*nv) ) nv++;
		if ( *nv!='\0' )
		{
			output_warning("check_version: newer versions than %s (Version %d.%d) are available", BRANCH, REV_MAJOR, REV_MINOR);
			rc|=CV_NEWVER;
		}
		/* not done yet */
	}
	if ( mypatch<patch )
	{
		output_warning("check_version: a newer patch of %s (Version %d.%d.%d-%d) is available", BRANCH, REV_MAJOR, REV_MINOR, patch, build);
		rc|=CV_NEWPATCH;
		/* not done yet */
	}
	if ( mybuild>0 && mybuild<build )
	{
		output_warning("check_version: a newer build of %s (Version %d.%d.%d-%d) is available", BRANCH, REV_MAJOR, REV_MINOR, patch, build);
		rc|=CV_NEWBUILD;
	}
	if ( rc==0 )
		output_verbose("this version is current");

	/* done */
Done:
	http_delete_result(result);
	return (void*)rc;
}
Esempio n. 20
0
/** Load and process the command-line arguments
	@return a STATUS value

	Arguments are processed immediately as they are seen.  This means that
	models are loaded when they are encountered, and in relation to the
	other flags.  Thus
	@code
	gridlabd --warn model1 --warn model2
	@endcode
	will load \p model1 with warnings on, and \p model2 with warnings off.
 **/
STATUS cmdarg_load(int argc, /**< the number of arguments in \p argv */
				   char *argv[]) /**< a list pointers to the argument string */
{
	int test_mod_num = 1;
	unsigned int pos=0;
	int i;
	char *pd1, *pd2;

	/* capture the execdir */
	strcpy(global_execname,argv[0]);
	strcpy(global_execdir,argv[0]);
	pd1 = strrchr(global_execdir,'/');
	pd2 = strrchr(global_execdir,'\\');
	if (pd1>pd2) *pd1='\0';
	else if (pd2>pd1) *pd2='\0';

	/* capture the command line */
	for (i=0; i<argc; i++)
	{
		if (pos<sizeof(global_command_line)-strlen(argv[i]))
			pos += sprintf(global_command_line+pos,"%s%s",pos>0?" ":"",argv[i]);
	}

	while (argv++,--argc>0)
	{
		if (strcmp(*argv,"--copyright")==0)
			legal_notice();
		else if (strcmp(*argv,"-w")==0 || strcmp(*argv,"--warn")==0)
			global_warn_mode=!global_warn_mode;
		else if (strcmp(*argv,"--bothstdout")==0)
			output_both_stdout();
		else if (strcmp(*argv,"-c")==0 || strcmp(*argv,"--check")==0)
			global_runchecks=!global_runchecks;
		else if (strcmp(*argv,"--debug")==0)
			global_debug_output=!global_debug_output;
		else if (strcmp(*argv,"--debugger")==0){
			global_debug_mode=1;
			global_debug_output=!global_debug_output;
		}
		else if (strcmp(*argv,"--dumpall")==0)
			global_dumpall=!global_dumpall;
		else if (strcmp(*argv,"-q")==0 || strcmp(*argv,"--quiet")==0)
			global_quiet_mode=!global_quiet_mode;
		else if (strcmp(*argv,"-v")==0 || strcmp(*argv,"--verbose")==0){
			global_verbose_mode=!global_verbose_mode;
		}
		else if (strcmp(*argv,"--profile")==0)
			global_profiler=!global_profiler;
		else if (strcmp(*argv,"--pause")==0)
			global_pauseatexit=!global_pauseatexit;
		else if (strcmp(*argv,"--compile")==0)
			global_compileonly = !global_compileonly;
		else if (strcmp(*argv,"--license")==0)
			legal_license();
		else if (strcmp(*argv,"--server_portnum")==0 || strcmp(*argv,"-P")==0)
		{
			if (argc-1>0)
				global_server_portnum = (argc--,atoi(*++argv));
			else
			{
				output_fatal("missing server port number");
				/*	TROUBLESHOOT
					The <b>-P</b> or <b>--server_portnum</b> command line directive
					was not followed by a valid number.  The correct syntax is
					<b>-P <i>number</i></b> or <b>--server_portnum <i>number</i></b>.
				 */
			}
		}
		else if (strcmp(*argv, "-V")==0 ||strcmp(*argv, "--version")==0)
		{
			char *buildinfo = strstr(BUILD,":");
			int build = buildinfo ? atoi(strstr(BUILD,":")+1) : 0;
			output_message("Revision major: %d", REV_MAJOR);
			output_message("Revision minor: %d", REV_MINOR);
			output_message("Patch number  : %d", REV_PATCH);
			output_message("Branch name   : %s", BRANCH);
			if (build>0)
				output_message("Build number  : %d", build);
			else
				output_message("Build number  : %s",
#ifdef WIN32
#ifdef _DEBUG
#ifdef _M_X64
			"WIN64-DEBUG"
#else
			"WIN32-DEBUG" 
#endif
#else
#ifdef _M_X64
			"WIN64-RELEASE"
#else
			"WIN32-RELEASE"
#endif
#endif
#else
			"DEV"
#endif		
			);
		}
		else if (strcmp(*argv,"--dsttest")==0)
			timestamp_test();
		else if (strcmp(*argv,"--randtest")==0)
			random_test();
		else if (strcmp(*argv,"--unitstest")==0)
			unit_test();
		else if (strcmp(*argv,"--scheduletest")==0)
			schedule_test();
		else if (strcmp(*argv,"--loadshapetest")==0)
			loadshape_test();
		else if (strcmp(*argv,"--endusetest")==0)
			enduse_test();
		else if (strcmp(*argv,"--xmlstrict")==0)
			global_xmlstrict = !global_xmlstrict;
		else if (strcmp(*argv,"--globaldump")==0)
		{
			global_dump();
			exit(0);
		}
		else if (strcmp(*argv,"--relax")==0)
			global_strictnames = FALSE;
		else if (strncmp(*argv,"--pidfile",9)==0)
		{
			char *filename = strchr(*argv,'=');
			if (filename==NULL)
				strcpy(global_pidfile,"gridlabd.pid");
			else
				strcpy(global_pidfile,filename+1);
		}
		else if (strncmp(*argv,"--kml",5)==0)
		{
			char *filename = strchr(*argv,'=');
			if (filename)
				strcpy(global_kmlfile,filename+1);
			else
				strcpy(global_kmlfile,"gridlabd.kml");
		}
		else if (strcmp(*argv, "--avlbalance") == 0){
			global_no_balance = !global_no_balance;
		}
		else if (strcmp(*argv,"--testall")==0){
			FILE *fd = NULL;
			if(*++argv != NULL)
				fd = fopen(*argv,"r");
			else {
				output_fatal("no filename for testall");
				/*	TROUBLESHOOT
					The --testall parameter was found on the command line, but
					if was not followed by a filename containing the test
					description file.
				*/
				return FAILED;
			}
			argc--;
			global_test_mode=TRUE;

			if(fd == NULL)
			{
				output_fatal("incorrect module list file name");
				/*	TROUBLESHOOT
					The --testall parameter was found on the command line, but
					if was not followed by a valid filename containing the test
					description file.
				*/
				return FAILED;
			}
			if(load_module_list(fd,&test_mod_num) == FAILED)
				return FAILED;
		}
		else if (strcmp(*argv,"--modhelp")==0)
		{
			if(argc-1 > 0){
				MODULE *mod = NULL;
				CLASS *oclass = NULL;
				argv++;
				argc--;
				if(strchr(argv[0], ':') == 0){ // no class
					mod = module_load(argv[0],0,NULL);
				} else {
					GLOBALVAR *var=NULL;
					char *cname;
					cname = strchr(argv[0], ':')+1;
					mod = module_load(strtok(argv[0],":"),0,NULL);
					oclass = class_get_class_from_classname(cname);
					if(oclass == NULL){
						output_fatal("Unable to find class '%s' in module '%s'", cname, argv[0]);
						/*	TROUBLESHOOT
							The <b>--modhelp</b> parameter was found on the command line, but
							if was followed by a class specification that isn't valid.
							Verify that the class exists in the module you specified.
						*/
						return FAILED;
					}

					/* dump module globals */
					printf("module %s {\n", mod->name);
					while ((var=global_getnext(var))!=NULL)
					{
						PROPERTY *prop = var->prop;
						char *proptype = class_get_property_typename(prop->ptype);
						if (strncmp(var->prop->name,mod->name,strlen(mod->name))!=0)
							continue;
						if (proptype!=NULL){
							if(prop->unit != NULL)
							{
								printf("\t%s %s[%s];", proptype, strrchr(prop->name,':')+1, prop->unit->name);
							}
							else if (prop->ptype==PT_set || prop->ptype==PT_enumeration)
							{
								KEYWORD *key;
								printf("\t%s {", proptype);
								for (key=prop->keywords; key!=NULL; key=key->next)
									printf("%s=%"FMT_INT64"u%s", key->name, (int64)key->value, key->next==NULL?"":", ");
								printf("} %s;", strrchr(prop->name,':')+1);
							} 
							else 
							{
								printf("\t%s %s;", proptype, strrchr(prop->name,':')+1);
							}
							if (prop->description!=NULL)
								printf(" // %s%s",prop->flags&PF_DEPRECATED?"(DEPRECATED) ":"",prop->description);
							printf("\n");
						}
					}
					printf("}\n");
				}
				if(mod == NULL){
					output_fatal("module %s is not found",*argv);
					/*	TROUBLESHOOT
						The <b>--modhelp</b> parameter was found on the command line, but
						if was followed by a module specification that isn't valid.
						Verify that the module exists in GridLAB-D's <b>lib</b> folder.
					*/
					return FAILED;
				}
				if(oclass != NULL)
				{
					print_class(oclass);
				}
				else
				{
					CLASS	*oclass;
					pntree	*ctree;
					/* lexographically sort all elements from class_get_first_class & oclass->next */

					oclass=class_get_first_class();
					ctree = (pntree *)malloc(sizeof(pntree));
					
					if(ctree == NULL){
						throw_exception("--modhelp: malloc failure");
						/* TROUBLESHOOT
							The memory allocation needed for module help to function has failed.  Try freeing up system memory and try again.
						 */
					}
					
					ctree->name = oclass->name;
					ctree->oclass = oclass;
					ctree->left = ctree->right = 0;
					
					for(; oclass != NULL; oclass = oclass->next){
						modhelp_alpha(&ctree, oclass);
						//print_class(oclass);
					}

					/* flatten tree */
					print_modhelp_tree(ctree);
				}
			}
		}
		else if (strcmp(*argv,"--modtest")==0)
		{
			if (argc-1>0)
			{
				MODULE *mod = module_load(argv[1],0,NULL);
				if (mod==NULL)
					output_fatal("module %s is not found",argv[1]);
					/*	TROUBLESHOOT
						The <b>--modtest</b> parameter was found on the command line, but
						if was followed by a module specification that isn't valid.
						Verify that the module exists in GridLAB-D's <b>lib</b> folder.
					*/
				else 
				{
					argv++;argc--;
					if (mod->test==NULL)
						output_fatal("module %s does not implement a test routine", argv[0]);
						/*	TROUBLESHOOT
							The <b>--modtest</b> parameter was found on the command line, but
							if was followed by a specification for a module that doesn't
							implement any test procedures.  See the <b>--libinfo</b> command
							line parameter for information on which procedures the
							module supports.
						*/
					else
					{
						output_test("*** modtest of %s beginning ***", argv[0]);
						mod->test(0,NULL);
						output_test("*** modtest of %s ended ***", argv[0]);
					}
				}			
			}
			else
			{
				output_fatal("definition is missing");
				/*	TROUBLESHOOT
					The <b>--modtest</b> parameter was found on the command line, but
					if was not followed by a module specification.  The correct
					syntax is <b>gridlabd --modtest <i>module_name</i></b>.
				*/
				return FAILED;
			}
		}
		else if (strcmp(*argv,"--test")==0){
			global_test_mode=TRUE;
			global_strictnames = FALSE;
			output_debug("disabling strict naming for tests");
			if (argc-1>0)
			{
				char mod_test[100];
				sprintf(mod_test,"mod_test%d=%s",test_mod_num++,*++argv);
				if (global_setvar(mod_test)==SUCCESS)
					argc--;
			}
			else
			{
				output_fatal("test module name is missing");
				/*	TROUBLESHOOT
					The <b>--test</b> parameter was found on the command line, but
					if was not followed by a module specification that is valid.
					The correct syntax is <b>gridlabd --test <i>module_name</i></b>.
				*/
				return FAILED;
			}

		}
		else if (strcmp(*argv,"-D")==0 || strcmp(*argv,"--define")==0)
		{
			if (argc-1>0)
			{
				bool namestate = global_strictnames;
				global_strictnames = FALSE;
				if (global_setvar(*++argv,NULL)==SUCCESS){
					argc--;
				}
				global_strictnames = namestate;
			}
			else
			{
				output_fatal("definition is missing");
				/* TROUBLESHOOT
					The <b>-D</b> or <b>--define</b> command line parameters was given, but
					it was not followed by a variable definition.  The correct syntax
					<b>-D </i>variable</i>=<i>value</i></b> or
					<b>--define </i>variable</i>=<i>value</i></b>
				 */
				return FAILED;
			}
		}
		else if (strcmp(*argv,"--globals")==0)
		{
			char *list[65536];
			int i, n=0;
			GLOBALVAR *var = NULL;

			/* load the list into the array */
			while ((var=global_getnext(var))!=NULL)
			{
				if (n<sizeof(list)/sizeof(list[0]))
					list[n++] = var->prop->name;
				else
				{
					output_fatal("--globals has insufficient buffer space to sort globals list");
					return FAILED;
				}
			}

			/* sort the array */
			qsort(list,n,sizeof(list[0]),compare);

			/* output sorted array */
			for (i=0; i<n; i++)
			{
				char buffer[1024];
				var = global_find(list[i]);
				printf("%s=%s;",var->prop->name,global_getvar(var->prop->name,buffer,sizeof(buffer))?buffer:"(error)");
				if (var->prop->description || var->prop->flags&PF_DEPRECATED)
					printf(" // %s%s", (var->prop->flags&PF_DEPRECATED)?"DEPRECATED ":"", var->prop->description?var->prop->description:"");
				printf("\n");
			}
		}
		else if (strcmp(*argv,"--redirect")==0)
		{
			if (argc-1>0)
			{
				char buffer[1024]; char *p;
				strcpy(buffer,*++argv); argc--;
				if (strcmp(buffer,"all")==0)
				{
					if (output_redirect("output",NULL)==NULL ||
						output_redirect("error",NULL)==NULL ||
						output_redirect("warning",NULL)==NULL ||
						output_redirect("debug",NULL)==NULL ||
						output_redirect("verbose",NULL)==NULL ||
						output_redirect("profile",NULL)==NULL ||
						output_redirect("progress",NULL)==NULL)
					{
						output_fatal("redirection of all failed");
						/* TROUBLESHOOT
							An attempt to close all standard stream from the
							command line using <b>--redirect all</b> has failed.
							One of the streams cannot be closed.  Try redirecting
							each stream separately until the problem stream is
							identified and the correct the problem with that stream.
						 */
						return FAILED;
					}
				}
				else if ((p=strchr(buffer,':'))!=NULL)
				{
					*p++='\0';
					if (output_redirect(buffer,p)==NULL)
					{
						output_fatal("redirection of %s to '%s' failed: %s",buffer,p, strerror(errno));
						/*	TROUBLESHOOT
							An attempt to redirect a standard stream from the 
							command line using <b>--redirect <i>stream</i>:<i>destination</i></b>
							has failed.  The message should provide an indication of why the
							attempt failed. The remedy will depend on the nature of the problem.
						 */
						return FAILED;
					}
				}
				else if (output_redirect(buffer,NULL)==NULL)
				{
						output_fatal("default redirection of %s failed: %s",buffer, strerror(errno));
						/*	TROUBLESHOOT
							An attempt to close a standard stream from the 
							command line using <b>--redirect <i>stream</i></b>
							has failed.  The message should provide an indication of why the
							attempt failed. The remedy will depend on the nature of the problem.
							
						 */
						return FAILED;
				}
			}
			else
			{
				output_fatal("redirection is missing");
				/*	TROUBLESHOOT
					A <b>--redirect</b> directive on the command line is missing
					its redirection specification.  The correct syntax is
					<b>--redirect <i>stream</i>[:<i>destination</i>]</b>.
				 */
				return FAILED;
			}
		}
		else if (strcmp(*argv,"-L")==0 || strcmp(*argv,"--libinfo")==0)
		{
			if (argc-1>0)
			{	argc--;
				module_libinfo(*++argv);
				exit(0);
			}
			else
			{
				output_fatal("missing library name");
				/*	TROUBLESHOOT
					The <b>-L</b> or <b>--libinfo</b> command line directive
					was not followed by a module name.  The correct syntax is
					<b>-L <i>module_name</i></b> or <b>--libinfo <i>module_name</i></b>.
				 */
				return FAILED;
			}
		}
		else if (strcmp(*argv,"-T")==0 || strcmp(*argv,"--threadcount")==0)
		{
			if (argc-1>0)
				global_threadcount = (argc--,atoi(*++argv));
			else
			{
				output_fatal("missing thread count");
				/*	TROUBLESHOOT
					The <b>-T</b> or <b>--threadcount</b> command line directive
					was not followed by a valid number.  The correct syntax is
					<b>-T <i>number</i></b> or <b>--threadcount <i>number</i></b>.
				 */
				return FAILED;
			}
		}
		else if (strcmp(*argv,"-o")==0 || strcmp(*argv,"--output")==0)
		{
			if (argc-1>0)
				strcpy(global_savefile,(argc--,*++argv));
			else
			{
				output_fatal("missing output file");
				/* TROUBLESHOOT
					The <b>-o</b> or <b>--output</b> command line directive
					was not followed by a valid filename.  The correct syntax is
					<b>-o <i>file</i></b> or <b>--output <i>file</i></b>.
				 */
				return FAILED;
			}
		}
		else if (strcmp(*argv,"-e")==0 || strcmp(*argv,"--environment")==0)
		{
			if (argc-1>0)
				strcpy(global_environment,(argc--,*++argv));
			else
			{
				output_fatal("environment not specified");
				/*	TROUBLESHOOT
					The <b>-e</b> or <b>--environment</b> command line directive
					was not followed by a valid environment specification.  The
					correct syntax is <b>-e <i>keyword</i></b> or <b>--environment <i>keyword</i></b>.
				 */
				return FAILED;
			}
		}
		else if (strcmp(*argv,"--xmlencoding")==0)
		{
			if (argc-1>0)
			{
				global_xml_encoding = atoi(*++argv);
				argc--;
			}
			else
			{
				output_fatal("xml encoding not specified");
				/*	TROUBLESHOOT
					The <b>--xmlencoding</b> command line directive
					was not followed by a encoding specification.  The
					correct syntax is <b>--xmlencoding <i>keyword</i></b>.
				 */
				return FAILED;
			}
		}
		else if (strcmp(*argv,"--xsd")==0)
		{
			if (argc-1>0)
			{
				argc--;
				exit(output_xsd(*++argv));
			}
			else
			{
				MODULE *mod;
				for (mod=module_get_first(); mod!=NULL; mod=mod->next)
					output_xsd(mod->name);
				return SUCCESS;
			}
		}
		else if (strcmp(*argv,"--xsl")==0)
		{
			if (argc-1>0)
			{
				char fname[1024];
				char *p_arg = *++argv;
				char n_args=1;
				char **p_args;
				argc--;
				while (*p_arg++!='\0') if (*p_arg==',')	n_args++;
				p_args = (char**)malloc(sizeof(char*)*n_args);
				p_arg = strtok(*argv,",");
				n_args=0;
				while (p_arg!=NULL)
				{
					p_args[n_args++] = p_arg;
					p_arg = strtok(NULL,",");
				}
				sprintf(fname,"gridlabd-%d_%d.xsl",global_version_major,global_version_minor);
				exit(output_xsl(fname,n_args,p_args));
			}
			else
			{
				output_fatal("module list not specified");
				/*	TROUBLESHOOT
					The <b>--xsl</b> command line directive
					was not followed by a validlist of modules.  The
					correct syntax is <b>--xsl <i>module1</i>[,<i>module2</i>[,...]]</b>.
				 */
				return FAILED;
			}
		}
		else if (strcmp(*argv,"--stream")==0)
			global_streaming_io_enabled = !global_streaming_io_enabled;
		else if (strcmp(*argv,"--server")==0)
			strcpy(global_environment,"server");
		else if (strcmp(*argv,"-h")==0 || strcmp(*argv,"--help")==0)
		{
			printf("Syntax: gridlabd [OPTIONS ...] <file> ... \nOptions:\n"
				"  --avlbalance              toggles AVL tree balancing\n"
				"  -c|--check                toggles module checks after model loads\n"
				"  -D|--define <def>         defines a macro value\n"
				"  --debug                   toggles debug output (prints internal messages)\n"
				"  --debugger                toggles debugger mode (generates internal messages)\n"
				"  --dumpall                 toggles module data dump after run completes\n"
				"  -e|--environment <name>   specifies user environment (default none)\n"
				"  --license                 print license information\n"
				"  -L|--libinfo <module>     print module library information\n"
				"  -o|--output <file>        specifies model should be output after run\n"
				"  --profile                 toggles profilers\n"
				"  -q|--quiet                toggles quiet mode (suppresses startup banner)\n"
				"  --test                    toggles test mode (activate testing procedures)\n"
				"  -T|--threadcount <n>      specifies the number of processor threads to use\n"
				"  -v|--verbose              toggles verbose mode (active verbose messages)\n"
				"  -V|--version              prints the GridlabD version information\n"
				"  -w|--warn                 toggles warning mode (generates warning messages)\n"
				"  --xmlencoding <num>       set the XML encoding (8, 16, or 32)\n"
				"  --xmlstrict               toggles XML encoding to be strict\n"
				"  --xsd <module>[:<object>] prints the xsd of an object\n"
				"  --xsl <modlist>           prints the xsl for the modules listed\n"
				);
			exit(0);
		}
		else if (**argv!='-')
		{
			if (global_test_mode)
				output_warning("file '%s' ignored in test mode", *argv);
				/* TROUBLESHOOT
				   This warning is caused by an attempt to read an input file in self-test mode.  
				   The use of self-test model precludes reading model files.  Try running the system
				   in normal more or leaving off the model file name.
				 */
			else {
				if (!loadall(*argv))
					return FAILED;
				/* preserve name of first model only */
				if (strcmp(global_modelname,"")==0)
					strcpy(global_modelname,*argv);
			}
		}
		else
		{
			int n = module_cmdargs(argc,argv);
			if (n==0)
			{
				output_error("command line option '%s' is not recognized",*argv);
				/* TROUBLESHOOT
					The command line option given is not valid where it was found.
					Check the command line for correct syntax and order of options.
				 */
				return FAILED;
			}
		}
	}
	/*debug_traverse_tree(NULL);*/  /* for checking the name tree & getting a test file. -mh */
	return SUCCESS;
}
Esempio n. 21
0
int convert_to_enduse(char *string, void *data, PROPERTY *prop)
{
	enduse *e = (enduse*)data;
	char buffer[1024];
	char *token = NULL;

	/* check string length before copying to buffer */
	if (strlen(string)>sizeof(buffer)-1)
	{
		output_error("convert_to_enduse(string='%-.64s...', ...) input string is too long (max is 1023)",string);
		return 0;
	}
	strcpy(buffer,string);

	/* parse tuples separate by semicolon*/
	while ((token=strtok(token==NULL?buffer:NULL,";"))!=NULL)
	{
		/* colon separate tuple parts */
		char *param = token;
		char *value = strchr(token,':');

		/* isolate param and token and eliminte leading whitespaces */
		while (isspace(*param) || iscntrl(*param)) param++;
		if (value==NULL)
			value="1";
		else
			*value++ = '\0'; /* separate value from param */
		while (isspace(*value) || iscntrl(*value)) value++;

		// parse params
		if (strcmp(param,"current_fraction")==0)
			e->current_fraction = atof(value);
		else if (strcmp(param,"impedance_fraction")==0)
			e->impedance_fraction = atof(value);
		else if (strcmp(param,"power_fraction")==0)
			e->power_fraction = atof(value);
		else if (strcmp(param,"power_factor")==0)
			e->power_factor = atof(value);
		else if (strcmp(param,"loadshape")==0)
		{
			PROPERTY *pref = class_find_property(prop->oclass,value);
			if (pref==NULL)
			{
				output_warning("convert_to_enduse(string='%-.64s...', ...) loadshape '%s' not found in class '%s'",string,value,prop->oclass->name);
				return 0;
			}
			e->shape = (loadshape*)((char*)e - (int64)(prop->addr) + (int64)(pref->addr));
		}
		else
		{
			output_error("convert_to_enduse(string='%-.64s...', ...) parameter '%s' is not valid",string,param);
			return 0;
		}
	}

	/* reinitialize the loadshape */
	if (enduse_init((enduse*)data))
		return 0;

	/* everything converted ok */
	return 1;
}
Esempio n. 22
0
glxlink::glxlink(char *filename)
{
	bool ok = true;
	globals = NULL;
	imports = NULL;
	exports = NULL;
	objects = NULL;
	handle = NULL;
	settag = NULL;
	init = NULL;
	sync = NULL;
	term = NULL;
	glxflags = 0;
	valid_to = 0;
	last_t = 0;

	FILE *fp = fopen(filename,"rt");
	if ( fp==NULL )
		throw "file open failed";
	output_debug("opened link '%s'", filename);

	char line[1024];
	int linenum=0;
	while ( fgets(line,sizeof(line),fp)!=NULL )
	{
		linenum++;
		if ( line[0]=='#' ) continue;
		char tag[64], data[1024]="";
		if ( sscanf(line,"%s %[^\r\n]",tag,data)>0 )
		{
			output_debug("%s(%d): %s %s", filename, linenum, tag,data);
			if ( settag!=NULL )
			{
				if ( strcmp(tag,"global")==0 )
				{
					add_global(data);
				}
				else if ( strcmp(tag,"object")==0 )
				{
					add_object(data);
				}
				else if ( strcmp(tag,"export")==0 )
				{
					add_export(data);
				}
				else if ( strcmp(tag,"import")==0 )
				{
					add_import(data);
				}
				else if ( !(*settag)(this,tag,data) )
					output_error("%s(%d): tag '%s' not accepted", filename, linenum, tag);
			}
			else if ( strcmp(tag,"target")==0)
			{
				if ( !set_target(data) )
				{
					output_error("%s(%d): target '%s' is not valid", filename, linenum, data);
					ok = false;
				}
			}
			else
				output_warning("%s(%d): tag '%s' cannot be processed until target module is loaded", filename, linenum, tag);
		}
	}

	fclose(fp);

	// append to link list
	next = first;
	first = this;

	if ( ok )
		output_verbose("link '%s' ok", filename);
	else
		throw "cannot establish link";
}
Esempio n. 23
0
void mexFunction( int nlhs, mxArray *plhs[],
		  int nrhs, const mxArray *prhs[] )
{
	static first = 1;
	char key[MAXNAME];
	int i;
	
	if (first==1)
	{
		first = 0;

		/* prevent Matlab from clearing GridLAB */
		mexLock(); 

		/* register Matlab output routines */
		output_set_stdout(mexPrintf);
		output_set_stderr(cmex_printerr);

		/* display legal stuff */
		legal_license();

		/* initialize GridLAB */
		exec_init();
	}

	/* check number of input arguments */
	if (nrhs<1)
	{
		output_error("Use gl('help') for a list of commands.");
		return;
	}
	
	/* check type of first argument */
	if (!mxIsChar(prhs[0]))
	{
		output_error("token must be a string");
		return;
	}
	
	/* read first argument */
	if (mxGetString(prhs[0],key,sizeof(key))!=0)
		output_warning("GridLAB key string too long");
		
	/* scan command map to find call function */
	for (i=0; i<sizeof(cmdMap)/sizeof(cmdMap[0]); i++)
	{
		if (strcmp(key,cmdMap[i].name)==0)
		{
			if (cmdMap[i].call == NULL) /* help request */
			{
				int j;
				if (nrhs==1)
				{
					output_raw("Available top-level commands\n");
					for (j=0; j<sizeof(cmdMap)/sizeof(cmdMap[0]); j++)
						output_raw("\t%s\t%s\n", cmdMap[j].name, cmdMap[j].brief);
					output_raw("Use gl('help',command) for details\n");
					return;
				}
				else if (mxIsChar(prhs[1]))
				{
					char cmd[MAXNAME];
					if (mxGetString(prhs[1],cmd,sizeof(cmd))!=0)
						output_warning("command string too long to read fully");

					for (j=0; j<sizeof(cmdMap)/sizeof(cmdMap[0]); j++)
					{
						if (strcmp(cmd,cmdMap[j].name)==0)
						{
							output_raw("Help for command '%s'\n\n%s\n", cmd, cmdMap[j].detail ? cmdMap[j].detail : "\tNo details available\n");
							return;
						}
					}
					output_error("Command '%s' does not exist", cmd);
					return;
				}
				else
				{
					output_error("command must be a string");
					return;
				}
			}
			else
			{
				(cmdMap[i].call)(nlhs,plhs,nrhs-1,prhs+1);
				return;
			}
		}
	}

	/* function not found */
	{	int nret = nlhs;
		output_error("unrecognized GridLAB operation--gl('help') for list");
		while (nret-->0)
			plhs[nret] = mxCreateDoubleMatrix(0,0,mxREAL);
	}
	return;
}