예제 #1
0
파일: jleaker.c 프로젝트: jleaker/jleaker
JNIEXPORT jint JNICALL
Agent_OnAttach(JavaVM *vm, char *options, __UNUSED__ void *reserved)
{
	jint rc = initAgent(vm, options);
	if (0 != rc)
	{
		return rc;
	}
    startDumperThread();
    return 0;
}
예제 #2
0
// partially initialises the thief and 4 detectives from a data file
// You may need to modify this function, to initialise all 
// important agent information
void initialiseAgents(char *filename, Agent agents[], int maxCycles, Graph g){
  FILE *fp;
  fp = fopen (filename, "r"); // open data file
  assert (fp != NULL);
  int stamina;
  Vertex start;
  Vertex end;
  char name[5];
  int i;
  int strategy;

  fscanf(fp, "%d %d %d %[^\n]", &stamina,&start,&end,name);
  agents[THIEF] = initAgent(start,maxCycles,stamina,RANDOM,g,name);
  setGoal(agents[THIEF], end);
  for(i=1; i<=NUM_DETECTIVES; i++){      
    fscanf(fp, "%d %d %d %[^\n]", &stamina,&start,&strategy,name);
    agents[i] = initAgent(start,maxCycles,stamina,strategy,g,name);    
  }  
  fclose(fp);
}
예제 #3
0
void ServiceMain(int argc, char** argv) 
{ 
	HSP sp;

	memset(&sp,0,sizeof(sp));
	sp.configFile = "";
	sp.pidFile = "";
 
    ServiceStatus.dwServiceType        = SERVICE_WIN32; 
    ServiceStatus.dwCurrentState       = SERVICE_START_PENDING; 
    ServiceStatus.dwControlsAccepted   = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
    ServiceStatus.dwWin32ExitCode      = 0; 
    ServiceStatus.dwServiceSpecificExitCode = 0; 
    ServiceStatus.dwCheckPoint         = 0; 
    ServiceStatus.dwWaitHint           = 0; 
 
	if(!debug){
    	hStatus = RegisterServiceCtrlHandler(
			"hsflowd", 
			(LPHANDLER_FUNCTION)ControlHandler); 
    	if (hStatus == (SERVICE_STATUS_HANDLE)0) 
    	{ 
        	// Registering Control Handler failed
        	return; 
    	}  
	}
    // report the running status to SCM. 
    ServiceStatus.dwCurrentState = SERVICE_RUNNING; 
    SetServiceStatus (hStatus, &ServiceStatus);

	readInterfaces(&sp);
	HSPReadConfig(&sp);
	initAgent(&sp);
 
    // main loop
    while (ServiceStatus.dwCurrentState == SERVICE_RUNNING)
	{
		sfl_agent_tick(sp.sFlow->agent, time(NULL));
		Sleep(SLEEP_TIME);
	}
    return; 
}
예제 #4
0
/* #define SERVER_DEBUG 1   */
int
main(int argc, char *argv[])
{
    int status;
    rsComm_t rsComm;
    char *tmpStr;

    ProcessType = AGENT_PT;

#ifdef RUN_SERVER_AS_ROOT
#ifndef windows_platform
    if (initServiceUser() < 0) {
        exit (1);
    }
#endif
#endif

#ifdef windows_platform
	iRODSNtAgentInit(argc, argv);
#endif

#ifndef windows_platform
    signal(SIGINT, signalExit);
    signal(SIGHUP, signalExit);
    signal(SIGTERM, signalExit);
    /* set to SIG_DFL as recommended by andy.salnikov so that system()
     * call returns real values instead of 1 */
    signal(SIGCHLD, SIG_DFL);
    signal(SIGUSR1, signalExit);
    signal(SIGPIPE, rsPipSigalHandler);
#endif

#ifndef windows_platform
#ifdef SERVER_DEBUG
    if (isPath ("/tmp/rodsdebug"))
        sleep (20);
#endif
#endif

#ifdef SYS_TIMING
    rodsLogLevel(LOG_NOTICE);
    printSysTiming ("irodsAgent", "exec", 1);
#endif

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

    status = initRsCommWithStartupPack (&rsComm, NULL);

    if (status < 0) {
	sendVersion (rsComm.sock, status, 0, NULL, 0);
        cleanupAndExit (status);
    }

    /* Handle option to log sql commands */
    tmpStr = getenv (SP_LOG_SQL);
    if (tmpStr != NULL) {
#ifdef IRODS_SYSLOG
       int j = atoi(tmpStr);
       rodsLogSqlReq(j);
#else
       rodsLogSqlReq(1);
#endif
    }

    /* Set the logging level */
    tmpStr = getenv (SP_LOG_LEVEL);
    if (tmpStr != NULL) {
       int i;
       i = atoi(tmpStr);
       rodsLogLevel(i);
    } else {
       rodsLogLevel(LOG_NOTICE); /* default */
    }

#ifdef IRODS_SYSLOG
/* Open a connection to syslog */
#ifdef SYSLOG_FACILITY_CODE
    openlog("rodsAgent",LOG_ODELAY|LOG_PID,SYSLOG_FACILITY_CODE);
#else
    openlog("rodsAgent",LOG_ODELAY|LOG_PID,LOG_DAEMON);
#endif
#endif

    status = getRodsEnv (&rsComm.myEnv);

    if (status < 0) {
	sendVersion (rsComm.sock, SYS_AGENT_INIT_ERR, 0, NULL, 0);
        cleanupAndExit (status);
    }

#if RODS_CAT
    if (strstr(rsComm.myEnv.rodsDebug, "CAT") != NULL) {
       chlDebug(rsComm.myEnv.rodsDebug);
    }
#endif

#ifdef RULE_ENGINE_N
    status = initAgent (RULE_ENGINE_TRY_CACHE, &rsComm);
#else
    status = initAgent (&rsComm);
#endif
#ifdef SYS_TIMING
    printSysTiming ("irodsAgent", "initAgent", 0);
#endif

    if (status < 0) {
	sendVersion (rsComm.sock, SYS_AGENT_INIT_ERR, 0, NULL, 0);
        cleanupAndExit (status);
    }

    /* move configConnectControl behind initAgent for now. need zoneName if
     * the user does not specify one in the input */
    initConnectControl ();

    if (rsComm.clientUser.userName[0] != '\0') {
        status = chkAllowedUser (rsComm.clientUser.userName,
         rsComm.clientUser.rodsZone);

        if (status < 0) {
            sendVersion (rsComm.sock, status, 0, NULL, 0);
            cleanupAndExit (status);
	}
    }

    /* send the server version and atatus as part of the protocol. Put
     * rsComm.reconnPort as the status */

    status = sendVersion (rsComm.sock, status, rsComm.reconnPort,
      rsComm.reconnAddr, rsComm.cookie);

    if (status < 0) {
	sendVersion (rsComm.sock, SYS_AGENT_INIT_ERR, 0, NULL, 0);
        cleanupAndExit (status);
    }
#ifdef SYS_TIMING
    printSysTiming ("irodsAgent", "sendVersion", 0);
#endif

    logAgentProc (&rsComm);

    status = agentMain (&rsComm);

    cleanupAndExit (status);

    return (status);
}
예제 #5
0
int
xmsgServerMain() {
    int status = 0;
    rsComm_t rsComm;
    rsComm_t svrComm;	/* rsComm is connection to icat, svrComm is the
                         * server's listening socket */
    fd_set sockMask;
    int numSock;

    initThreadEnv();
    initXmsgHashQue();

    status = startXmsgThreads();

    if ( status < 0 ) {
        rodsLog( LOG_ERROR,
                 "xmsgServerMain: startXmsgThreads error. status = %d", status );
        return status;
    }

    status = initRsComm( &rsComm );

    if ( status < 0 ) {
        rodsLog( LOG_ERROR, "xmsgServerMain: initRsComm error. status = %d",
                 status );
        return status;
    }

    status = initRsComm( &svrComm );

    if ( status < 0 ) {
        rodsLog( LOG_ERROR, "xmsgServerMain: initRsComm error. status = %d",
                 status );
        return status;
    }

    status = initAgent( RULE_ENGINE_NO_CACHE, &rsComm );

    if ( status < 0 ) {
        rodsLog( LOG_ERROR, "xmsgServerMain: initAgent error. status = %d",
                 status );
        return status;
    }


    // =-=-=-=-=-=-=-
    // handle negotiations with the client regarding TLS if requested
    irods::error ret;

    // =-=-=-=-=-=-=-
    // manufacture a network object for comms
    irods::network_object_ptr net_obj;
    ret = irods::network_factory( &rsComm, net_obj );
    if ( !ret.ok() ) {
        irods::log( PASS( ret ) );
    }

    std::string neg_results;
    ret = irods::client_server_negotiation_for_server( net_obj, neg_results );
    if ( !ret.ok() || neg_results == irods::CS_NEG_FAILURE ) {
        irods::log( PASS( ret ) );
        // =-=-=-=-=-=-=-
        // send a 'we failed to negotiate' message here??
        // or use the error stack rule engine thingie
        irods::log( PASS( ret ) );
        sendVersion( net_obj, SYS_AGENT_INIT_ERR, 0, NULL, 0 );
        cleanupAndExit( ret.code() );

    }
    else {
        // =-=-=-=-=-=-=-
        // copy negotiation results to comm for action by network objects
        snprintf( rsComm.negotiation_results, sizeof( rsComm.negotiation_results ),
                  "%s", neg_results.c_str() );
        //rsComm.ssl_do_accept = 1;

    }

    int xmsg_port = 0;
    ret = irods::get_server_property<
          int > (
              irods::CFG_XMSG_PORT,
              xmsg_port );
    if ( !ret.ok() ) {
        irods::log( PASS( ret ) );
        return ret.code();

    }

    /* open  a socket and listen for connection */
    svrComm.sock = sockOpenForInConn(
                       &svrComm,
                       &xmsg_port,
                       NULL,
                       SOCK_STREAM );

    if ( svrComm.sock < 0 ) {
        rodsLog( LOG_NOTICE, "xmsgServerMain: sockOpenForInConn error. status = %d",
                 svrComm.sock );
        exit( 1 );
    }

    listen( svrComm.sock, MAX_LISTEN_QUE );

    FD_ZERO( &sockMask );

    rodsLog( LOG_NOTICE, "xmsgServer version %s is up", RODS_REL_VERSION );

    while ( 1 ) {       /* infinite loop */
        FD_SET( svrComm.sock, &sockMask );
        while ( ( numSock = select( svrComm.sock + 1, &sockMask,
                                    ( fd_set * ) NULL, ( fd_set * ) NULL, ( struct timeval * ) NULL ) ) < 0 ) {

            if ( errno == EINTR ) {
                rodsLog( LOG_NOTICE, "xmsgServerMain: select() interrupted" );
                FD_SET( svrComm.sock, &sockMask );
                continue;
            }
            else {
                rodsLog( LOG_NOTICE, "xmsgServerMain: select() error, errno = %d", errno );
                return -1;
            }
        }

        const int newSock = rsAcceptConn( &svrComm );

        if ( newSock < 0 ) {
            rodsLog( LOG_NOTICE,
                     "xmsgServerMain: acceptConn () error, errno = %d", errno );
            continue;
        }

        addReqToQue( newSock );

        if ( loopCnt > 0 ) {
            loopCnt--;
            if ( loopCnt == 0 ) {
                return 0;
            }
        }


    }
    return 0;
}
예제 #6
0
void ServiceMain(int argc, char** argv) 
{ 
	ServiceStatus.dwServiceType        = SERVICE_WIN32; 
	ServiceStatus.dwCurrentState       = SERVICE_START_PENDING; 
	ServiceStatus.dwControlsAccepted   = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
	ServiceStatus.dwWin32ExitCode      = 0; 
	ServiceStatus.dwServiceSpecificExitCode = 0; 
	ServiceStatus.dwCheckPoint         = 0;
	ServiceStatus.dwWaitHint           = 0;
	if (isService) {
		hStatus = RegisterServiceCtrlHandler(HSP_SERVICE_NAME, 
											 (LPHANDLER_FUNCTION)ControlHandler); 

		if (hStatus == 0) 
		{ 
			return; 
		}
	}
	// Test for only one instance is running
	HANDLE mutex = CreateMutex(NULL, TRUE, instanceMutexName);
	DWORD err = GetLastError();
	if (mutex != NULL && err == ERROR_ALREADY_EXISTS ||
		mutex == NULL && err == ERROR_ACCESS_DENIED) {
			// Mutex found, so another instance is running
		if (hStatus != 0) {
			ServiceStatus.dwCurrentState = SERVICE_STOPPED;
			ServiceStatus.dwWin32ExitCode = ERROR_SINGLE_INSTANCE_APP;
			SetServiceStatus(hStatus, &ServiceStatus);
		} else {
			myLog(LOG_ERR, "%s.ServiceMain: only one instance can run, existing instance found", HSP_SERVICE_NAME);
		}
		return;
	} else {
		ServiceStatus.dwCurrentState = SERVICE_RUNNING; 
		if (hStatus != 0) {
			// We are the first instance, report the running status to SCM. 
			SetServiceStatus (hStatus, &ServiceStatus);
		}
	}
	wchar_t programDataDir[MAX_PATH];
	if (!initialiseProgramDataDir(programDataDir, MAX_PATH)) {
		*programDataDir = NULL;
	}
	char mbcLogFilename[MAX_PATH];
	if (isService && *programDataDir != NULL) {
		//set the log file name to the default.
		size_t dirLen = 0;
		if (0 == wcstombs_s(&dirLen, mbcLogFilename, MAX_PATH, programDataDir, wcslen(programDataDir))) {
			PathAppend(mbcLogFilename, HSP_DEFAULT_LOGFILE);
			logFilename = mbcLogFilename;
		} else {
			logFilename = NULL;
		}
	}
	if (logFilename != NULL) {
        // Logging on
     	errno_t error = fopen_s(&logFile, logFilename, "wt");
        if (error != 0) {
			logFile = stderr;
			myLog(LOG_ERR, "%s.ServiceMain: could not open log file %s: error %d\n", HSP_SERVICE_NAME, logFilename, error);
        }
		logFilename = NULL;
    }
	myLog(debug, "-------------Starting %s %s--------------", HSP_SERVICE_NAME, HSP_VERSION);
	fflush(logFile);

	HSP sp = { 0 };
	// look up host-id fields at startup only (hostname
	// may change dynamically so will have to revisit this $$$)
	sp.host_hid.hostname.str = (char *)my_calloc(SFL_MAX_HOSTNAME_CHARS+1);
	sp.host_hid.os_release.str = (char *)my_calloc(SFL_MAX_OSRELEASE_CHARS+1);
	readHidCounters(&sp, &sp.host_hid);
	
	sp.nio_polling_secs = HSP_NIO_POLLING_SECS_32BIT;

	readInterfaces(&sp, TRUE);
	if (!readConfig(&sp)) {
		myLog(LOG_ERR, "%s.ServiceMain: invalid configuration", HSP_SERVICE_NAME);
		if (hStatus != 0) {
			ServiceStatus.dwCurrentState = SERVICE_STOPPED;
			ServiceStatus.dwWin32ExitCode = ERROR_INVALID_PARAMETER;
			SetServiceStatus(hStatus, &ServiceStatus);
		}
		return;
	}
	sp.hyperV = testForHyperv();
	if (sp.hyperV) {
		myLog(debug, "%s.ServiceMain Hyper-V services are running", HSP_SERVICE_NAME);
		if (programDataDir == NULL || !initialiseProgramDataFiles(&sp, programDataDir)) {
			myLog(LOG_ERR, "%s.ServiceMain: cannot initialise switch port and VM state files", HSP_SERVICE_NAME);
			if (hStatus != 0) {
				ServiceStatus.dwCurrentState = SERVICE_STOPPED;
				ServiceStatus.dwWin32ExitCode = ERROR_FILE_NOT_FOUND;
				SetServiceStatus(hStatus, &ServiceStatus);
			}
			return;
		}
		readGuidStore(sp.f_vmStore, sp.vmStoreFile, &sp.vmStore, &sp.maxDsIndex);
		readGuidStore(sp.f_portStore, sp.portStoreFile, &sp.portStore, &sp.maxIfIndex);
	}
	openFilter(&sp); //try to initialise the sFlow filter for sampling
	initAgent(&sp);

	// initialize the clock so we can detect second boundaries
	sp.clk = time(NULL);
 
    // main loop
	BOOL dataAvailable = true;
	uint32_t currReadNum = 0;
    while (ServiceStatus.dwCurrentState == SERVICE_RUNNING && dataAvailable)
	{
		// check for second boundaries and generate ticks for the sFlow library
		time_t now = time(NULL);
		if ((now < sp.clk) || (now - sp.clk) > HSP_MAX_TICKS) {
			// avoid a busy-loop of ticks if time jumps
			myLog(LOG_INFO, "%s.ServiceMain: time jump detected", HSP_SERVICE_NAME);
			sp.clk = now - 1;
		}
		while (sp.clk < now) { //only happens on second boundary
			//start critical
			if (sp.sFlow->sFlowSettings) {
				// update polling interval here if config has changed.
				tick(&sp);
			}
			//end critical
			sp.clk++;
		}
		DWORD result;
		//process a queued counter poller
		processQueuedPoller(&sp);
		//timeout is set so that we loop around checking for ticks and samples
		//several times/s.
		//calculate timeout 200 if the counter poller queue is empty, 0 otherwise
		DWORD timeout = sp.pollerQHead == NULL ? HSP_TIMEOUT : 0;
		if (HSP_FILTER_ACTIVE(sp.filter)) {
			result = WaitForSingleObject(sp.filter.overlaps[currReadNum].hEvent, 
										 timeout);
			if (result == WAIT_OBJECT_0) {
				dataAvailable = sp.filter.overlaps[currReadNum].Internal == ERROR_SUCCESS;
				if (dataAvailable && sp.filter.overlaps[currReadNum].InternalHigh > 0) {
					//process the sample info in sp.filter.buffers[currReadNum]
					readPackets(&sp, sp.filter.buffers[currReadNum]);
				}
				// Re-queue this read
				queueRead(sp.filter.dev,
					      sp.filter.buffers[currReadNum], 
					      sizeof(sp.filter.buffers[currReadNum]), 
						  &sp.filter.overlaps[currReadNum]);
				//set the next buffer to read
				currReadNum = (currReadNum+1)%numConcurrentReads;
			}
		} else {
			Sleep(timeout);
		}
	}
    return; 
}
예제 #7
0
void Test :: run(){
    
    
    //Test frand
//    assert( frand()==0.1f );
//    assert( frand()==0.7f );
//    assert( frand()==0.7f );
//    assert( frand()==0.1f );
//    cout << "gismoManager::randmom() is OK."<<endl;
    

    cout << "CLASS Sound is ok.(check the receive yourself.)" << endl;

    
    //TestEventHandler
    EventHandler eventHandler;
    EvTest evTest;
    eventHandler.eventAdd("/t01" , &evTest);
    int args[] = {0,1,2};
    assert ( eventHandler.bang("/t01", args) == 138 );
    assert ( eventHandler.bang("/t01") == 137 );
    cout << "GismoBundledClass::eventHandler is OK." << endl;
    //Test EventHandler with Gismo
    gismo.eventAdd("/t01" , &evTest);
    assert ( gismo.bang("/t01" , args) == 138 );
    //Sound Trigger
    int snd_id = 0;
    setSound(0);
    setSound(2);
    setSound(4);
    cout << "GismoManager::eventHandler with Gismo is OK." << endl;
    
    
    
    //Define an agent
    ag_t ag;
    
    //Test GismoManager.getAgents()
    ag_t *agents = gismo.getAgents();
    agents[0].posi.x = 0.13f;
    agents[0].posi.y = 0.2f;
    assert(agents[0].posi.x == 0.13f);
    assert(agents[0].posi.y == 0.2f);
    cout << "GismoManager:getAgent() is OK." << endl;
    
    //Test GismoLibrary distance()
    posi_t tmp1, tmp2;
    tmp1.x = 0.0f;
    tmp1.y = 0.0f;
    tmp2.x = 3.0f;
    tmp2.y = 4.0f;
    assert(distance(tmp1, tmp2) == 5.0f);
    tmp1.x = 0.5f;
    tmp1.y = 0.5f;
    tmp2.x = -0.5f;
    tmp2.y = -0.5f;
    assert(distance(tmp1, tmp2)==(float)sqrt(2.0f));
    tmp1.x = 3.0f;
    tmp1.y = 4.0f;
    tmp2.x = 0.0f;
    tmp2.y = 0.0f;
    assert(distance(tmp1, tmp2) == 5.0f);
    tmp1.x = 5.0f;
    tmp1.y = 12.0f;
    tmp2.x = 0.0f;
    tmp2.y = 0.0f;
    assert(distance(tmp1, tmp2) == 13.0f);
    cout << "GismoLibrary:distance() is OK." << endl;
    
    
    //Test Init AgentActive
    initAgentActive(&ag);
    assert(ag.size == AG_DEF_SIZE);
    assert(ag.active==true);
    cout << "GismoLibrary:initAgentActive() is OK." << endl;
    
    //TestAgentAdd
    initAgentActive(&ag);
    ag.view = 0.23f;
    ag.posi.x = 0.2f; ag.posi.y=0.2f;
    gismo.addAgent(ag);
    assert (gismo.add.buf[0].view == 0.23f);
    assert (gismo.add.count == 1);
    cout << "GismoManager:addAgent() is OK." << endl;
    
    //TestSync
    ag_t ag2;
    initAgentActive(&ag2);
    ag2.view = 0.34f;
    gismo.addAgent(ag2);
    gismo.addSync(); //Finally gismo requires sync to avoid direct agent addition when processing agents.
    assert(gismo.add.count==0 && gismo.agents.count==2);
    assert(agents[0].active && agents[1].active);
    assert(agents[0].view==0.23f && agents[1].view==0.34f);
    cout << "gismoLibrary:addSync() is OK." << endl;
    
    //Test gismo Library seekNearest();
    agents[0].posi.x = 0.0f;
    agents[0].posi.y = 0.0f;
    agents[1].posi.x = 0.5f;
    agents[1].posi.y = 0.5f;
    ag_t ag3;
    initAgentActive(&ag3);
    ag3.posi.x = 0.5f;
    ag3.posi.y = 0.49f;
    gismo.addAgent(ag3); //add the new agent to addBuffer
    ag_t ag4;
    ag4.posi.x = 0.7f;
    ag4.posi.y = 0.49f;
    gismo.addAgent(ag3); //add the new agent to addBuffer
    gismo.addSync(); //refrect the add buffer to actual buffer
    int nearest_agent = seekNearest(0, &gismo.agents); //seek the nearest agent of agent[0]
    cout << nearest_agent << endl;
    assert(nearest_agent==2);
    cout << "gismoManager:seekNearest() is OK."<<endl;
    
    
    //Test isViewRange
    /* REST FOR  VIEW/MOV  RATE
    ag_t ag5;
    ag5.view = 0.5f;
    assert( isViewRange(&ag5,0.3f)==true );
    assert( isViewRange(&ag5,0.51f)==false );
    cout << "gismoLibrary::isViewRange() is OK" << endl;
    
    //Test isLarge
    assert( isLarge(0.5 , 0.4)==true );
    assert( isLarge(0.5, 0.501)==false);
    cout << "gismoLibrary::isaLarge is OK" <<endl;

     
    //Test Move
    ag_t ag6;
    posi_t tmp;
    tmp.x=1.0; tmp.y=0.0;
    initAgent(&ag6);
    ag6.posi.x=0.5; ag6.posi.y=0.5;
    move(&ag6,&tmp);
    assert(ag6.posi.x >= 0.5f);
    assert(ag6.posi.y <= 0.5f);
    cout << "gismoLibrary::move() is OK." << endl;
    
    //Test Run
    ag_t tmpAg1, tmpAg2;
    tmpAg1.posi.x = 0.75f;
    tmpAg1.posi.y = 0.75f;
    tmpAg1.mov = 0.001f;
    tmpAg1.spd.x = 0.0f;
    tmpAg1.spd.y = 0.0f;
    tmpAg2.posi.x = 0.5f;
    tmpAg2.posi.y = 0.5f;
    running(&tmpAg1, &tmpAg2.posi);
    assert(tmpAg1.posi.x >= 0.75f);
    assert(tmpAg1.posi.y >= 0.75f);
    tmpAg1.posi.x = 0.25f;
    tmpAg1.posi.y = 0.75f;
    tmpAg1.spd.x = 0.0f;
    tmpAg1.spd.y = 0.0f;
    running(&tmpAg1, &tmpAg2.posi);
    assert(tmpAg1.posi.x <= 0.25f);
    assert(tmpAg1.posi.y >= 0.75f);
    tmpAg1.posi.x = 0.75f;
    tmpAg1.posi.y = 0.45f;
    tmpAg1.spd.x = 0.0f;
    tmpAg1.spd.y = 0.0f;
    running(&tmpAg1, &tmpAg2.posi);
    assert(tmpAg1.posi.x >= 0.75f);
    assert(tmpAg1.posi.y <= 0.45f);
    tmpAg1.posi.x = 0.25f;
    tmpAg1.posi.y = 0.25f;
    tmpAg1.spd.x = 0.0f;
    tmpAg1.spd.y = 0.0f;    
    running(&tmpAg1, &tmpAg2.posi);
    //0115 assert(tmpAg1.posi.x < 0.25f);
    //assert(tmpAg1.posi.y < 0.25f);
    cout << "gismoLibrary::running() is OK." << endl;
    
    //TestConditionCheck
    condition_e cond1 = CALM;
    condition_e cond2 = RUN;
    assert ( conditionCheck(cond1, cond2) == false );
    cond2 = CALM;
    assert ( conditionCheck(cond1, cond2) == true );
    
    //Test interactWith()
    ag_t ag8 , ag9;
    initAgent(&ag8);
    initAgent(&ag9);
    ag8.size = 1.0f;
    ag8.posi.x = 0.0f; ag8.posi.y = 0.0f;
    ag9.posi.x = 1.0f; ag9.posi.y = 1.0f;
    ag8.view = 1.5;
    interactWith(&ag8 , &ag9);
    */
    
    //TestReset
    agents[0].active=true;
    agents[1].active=true;
    agBuffReset(&gismo.agents);
    assert(agents[0].active==false);
    assert(agents[1].active==false);
    assert(gismo.agents.count == 0);
    
    
    //TestLogistic
    float fval=0.5;
    fval = logistic(fval);
    assert(fval==0.75f);
    fval = logistic(fval);
    cout << "GismoLibrary::logistic() is OK." << endl;        

    //Test
    //agBuffReset(&gismo.agents);
    int val = 1;
    gismo.bang("/gismo/reset" , &val);
    ag_t ag1;
    initAgent(&ag1);
    ag1.view = 256.0f;
    gismo.agents.buf[0] = ag1;
    ag1.view = 356.0f;
    gismo.agents.buf[1] = ag1;
    ag_t *pAg1 = gismo.getAgent(0);
    assert(pAg1->view == 256.0f);
    ag_t *pAg2 = gismo.getAgent(1);
    assert(pAg2->view == 356.0f);
    
    //TestSpeedLimit
    assert ( limitter(1.1f, 1.0f) == 1.0f );
    assert ( limitter(-1.1f, 1.0f) == -1.0f );
    assert ( limitter(0.49f, 0.5f) == 0.49f );
    assert ( limitter(-0.49f, 0.5f) == -0.49f );
    assert ( limitter(0.0051f, 0.005f) == 0.005f );
    assert ( limitter(-0.00501f, 0.005f) == -0.005f );

    cout << "speedLimitter is OK." << endl;
    
    
    //Test positionLoop()
    posi_t pos;
    pos.x = 1.1; pos.y = -0.01;
    positionLoop(&pos, 1.0f, 1.0f);
    assert (pos.x == 0.0f);
    assert (pos.y == 1.0f);
    pos.x = -0.1; pos.y = 1.4;
    positionLoop(&pos, 1.0f, 1.0f);
    assert (pos.x == 1.0f);
    assert (pos.y == 0.0f);
    pos.x = 0.0f; pos.y = 1.0f;
    positionLoop(&pos, 1.0f, 1.0f);
    assert (pos.x == 1.0f);
    assert (pos.y == 1.0f);
    //Check result check
    pos.x = 0.5f;
    pos.y = 0.5f;
    bool result = positionLoop(&pos , 1.0f, 1.0f);
    assert (result==false);
    pos.x = 1.0f;
    pos.y = 1.0f;
    result = positionLoop(&pos , 1.0f, 1.0f);
    assert (result==false);
    pos.x = 1.05f;
    pos.y = 1.05f;
    result = positionLoop(&pos , 1.0f, 1.0f);
    assert (result==true);
    pos.x = 1.05f;
    pos.y = 1.00f;
    result = positionLoop(&pos , 1.0f, 1.0f);
    assert (result==true);
    cout << "GismoLibrary::positionLoop() is OK" << endl;
    
    
    //Test attackCheck
    float fval2 = 0.0f;
    float size2 = 1.0f;
    attackCheck(fval2, &size2);
    bool size_test2 = true;
    if ( size2 != (1.0f-AG_DMG) ) size_test2 = false;
    assert(size_test2);
    assert(size2 == 1.0f-AG_DMG);
    size2 = 1.0f;
    fval2 = ATK_DIST+0.1;
    attackCheck(fval2, &size2);
    assert(size2 == 1.0f);
    cout << "GismoLibrary::attackCheck() is OK" << endl;

    size2 = 1.0f;
    fval2 = ATK_DIST;
    attackCheck(fval2, &size2);
    assert(size2 == 1.0f-AG_DMG);
    
    //Test deadCheck
    float dummy_size = 0.0001f;
    bool active = true;
    deadCheck( &dummy_size , &active );
    assert(active == false);
    assert(dummy_size == 0.0f);
    dummy_size = 1.0f;
    active = true;
    deadCheck( &dummy_size , &active );
    assert(active == true);
    cout << "GismoLibrary::deadCheck is OK" << endl;
    
    //Test Shape2Agent
    ag_shape_t shape;
    shape.nodes[0].x = 0.5f;
    shape.nodes[0].y = 0.5f;
    shape.nodes[1].x = 1.0f;
    shape.nodes[1].y = 1.0f;
    shape.node_count = 2;
    shape.edges[0].node_id_a = 0;
    shape.edges[0].node_id_b = 1;
    shape.edge_count = 1;
    ag_t tmpAg = shape2Agent(shape);
    assert(tmpAg.view == 0.005f);
    //assert(tmpAg.size == 0.011f);
    assert(tmpAg.mov == 0.35f);
    ag_shape_t shape2;
    shape2.node_count = 50000;
    ag_t tmpAg3 = shape2Agent(shape2);
    cout << tmpAg3.mov << endl;
    assert(tmpAg3.mov == MOV_MINIMUM);
    cout << "Shape2Agent.hpp::shape2Agent() is OK" << endl;
    
    //Test moveOnLine()
    posi_t posi = moveOnLine(0.5f, 0.0f, 0.0f, 1.0f, 1.0f);
    assert(posi.x == 0.5f && posi.y == 0.5f);
    posi = moveOnLine(1.0f, 0.0f, 0.0f, 1.0f, 1.0f);
    assert(posi.x == 1.0f && posi.y == 1.0f);
    posi = moveOnLine(0.5f, -1.0f, -1.0f, -2.0f, -2.0f);
    assert(posi.x == -1.5f && posi.y == -1.5f);
    posi = moveOnLine(0.0f, -1.0f, -1.0f, -2.0f, -2.0f);
    assert(posi.x == -1.0f && posi.y == -1.0f);
    posi = moveOnLine(0.5f, 0.0f, 0.0f, -1.0f, -2.0f);
    assert(posi.x == -0.5f && posi.y == -1.0f);

    //TestGetArraySize
    int iArray[137];
    posi_t posiArray[138];
    assert(getArraySize(iArray)==137);
    assert(getArraySize(posiArray)==138);
    cout << "TestGetArraySize.h::getArraySize() is ok." << endl;
    
    //Test lambda bang
    int myArg[2];
    myArg[0] = 12;
    myArg[1] = 13;
    gismo.bang("/lambdaTest", myArg);

    //TestSoundTrigger
    param_u params[4];
    params[0].ival = 0; //Genre
    params[1].ival = 1; //Song
    params[2].ival = 2; //Slice
    params[3].fval = 1.0f;//effect
    gismo.bang("/soundTrg" , &params);
    cout << "sound trigger is ok. If you could listen the RM sound" << endl;
    
    //Test shape2Sound
    ag_shape_t shapeForSound;
    shapeForSound.node_count = 12;
    shapeForSound.color = 0.50f;
    sound_t snd = shape2sound(shapeForSound,5);
    assert(snd.genre == 2);
    assert(snd.song == 5);
    shapeForSound.node_count = 6;
    shapeForSound.color = 1.0f;
    snd = shape2sound(shapeForSound,1137);
    assert(snd.genre == 0);
    assert(snd.song == 137);
    cout << "SoundTrigger::shape2Sound is OK" << endl;
    ag_t test;
    test.condition = CALM;
    ag2sound(&test, &snd);
    assert(snd.slice == 0);
    assert(snd.effect_val == EF_VAL_CALM);
    test.condition = RUN;
    ag2sound(&test, &snd);
    assert(snd.slice == 1);
    assert(snd.effect_val == EF_VAL_RUN);
    test.condition = CHASE;
    ag2sound(&test, &snd);
    assert(snd.slice == 2);
    assert(snd.effect_val == EF_VAL_CHASE);
    test.condition = DMG;
    ag2sound(&test, &snd);
    assert(snd.slice == 3);
    assert(snd.effect_val == EF_VAL_DMG);
    test.condition = DEATH;
    ag2sound(&test, &snd);
    assert(snd.slice == 4);
    assert(snd.effect_val == EF_VAL_DEATH);
    cout << "SoundTrigger::ag2Sound is OK" << endl;
    
    
    //Test makePositionToAdd in Shape2Agent
//    posi_t myPosi = makePositionToAdd();
//    assert(myPosi.x == )
//    
}
예제 #8
0
int
main(int argc, char **argv)
{
    int status;
    int c;
    rsComm_t rsComm;
    int runMode = IRODS_SERVER;
    int flagval = 0;
    char *logDir = NULL;
    char *tmpStr;
    int logFd;
    char *ruleExecId = NULL;
    int jobType = 0;

    ProcessType = RE_SERVER_PT;

#ifdef RUN_SERVER_AS_ROOT
#ifndef windows_platform
    if (initServiceUser() < 0) {
        exit (1);
    }
#endif
#endif

#ifndef _WIN32
    signal(SIGINT, signalExit);
    signal(SIGHUP, signalExit);
    signal(SIGTERM, signalExit);
    signal(SIGUSR1, signalExit);
    signal(SIGPIPE, rsPipSigalHandler);
    /* XXXXX switched to SIG_DFL for embedded python. child process 
     * went away. But probably have to call waitpid. 
     * signal(SIGCHLD, SIG_IGN); */
    signal(SIGCHLD, SIG_DFL);
#endif

    /* Handle option to log sql commands */
    tmpStr = getenv (SP_LOG_SQL);
    if (tmpStr != NULL) {
#ifdef IRODS_SYSLOG
       int j = atoi(tmpStr);
       rodsLogSqlReq(j);
#else
       rodsLogSqlReq(1);
#endif
    }

    /* Set the logging level */
    tmpStr = getenv (SP_LOG_LEVEL);
    if (tmpStr != NULL) {
       int i;
       i = atoi(tmpStr);
       rodsLogLevel(i);
    } else {
         rodsLogLevel(LOG_NOTICE); /* default */
    }

#ifdef IRODS_SYSLOG
/* Open a connection to syslog */
    openlog("rodsReServer",LOG_ODELAY|LOG_PID,LOG_DAEMON);
#endif

    while ((c=getopt(argc, argv,"sSvD:j:t:")) != EOF) {
        switch (c) {
	    case 's':
		runMode = SINGLE_PASS;
		break;
	    case 'S':
		runMode = STANDALONE_SERVER;
		break;
            case 'v':   /* verbose */
                flagval |= v_FLAG;
                break;
            case 'D':   /* user specified a log directory */
		logDir = strdup (optarg);
		break;
	    case 'j':
		runMode = SINGLE_PASS;
		ruleExecId = strdup (optarg);
		break;
            case 't':
                jobType = atoi (optarg);
                break;
            default:
                usage (argv[0]);
                exit (1);
        }
    }

    status = initRsComm (&rsComm);

    if (status < 0) {
        cleanupAndExit (status);
    }

    if ((logFd = logFileOpen (runMode, logDir, RULE_EXEC_LOGFILE)) < 0) {
        exit (1);
    }

    daemonize (runMode, logFd);

#ifdef RULE_ENGINE_N
    status = initAgent (RULE_ENGINE_INIT_CACHE, &rsComm);
#else
    status = initAgent (&rsComm);
#endif
    if (status < 0) {
        cleanupAndExit (status);
    }

    if (ruleExecId != NULL) {
	status = reServerSingleExec (&rsComm, ruleExecId, jobType);
	if (status >= 0) {
            exit (0);
        } else {
             exit (1);
        }
    } else {
        reServerMain (&rsComm);
    }
    cleanupAndExit (status);

    exit (0);
}
예제 #9
0
파일: rodsAgent.cpp 프로젝트: nesi/irods
/* #define SERVER_DEBUG 1   */
int
main( int, char ** ) {

    int status;
    rsComm_t rsComm;
    char *tmpStr;

    ProcessType = AGENT_PT;

    // capture server properties
    irods::server_properties& props = irods::server_properties::getInstance();
    irods::error result = props.capture_if_needed();
    if ( !result.ok() ) {
        irods::log( PASSMSG( "failed to read server configuration", result ) );
    }

#ifdef windows_platform
    iRODSNtAgentInit( argc, argv );
#endif

#ifndef windows_platform
    signal( SIGINT, signalExit );
    signal( SIGHUP, signalExit );
    signal( SIGTERM, signalExit );
    /* set to SIG_DFL as recommended by andy.salnikov so that system()
     * call returns real values instead of 1 */
    signal( SIGCHLD, SIG_DFL );
    signal( SIGUSR1, signalExit );
    signal( SIGPIPE, SIG_IGN );

    // register irods signal handlers
    register_handlers();
#endif

#ifndef windows_platform
#ifdef SERVER_DEBUG
    if ( isPath( "/tmp/rodsdebug" ) ) {
        sleep( 20 );
    }
#endif
#endif

    memset( &rsComm, 0, sizeof( rsComm ) );
    rsComm.thread_ctx = ( thread_context* )malloc( sizeof( thread_context ) );

    status = initRsCommWithStartupPack( &rsComm, NULL );

    // =-=-=-=-=-=-=-
    // manufacture a network object for comms
    irods::network_object_ptr net_obj;
    irods::error ret = irods::network_factory( &rsComm, net_obj );
    if ( !ret.ok() ) {
        irods::log( PASS( ret ) );
    }

    if ( status < 0 ) {
        sendVersion( net_obj, status, 0, NULL, 0 );
        cleanupAndExit( status );
    }

    /* Handle option to log sql commands */
    tmpStr = getenv( SP_LOG_SQL );
    if ( tmpStr != NULL ) {
#ifdef SYSLOG
        int j = atoi( tmpStr );
        rodsLogSqlReq( j );
#else
        rodsLogSqlReq( 1 );
#endif
    }

    /* Set the logging level */
    tmpStr = getenv( SP_LOG_LEVEL );
    if ( tmpStr != NULL ) {
        int i;
        i = atoi( tmpStr );
        rodsLogLevel( i );
    }
    else {
        rodsLogLevel( LOG_NOTICE ); /* default */
    }

#ifdef SYSLOG
    /* Open a connection to syslog */
    openlog( "rodsAgent", LOG_ODELAY | LOG_PID, LOG_DAEMON );
#endif
    status = getRodsEnv( &rsComm.myEnv );

    if ( status < 0 ) {
        rodsLog( LOG_ERROR, "agentMain :: getRodsEnv failed" );
        sendVersion( net_obj, SYS_AGENT_INIT_ERR, 0, NULL, 0 );
        cleanupAndExit( status );
    }

    ret = setRECacheSaltFromEnv();
    if ( !ret.ok() ) {
        rodsLog( LOG_ERROR, "rodsAgent::main: Failed to set RE cache mutex name\n%s", ret.result().c_str() );
        exit( 1 );
    }

    // =-=-=-=-=-=-=-
    // load server side pluggable api entries
    irods::api_entry_table&  RsApiTable   = irods::get_server_api_table();
    irods::pack_entry_table& ApiPackTable = irods::get_pack_table();
    ret = irods::init_api_table(
              RsApiTable,
              ApiPackTable,
              false );
    if ( !ret.ok() ) {
        irods::log( PASS( ret ) );
        return 1;
    }

    // =-=-=-=-=-=-=-
    // load client side pluggable api entries
    irods::api_entry_table&  RcApiTable = irods::get_client_api_table();
    ret = irods::init_api_table(
              RcApiTable,
              ApiPackTable,
              true );
    if ( !ret.ok() ) {
        irods::log( PASS( ret ) );
        return 1;
    }




#if RODS_CAT
    if ( strstr( rsComm.myEnv.rodsDebug, "CAT" ) != NULL ) {
        chlDebug( rsComm.myEnv.rodsDebug );
    }
#endif

    status = initAgent( RULE_ENGINE_TRY_CACHE, &rsComm );

    if ( status < 0 ) {
        rodsLog( LOG_ERROR, "agentMain :: initAgent failed: %d", status );
        sendVersion( net_obj, SYS_AGENT_INIT_ERR, 0, NULL, 0 );
        cleanupAndExit( status );
    }

    /* move configConnectControl behind initAgent for now. need zoneName if
     * the user does not specify one in the input */
    initConnectControl();

    if ( rsComm.clientUser.userName[0] != '\0' ) {
        status = chkAllowedUser( rsComm.clientUser.userName,
                                 rsComm.clientUser.rodsZone );

        if ( status < 0 ) {
            sendVersion( net_obj, status, 0, NULL, 0 );
            cleanupAndExit( status );
        }
    }

    // =-=-=-=-=-=-=-
    // handle negotiations with the client regarding TLS if requested
    // this scope block makes valgrind happy
    {
        std::string neg_results;
        ret = irods::client_server_negotiation_for_server( net_obj, neg_results );
        if ( !ret.ok() || neg_results == irods::CS_NEG_FAILURE ) {
            irods::log( PASS( ret ) );
            // =-=-=-=-=-=-=-
            // send a 'we failed to negotiate' message here??
            // or use the error stack rule engine thingie
            irods::log( PASS( ret ) );
            sendVersion( net_obj, SYS_AGENT_INIT_ERR, 0, NULL, 0 );
            cleanupAndExit( ret.code() );

        }
        else {
            // =-=-=-=-=-=-=-
            // copy negotiation results to comm for action by network objects
            snprintf( rsComm.negotiation_results, sizeof( rsComm.negotiation_results ), "%s", neg_results.c_str() );
            //rsComm.ssl_do_accept = 1;

        }
    }

    /* send the server version and atatus as part of the protocol. Put
     * rsComm.reconnPort as the status */
    ret = sendVersion( net_obj, status, rsComm.reconnPort,
                       rsComm.reconnAddr, rsComm.cookie );

    if ( !ret.ok() ) {
        irods::log( PASS( ret ) );
        sendVersion( net_obj, SYS_AGENT_INIT_ERR, 0, NULL, 0 );
        cleanupAndExit( status );
    }

    logAgentProc( &rsComm );

    // call initialization for network plugin as negotiated
    irods::network_object_ptr new_net_obj;
    ret = irods::network_factory( &rsComm, new_net_obj );
    if ( !ret.ok() ) {
        return ret.code();
    }

    ret = sockAgentStart( new_net_obj );
    if ( !ret.ok() ) {
        irods::log( PASS( ret ) );
        return ret.code();
    }

    new_net_obj->to_server( &rsComm );
    status = agentMain( &rsComm );

    // call initialization for network plugin as negotiated
    ret = sockAgentStop( new_net_obj );
    if ( !ret.ok() ) {
        irods::log( PASS( ret ) );
        return ret.code();
    }

    new_net_obj->to_server( &rsComm );
    cleanup();
    free( rsComm.thread_ctx );
    free( rsComm.auth_scheme );
    rodsLog( LOG_NOTICE, "Agent exiting with status = %d", status );
    return status;
}