int isDividableValue(struct timeval *tRet, unsigned int uiReqInterval)
{
	struct __client *pClient = g_Resource1.next;
	int iRet = 0;
	while(pClient)
	{
		if(uiReqInterval == pClient->uiReqInterval)
		{
			setTimeValue(tRet, pClient->tSched.tv_sec, pClient->tSched.tv_usec);
			return  pClient->uiReqInterval;
		}
		else if( (uiReqInterval/pClient->uiReqInterval>1) && (uiReqInterval%pClient->uiReqInterval==0) )
		{
			if(iRet == 0)
			{
				setTimeValue(tRet, pClient->tSched.tv_sec, pClient->tSched.tv_usec);
				iRet = pClient->uiReqInterval;
			}
			else if(iRet < pClient->uiReqInterval)
			{
				setTimeValue(tRet, pClient->tSched.tv_sec, pClient->tSched.tv_usec);
				iRet = pClient->uiReqInterval;
			}
		}
		pClient = pClient->next;
	}
	return iRet;
}
int getResourceFromServer(struct __message *msg)
{
	struct __message resp;
	struct timeval timeEnd;
	struct timeval timeStart;
			
	gettimeofday(&timeStart, NULL);
			
	//TODO: send information request from a proxy to a resource server
	//memset(&msg, 0x0, sizeof(struct __message));
	if(send(g_iSocketServer, msg, sizeof(struct __message), 0) < 0)
	{
		printf("proxy : send failed!\n");
	}	//if(send(

	//TODO: get information from a resource server to proxy
	int size;
	memset(&resp, 0x0, sizeof(struct __message));
	if((size = recv(g_iSocketServer, &resp, sizeof(struct __message), 0)) > 0)
	{
		setTimeValue(&(msg->server_recved), resp.server_recved.tv_sec, resp.server_recved.tv_usec);
		setTimeValue(&(msg->server_started), resp.server_started.tv_sec, resp.server_started.tv_usec);
		setTimeValue(&(msg->server_finished), resp.server_finished.tv_sec, resp.server_finished.tv_usec);
	} //if((size
		
	msg->resource = resp.resource;
	msg->uiMaxAge = resp.uiMaxAge;

	//pthread_mutex_unlock(&m_lock);
			
	return 0;
}
Beispiel #3
0
void
TrajectoryAnalysisRunnerCommon::optionsFinished()
{
    if (impl_->trjfile_.empty() && impl_->topfile_.empty())
    {
        GMX_THROW(InconsistentInputError("No trajectory or topology provided, nothing to do!"));
    }

    if (impl_->trajectoryGroup_.isValid() && impl_->trjfile_.empty())
    {
        GMX_THROW(InconsistentInputError("-fgroup only makes sense together with a trajectory (-f)"));
    }

    impl_->settings_.impl_->plotSettings.setTimeUnit(impl_->settings_.timeUnit());

    if (impl_->bStartTimeSet_)
    {
        setTimeValue(TBEGIN, impl_->startTime_);
    }
    if (impl_->bEndTimeSet_)
    {
        setTimeValue(TEND, impl_->endTime_);
    }
    if (impl_->bDeltaTimeSet_)
    {
        setTimeValue(TDELTA, impl_->deltaTime_);
    }
}
bool
TrajectoryAnalysisRunnerCommon::optionsFinished(Options *options)
{
    if (impl_->bHelp_)
    {
        return false;
    }

    impl_->settings_.impl_->plotSettings.setTimeUnit(
            impl_->settings_.impl_->timeUnitManager.timeUnit());

    if (impl_->trjfile_.empty() && impl_->topfile_.empty())
    {
        GMX_THROW(InconsistentInputError("No trajectory or topology provided, nothing to do!"));
    }

    if (options->isSet("b"))
    {
        setTimeValue(TBEGIN, impl_->startTime_);
    }
    if (options->isSet("e"))
    {
        setTimeValue(TEND, impl_->endTime_);
    }
    if (options->isSet("dt"))
    {
        setTimeValue(TDELTA, impl_->deltaTime_);
    }

    return true;
}
int setSchedTime(struct timeval tMin)
{
	int ret = 0;
	struct __client *pClient;
	struct timeval tRet;
	
	pClient = g_Resource1.next;
		
	while(pClient)
	{
		struct timeval tCPaddMA; 
		struct timeval tMaxAge; 
		setTimeValue(&tMaxAge, g_Resource1.uiMaxAge/1000, (g_Resource1.uiMaxAge%1000)*1000);
		addTimeValue(&tCPaddMA, g_Resource1.tBaseTime, tMaxAge);
		
		if(isBiggerThan(pClient->tSched, tCPaddMA))
		{
			struct timeval tTemp;
			struct timeval tAllow;
			subTimeValue(&tTemp, pClient->tSched, tCPaddMA);
			
			setTimeValue(&tAllow, (pClient->uiReqInterval*2/10)/1000, ((pClient->uiReqInterval*2/10)%1000)*1000);
			//setTimeValue(&tAllow, (pClient->uiReqInterval*3/10)/1000, ((pClient->uiReqInterval*3/10)%1000)*1000);
			//setTimeValue(&tAllow, (pClient->uiReqInterval/10)/1000, ((pClient->uiReqInterval/10)%1000)*1000);
			//setTimeValue(&tAllow, (pClient->uiReqInterval/5)/1000, ((pClient->uiReqInterval/5)%1000)*1000);
			//setTimeValue(&tAllow, (pClient->uiReqInterval/4)/1000, ((pClient->uiReqInterval/4)%1000)*1000);
			//setTimeValue(&tAllow, (pClient->uiReqInterval/2)/1000, ((pClient->uiReqInterval/2)%1000)*1000);
			//setTimeValue(&tAllow, 0, 10*1000);
			if(isBiggerThan(tAllow, tTemp))
			{
				//TODO: set new schedule time
				//setTimeValue(&(pClient->tSched), tCPaddMA.tv_sec , tCPaddMA.tv_usec);
				setTimeValue(&(pClient->tSched), g_Resource1.tBaseTime.tv_sec , g_Resource1.tBaseTime.tv_usec);
			}
			else
			{
				//TODO: leave it for next processing
				;
			}
		}
		else
		{
			setTimeValue(&(pClient->tSched), g_Resource1.tBaseTime.tv_sec , g_Resource1.tBaseTime.tv_usec);
		}
					
		pClient = pClient->next;
	}

	return ret;
}
int setSchedule(struct timeval curTime)
{
	struct timeval tRet;

	setTimeValue(&tRet, 0x7FFFFFFF, 0x7FFFFFFF);
		
	//TODO: get the earliest schedule time
	getEarlistSchedTime(&tRet, curTime);
	
	//TODO: set base time
	setTimeValue(&g_Resource1.tBaseTime, tRet.tv_sec, tRet.tv_usec);
				
	//TODO: reschedule
	setSchedTime(tRet);
}
int handleMessage(struct __message *arg)
{
	struct timeval timeStart, timeEnd;
	struct __message msg;

	//TODO: rx delay
	usleep(DELAY_SERVER_RX*1000);

	memcpy(&msg, arg, sizeof(struct __message));

	gettimeofday(&timeStart, NULL);
	
#if ENABLE_MUTEX	
	pthread_mutex_lock(&m_lock);
#endif
    		
	//TODO: process delay
	usleep(DELAY_SERVER_PROCESS*1000);
	
#if ENABLE_MUTEX
	pthread_mutex_unlock(&m_lock);
#endif	//#if ENABLE_MUTEX

	gettimeofday(&timeEnd, NULL);

	setTimeValue(&(msg.server_started), timeStart.tv_sec, timeStart.tv_usec);
	setTimeValue(&(msg.server_finished), timeEnd.tv_sec, timeEnd.tv_usec);

#if 0
	msg.resource =  timeEnd.tv_sec%1000000;
	msg.uiMaxAge = (1000000-timeEnd.tv_usec)/1000;
#else
	msg.resource =  g_iCount++;
	msg.uiMaxAge = (DELAY_SERVER_PROCESS);
#endif	
	//TODO: tx delay
	usleep(DELAY_SERVER_TX*1000);

	//printf("[%d-%d]Resource=%d, uiMaxAge=%d, msg.iFd=%d ", msg.owner, msg.cnt, msg.resource, msg.uiMaxAge, msg.iFd);
	
	int temp = send(msg.iFd, &msg, sizeof(struct __message), 0);
	
#if 1
	dumpMessage(msg);
#endif	
	
	return 0;
}
int isCachedDataValid(struct timeval curTime)
{
	struct timeval timeB;
	struct timeval timeRet;
	int ret = 0;
//printf("%s:g_Resource1.uiCachedAge=%d, g_Resource1.uiMaxAge=%d\n", __func__, g_Resource1.uiCachedAge, g_Resource1.uiMaxAge);

	if( (g_Resource1.uiCachedAge<g_Resource1.uiMaxAge) && (g_Resource1.tCachedTime.tv_sec>0) )
	{
		struct timeval tMaxAge;
		struct timeval tTemp;
		setTimeValue(&tMaxAge, g_Resource1.uiMaxAge/1000, (g_Resource1.uiMaxAge%1000)*1000);
		addTimeValue(&tTemp, g_Resource1.tCachedTime, tMaxAge);
		//printf("%s:tMaxAge=%6ld.%06ld\n", __func__, tMaxAge.tv_sec, tMaxAge.tv_usec);
		printf("%s:tTemp=%6ld.%06ld,curTime=%6ld.%06ld\n", __func__, 
			tTemp.tv_sec, tTemp.tv_usec,
			curTime.tv_sec, curTime.tv_usec);	
		if(isBiggerThan(tTemp, curTime))
			ret = 1;
		else
			ret = 0;
	}
	else
	{
		ret = 0;
	}

	return ret;
}
Beispiel #9
0
bool ExpressionItem::setValue(void* value_str,const data_type type) {
    switch(type) {
    case t_int: {
        setIntValue(*(int *)value_str);
        break;
    }
    case t_float: {
        setFloatValue(*(float *)value_str);
        break;
    }
    case t_smallInt:
    {
        setSmallIntValue(*(short *)value_str);
        break;
    }
    case t_double: {
        setDoubleValue(*(double *)value_str);
        break;
    }
    case t_u_long: {
        setULongValue(*(unsigned long*)value_str);
        break;
    }
    case t_string: {
        setStringValue(string((char *)value_str));
        break;
    }
    case t_decimal: {
        setDecimalValue((const char *)value_str);
        break;
    }
    case t_datetime: {
        setDatetimeValue((const char *)value_str);
        break;
    }
    case t_date: {
        setDateValue((const char *)value_str);
        break;
    }
    case t_time: {
        setTimeValue((const char *)value_str);
        break;
    }
    case t_boolean: {
        setBooleanValue(*(bool *)value_str);
        break;
    }
    default: {
        cout<<"no matching operator exists!!!"<<endl;
        /*
         * In the debug phase, it's better to show the assert failure in case of unexpected input.
         * The bug can be found much more easily in such a way.
         */
        assert(false);
        break;
    }
    }
    return true;
}
int setCache(struct __message msg, struct timeval tNow)
{
	g_Resource1.iCachedResource = msg.resource;
	g_Resource1.uiMaxAge = msg.uiMaxAge;
	//g_Resource1.uiCachedAge = 0;
	setTimeValue(&(g_Resource1.tCachedTime), tNow.tv_sec, tNow.tv_usec);
	
}
//TODO: first schedule time = candidate
int addObserver1(int iId, int iFd, unsigned int uiResource, unsigned int uiReqInterval, struct timeval tNow)
{
	struct __client *pObserver;
	struct __client *pNew;
	struct __client *pPrev;
	int fAdd;
	
	pNew = (struct __client *)malloc(sizeof(struct __client));
	pNew->iId = iId;
	pNew->iFd = iFd;
	pNew->uiReqInterval = uiReqInterval;
	pNew->next = NULL;
	
	setTimeValue(&(pNew->tSched), 0, 0);
	getSchedTime(&(pNew->tSched), tNow, uiReqInterval);
		
	if(g_Resource1.next == NULL)
	{
		g_Resource1.next = pNew;
		g_Resource1.iClientNumber++;
	}
	else
	{	
		pObserver = g_Resource1.next;
				
		fAdd = 1;
		pPrev = NULL;
		while(pObserver)
		{	
			//printf("pNew->uiReqInterval=%d, pObserver->uiReqInterval=%d\n", pNew->uiReqInterval, pObserver->uiReqInterval);
			if(pNew->uiReqInterval < pObserver->uiReqInterval)
			{
				if(pPrev == NULL)
				{
					pNew->next = g_Resource1.next;
					g_Resource1.next = pNew;
				}
				else
				{
					pNew->next = pPrev->next;
					pPrev->next = pNew;
				}
				g_Resource1.iClientNumber++;
				break;
			}
			pPrev = pObserver;
			pObserver = pObserver->next;
			
			if(pObserver == NULL)
			{
					pPrev->next = pNew;
					g_Resource1.iClientNumber++;
			}
		}
	}
		
	return 0;
}
int getSchedTime(struct timeval *tRet, struct timeval tNow, unsigned int uiReqInterval)
{
	struct __client *pClient = g_Resource1.next;
	struct timeval tReqInterval;
	
	tReqInterval.tv_sec = uiReqInterval/1000;
	tReqInterval.tv_usec = uiReqInterval%1000*1000;
	
	if(g_Resource1.iClientNumber == 0)
	{
		tRet->tv_sec = tNow.tv_sec+1;
		tRet->tv_usec = 0;

		addTimeValue(&(g_Resource1.tBaseTime), *tRet, tReqInterval);

	}
	else 
	{
		//struct timeval tSched = pClient->tSched;
		struct timeval tSched;
		setTimeValue(&tSched, g_Resource1.tBaseTime.tv_sec, g_Resource1.tBaseTime.tv_usec);
		
		while(1)
		{
			struct timeval tTemp = tSched;
			subTimeValue(&tTemp, tTemp, tReqInterval);
			
			if(isBiggerThan(tTemp, tNow))
			{
				tSched = tTemp;
			}
			else
			{
				break;
			}
		}
		setTimeValue(tRet, tSched.tv_sec, tSched.tv_usec);
	}
		
	printf("Req=%d;S(%ld.%06ld);B(%ld.%06ld);N(%ld.%06ld)\n", 
			uiReqInterval,
			tRet->tv_sec, tRet->tv_usec, 
			g_Resource1.tBaseTime.tv_sec, g_Resource1.tBaseTime.tv_usec,
			tNow.tv_sec, tNow.tv_usec);
}
int initCache()
{
	g_Resource1.iCachedResource = 0;
	g_Resource1.uiMaxAge = 0;
	g_Resource1.uiCachedAge = 0;
	setTimeValue(&(g_Resource1.tCachedTime), 0, 0);
	
	return 0;
}
Beispiel #14
0
void
TrajectoryAnalysisRunnerCommon::optionsFinished()
{
    impl_->settings_.impl_->plotSettings.setTimeUnit(
            impl_->settings_.impl_->timeUnitManager.timeUnit());

    if (impl_->trjfile_.empty() && impl_->topfile_.empty())
    {
        GMX_THROW(InconsistentInputError("No trajectory or topology provided, nothing to do!"));
    }

    if (impl_->bStartTimeSet_)
    {
        setTimeValue(TBEGIN, impl_->startTime_);
    }
    if (impl_->bEndTimeSet_)
    {
        setTimeValue(TEND, impl_->endTime_);
    }
    if (impl_->bDeltaTimeSet_)
    {
        setTimeValue(TDELTA, impl_->deltaTime_);
    }
}
int setCache(struct __message msg, struct timeval tNow)
{
	g_Resource1.iCachedResource = msg.resource;
#if 0
	if(g_uiCacheAlgorithm == 2)
		g_Resource1.uiMaxAge = DELAY_PROXY_TIMESLICE;
	else
		g_Resource1.uiMaxAge = RESOURCE_DEFAULT_DELAY;
#else
		//g_Resource1.uiMaxAge = msg.uiMaxAge;
		g_Resource1.uiMaxAge = RESOURCE_DEFAULT_DELAY;
#endif		
	//g_Resource1.uiCachedAge = 0;
	setTimeValue(&(g_Resource1.tCachedTime), tNow.tv_sec, tNow.tv_usec);
	
}
Beispiel #16
0
int main( void )
{	
	void setTimeValue( char * ) ;
	void getConfiguartionData( char *, char * ) ;
	
 	char cwd[BUFFER_SIZE] = { '\0' } ;
 	char searchDir[BUFFER_SIZE] = { '\0' } ;
 	
	if( getcwd ( cwd , BUFFER_SIZE ) == NULL )
		_debug( __FILE__, __LINE__, 0, "error from getcwd()..." ) ;
	else
	{
		getConfiguartionData( cwd, searchDir ) ;
		_debug( __FILE__, __LINE__, 5, "cwd is %s", cwd ) ;
		_debug( __FILE__, __LINE__, 5, "searchDir is %s", searchDir ) ;
		
		setTimeValue( searchDir ) ;
	}

	return 0 ;
}
int getEarlistSchedTime(struct timeval *ptMin, struct timeval curTime)
{
	int ret = 0;
	struct __client *pClient;
	
	pClient = g_Resource1.next;
		
	while(pClient)
	{
		//if(pClient->tSched)
		{
			if(isBiggerThan(*ptMin, pClient->tSched))
			{
				setTimeValue(ptMin, pClient->tSched.tv_sec, pClient->tSched.tv_usec);
			}
		}
				
		pClient = pClient->next;
	}

	return ret;
}
int setSchedTime(struct timeval tMin)
{
	int ret = 0;
	struct __client *pClient;
	struct timeval tRet;
	
	pClient = g_Resource1.next;
		
	while(pClient)
	{
		if(isEqualTo(pClient->tSched, tMin))
		{
			;
			//printf("Equal!\n");
		}
		else
		{
			subTimeValue(&tRet, pClient->tSched, tMin);
			addTimeValue(&tRet, tRet, tRet);
			
			struct timeval tB;
			tB.tv_sec = pClient->uiReqInterval/1000;
			tB.tv_usec = (pClient->uiReqInterval%1000)*1000;
			
			//printf("NOT Equal!\n");
			
			if(isBiggerThan(tB, tRet))
			{
				setTimeValue(&(pClient->tSched), tMin.tv_sec , tMin.tv_usec);
			}
		}
					
		pClient = pClient->next;
	}

	return ret;
}
int updateBaseTime()
{
	int ret;
	struct __client *pClient;
	
	pClient = g_Resource1.next;
	ret = pClient->uiReqInterval;
		
	while(pClient)
	{
		if((pClient->next!=NULL) && (pClient->next->uiReqInterval))
		{
			ret = getLCM(ret, pClient->next->uiReqInterval);
		}
		pClient = pClient->next;
	}

	struct timeval tTemp;
	setTimeValue(&tTemp, ret/1000, (ret%1000)*1000);
	addTimeValue(&(g_Resource1.tBaseTime), g_Resource1.tBaseTime, tTemp);

	//printf("ret=%d\n", ret);
	return ret;
}
Beispiel #20
0
gmx_bool parse_common_args(int *argc, char *argv[], unsigned long Flags,
                           int nfile, t_filenm fnm[], int npargs, t_pargs *pa,
                           int ndesc, const char **desc,
                           int nbugs, const char **bugs,
                           gmx_output_env_t **oenv)
{
    /* This array should match the order of the enum in oenv.h */
    const char *const xvg_formats[] = { "xmgrace", "xmgr", "none" };

    // Handle the flags argument, which is a bit field
    // The FF macro returns whether or not the bit is set
#define FF(arg) ((Flags & arg) == arg)

    try
    {
        double                          tbegin        = 0.0, tend = 0.0, tdelta = 0.0;
        bool                            bBeginTimeSet = false, bEndTimeSet = false, bDtSet = false;
        bool                            bView         = false;
        int                             xvgFormat     = 0;
        gmx::OptionsAdapter             adapter(*argc, argv);
        gmx::Options                    options(NULL, NULL);
        gmx::OptionsBehaviorCollection  behaviors(&options);
        gmx::FileNameOptionManager      fileOptManager;

        fileOptManager.disableInputOptionChecking(
                FF(PCA_NOT_READ_NODE) || FF(PCA_DISABLE_INPUT_FILE_CHECKING));
        options.addManager(&fileOptManager);

        if (FF(PCA_CAN_SET_DEFFNM))
        {
            fileOptManager.addDefaultFileNameOption(&options, "deffnm");
        }
        if (FF(PCA_CAN_BEGIN))
        {
            options.addOption(
                    gmx::DoubleOption("b")
                        .store(&tbegin).storeIsSet(&bBeginTimeSet).timeValue()
                        .description("First frame (%t) to read from trajectory"));
        }
        if (FF(PCA_CAN_END))
        {
            options.addOption(
                    gmx::DoubleOption("e")
                        .store(&tend).storeIsSet(&bEndTimeSet).timeValue()
                        .description("Last frame (%t) to read from trajectory"));
        }
        if (FF(PCA_CAN_DT))
        {
            options.addOption(
                    gmx::DoubleOption("dt")
                        .store(&tdelta).storeIsSet(&bDtSet).timeValue()
                        .description("Only use frame when t MOD dt = first time (%t)"));
        }
        gmx::TimeUnit  timeUnit = gmx::TimeUnit_Default;
        if (FF(PCA_TIME_UNIT))
        {
            std::shared_ptr<gmx::TimeUnitBehavior> timeUnitBehavior(
                    new gmx::TimeUnitBehavior());
            timeUnitBehavior->setTimeUnitStore(&timeUnit);
            timeUnitBehavior->setTimeUnitFromEnvironment();
            timeUnitBehavior->addTimeUnitOption(&options, "tu");
            behaviors.addBehavior(timeUnitBehavior);
        }
        if (FF(PCA_CAN_VIEW))
        {
            options.addOption(
                    gmx::BooleanOption("w").store(&bView)
                        .description("View output [REF].xvg[ref], [REF].xpm[ref], "
                                     "[REF].eps[ref] and [REF].pdb[ref] files"));
        }

        bool bXvgr = false;
        for (int i = 0; i < nfile; i++)
        {
            bXvgr = bXvgr || (fnm[i].ftp == efXVG);
        }
        xvgFormat = gmx::getDefaultXvgFormat(xvg_formats);
        if (bXvgr)
        {
            options.addOption(
                    gmx::EnumIntOption("xvg").enumValue(xvg_formats)
                        .store(&xvgFormat)
                        .description("xvg plot formatting"));
        }

        /* Now append the program specific arguments */
        for (int i = 0; i < nfile; i++)
        {
            adapter.filenmToOptions(&options, &fnm[i]);
        }
        for (int i = 0; i < npargs; i++)
        {
            adapter.pargsToOptions(&options, &pa[i]);
        }

        const gmx::CommandLineHelpContext *context =
            gmx::GlobalCommandLineHelpContext::get();
        if (context != NULL)
        {
            GMX_RELEASE_ASSERT(gmx_node_rank() == 0,
                               "Help output should be handled higher up and "
                               "only get called only on the master rank");
            gmx::CommandLineHelpWriter(options)
                .setHelpText(gmx::constArrayRefFromArray<const char *>(desc, ndesc))
                .setKnownIssues(gmx::constArrayRefFromArray(bugs, nbugs))
                .writeHelp(*context);
            return FALSE;
        }

        /* Now parse all the command-line options */
        gmx::CommandLineParser(&options).skipUnknown(FF(PCA_NOEXIT_ON_ARGS))
            .parse(argc, argv);
        behaviors.optionsFinishing();
        options.finish();

        /* set program name, command line, and default values for output options */
        output_env_init(oenv, gmx::getProgramContext(),
                        (time_unit_t)(timeUnit + 1), bView,
                        (xvg_format_t)(xvgFormat + 1), 0);

        /* Extract Time info from arguments */
        if (bBeginTimeSet)
        {
            setTimeValue(TBEGIN, tbegin);
        }
        if (bEndTimeSet)
        {
            setTimeValue(TEND, tend);
        }
        if (bDtSet)
        {
            setTimeValue(TDELTA, tdelta);
        }

        adapter.copyValues(!FF(PCA_NOT_READ_NODE));

        return TRUE;
    }
    GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR;
#undef FF
}
gmx_bool parse_common_args(int *argc, char *argv[], unsigned long Flags,
                           int nfile, t_filenm fnm[], int npargs, t_pargs *pa,
                           int ndesc, const char **desc,
                           int nbugs, const char **bugs,
                           output_env_t *oenv)
{
    /* This array should match the order of the enum in oenv.h */
    const char *xvg_format[] = { NULL, "xmgrace", "xmgr", "none", NULL };
    /* This array should match the order of the enum in oenv.h */
    const char *time_units[] = {
        NULL, "fs", "ps", "ns", "us", "ms", "s",
        NULL
    };
    int         nicelevel = 0, debug_level = 0;
    char       *deffnm    = NULL;
    real        tbegin    = 0, tend = 0, tdelta = 0;
    gmx_bool    bView     = FALSE;

    t_pargs    *all_pa = NULL;

    t_pargs     nice_pa   = {
        "-nice", FALSE, etINT,   {&nicelevel},
        "Set the nicelevel"
    };
    t_pargs     deffnm_pa = {
        "-deffnm", FALSE, etSTR, {&deffnm},
        "Set the default filename for all file options"
    };
    t_pargs     begin_pa  = {
        "-b",    FALSE, etTIME,  {&tbegin},
        "First frame (%t) to read from trajectory"
    };
    t_pargs     end_pa    = {
        "-e",    FALSE, etTIME,  {&tend},
        "Last frame (%t) to read from trajectory"
    };
    t_pargs     dt_pa     = {
        "-dt",   FALSE, etTIME,  {&tdelta},
        "Only use frame when t MOD dt = first time (%t)"
    };
    t_pargs     view_pa   = {
        "-w",    FALSE, etBOOL,  {&bView},
        "View output [TT].xvg[tt], [TT].xpm[tt], [TT].eps[tt] and [TT].pdb[tt] files"
    };
    t_pargs     xvg_pa    = {
        "-xvg",  FALSE, etENUM,  {xvg_format},
        "xvg plot formatting"
    };
    t_pargs     time_pa   = {
        "-tu",   FALSE, etENUM,  {time_units},
        "Time unit"
    };
    /* Maximum number of extra arguments */
#define EXTRA_PA 16

    t_pargs  pca_pa[] = {
        { "-debug", FALSE, etINT, {&debug_level},
          "HIDDENWrite file with debug information, 1: short, 2: also x and f" },
    };
#define NPCA_PA asize(pca_pa)
    gmx_bool bXvgr;
    int      i, j, k, npall, max_pa;

    // Handle the flags argument, which is a bit field
    // The FF macro returns whether or not the bit is set
#define FF(arg) ((Flags & arg) == arg)

    /* Check for double arguments */
    for (i = 1; (i < *argc); i++)
    {
        if (argv[i] && (strlen(argv[i]) > 1) && (!std::isdigit(argv[i][1])))
        {
            for (j = i+1; (j < *argc); j++)
            {
                if ( (argv[i][0] == '-') && (argv[j][0] == '-') &&
                     (strcmp(argv[i], argv[j]) == 0) )
                {
                    if (FF(PCA_NOEXIT_ON_ARGS))
                    {
                        fprintf(stderr, "Double command line argument %s\n",
                                argv[i]);
                    }
                    else
                    {
                        gmx_fatal(FARGS, "Double command line argument %s\n",
                                  argv[i]);
                    }
                }
            }
        }
    }
    debug_gmx();

    /* Check ALL the flags ... */
    max_pa = NPCA_PA + EXTRA_PA + npargs+1;
    snew(all_pa, max_pa);

    for (i = npall = 0; (i < static_cast<int>(NPCA_PA)); i++)
    {
        npall = add_parg(npall, all_pa, &(pca_pa[i]));
    }

    if (FF(PCA_BE_NICE))
    {
        nicelevel = 19;
    }
    npall = add_parg(npall, all_pa, &nice_pa);

    if (FF(PCA_CAN_SET_DEFFNM))
    {
        npall = add_parg(npall, all_pa, &deffnm_pa);
    }
    if (FF(PCA_CAN_BEGIN))
    {
        npall = add_parg(npall, all_pa, &begin_pa);
    }
    if (FF(PCA_CAN_END))
    {
        npall = add_parg(npall, all_pa, &end_pa);
    }
    if (FF(PCA_CAN_DT))
    {
        npall = add_parg(npall, all_pa, &dt_pa);
    }
    if (FF(PCA_TIME_UNIT))
    {
        npall = add_parg(npall, all_pa, &time_pa);
    }
    if (FF(PCA_CAN_VIEW))
    {
        npall = add_parg(npall, all_pa, &view_pa);
    }

    bXvgr = FALSE;
    for (i = 0; (i < nfile); i++)
    {
        bXvgr = bXvgr ||  (fnm[i].ftp == efXVG);
    }
    if (bXvgr)
    {
        npall = add_parg(npall, all_pa, &xvg_pa);
    }

    /* Now append the program specific arguments */
    for (i = 0; (i < npargs); i++)
    {
        npall = add_parg(npall, all_pa, &(pa[i]));
    }

    /* set etENUM options to default */
    for (i = 0; (i < npall); i++)
    {
        if (all_pa[i].type == etENUM)
        {
            all_pa[i].u.c[0] = all_pa[i].u.c[1];
        }
    }
    set_default_time_unit(time_units, FF(PCA_TIME_UNIT));
    set_default_xvg_format(xvg_format);

    /* Now parse all the command-line options */
    get_pargs(argc, argv, npall, all_pa);

    /* set program name, command line, and default values for output options */
    output_env_init(oenv, gmx::getProgramContext(), (time_unit_t)nenum(time_units), bView,
                    (xvg_format_t)nenum(xvg_format), 0, debug_level);

    /* Parse the file args */
    parse_file_args(argc, argv, nfile, fnm, deffnm, !FF(PCA_NOT_READ_NODE));

    /* Open the debug file */
    if (debug_level > 0)
    {
        char buf[256];

        if (gmx_mpi_initialized())
        {
            sprintf(buf, "%s%d.debug", output_env_get_short_program_name(*oenv),
                    gmx_node_rank());
        }
        else
        {
            sprintf(buf, "%s.debug", output_env_get_short_program_name(*oenv));
        }

        init_debug(debug_level, buf);
        fprintf(stderr, "Opening debug file %s (src code file %s, line %d)\n",
                buf, __FILE__, __LINE__);
    }

    /* Now copy the results back... */
    for (i = 0, k = npall-npargs; (i < npargs); i++, k++)
    {
        memcpy(&(pa[i]), &(all_pa[k]), (size_t)sizeof(pa[i]));
    }

    bool bExit = false;
    try
    {
        const gmx::CommandLineHelpContext *context =
            gmx::GlobalCommandLineHelpContext::get();
        bExit = (context != NULL);
        if (context != NULL && !(FF(PCA_QUIET)))
        {
            gmx::Options options(NULL, NULL);
            options.setDescription(gmx::constArrayRefFromArray(desc, ndesc));
            for (i = 0; i < nfile; i++)
            {
                gmx::filenmToOptions(&options, &fnm[i]);
            }
            for (i = 0; i < npall; i++)
            {
                gmx::pargsToOptions(&options, &all_pa[i]);
            }
            gmx::CommandLineHelpWriter(options)
                .setShowDescriptions(true)
                .setTimeUnitString(output_env_get_time_unit(*oenv))
                .setKnownIssues(gmx::constArrayRefFromArray(bugs, nbugs))
                .writeHelp(*context);
        }
    }
    GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR;

    /* Set the nice level */
#if defined(HAVE_UNISTD_H) && !defined(__MINGW32__)
#ifndef GMX_NO_NICE
    /* The some system, e.g. the catamount kernel on cray xt3 do not have nice(2). */
    if (nicelevel != 0 && !bExit)
    {
        static gmx_bool            nice_set   = FALSE; /* only set it once */
        static tMPI_Thread_mutex_t init_mutex = TMPI_THREAD_MUTEX_INITIALIZER;
        tMPI_Thread_mutex_lock(&init_mutex);
        if (!nice_set)
        {
            if (nice(nicelevel) == -1)
            {
                /* Do nothing, but use the return value to avoid warnings. */
            }
            nice_set = TRUE;
        }
        tMPI_Thread_mutex_unlock(&init_mutex);
    }
#endif
#endif

    /* convert time options, must be done after printing! */

    for (i = 0; i < npall; i++)
    {
        if (all_pa[i].type == etTIME && all_pa[i].bSet)
        {
            *all_pa[i].u.r *= output_env_get_time_invfactor(*oenv);
        }
    }

    /* Extract Time info from arguments */
    if (FF(PCA_CAN_BEGIN) && opt2parg_bSet("-b", npall, all_pa))
    {
        setTimeValue(TBEGIN, opt2parg_real("-b", npall, all_pa));
    }

    if (FF(PCA_CAN_END) && opt2parg_bSet("-e", npall, all_pa))
    {
        setTimeValue(TEND, opt2parg_real("-e", npall, all_pa));
    }

    if (FF(PCA_CAN_DT) && opt2parg_bSet("-dt", npall, all_pa))
    {
        setTimeValue(TDELTA, opt2parg_real("-dt", npall, all_pa));
    }

    /* clear memory */
    sfree(all_pa);

    if (!FF(PCA_NOEXIT_ON_ARGS))
    {
        if (*argc > 1)
        {
            gmx_cmd(argv[1]);
        }
    }
    return !bExit;
#undef FF
}
void *pthreadWatchResource(void *arg)
{
	struct timeval timeSched;
	struct timeval tStart;
			
	while(!g_iExit)
	{
		if(g_Resource1.iClientNumber)
		{
			//TODO: get current time
			//gettimeofday(&tStart, NULL);

			//TODO: search all clients registered
			struct __client *client = g_Resource1.next;
			while(client)
			{
				gettimeofday(&tStart, NULL);

				//TODO: find scheduled client
				if(isBiggerThan(tStart, client->tSched))
				{
					struct __message msg;
					struct timeval tEnd;

					//TODO: if cached resource is valid, then use it
					if(g_uiCacheMode && isCachedDataValid(tStart) )
					{
						//TODO: update cache timing information
						updateCache(tStart);
						
						//TODO: set server process time with zero
						setTimeValue(&(msg.server_recved), 0, 0);
						setTimeValue(&(msg.server_started), 0, 0);
						setTimeValue(&(msg.server_finished), 0, 0);
						
						//TODO: set message with time information		
						msg.resource = g_Resource1.iCachedResource;
						msg.uiMaxAge = g_Resource1.uiMaxAge - g_Resource1.uiCachedAge;
						//printf("%s:uiMaxAge=%d(%d-%d)\n", __func__, msg.uiMaxAge, g_Resource1.uiMaxAge, g_Resource1.uiCachedAge);	
						
						//TODO: get current time
						gettimeofday(&tEnd, NULL);
					}
					else
					{
						//TODO: init cache
						initCache();
						
						//TODO: get a fresh resource from a server
						getResourceFromServer(&msg);
						
						//TODO: get current time
						gettimeofday(&tEnd, NULL);
					
						//TODO: set cached with information
						setCache(msg, tEnd);
					}
					
					//TODO: set client process time
					setTimeValue(&(msg.client_recved), 0, 0);
					setTimeValue(&(msg.client_started), 0, 0);
					
					//TODO: set proxy process time
					setTimeValue(&(msg.proxy_recved), tStart.tv_sec, tStart.tv_usec);
					setTimeValue(&(msg.proxy_started), tStart.tv_sec, tStart.tv_usec);
					setTimeValue(&(msg.proxy_finished), tEnd.tv_sec, tEnd.tv_usec);

					//TODO: dump message
					dumpMessage(msg);
					
					//TODO: send information as response from proxy to client
					int temp = send(client->iFd, &msg, sizeof(struct __message), 0);
					
					//TODO: set a new scheduled time of client
					struct timeval tB;
					tB.tv_sec = client->uiReqInterval/1000;
					tB.tv_usec = (client->uiReqInterval%1000)*1000;
					addTimeValue(&(client->tSched), client->tSched, tB);
					
//printf("tStart=%ld.%06ld, tSched=%ld.%06ld\n", 
//	tStart.tv_sec, tStart.tv_usec,
//	client->tSched.tv_sec, client->tSched.tv_usec);
				}
				client = client->next;
//printf("%s:client=0x%x\n", __func__, (unsigned int)client);
			}
			
			//TODO: inser client node as time sequence
			//updateClient();
			
			//TODO: 
			if(g_uiCacheAlgorithm == 1)
			{
				if(isBiggerThan(tStart, g_Resource1.tBaseTime))
				{
					//TODO: update check point
					updateBaseTime();
				}
			}
			else if(g_uiCacheAlgorithm == 2)
			{
				struct timeval tCPaddMA; 
				struct timeval tMaxAge; 
				setTimeValue(&tMaxAge, g_Resource1.uiMaxAge/1000, (g_Resource1.uiMaxAge%1000)*1000);
				addTimeValue(&tCPaddMA, g_Resource1.tBaseTime, tMaxAge);				
				if(isBiggerThan(tStart, tCPaddMA))
				{
					setSchedule(tStart);
				}
			}			
			
			usleep(5*1000);
		}	//if(g_Resource1.iClientNumber)
		
		usleep(50*1000);
	}
		
	return NULL;
}
Beispiel #23
0
gmx_bool parse_common_args(int *argc, char *argv[], unsigned long Flags,
                           int nfile, t_filenm fnm[], int npargs, t_pargs *pa,
                           int ndesc, const char **desc,
                           int nbugs, const char **bugs,
                           output_env_t *oenv)
{
    /* This array should match the order of the enum in oenv.h */
    const char *const xvg_formats[] = { "xmgrace", "xmgr", "none" };

    // Handle the flags argument, which is a bit field
    // The FF macro returns whether or not the bit is set
#define FF(arg) ((Flags & arg) == arg)

    try
    {
        int                        nicelevel = 0, debug_level = 0;
        double                     tbegin    = 0.0, tend = 0.0, tdelta = 0.0;
        bool                       bView     = false;
        int                        xvgFormat = 0;
        gmx::TimeUnitManager       timeUnitManager;
        gmx::OptionsAdapter        adapter(*argc, argv);
        gmx::Options               options(NULL, NULL);
        gmx::FileNameOptionManager fileOptManager;

        options.addManager(&fileOptManager);
        options.setDescription(gmx::ConstArrayRef<const char *>(desc, ndesc));
        options.addOption(
                gmx::IntegerOption("debug").store(&debug_level).hidden()
                    .description("Write file with debug information, "
                                 "1: short, 2: also x and f"));

        options.addOption(
                gmx::IntegerOption("nice").store(&nicelevel)
                    .defaultValue(FF(PCA_BE_NICE) ? 19 : 0)
                    .description("Set the nicelevel"));

        if (FF(PCA_CAN_SET_DEFFNM))
        {
            fileOptManager.addDefaultFileNameOption(&options, "deffnm");
        }
        if (FF(PCA_CAN_BEGIN))
        {
            options.addOption(
                    gmx::DoubleOption("b").store(&tbegin).timeValue()
                        .description("First frame (%t) to read from trajectory"));
        }
        if (FF(PCA_CAN_END))
        {
            options.addOption(
                    gmx::DoubleOption("e").store(&tend).timeValue()
                        .description("Last frame (%t) to read from trajectory"));
        }
        if (FF(PCA_CAN_DT))
        {
            options.addOption(
                    gmx::DoubleOption("dt").store(&tdelta).timeValue()
                        .description("Only use frame when t MOD dt = first time (%t)"));
        }
        if (FF(PCA_TIME_UNIT))
        {
            timeUnitManager.setTimeUnitFromEnvironment();
            timeUnitManager.addTimeUnitOption(&options, "tu");
        }
        if (FF(PCA_CAN_VIEW))
        {
            options.addOption(
                    gmx::BooleanOption("w").store(&bView)
                        .description("View output [TT].xvg[tt], [TT].xpm[tt], "
                                     "[TT].eps[tt] and [TT].pdb[tt] files"));
        }

        bool bXvgr = false;
        for (int i = 0; i < nfile; i++)
        {
            bXvgr = bXvgr || (fnm[i].ftp == efXVG);
        }
        xvgFormat = gmx::getDefaultXvgFormat(xvg_formats);
        if (bXvgr)
        {
            options.addOption(
                    gmx::StringOption("xvg").enumValue(xvg_formats)
                        .storeEnumIndex(&xvgFormat)
                        .description("xvg plot formatting"));
        }

        /* Now append the program specific arguments */
        for (int i = 0; i < nfile; i++)
        {
            adapter.filenmToOptions(&options, &fnm[i]);
        }
        for (int i = 0; i < npargs; i++)
        {
            adapter.pargsToOptions(&options, &pa[i]);
        }

        const gmx::CommandLineHelpContext *context =
            gmx::GlobalCommandLineHelpContext::get();
        if (context != NULL)
        {
            if (!(FF(PCA_QUIET)))
            {
                gmx::CommandLineHelpWriter(options)
                    .setShowDescriptions(true)
                    .setTimeUnitString(timeUnitManager.timeUnitAsString())
                    .setKnownIssues(gmx::ConstArrayRef<const char *>(bugs, nbugs))
                    .writeHelp(*context);
            }
            return FALSE;
        }

        /* Now parse all the command-line options */
        gmx::CommandLineParser(&options).skipUnknown(FF(PCA_NOEXIT_ON_ARGS))
            .parse(argc, argv);
        options.finish();

        /* set program name, command line, and default values for output options */
        output_env_init(oenv, gmx::getProgramContext(),
                        (time_unit_t)(timeUnitManager.timeUnit() + 1), bView,
                        (xvg_format_t)(xvgFormat + 1), 0, debug_level);

        /* Open the debug file */
        if (debug_level > 0)
        {
            char buf[256];

            if (gmx_mpi_initialized())
            {
                sprintf(buf, "%s%d.debug", output_env_get_short_program_name(*oenv),
                        gmx_node_rank());
            }
            else
            {
                sprintf(buf, "%s.debug", output_env_get_short_program_name(*oenv));
            }

            init_debug(debug_level, buf);
            fprintf(stderr, "Opening debug file %s (src code file %s, line %d)\n",
                    buf, __FILE__, __LINE__);
        }

        /* Set the nice level */
#ifdef HAVE_UNISTD_H
#ifndef GMX_NO_NICE
        /* The some system, e.g. the catamount kernel on cray xt3 do not have nice(2). */
        if (nicelevel != 0)
        {
            static gmx_bool            nice_set   = FALSE; /* only set it once */
            static tMPI_Thread_mutex_t init_mutex = TMPI_THREAD_MUTEX_INITIALIZER;
            tMPI_Thread_mutex_lock(&init_mutex);
            if (!nice_set)
            {
                if (nice(nicelevel) == -1)
                {
                    /* Do nothing, but use the return value to avoid warnings. */
                }
                nice_set = TRUE;
            }
            tMPI_Thread_mutex_unlock(&init_mutex);
        }
#endif
#endif

        timeUnitManager.scaleTimeOptions(&options);

        /* Extract Time info from arguments */
        // TODO: Use OptionInfo objects instead of string constants
        if (FF(PCA_CAN_BEGIN) && options.isSet("b"))
        {
            setTimeValue(TBEGIN, tbegin);
        }
        if (FF(PCA_CAN_END) && options.isSet("e"))
        {
            setTimeValue(TEND, tend);
        }
        if (FF(PCA_CAN_DT) && options.isSet("dt"))
        {
            setTimeValue(TDELTA, tdelta);
        }

        adapter.copyValues(!FF(PCA_NOT_READ_NODE));

        return TRUE;
    }
    GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR;
#undef FF
}
Beispiel #24
0
void parse_common_args(int *argc,char *argv[],unsigned long Flags,
		       int nfile,t_filenm fnm[],int npargs,t_pargs *pa,
		       int ndesc,const char **desc,
		       int nbugs,const char **bugs,
                       output_env_t *oenv)
{
    gmx_bool bHelp=FALSE,bHidden=FALSE,bQuiet=FALSE,bVersion=FALSE;
    const char *manstr[] = { NULL, "no", "html", "tex", "nroff", "ascii", 
                            "completion", "py", "xml", "wiki", NULL };
    /* This array should match the order of the enum in oenv.h */
    const char *xvg_format[] = { NULL, "xmgrace", "xmgr", "none", NULL };
    /* This array should match the order of the enum in oenv.h */
    const char *time_units[] = { NULL, "fs", "ps", "ns", "us", "ms", "s", 
                                NULL };
    int  nicelevel=0,mantp=0,npri=0,debug_level=0,verbose_level=0;
    char *deffnm=NULL;
    real tbegin=0,tend=0,tdelta=0;
    gmx_bool bView=FALSE;
    
    t_pargs *all_pa=NULL;
    
    t_pargs npri_pa   = { "-npri", FALSE, etINT,   {&npri},
    "HIDDEN Set non blocking priority (try 128)" };
    t_pargs nice_pa   = { "-nice", FALSE, etINT,   {&nicelevel}, 
    "Set the nicelevel" };
    t_pargs deffnm_pa = { "-deffnm", FALSE, etSTR, {&deffnm}, 
    "Set the default filename for all file options" };
    t_pargs begin_pa  = { "-b",    FALSE, etTIME,  {&tbegin},        
    "First frame (%t) to read from trajectory" };
    t_pargs end_pa    = { "-e",    FALSE, etTIME,  {&tend},        
    "Last frame (%t) to read from trajectory" };
    t_pargs dt_pa     = { "-dt",   FALSE, etTIME,  {&tdelta},        
    "Only use frame when t MOD dt = first time (%t)" };
    t_pargs view_pa   = { "-w",    FALSE, etBOOL,  {&bView},
    "View output xvg, xpm, eps and pdb files" };
    t_pargs xvg_pa    = { "-xvg",  FALSE, etENUM,  {xvg_format},
    "xvg plot formatting" };
    t_pargs time_pa   = { "-tu",   FALSE, etENUM,  {time_units},
    "Time unit" };
    /* Maximum number of extra arguments */
#define EXTRA_PA 16
    
    t_pargs pca_pa[] = {
      { "-h",    FALSE, etBOOL, {&bHelp},     
	"Print help info and quit" }, 
      { "-version",  FALSE, etBOOL, {&bVersion},     
	"Print version info and quit" }, 
      { "-verb",    FALSE,  etINT, {&verbose_level},
	"HIDDENLevel of verbosity for this program" },
      { "-hidden", FALSE, etBOOL, {&bHidden},
	  "HIDDENPrint hidden options" },
      { "-quiet",FALSE, etBOOL, {&bQuiet},
        "HIDDENDo not print help info" },
      { "-man",  FALSE, etENUM,  {manstr},
        "HIDDENWrite manual and quit" },
      { "-debug",FALSE, etINT, {&debug_level},
        "HIDDENWrite file with debug information, 1: short, 2: also x and f" },
    };
#define NPCA_PA asize(pca_pa)
    FILE *fp;  
    gmx_bool bPrint,bExit,bXvgr;
    int  i,j,k,npall,max_pa,cmdlength;
    char *ptr,*newdesc;
    const char *envstr;
    
#define FF(arg) ((Flags & arg)==arg)

    snew(*oenv, 1);
    
    cmdlength = strlen(argv[0]);
    /* Check for double arguments */
    for (i=1; (i<*argc); i++) 
    {
        cmdlength += strlen(argv[i]);
        if (argv[i] && (strlen(argv[i]) > 1) && (!isdigit(argv[i][1]))) 
        {
            for (j=i+1; (j<*argc); j++) 
            {
                if ( (argv[i][0]=='-') && (argv[j][0]=='-') && 
                    (strcmp(argv[i],argv[j])==0) ) 
                {
                    if (FF(PCA_NOEXIT_ON_ARGS))
                        fprintf(stderr,"Double command line argument %s\n",
                                argv[i]);
                    else
                        gmx_fatal(FARGS,"Double command line argument %s\n",
                                  argv[i]);
                }
            }
        }
    }
    debug_gmx();
    set_program_name(argv[0]);
    set_command_line(*argc, argv);
      
    /* Handle the flags argument, which is a bit field 
     * The FF macro returns whether or not the bit is set
     */
    bPrint        = !FF(PCA_SILENT);
    
    /* Check ALL the flags ... */
    max_pa = NPCA_PA + EXTRA_PA + npargs+1;
    snew(all_pa,max_pa);
    
    for(i=npall=0; (i<NPCA_PA); i++)
        npall = add_parg(npall,all_pa,&(pca_pa[i]));
    
#ifdef __sgi
    envstr = getenv("GMXNPRIALL");
    if (envstr)
        npri=strtol(envstr,NULL,10);
    if (FF(PCA_BE_NICE)) {
        envstr = getenv("GMXNPRI");
        if (envstr)
            npri=strtol(envstr,NULL,10);
    }
    npall = add_parg(npall,all_pa,&npri_pa);
#endif
    
    if (FF(PCA_BE_NICE)) 
        nicelevel=19;
    npall = add_parg(npall,all_pa,&nice_pa);
    
    if (FF(PCA_CAN_SET_DEFFNM)) 
        npall = add_parg(npall,all_pa,&deffnm_pa);   
    if (FF(PCA_CAN_BEGIN)) 
        npall = add_parg(npall,all_pa,&begin_pa);
    if (FF(PCA_CAN_END))
        npall = add_parg(npall,all_pa,&end_pa);
    if (FF(PCA_CAN_DT))
    {
        npall = add_parg(npall,all_pa,&dt_pa);
    }
    if (FF(PCA_TIME_UNIT)) {
        npall = add_parg(npall,all_pa,&time_pa);
    } 
    if (FF(PCA_CAN_VIEW)) 
        npall = add_parg(npall,all_pa,&view_pa);
    
    bXvgr = FALSE;
    for(i=0; (i<nfile); i++)
    {
        bXvgr = bXvgr ||  (fnm[i].ftp == efXVG);
    }
    if (bXvgr)
    {
        npall = add_parg(npall,all_pa,&xvg_pa);
    }
    
    /* Now append the program specific arguments */
    for(i=0; (i<npargs); i++)
        npall = add_parg(npall,all_pa,&(pa[i]));
    
    /* set etENUM options to default */
    for(i=0; (i<npall); i++)
    {
        if (all_pa[i].type==etENUM)
        {
            all_pa[i].u.c[0]=all_pa[i].u.c[1];
        }
    }
    set_default_time_unit(time_units,FF(PCA_TIME_UNIT));
    set_default_xvg_format(xvg_format);
  
    /* Now parse all the command-line options */
    get_pargs(argc,argv,npall,all_pa,FF(PCA_KEEP_ARGS));

    /* set program name, command line, and default values for output options */
    output_env_init(*oenv, *argc, argv, (time_unit_t)nenum(time_units), bView, 
                    (xvg_format_t)nenum(xvg_format), verbose_level, debug_level);
 
    if (bVersion) {
      printf("Program: %s\n",output_env_get_program_name(*oenv));
      gmx_print_version_info(stdout);
      exit(0);
    }
    
    if (FF(PCA_CAN_SET_DEFFNM) && (deffnm!=NULL))
        set_default_file_name(deffnm);
    
    /* Parse the file args */
    parse_file_args(argc,argv,nfile,fnm,FF(PCA_KEEP_ARGS),!FF(PCA_NOT_READ_NODE));
    
    /* Open the debug file */
    if (debug_level > 0) {
        char buf[256];
        
        if (gmx_mpi_initialized())
            sprintf(buf,"%s%d.debug",output_env_get_short_program_name(*oenv),
                    gmx_node_rank());
        else
            sprintf(buf,"%s.debug",output_env_get_short_program_name(*oenv));
        
        init_debug(debug_level,buf);
        fprintf(stderr,"Opening debug file %s (src code file %s, line %d)\n",
                buf,__FILE__,__LINE__);
    }
    
    /* Now copy the results back... */
    for(i=0,k=npall-npargs; (i<npargs); i++,k++) 
        memcpy(&(pa[i]),&(all_pa[k]),(size_t)sizeof(pa[i]));


    for(i=0; (i<npall); i++)
        all_pa[i].desc = mk_desc(&(all_pa[i]), output_env_get_time_unit(*oenv));
   
    bExit = bHelp || (strcmp(manstr[0],"no") != 0);
    
#if (defined __sgi && USE_SGI_FPE)
    doexceptions();
#endif
    
    /* Set the nice level */
#ifdef __sgi
    if (npri != 0 && !bExit) {
        schedctl(MPTS_RTPRI,0,npri);
    }
#endif 
    
#ifdef HAVE_UNISTD_H
    
#ifndef GMX_NO_NICE
    /* The some system, e.g. the catamount kernel on cray xt3 do not have nice(2). */
    if (nicelevel != 0 && !bExit)
    {
#ifdef GMX_THREADS
        static gmx_bool nice_set=FALSE; /* only set it once */
        tMPI_Thread_mutex_lock(&init_mutex);
        if (!nice_set)
        {
#endif
            i=nice(nicelevel); /* assign ret value to avoid warnings */
#ifdef GMX_THREADS
            nice_set=TRUE;
        }
        tMPI_Thread_mutex_unlock(&init_mutex);
#endif
    }
#endif
#endif
   
    /* Update oenv for parsed command line options settings. */
    (*oenv)->xvg_format = (xvg_format_t)nenum(xvg_format);
    (*oenv)->time_unit  = (time_unit_t)nenum(time_units);
    
    if (!(FF(PCA_QUIET) || bQuiet )) {
        if (bHelp)
            write_man(stderr,"help",output_env_get_program_name(*oenv),
                      ndesc,desc,nfile, fnm,npall,all_pa, nbugs,bugs,bHidden);
        else if (bPrint) {
            pr_fns(stderr,nfile,fnm);
            print_pargs(stderr,npall,all_pa,FALSE);
        }
    }
    
    if (strcmp(manstr[0],"no") != 0) {
        if(!strcmp(manstr[0],"completion")) {
            /* one file each for csh, bash and zsh if we do completions */
            fp=man_file(*oenv,"completion-zsh");
        
            write_man(fp,"completion-zsh",output_env_get_program_name(*oenv),
                      ndesc,desc,nfile, fnm, npall,all_pa,nbugs,bugs,bHidden);
            gmx_fio_fclose(fp);
            fp=man_file(*oenv,"completion-bash");
            write_man(fp,"completion-bash",output_env_get_program_name(*oenv),
                      ndesc,desc,nfile, fnm, npall,all_pa,nbugs,bugs,bHidden);
            gmx_fio_fclose(fp);
            fp=man_file(*oenv,"completion-csh");
            write_man(fp,"completion-csh",output_env_get_program_name(*oenv),
                      ndesc,desc,nfile, fnm, npall,all_pa,nbugs,bugs,bHidden);
            gmx_fio_fclose(fp);
        } else {
            fp=man_file(*oenv,manstr[0]);
            write_man(fp,manstr[0],output_env_get_program_name(*oenv),
                      ndesc,desc,nfile,fnm, npall, all_pa,nbugs,bugs,bHidden);
            gmx_fio_fclose(fp);
        }
    }
    
    /* convert time options, must be done after printing! */
    
    for(i=0; i<npall; i++) {
        if ((all_pa[i].type == etTIME) && (*all_pa[i].u.r >= 0)) {
            *all_pa[i].u.r *= output_env_get_time_invfactor(*oenv);
        }
    }
    
    /* Extract Time info from arguments */
    if (FF(PCA_CAN_BEGIN) && opt2parg_bSet("-b",npall,all_pa))
        setTimeValue(TBEGIN,opt2parg_real("-b",npall,all_pa));
    
    if (FF(PCA_CAN_END) && opt2parg_bSet("-e",npall,all_pa))
        setTimeValue(TEND,opt2parg_real("-e",npall,all_pa));
    
    if (FF(PCA_CAN_DT) && opt2parg_bSet("-dt",npall,all_pa))
        setTimeValue(TDELTA,opt2parg_real("-dt",npall,all_pa));
    
    /* clear memory */
    for (i = 0; i < npall; ++i)
        sfree((void *)all_pa[i].desc);
    sfree(all_pa);
    
    if (!FF(PCA_NOEXIT_ON_ARGS)) {
        if (*argc > 1) {
            gmx_cmd(argv[1]);
        }
    } 
    if (bExit) {
        if (gmx_parallel_env_initialized())
            /*gmx_abort(gmx_node_rank(),gmx_node_num(),0);*/
            gmx_finalize();
        exit(0);
    }
#undef FF
}
void parse_common_args(int *argc,char *argv[],unsigned long Flags,
		       int nfile,t_filenm fnm[],int npargs,t_pargs *pa,
		       int ndesc,char **desc,int nbugs,char **bugs)
{
  static bool bHelp=FALSE,bHidden=FALSE,bQuiet=FALSE;
  static char *manstr[]      = { NULL, "no", "html", "tex", "nroff", "ascii", "completion", "py", "xml", "wiki", NULL };
  static int  nicelevel=0,mantp=0,npri=0,debug_level=0;
  static char *deffnm=NULL;
  static real tbegin=0,tend=0,tdelta=0;
       
  t_pargs *all_pa=NULL;
  
  t_pargs npri_pa   = { "-npri", FALSE, etINT,   {&npri},
		       "HIDDEN Set non blocking priority (try 128)" };
  t_pargs nice_pa   = { "-nice", FALSE, etINT,   {&nicelevel}, 
		       "Set the nicelevel" };
  t_pargs deffnm_pa = { "-deffnm", FALSE, etSTR, {&deffnm}, 
		       "Set the default filename for all file options" };
  t_pargs begin_pa  = { "-b",    FALSE, etTIME,  {&tbegin},        
		       "First frame (%t) to read from trajectory" };
  t_pargs end_pa    = { "-e",    FALSE, etTIME,  {&tend},        
		       "Last frame (%t) to read from trajectory" };
  t_pargs dt_pa     = { "-dt",   FALSE, etTIME,  {&tdelta},        
		       "Only use frame when t MOD dt = first time (%t)" };
  t_pargs view_pa   = { "-w",    FALSE, etBOOL,  {&bView},
		       "View output xvg, xpm, eps and pdb files" };
  t_pargs code_pa   = { "-xvgr", FALSE, etBOOL,  {&bXvgrCodes},
		       "Add specific codes (legends etc.) in the output xvg files for the xmgrace program" };
  t_pargs time_pa   = { "-tu",   FALSE, etENUM,  {timestr},
			"Time unit" };
  /* Maximum number of extra arguments */
#define EXTRA_PA 16

  t_pargs pca_pa[] = {
    { "-h",    FALSE, etBOOL, {&bHelp},     
      "Print help info and quit" }, 
    { "-hidden", FALSE, etBOOL, {&bHidden},
      "HIDDENPrint hidden options" },
    { "-quiet",FALSE, etBOOL, {&bQuiet},
      "HIDDENDo not print help info" },
    { "-man",  FALSE, etENUM,  {manstr},
      "HIDDENWrite manual and quit" },
    { "-debug",FALSE, etINT, {&debug_level},
      "HIDDENWrite file with debug information, 1: short, 2: also x and f" },
  };
#define NPCA_PA asize(pca_pa)
  FILE *fp;  
  bool bPrint,bExit,bXvgr;
  int  i,j,k,npall,max_pa,cmdlength;
  char *ptr,*newdesc;
  char *envstr;

#define FF(arg) ((Flags & arg)==arg)

  cmdlength = strlen(argv[0]);
  /* Check for double arguments */
  for (i=1; (i<*argc); i++) {
    cmdlength += strlen(argv[i]);
    if (argv[i] && (strlen(argv[i]) > 1) && (!isdigit(argv[i][1]))) {
      for (j=i+1; (j<*argc); j++) {
	if ( (argv[i][0]=='-') && (argv[j][0]=='-') && 
	     (strcmp(argv[i],argv[j])==0) ) {
	  if (FF(PCA_NOEXIT_ON_ARGS))
	    fprintf(stderr,"Double command line argument %s\n",argv[i]);
	  else
	    gmx_fatal(FARGS,"Double command line argument %s\n",argv[i]);
	}
      }
    }
  }
  debug_gmx();

  /* Fill the cmdline string */
  snew(cmdline,cmdlength+*argc+1);
  for (i=0; (i<*argc); i++) {
    strcat(cmdline,argv[i]);
    strcat(cmdline," ");
  }
  
  /* Handle the flags argument, which is a bit field 
   * The FF macro returns whether or not the bit is set
   */
  bPrint        = !FF(PCA_SILENT);
  
  set_program_name(argv[0]);

  /* Check ALL the flags ... */
  max_pa = NPCA_PA + EXTRA_PA + npargs;
  snew(all_pa,max_pa);
  
  for(i=npall=0; (i<NPCA_PA); i++)
    npall = add_parg(npall,all_pa,&(pca_pa[i]));

#ifdef __sgi
  envstr = getenv("GMXNPRIALL");
  if (envstr)
    npri=atoi(envstr);
  if (FF(PCA_BE_NICE)) {
    envstr = getenv("GMXNPRI");
    if (envstr)
      npri=atoi(envstr);
  }
  npall = add_parg(npall,all_pa,&npri_pa);
#endif

  if (FF(PCA_BE_NICE)) 
    nicelevel=19;
  npall = add_parg(npall,all_pa,&nice_pa);

  if (FF(PCA_CAN_SET_DEFFNM)) 
    npall = add_parg(npall,all_pa,&deffnm_pa);   
  if (FF(PCA_CAN_BEGIN)) 
    npall = add_parg(npall,all_pa,&begin_pa);
  if (FF(PCA_CAN_END))
    npall = add_parg(npall,all_pa,&end_pa);
  if (FF(PCA_CAN_DT))
    npall = add_parg(npall,all_pa,&dt_pa);
  if (FF(PCA_TIME_UNIT)) {
    envstr = getenv("GMXTIMEUNIT");
    if ( envstr == NULL )
      envstr="ps";
    set_default_time_unit(envstr);
    npall = add_parg(npall,all_pa,&time_pa);
  } else
    set_default_time_unit("ps");
  if (FF(PCA_CAN_VIEW)) 
    npall = add_parg(npall,all_pa,&view_pa);
    
  bXvgr = FALSE;
  for(i=0; (i<nfile); i++)
    bXvgr = bXvgr ||  (fnm[i].ftp == efXVG);
  if (bXvgr)
    npall = add_parg(npall,all_pa,&code_pa);
  
  /* Now append the program specific arguments */
  for(i=0; (i<npargs); i++)
    npall = add_parg(npall,all_pa,&(pa[i]));

  /* set etENUM options to default */
  for(i=0; (i<npall); i++)
    if (all_pa[i].type==etENUM)
      all_pa[i].u.c[0]=all_pa[i].u.c[1];
  
  /* Now parse all the command-line options */
  get_pargs(argc,argv,npall,all_pa,FF(PCA_KEEP_ARGS));

  if (FF(PCA_CAN_SET_DEFFNM) && (deffnm!=NULL))
    set_default_file_name(deffnm);

  /* Parse the file args */
  parse_file_args(argc,argv,nfile,fnm,FF(PCA_KEEP_ARGS));

  /* Open the debug file */
  if (debug_level > 0) {
    char buf[256];

    if (gmx_mpi_initialized())
      sprintf(buf,"%s%d.log",ShortProgram(),gmx_node_rank());
    else
      sprintf(buf,"%s.log",ShortProgram());
      
    init_debug(debug_level,buf);
    fprintf(stderr,"Opening debug file %s (src code file %s, line %d)\n",
	    buf,__FILE__,__LINE__);
  }

  /* Now copy the results back... */
  for(i=0,k=npall-npargs; (i<npargs); i++,k++) 
    memcpy(&(pa[i]),&(all_pa[k]),(size_t)sizeof(pa[i]));
  
  for(i=0; (i<npall); i++)
    all_pa[i].desc = mk_desc(&(all_pa[i]), time_unit() );

  bExit = bHelp || (strcmp(manstr[0],"no") != 0);

#if (defined __sgi && USE_SGI_FPE)
  doexceptions();
#endif

  /* Set the nice level */
#ifdef __sgi
  if (npri != 0 && !bExit) {
    schedctl(MPTS_RTPRI,0,npri);
  }
#endif 

#ifdef HAVE_UNISTD_H

#ifndef GMX_NO_NICE
  /* The some system, e.g. the catamount kernel on cray xt3 do not have nice(2). */
  if (nicelevel != 0 && !bExit)
    i=nice(nicelevel); /* assign ret value to avoid warnings */
#endif

#endif
  
  if (!(FF(PCA_QUIET) || bQuiet )) {
    if (bHelp)
      write_man(stderr,"help",program,ndesc,desc,nfile,fnm,npall,all_pa,
		nbugs,bugs,bHidden);
    else if (bPrint) {
      pr_fns(stderr,nfile,fnm);
      print_pargs(stderr,npall,all_pa,FALSE);
    }
  }

  if (strcmp(manstr[0],"no") != 0) {
    if(!strcmp(manstr[0],"completion")) {
      /* one file each for csh, bash and zsh if we do completions */
      fp=man_file(program,"completion-zsh");
      write_man(fp,"completion-zsh",program,ndesc,desc,nfile,fnm,npall,all_pa,nbugs,bugs,bHidden);
      gmx_fio_fclose(fp);
      fp=man_file(program,"completion-bash");
      write_man(fp,"completion-bash",program,ndesc,desc,nfile,fnm,npall,all_pa,nbugs,bugs,bHidden);
      gmx_fio_fclose(fp);
      fp=man_file(program,"completion-csh");
      write_man(fp,"completion-csh",program,ndesc,desc,nfile,fnm,npall,all_pa,nbugs,bugs,bHidden);
      gmx_fio_fclose(fp);
    } else {
      fp=man_file(program,manstr[0]);
      write_man(fp,manstr[0],program,ndesc,desc,nfile,fnm,npall,all_pa,nbugs,bugs,bHidden);
      gmx_fio_fclose(fp);
    }
  }
  
  /* convert time options, must be done after printing! */
  init_time_factor();
  for(i=0; i<npall; i++) {
    if ((all_pa[i].type == etTIME) && (*all_pa[i].u.r >= 0)) {
      *all_pa[i].u.r *= timeinvfac;
    }
  }

  /* Extract Time info from arguments */
  if (FF(PCA_CAN_BEGIN) && opt2parg_bSet("-b",npall,all_pa))
    setTimeValue(TBEGIN,opt2parg_real("-b",npall,all_pa));

  if (FF(PCA_CAN_END) && opt2parg_bSet("-e",npall,all_pa))
    setTimeValue(TEND,opt2parg_real("-e",npall,all_pa));
  
  if (FF(PCA_CAN_DT) && opt2parg_bSet("-dt",npall,all_pa))
    setTimeValue(TDELTA,opt2parg_real("-dt",npall,all_pa));
  
  /* clear memory */
  sfree(all_pa);
  
  if (!FF(PCA_NOEXIT_ON_ARGS)) {
    if (*argc > 1) {
      gmx_cmd(argv[1]);
    }
  } 
  if (bExit) {
    if (gmx_parallel_env)
      gmx_abort(gmx_node_rank(),gmx_node_num(),0);
    else
      exit(0);
  }
#undef FF
}
int handleMessage(struct __message *arg)
{
	struct timeval tStart;
	struct __message msg = {0x0, };
	struct __message resp = {0x0, };

	memcpy(&msg, arg, sizeof(struct __message));

	//TODO: handle packet
	//gettimeofday(&tStart, NULL);

	//TODO: wait until other request responded
	pthread_mutex_lock(&m_lock);
	
	gettimeofday(&tStart, NULL);

	//TODO: use cached resource
	if(msg.cmd == RESOURCE_CMD_REGISTER)
	{
		if(g_uiCacheAlgorithm == 0)
		{
			addObserver0(msg.owner, msg.iFd, msg.resource, msg.req_dur);
		}
		else if(g_uiCacheAlgorithm == 1)
		{
			addObserver1(msg.owner, msg.iFd, msg.resource, msg.req_dur, tStart);
		}
		else if(g_uiCacheAlgorithm == 2)
		{
			addObserver1(msg.owner, msg.iFd, msg.resource, msg.req_dur, tStart);
		}
		dumpObserver();
	}
	else if (msg.cmd == RESOURCE_CMD_GET)
	{
		struct timeval tEnd;
		
		//TODO: get cached resource
		if(g_uiCacheMode && isCachedDataValid(tStart))
		{
			//TODO: update cache timing information
			updateCache(tStart);
			
			//TODO: set server process time with zero
			setTimeValue(&(msg.server_recved), 0, 0);
			setTimeValue(&(msg.server_started), 0, 0);
			setTimeValue(&(msg.server_finished), 0, 0);
			
			//TODO: set message with time information		
			gettimeofday(&tEnd, NULL);
			
			//TODO: set message with time information		
			msg.resource = g_Resource1.iCachedResource;
			msg.uiMaxAge = g_Resource1.uiMaxAge - g_Resource1.uiCachedAge;

			printf("CACHED! Owner=%d, R=%d, MaxAge=%d, CachedAge=%d(%ld.%06ld)\n", 
				msg.owner,
				g_Resource1.iCachedResource, 
				g_Resource1.uiMaxAge,
				g_Resource1.uiCachedAge,
				tEnd.tv_sec%1000,	\
				tEnd.tv_usec
				);
		}
		else
		{
			//TODO: init cache
			initCache();
	
			//TODO: get a fresh resource from a server
			getResourceFromServer(&msg);

			//TODO: get current time
			gettimeofday(&tEnd, NULL);
	
			//TODO: set cached with information
			setCache(msg, tEnd);
		
			printf("NOT cached! Owner=%d, R=%d, MaxAge=%d, CachedAge=%d(%ld.%06ld)\n",
				msg.owner,
				g_Resource1.iCachedResource, 
				g_Resource1.uiMaxAge,
				g_Resource1.uiCachedAge,
				tEnd.tv_sec%1000,	\
				tEnd.tv_usec
				);
		}
		
		//TODO: set client process time
		//setTimeValue(&(msg.client_recved), 0, 0);
		//setTimeValue(&(msg.client_started), 0, 0);
					
		//TODO: set proxy process time
		//setTimeValue(&(msg.proxy_recved), tStart.tv_sec, tStart.tv_usec);
		setTimeValue(&(msg.proxy_started), tStart.tv_sec, tStart.tv_usec);
		setTimeValue(&(msg.proxy_finished), tEnd.tv_sec, tEnd.tv_usec);

		//TODO: send information as response from proxy to client
		int temp = send(msg.iFd, &msg, sizeof(struct __message), 0);

		//TODO: set a new scheduled time of client
		/*
		struct timeval tB;
		tB.tv_sec = client->uiReqInterval/1000;
		tB.tv_usec = (client->uiReqInterval%1000)*1000;
			addTimeValue(&(client->tSched), client->tSched, tB);
		*/
#if 1
	dumpMessage(msg);
#endif
	}
	
	pthread_mutex_unlock(&m_lock);
//printf("---\n");		
	return 0;
}