示例#1
0
/* Retrieves the task specification and initializes the agent with it.
* Then it gets the agent name, cleans it and sends it to the environment.
*/
int performInit(int sd, int argc, const char* agent_params[])
{
  const char* agent_name;
  char* clean_agent_name;
  // Send Get_TASK command
  int rc = sendTokenOnSocket(sd, CMD_GETTASK);

  // Retrieve the number of states and actions
  if(rc >= 0) rc = getIntFromSocket(sd, &numStates);
  if(rc >= 0) rc = getIntFromSocket(sd, &numActions);
  if(rc >= 0) rc = agent_init(numStates, numActions, argc, agent_params);
  if(rc >= 0)
  {
    agent_name = agent_get_name();
    if(!agent_name) agent_name = "Unnamed";
    clean_agent_name = strdup(agent_name);
    clean_name(clean_agent_name);
    // Send START_LOG command and the agent name
    rc = sendTokenOnSocket(sd, CMD_STARTLOG);
    if(rc >= 0) rc = sendTokenOnSocket(sd, clean_agent_name);
    free(clean_agent_name);
  }

  return rc;
}
示例#2
0
文件: agent.c 项目: GGFT3/micromouse
int main(void) {
    agent_init();
    while(1) {
        agent_learn();
        enum action_t act = agent_explore();
        bool end = false;
        switch(act) {
        case GO_FORWARD:
            printf("GO_FORWARD");
            break;

        case TURN_LEFT:
            printf("TURN_LEFT");
            break;

        case TURN_RIGHT:
            printf("TURN_RIGHT");
            break;

        case NO_OPERATION:
            printf("NO_OPERATION");
            end = true;
            break;
        }
        if(end) break;
        char buf[1024];
        fgets(buf, sizeof(buf), stdin);
    }
    puts("");
    return 0;
}
C_RESULT video_open (video_cfg_t *cfg)
{

	// Initialize the Python (or Matlab or C) agent
	agent_init();
    
    return C_OK;
}
示例#4
0
文件: event.c 项目: kghost/lldpd
static void
levent_init(struct lldpd *cfg)
{
	/* Setup libevent */
	log_debug("event", "initialize libevent");
	event_set_log_callback(levent_log_cb);
	if (!(cfg->g_base = event_base_new()))
		fatalx("unable to create a new libevent base");
	log_info("event", "libevent %s initialized with %s method",
		  event_get_version(),
		  event_base_get_method(cfg->g_base));

	/* Setup SNMP */
#ifdef USE_SNMP
	if (cfg->g_snmp) {
		agent_init(cfg, cfg->g_snmp_agentx);
		cfg->g_snmp_timeout = evtimer_new(cfg->g_base,
		    levent_snmp_timeout,
		    cfg);
		if (!cfg->g_snmp_timeout)
			fatalx("unable to setup timeout function for SNMP");
		if ((cfg->g_snmp_fds =
			malloc(sizeof(struct ev_l))) == NULL)
			fatalx("unable to allocate memory for SNMP events");
		TAILQ_INIT(levent_snmp_fds(cfg));
	}
#endif

	/* Setup loop that will run every X seconds. */
	log_debug("event", "register loop timer");
	if (!(cfg->g_main_loop = event_new(cfg->g_base, -1, 0,
					   levent_update_and_send,
					   cfg)))
		fatalx("unable to setup main timer");
	event_active(cfg->g_main_loop, EV_TIMEOUT, 1);

	/* Setup unix socket */
	log_debug("event", "register Unix socket");
	TAILQ_INIT(&lldpd_clients);
	evutil_make_socket_nonblocking(cfg->g_ctl);
	if ((cfg->g_ctl_event = event_new(cfg->g_base, cfg->g_ctl,
		    EV_READ|EV_PERSIST, levent_ctl_accept, cfg)) == NULL)
		fatalx("unable to setup control socket event");
	event_add(cfg->g_ctl_event, NULL);

	/* Signals */
	log_debug("event", "register signals");
	signal(SIGHUP, SIG_IGN);
	evsignal_add(evsignal_new(cfg->g_base, SIGUSR1,
		levent_dump, cfg->g_base),
	    NULL);
	evsignal_add(evsignal_new(cfg->g_base, SIGINT,
		levent_stop, cfg->g_base),
	    NULL);
	evsignal_add(evsignal_new(cfg->g_base, SIGTERM,
		levent_stop, cfg->g_base),
	    NULL);
}
示例#5
0
文件: cpumem_agent.c 项目: kadoma/fms
fmd_module_t *
fmd_module_init(char *path, fmd_t *pfmd)
{
	if (cpumem_agent_init()) {
		wr_log(CMEA_LOG_DOMAIN, WR_LOG_ERROR,
			"failed to cpumem agent init");
		return NULL;
	}
	
	return (fmd_module_t *)agent_init(&cpumem_mops, path, pfmd);
}
示例#6
0
int main(void)
{
	int err;

	/* Init SNMP subagent */
	agent_init();

	/* Register OID */
	err = nsh_register_scalar_ro(exampleOid);
	if (err) {
		fprintf(stderr, "Error registering OID\n");
		return err;
	}

	/* Event loop to handle SNMP requests */
	agent_event_loop();
}
static void onAgentInit(int theConnection) {
	unsigned int theTaskSpecLength = 0;
	unsigned int offset = 0;

	/* Read the data in the buffer (data from server) */
	offset = rlBufferRead(&theBuffer, offset, &theTaskSpecLength, 1, sizeof(int));
	if (theTaskSpecLength > 0) {
		theTaskSpec = (char*)calloc(theTaskSpecLength+1, sizeof(char));
		offset = rlBufferRead(&theBuffer, offset, theTaskSpec, theTaskSpecLength, sizeof(char));
		/*Make sure the string is null terminated */
		theTaskSpec[theTaskSpecLength]='\0';
	}

	/* Call RL method on the recv'd data */
	agent_init(theTaskSpec);

	/* Prepare the buffer for sending data back to the server */
	rlBufferClear(&theBuffer);
}
示例#8
0
/**
 * Init function called by the Contiki netstack
 */
static void dtn_network_init(void) 
{
	/* Set up log domains */
	logging_init();
	logging_domain_level_set(LOGD_DTN, LOG_NET, LOGLEVEL);
	logging_domain_level_set(LOGD_DTN, LOG_BUNDLE, LOGLEVEL);
	logging_domain_level_set(LOGD_DTN, LOG_ROUTE, LOGLEVEL);
	logging_domain_level_set(LOGD_DTN, LOG_STORE, LOGLEVEL);
	logging_domain_level_set(LOGD_DTN, LOG_SDNV, LOGLEVEL);
	logging_domain_level_set(LOGD_DTN, LOG_SLOTS, LOGLEVEL);
	logging_domain_level_set(LOGD_DTN, LOG_AGENT, LOGLEVEL);
	logging_domain_level_set(LOGD_DTN, LOG_CL, LOGLEVEL);
	logging_domain_level_set(LOGD_DTN, LOG_DISCOVERY, LOGLEVEL);

	/* Clear the packet buffer */
	packetbuf_clear();

	/* Initialize logging */
	LOG(LOGD_DTN, LOG_NET, LOGL_DBG, "init");

	/* Start the agent */
	agent_init();
}
示例#9
0
fmd_module_t *
fmd_init(const char *path, fmd_t *pfmd)
{
	fmd_debug;
	return (fmd_module_t *)agent_init(&apache_mops, path, pfmd);
}
示例#10
0
文件: agent.c 项目: misterlihao/MBA
MBA_AGENT_RETURN agent_reset( Monitor *mon ) {
    // Copy the previous fwd_port
    int fwd_port = ac->fwd_port;
    agent_cleanup();
    return agent_init( mon, fwd_port, NULL );
}
示例#11
0
int main(int argc, char ** argv) {
  int ii;

  FixedAllocator fa = fixed_allocator_make(sizeof(long), 100, "fa");
  void* last;
  for(ii=0; ii < 100; ++ii) {
    ASSERT((last = fixed_allocator_alloc(fa)) != NULL);
  }

  //ASSERT(fixed_allocator_alloc(fa) == NULL);
  fixed_allocator_free(fa, last);
  ASSERT(fixed_allocator_alloc(fa) != NULL);

  StackAllocator sa = stack_allocator_make(sizeof(long) * 100, "sa");
  for(ii=0; ii < 100; ++ii) {
    ASSERT((last = stack_allocator_alloc(sa, sizeof(long))) != NULL);
  }

  //ASSERT(stack_allocator_alloc(sa, sizeof(long)) == NULL);
  stack_allocator_freeall(sa);
  ASSERT(stack_allocator_alloc(sa, sizeof(long) * 5) != NULL);

  CircularBuffer buffer = circularbuffer_make(100);
  ASSERT(circularbuffer_bytes_writable(buffer) == 100);
  ASSERT(circularbuffer_bytes_readable(buffer) == 0);

  char bytes[100];
  for(ii = 0; ii < 100; ++ii) {
    bytes[ii] = ii;
  }

  circularbuffer_insert(buffer, bytes, 100);
  ASSERT(circularbuffer_bytes_writable(buffer) == 0);
  ASSERT(circularbuffer_bytes_readable(buffer) == 100);

  char morebytes[100];
  circularbuffer_read(buffer, morebytes, 50);
  ASSERT(circularbuffer_bytes_readable(buffer) == 50);
  ASSERT(circularbuffer_bytes_writable(buffer) == 50);
  for(int ii = 0; ii < 50; ++ii) {
    ASSERT(morebytes[ii] == ii);
  }

  circularbuffer_insert(buffer, bytes, 50);
  ASSERT(circularbuffer_bytes_writable(buffer) == 0);
  ASSERT(circularbuffer_bytes_readable(buffer) == 100);

  circularbuffer_read(buffer, morebytes, 100);
  ASSERT(circularbuffer_bytes_writable(buffer) == 100);
  ASSERT(circularbuffer_bytes_readable(buffer) == 0);
  for(int ii = 0; ii < 100; ++ii) {
    if(ii < 50) {
      ASSERT(morebytes[ii] == ii + 50);
    } else {
      ASSERT(morebytes[ii] == ii - 50);
    }
  }

  testlib_init();
  screen_width = 640;
  screen_height = 480;

  game_init();
  agent_init();

  Particle particle = particle_make();
  Enemy enemy = enemy_make((Particle)particle, 100);

  ASSERT(enemy->agent.inbox.head == NULL);
  ASSERT(enemy->agent.outbox.head == NULL);

  agent_update((Agent)enemy);
  ASSERT(enemy->agent.state == ENEMY_IDLE);

  ASSERT(enemy->agent.inbox.head == NULL);
  ASSERT(enemy->agent.outbox.head == NULL);

  Message terminate = message_make(NULL, MESSAGE_TERMINATE, NULL);
  message_postinbox((Agent)enemy, terminate);

  agent_update((Agent)enemy);

  ASSERT(enemy->agent.inbox.head == NULL);
  ASSERT(enemy->agent.outbox.head != NULL);

  Message reply = (Message)dll_remove_tail(&enemy->agent.outbox);
  ASSERT(reply->kind == MESSAGE_TERMINATING);
  ASSERT(enemy->agent.state != ENEMY_MAX);
  message_report_read(reply);
  ASSERT(enemy->agent.state == ENEMY_MAX);

  // now use a collective
  Collective collective = collective_make();
  Agent ca = (Agent)collective;

  ASSERT(ca->inbox.head == NULL);
  ASSERT(ca->outbox.head == NULL);
  ASSERT(dll_count(&collective->children) == 1);

  Dispatcher dispatcher = (Dispatcher)collective->children.head;
  ASSERT(dll_count(&dispatcher->dispatchees) == 0);

  agent_update((Agent)collective);

  ASSERT(ca->inbox.head == NULL);
  ASSERT(ca->outbox.head == NULL);
  ASSERT(dll_count(&collective->children) == 1);

  Message spawn = message_make(NULL, COLLECTIVE_SPAWN_ENEMY, NULL);
  message_postinbox((Agent)collective, spawn);

  agent_update((Agent)collective);

  ASSERT(ca->inbox.head == NULL);
  ASSERT(ca->outbox.head == NULL);
  ASSERT(dll_count(&collective->children) == 2);
  ASSERT(dll_count(&dispatcher->dispatchees) == 1);

  Dispatchee entry = (Dispatchee)dispatcher->dispatchees.head;
  enemy = (Enemy)entry->agent;
  Particle ep = enemy->visual;

  // park a bullet on top of the enemy and see if the notifications
  // flow
  struct ImageResource_ image;
  image.w = 128;
  image.h = 128;

  Particle bullet =
    (Particle)spawn_bullet(&ep->pos, &ep->vel, &image);
  dll_add_head(&player_bullets, (DLLNode)bullet);

  // current update strategy takes two cycles to push through the
  // deletion
  agent_update((Agent)collective);
  agent_update((Agent)collective);

  ASSERT(dll_count(&collective->children) == 1);
  ASSERT(dll_count(&dispatcher->dispatchees) == 0);

  END_MAIN();
}
示例#12
0
int main(int argc, char** argv)
{
	testCount = 0;
	while (g_testEntries[testCount].createFcn != NULL)
	{
		++testCount;
	}

	testIndex = b2Clamp(testIndex, 0, testCount-1);
	testSelection = testIndex;

	entry = g_testEntries + testIndex;

	test = entry->createFcn();

	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);
	glutInitWindowSize(width, height);
	char title[32];
	sprintf(title, "Box2D Version %d.%d.%d", b2_version.major, b2_version.minor, b2_version.revision);
	mainWindow = glutCreateWindow(title);
	//glutSetOption (GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_GLUTMAINLOOP_RETURNS);

	glutDisplayFunc(SimulationLoop);

/*	int theConnection=0;
	theConnection=setup_rlglue_network();
	runEnvironmentEventLoop(theConnection);*/

	GLUI_Master.set_glutReshapeFunc(Resize);  
	GLUI_Master.set_glutKeyboardFunc(Keyboard);
	GLUI_Master.set_glutSpecialFunc(KeyboardSpecial);
	GLUI_Master.set_glutMouseFunc(Mouse);
#ifdef FREEGLUT
	glutMouseWheelFunc(MouseWheel);
#endif
	glutMotionFunc(MouseMotion);

	glui = GLUI_Master.create_glui_subwindow( mainWindow, 
		GLUI_SUBWINDOW_RIGHT );

	glui->add_statictext("Tests");
	GLUI_Listbox* testList =
		glui->add_listbox("", &testSelection);

	glui->add_separator();

	GLUI_Spinner* velocityIterationSpinner =
		glui->add_spinner("Vel Iters", GLUI_SPINNER_INT, &settings.velocityIterations);
	velocityIterationSpinner->set_int_limits(1, 500);

	GLUI_Spinner* positionIterationSpinner =
		glui->add_spinner("Pos Iters", GLUI_SPINNER_INT, &settings.positionIterations);
	positionIterationSpinner->set_int_limits(0, 100);

	GLUI_Spinner* hertzSpinner =
		glui->add_spinner("Hertz", GLUI_SPINNER_FLOAT, &settingsHz);

	hertzSpinner->set_float_limits(5.0f, 200.0f);

	glui->add_checkbox("Warm Starting", &settings.enableWarmStarting);
	glui->add_checkbox("Time of Impact", &settings.enableContinuous);

	//glui->add_separator();

	GLUI_Panel* drawPanel =	glui->add_panel("Draw");
	glui->add_checkbox_to_panel(drawPanel, "Shapes", &settings.drawShapes);
	glui->add_checkbox_to_panel(drawPanel, "Joints", &settings.drawJoints);
	glui->add_checkbox_to_panel(drawPanel, "AABBs", &settings.drawAABBs);
	glui->add_checkbox_to_panel(drawPanel, "Pairs", &settings.drawPairs);
	glui->add_checkbox_to_panel(drawPanel, "Contact Points", &settings.drawContactPoints);
	glui->add_checkbox_to_panel(drawPanel, "Contact Normals", &settings.drawContactNormals);
	glui->add_checkbox_to_panel(drawPanel, "Contact Forces", &settings.drawContactForces);
	glui->add_checkbox_to_panel(drawPanel, "Friction Forces", &settings.drawFrictionForces);
	glui->add_checkbox_to_panel(drawPanel, "Center of Masses", &settings.drawCOMs);
	glui->add_checkbox_to_panel(drawPanel, "Statistics", &settings.drawStats);

	int32 testCount = 0;
	TestEntry* e = g_testEntries;
	while (e->createFcn)
	{
		testList->add_item(testCount, e->name);
		++testCount;
		++e;
	}

	glui->add_button("Pause", 0, Pause);
	glui->add_button("Single Step", 0, SingleStep);
	glui->add_button("Restart", 0, Restart);

	glui->add_button("Quit", 0,(GLUI_Update_CB)exit);
	glui->set_main_gfx_window( mainWindow );

	// Use a timer to control the frame rate.
	glutTimerFunc(framePeriod, Timer, 0);

////////////////////////////////////////////////////////////////////////////////////////////
	/*const char *task_spec;
	printf("\nThis is a RL Test program(Start)\n");
	task_spec = RL_init();
	printf("\nTASK SPEC : %s\n",task_spec);
   	printf("Starting offline demo\n----------------------------\nWill alternate learning for 25 episodes, then freeze policy and evaluate for 10 episodes.\n\n");
	printf("After Episode\tMean Return\tStandard Deviation\n-------------------------------------------------------------------------\n");

	oa = RL_start();

	RL_agent_message("load_policy results.dat");
	RL_agent_message("freeze learning");*/

	const char* task_spec;
	task_spec = env_init();
	agent_init(task_spec);

////////////////////////////////////////////////////////////////////////////////////////////
/*
	agent_message("load_policy results.dat");
	agent_message("freeze learning");*/

	glutMainLoop();

	return 0;
}
示例#13
0
main(int argc, char *argv[]) {
	char *pgm;
	int   ok, help, debug, verbose, query;
	char *what = "*", whatbuf[256] = { '\0' };
	char *world;
	char *server;
	char *logger;
	char *host;
	int   id, nc;
	int   i, nmod;
	char  argbuf[256];
	MODULE_HOST modlocs[MAX_AGENT];

	pgm = argv[0];
	++argv; --argc;

	ok      = 1;
	help    = 0;
	debug   = 0;
	verbose = 0;
	query   = 0;
	world   = NULL;
	logger  = NULL;
	host    = NULL;
	while (argc && *argv[0] == '-') {
		char *opt;

		opt = argv[0] + 1;
		++argv; --argc;

		if      (streq(opt, "help"))    ++help;
		else if (substr(opt, "debug"))  ++debug;
		else if (substr(opt, "verbose"))++verbose;
		else if (substr(opt, "earlab")) {
			world  = "Earlab*Master";
		}
		else if (substr(opt, "search")) {
			if (!argc || argv[0][0] == '-') {
				fprintf(stderr,
					"%s: missing argument to -%s\n",
					pgm, opt);
				ok = 0;
			}
			else {
				world = argv[0];
				++argv; --argc;
			}
		}
		else if (substr(opt, "logserver")) {
			if (!argc || argv[0][0] == '-') {
				fprintf(stderr,
					"%s: missing argument to -%s\n",
					pgm, opt);
				ok = 0;
			}
			else {
				logger = argv[0];
				++argv; --argc;
			}
		}
		else if (substr(opt, "module")) {
			if (!argc || argv[0][0] == '-') {
				fprintf(stderr,
					"%s: missing argument to -%s\n",
					pgm, opt);
				ok = 0;
			}
			else {
				if (!whatbuf[0]) strcpy(whatbuf, "{");
				else             strcat(whatbuf, ",");
				strcat(whatbuf, argv[0]);
				what = whatbuf;

				++argv; --argc;
			}
		}
		else if (substr(opt, "host")) {
			if (!argc || argv[0][0] == '-') {
				fprintf(stderr,
					"%s: missing argument to -%s\n",
					pgm, opt);
				ok = 0;
			}
			else {
				host = argv[0];
				++argv; --argc;
			}
		}
		else {
			fprintf(stderr, "%s: ignoring argument -%s\n", pgm, opt)
;
			help = 1;
			ok   = 0;
		}
	}
	if (!ok || help || (argc == 0 && !world)) {
		usage(pgm, help);
		exit(!help);
	}
	event_verbose(verbose);

	if (world) {
		server = SearchWorld(NULL, world);
		if (!server) {
			fprintf(stderr, "%s: couldn't find earlab master server\n", pgm);
			exit(1);
		}
	}
	else if (argc) {
		server = argv[0];
		++argv; --argc;
	}
	else {
		usage(pgm, help);
		exit(1);
	}

	if (argc) {
		if (!whatbuf[0]) what = argv[0];
		else {
			strcat(whatbuf, ",");
			strcat(whatbuf, argv[0]);
			strcat(whatbuf, "}");
		}
		++argv; --argc;
	}
	else if (!whatbuf[0]) {
		usage(pgm, 0);
		exit(1);
	}

	argbuf[0] = '\0';
	while (argc) {
		strcat(argbuf, argv[0]);
		++argv; --argc;
		if (argc) strcat(argbuf, " ");
	}


printf("Module search is \"%s\"\n", what);

	/* local initialization */
	agent_init();

	id = event_join(server, &nc);
	if (!id) {
		fprintf(stderr, "%s: couldn't join server \"%s\"\n", server);
		exit(4);
	}
	printf("%s: joined %s as client id %d (%d clients)\n", pgm, server, id, nc);

	event_register("earlab", "control", pgm);

	event_select_type(0, 0, ET_MAX);
	event_select_type(1, ET_AGENTD_MIN, ET_AGENTD_MAX);

	nmod = LocateModule(what, modlocs, MAX_AGENT);

	for (i = 0; i < nmod; ++i) {
		printf("%s: module \"%s\" available on host %s\n",
		       pgm, modlocs[i].module, modlocs[i].host);
	}

	if (query) {
		event_leave();
		exit(0);
	}

	if (host) for (i = 0; i < nmod; ++i) {
		 if (strmatch(host, modlocs[i].host)) break;
	}
	else i = 0;

	if (nmod == 0 || i == nmod) {
		printf("%s: module \"%s\" not available on host %s\n",
		       pgm, what, host?host:"*");
		event_leave();
		exit(1);
	}
	StartModule(modlocs[i].clientid, logger,
		    modlocs[i].module, argbuf);

	event_leave();

	exit(0);
}
示例#14
0
int
main(int argc, char **argv)
{
  int c;
  sigset_t set;
  const char *cfgfile = NULL;
  const char *jobfile = NULL;
  const char *defconf = "doozer-agent.json";

  signal(SIGPIPE, handle_sigpipe);

  while((c = getopt(argc, argv, "c:s:j:")) != -1) {
    switch(c) {
    case 'c':
      cfgfile = optarg;
      break;
    case 's':
      enable_syslog("doozer-agent", optarg);
      break;
    case 'j':
      jobfile = optarg;
      break;
    }
  }

  sigfillset(&set);
  sigprocmask(SIG_BLOCK, &set, NULL);

  srand48(getpid() ^ time(NULL));

  if(cfg_load(cfgfile, defconf)) {
    fprintf(stderr, "Unable to load config (check -c option). Giving up\n");
    exit(1);
  }

  create_heaps();

  if(geteuid() == 0) {

    get_uid_gid();

    if(setgid(build_gid)) {
      trace(LOG_ERR, "Unable to setgid(%d) -- %s", build_gid,
            strerror(errno));
      exit(1);
    }

    if(seteuid(build_uid)) {
      trace(LOG_ERR, "Unable to seteuid(%d) -- %s", build_uid,
            strerror(errno));
    }
  }

  git_threads_init();

  artifact_init();

  agent_init(jobfile);

  running = 1;
  sigemptyset(&set);
  sigaddset(&set, SIGTERM);
  sigaddset(&set, SIGINT);
  sigaddset(&set, SIGHUP);

  signal(SIGTERM, doexit);
  signal(SIGINT, doexit);
  signal(SIGHUP, doreload);

  pthread_sigmask(SIG_UNBLOCK, &set, NULL);

  while(running) {
    if(reload) {
      reload = 0;
      if(!cfg_load(NULL, defconf)) {
      }
    }
    pause();
  }

  spawn_stop_all();
  trace(LOG_NOTICE, "Waiting for jobs to stop");
  agent_join();
  return 0;
}
示例#15
0
/**
 * @brief Update function called after every event
 *
 * The heart of the scheduler, the actual scheduling algorithm. This will be
 * passed to the event loop as a call back and will be called every time an event
 * is executed. Therefore the code should be light weight since it will be run
 * very frequently.
 *
 * @TODO:
 *   currently this will only grab a job and create a single agent to execute
 *   the job.
 *
 *   @TODO: allow for runonpfile jobs to have multiple agents based on size
 *   @TODO: allow for job preemption. The scheduler can pause jobs, allow it
 *   @TODO: allow for specific hosts to be chosen.
 */
void scheduler_update(scheduler_t* scheduler)
{
  /* queue used to hold jobs if an exclusive job enters the system */
  static job_t*  job  = NULL;
  static host_t* host = NULL;
  static int lockout = 0;

  /* locals */
  int n_agents = g_tree_nnodes(scheduler->agents);
  int n_jobs   = active_jobs(scheduler->job_list);

  /* check to see if we are in and can exit the startup state */
  if(scheduler->s_startup && n_agents == 0)
  {
    event_signal(database_update_event, NULL);
    scheduler->s_startup = 0;
  }

  /* check if we are able to close the scheduler */
  if(closing && n_agents == 0 && n_jobs == 0)
  {
    event_loop_terminate();
    return;
  }

  if(lockout && n_agents == 0 && n_jobs == 0)
    lockout = 0;

  if(job == NULL && !lockout)
  {
    while((job = peek_job(scheduler->job_queue)) != NULL)
    {
      // check if the agent is required to run on local host
      if(is_meta_special(
          g_tree_lookup(scheduler->meta_agents, job->agent_type), SAG_LOCAL))
      {
        host = g_tree_lookup(scheduler->host_list, LOCAL_HOST);
        if(!(host->running < host->max))
        {
          job = NULL;
          break;
        }
      }
      // check if the job is required to run on a specific machine
      else if((job->required_host != NULL))
      {
        host = g_tree_lookup(scheduler->host_list, job->required_host);
        if(host != NULL)
        { 
          if(!(host->running < host->max))
          {
          job = NULL;
          break;
        }
       } else {
         //log_printf("ERROR %s.%d: jq_pk %d jq_host '%s' not in the agent list!\n",
         //  __FILE__, __LINE__, job->id, job->required_host);
         job->message = "ERROR: jq_host not in the agent list!";
         job_fail_event(scheduler, job);
         job = NULL;
         break;
       }
      }
      // the generic case, this can run anywhere, find a place
      else if((host = get_host(&(scheduler->host_queue), 1)) == NULL)
      {
        job = NULL;
        break;
      }

      next_job(scheduler->job_queue);
      if(is_meta_special(
          g_tree_lookup(scheduler->meta_agents, job->agent_type), SAG_EXCLUSIVE))
      {
        V_SCHED("JOB_INIT: exclusive, postponing initialization\n");
        break;
      }

      V_SCHED("Starting JOB[%d].%s\n", job->id, job->agent_type);
      agent_init(scheduler, host, job);
      job = NULL;
    }
  }

  if(job != NULL && n_agents == 0 && n_jobs == 0)
  {
    agent_init(scheduler, host, job);
    lockout = 1;
    job  = NULL;
    host = NULL;
  }

  if(scheduler->s_pause)
  {
    scheduler->s_startup = 1;
    scheduler->s_pause = 0;
  }
}
示例#16
0
/* Client program */
int
main(int argc, char *argv[])
{
	char server[64];
	char fullhostname[64];
	char domain[256];
	char password[64];
	char shell[256];
	char directory[256];
	RD_BOOL prompt_password, deactivated;
	struct passwd *pw;
	uint32 flags, ext_disc_reason = 0;
	char *p;
	int c;
	char *locale = NULL;
	int username_option = 0;
	RD_BOOL geometry_option = False;
#ifdef WITH_RDPSND
	char *rdpsnd_optarg = NULL;
#endif

#ifdef HAVE_LOCALE_H
	/* Set locale according to environment */
	locale = setlocale(LC_ALL, "");
	if (locale)
	{
		locale = xstrdup(locale);
	}

#endif

	/* Ignore SIGPIPE, since we are using popen() */
	struct sigaction act;
	memset(&act, 0, sizeof(act));
	act.sa_handler = SIG_IGN;
	sigemptyset(&act.sa_mask);
	act.sa_flags = 0;
	sigaction(SIGPIPE, &act, NULL);

	flags = RDP_LOGON_NORMAL;
	prompt_password = False;
	domain[0] = password[0] = shell[0] = directory[0] = 0;
	g_embed_wnd = 0;

	g_num_devices = 0;

#ifdef RDP2VNC
#define VNCOPT "V:Q:"
#else
#define VNCOPT
#endif

	while ((c = getopt(argc, argv,
			   VNCOPT "Au:L:d:s:c:p:n:k:G:g:fbBeEmzCDKS:T:NX:a:x:Pr:045h?")) != -1)
	{
		switch (c)
		{
            case 'G':
				STRNCPY(g_agent, optarg, sizeof(g_agent));
                break;

#ifdef RDP2VNC
			case 'V':
				rfb_port = strtol(optarg, NULL, 10);
				if (rfb_port < 100)
					rfb_port += 5900;
				break;

			case 'Q':
				defer_time = strtol(optarg, NULL, 10);
				if (defer_time < 0)
					defer_time = 0;
				break;
#endif

			case 'A':
				g_seamless_rdp = True;
				break;

			case 'u':
				g_username = (char *) xmalloc(strlen(optarg) + 1);
				STRNCPY(g_username, optarg, strlen(optarg) + 1);
				username_option = 1;
				break;

			case 'L':
#ifdef HAVE_ICONV
				STRNCPY(g_codepage, optarg, sizeof(g_codepage));
#else
				error("iconv support not available\n");
#endif
				break;

			case 'd':
				STRNCPY(domain, optarg, sizeof(domain));
				break;

			case 's':
				STRNCPY(shell, optarg, sizeof(shell));
				break;

			case 'c':
				STRNCPY(directory, optarg, sizeof(directory));
				break;

			case 'p':
				if ((optarg[0] == '-') && (optarg[1] == 0))
				{
					prompt_password = True;
					break;
				}

				STRNCPY(password, optarg, sizeof(password));
				flags |= RDP_LOGON_AUTO;

				/* try to overwrite argument so it won't appear in ps */
				p = optarg;
				while (*p)
					*(p++) = 'X';
				break;

			case 'n':
				STRNCPY(g_hostname, optarg, sizeof(g_hostname));
				break;

			case 'k':
				STRNCPY(g_keymapname, optarg, sizeof(g_keymapname));
				break;

			case 'g':
				geometry_option = True;
				g_fullscreen = False;
				if (!strcmp(optarg, "workarea"))
				{
					g_sizeopt = 1;
					break;
				}

				g_width = strtol(optarg, &p, 10);
				if (g_width <= 0)
				{
					error("invalid geometry\n");
					return EX_USAGE;
				}

				if (*p == 'x')
					g_height = strtol(p + 1, &p, 10);

				if (g_height <= 0)
				{
					error("invalid geometry\n");
					return EX_USAGE;
				}

				if (*p == '%')
				{
					g_sizeopt = -g_width;
					g_width = 800;
					p++;
				}

				if (*p == '+' || *p == '-')
				{
					g_pos |= (*p == '-') ? 2 : 1;
					g_xpos = strtol(p, &p, 10);

				}
				if (*p == '+' || *p == '-')
				{
					g_pos |= (*p == '-') ? 4 : 1;
					g_ypos = strtol(p, NULL, 10);
				}

				break;

			case 'f':
				g_fullscreen = True;
				break;

			case 'b':
				g_bitmap_cache = False;
				break;

			case 'B':
				g_ownbackstore = False;
				break;

			case 'e':
				g_encryption = False;
				break;
			case 'E':
				g_packet_encryption = False;
				break;
			case 'm':
				g_sendmotion = False;
				break;

			case 'C':
				g_owncolmap = True;
				break;

			case 'D':
				g_hide_decorations = True;
				break;

			case 'K':
				g_grab_keyboard = False;
				break;

			case 'S':
				if (!strcmp(optarg, "standard"))
				{
					g_win_button_size = 18;
					break;
				}

				g_win_button_size = strtol(optarg, &p, 10);

				if (*p)
				{
					error("invalid button size\n");
					return EX_USAGE;
				}

				break;

			case 'T':
				STRNCPY(g_title, optarg, sizeof(g_title));
				break;

			case 'N':
				g_numlock_sync = True;
				break;

			case 'X':
				g_embed_wnd = strtol(optarg, NULL, 0);
				break;

			case 'a':
				g_server_depth = strtol(optarg, NULL, 10);
				if (g_server_depth != 8 &&
				    g_server_depth != 16 &&
				    g_server_depth != 15 && g_server_depth != 24
				    && g_server_depth != 32)
				{
					error("Invalid server colour depth.\n");
					return EX_USAGE;
				}
				break;

			case 'z':
				DEBUG(("rdp compression enabled\n"));
				flags |= (RDP_LOGON_COMPRESSION | RDP_LOGON_COMPRESSION2);
				break;

			case 'x':
				if (str_startswith(optarg, "m"))	/* modem */
				{
					g_rdp5_performanceflags =
						RDP5_NO_WALLPAPER | RDP5_NO_FULLWINDOWDRAG |
						RDP5_NO_MENUANIMATIONS | RDP5_NO_THEMING;
				}
				else if (str_startswith(optarg, "b"))	/* broadband */
				{
					g_rdp5_performanceflags = RDP5_NO_WALLPAPER;
				}
				else if (str_startswith(optarg, "l"))	/* lan */
				{
					g_rdp5_performanceflags = RDP5_DISABLE_NOTHING;
				}
				else
				{
					g_rdp5_performanceflags = strtol(optarg, NULL, 16);
				}
				break;

			case 'P':
				g_bitmap_cache_persist_enable = True;
				break;

			case 'r':

				if (str_startswith(optarg, "sound"))
				{
					optarg += 5;

					if (*optarg == ':')
					{
						optarg++;
						while ((p = next_arg(optarg, ',')))
						{
							if (str_startswith(optarg, "remote"))
								flags |= RDP_LOGON_LEAVE_AUDIO;

							if (str_startswith(optarg, "local"))
#ifdef WITH_RDPSND
							{
								rdpsnd_optarg =
									next_arg(optarg, ':');
								g_rdpsnd = True;
							}

#else
								warning("Not compiled with sound support\n");
#endif

							if (str_startswith(optarg, "off"))
#ifdef WITH_RDPSND
								g_rdpsnd = False;
#else
								warning("Not compiled with sound support\n");
#endif

							optarg = p;
						}
					}
					else
					{
#ifdef WITH_RDPSND
						g_rdpsnd = True;
#else
						warning("Not compiled with sound support\n");
#endif
					}
				}
				else if (str_startswith(optarg, "disk"))
				{
					/* -r disk:h:=/mnt/floppy */
					disk_enum_devices(&g_num_devices, optarg + 4);
				}
				else if (str_startswith(optarg, "comport"))
				{
					serial_enum_devices(&g_num_devices, optarg + 7);
				}
				else if (str_startswith(optarg, "lspci"))
				{
					g_lspci_enabled = True;
				}
				else if (str_startswith(optarg, "lptport"))
				{
					parallel_enum_devices(&g_num_devices, optarg + 7);
				}
				else if (str_startswith(optarg, "printer"))
				{
					printer_enum_devices(&g_num_devices, optarg + 7);
				}
				else if (str_startswith(optarg, "clientname"))
				{
					g_rdpdr_clientname = xmalloc(strlen(optarg + 11) + 1);
					strcpy(g_rdpdr_clientname, optarg + 11);
				}
				else if (str_startswith(optarg, "clipboard"))
				{
					optarg += 9;

					if (*optarg == ':')
					{
						optarg++;

						if (str_startswith(optarg, "off"))
							g_rdpclip = False;
						else
							cliprdr_set_mode(optarg);
					}
					else
						g_rdpclip = True;
				}
				else if (strncmp("scard", optarg, 5) == 0)
				{
#ifdef WITH_SCARD
					scard_enum_devices(&g_num_devices, optarg + 5);
#else
					warning("Not compiled with smartcard support\n");
#endif
				}
				else
				{
					warning("Unknown -r argument\n\n\tPossible arguments are: comport, disk, lptport, printer, sound, clipboard, scard\n");
				}
				break;

			case '0':
				g_console_session = True;
				break;

			case '4':
				g_use_rdp5 = False;
				break;

			case '5':
				g_use_rdp5 = True;
				break;

			case 'h':
			case '?':
			default:
				usage(argv[0]);
				return EX_USAGE;
		}
	}

	if (argc - optind != 1)
	{
		usage(argv[0]);
		return EX_USAGE;
	}

	STRNCPY(server, argv[optind], sizeof(server));
	parse_server_and_port(server);

	if (g_seamless_rdp)
	{
		if (g_win_button_size)
		{
			error("You cannot use -S and -A at the same time\n");
			return EX_USAGE;
		}
		g_rdp5_performanceflags &= ~RDP5_NO_FULLWINDOWDRAG;
		if (geometry_option)
		{
			error("You cannot use -g and -A at the same time\n");
			return EX_USAGE;
		}
		if (g_fullscreen)
		{
			error("You cannot use -f and -A at the same time\n");
			return EX_USAGE;
		}
		if (g_hide_decorations)
		{
			error("You cannot use -D and -A at the same time\n");
			return EX_USAGE;
		}
		if (g_embed_wnd)
		{
			error("You cannot use -X and -A at the same time\n");
			return EX_USAGE;
		}
		if (!g_use_rdp5)
		{
			error("You cannot use -4 and -A at the same time\n");
			return EX_USAGE;
		}
		g_sizeopt = -100;
		g_grab_keyboard = False;
	}

	if (!username_option)
	{
		pw = getpwuid(getuid());
		if ((pw == NULL) || (pw->pw_name == NULL))
		{
			error("could not determine username, use -u\n");
			return EX_OSERR;
		}
		/* +1 for trailing \0 */
		int pwlen = strlen(pw->pw_name) + 1;
		g_username = (char *) xmalloc(pwlen);
		STRNCPY(g_username, pw->pw_name, pwlen);
	}

#ifdef HAVE_ICONV
	if (g_codepage[0] == 0)
	{
		if (setlocale(LC_CTYPE, ""))
		{
			STRNCPY(g_codepage, nl_langinfo(CODESET), sizeof(g_codepage));
		}
		else
		{
			STRNCPY(g_codepage, DEFAULT_CODEPAGE, sizeof(g_codepage));
		}
	}
#endif

	if (g_hostname[0] == 0)
	{
		if (gethostname(fullhostname, sizeof(fullhostname)) == -1)
		{
			error("could not determine local hostname, use -n\n");
			return EX_OSERR;
		}

		p = strchr(fullhostname, '.');
		if (p != NULL)
			*p = 0;

		STRNCPY(g_hostname, fullhostname, sizeof(g_hostname));
	}

	if (g_keymapname[0] == 0)
	{
		if (locale && xkeymap_from_locale(locale))
		{
			fprintf(stderr, "Autoselected keyboard map %s\n", g_keymapname);
		}
		else
		{
			STRNCPY(g_keymapname, "en-us", sizeof(g_keymapname));
		}
	}
	if (locale)
		xfree(locale);


	if (prompt_password && read_password(password, sizeof(password)))
		flags |= RDP_LOGON_AUTO;

	if (g_title[0] == 0)
	{
		strcpy(g_title, "rdesktop - ");
		strncat(g_title, server, sizeof(g_title) - sizeof("rdesktop - "));
	}

    agent_init();

#ifdef RDP2VNC
	rdp2vnc_connect(server, flags, domain, password, shell, directory);
	return EX_OK;
#else

	if (!ui_init())
		return EX_OSERR;

#ifdef WITH_RDPSND
	if (g_rdpsnd)
	{
		if (!rdpsnd_init(rdpsnd_optarg))
			warning("Initializing sound-support failed!\n");
	}
#endif

	if (g_lspci_enabled)
		lspci_init();

	rdpdr_init();

	while (1)
	{
		rdesktop_reset_state();

		if (g_redirect)
		{
			STRNCPY(domain, g_redirect_domain, sizeof(domain));
			xfree(g_username);
			g_username = (char *) xmalloc(strlen(g_redirect_username) + 1);
			STRNCPY(g_username, g_redirect_username, sizeof(g_username));
			STRNCPY(password, g_redirect_password, sizeof(password));
			STRNCPY(server, g_redirect_server, sizeof(server));
			flags |= RDP_LOGON_AUTO;
		}

		ui_init_connection();
		if (!rdp_connect(server, flags, domain, password, shell, directory, g_redirect))
			return EX_PROTOCOL;

		/* By setting encryption to False here, we have an encrypted login 
		   packet but unencrypted transfer of other packets */
		if (!g_packet_encryption)
			g_encryption = False;


		DEBUG(("Connection successful.\n"));
		memset(password, 0, sizeof(password));

		if (!g_redirect)
			if (!ui_create_window())
				return EX_OSERR;

		g_redirect = False;
		rdp_main_loop(&deactivated, &ext_disc_reason);

		DEBUG(("Disconnecting...\n"));
		rdp_disconnect();

		if (g_redirect)
			continue;

		ui_seamless_end();
		ui_destroy_window();
		if (g_pending_resize)
		{
			/* If we have a pending resize, reconnect using the new size, rather than exit */
			g_pending_resize = False;
			continue;
		}
		break;
	}

	cache_save_state();
	ui_deinit();

	if (g_user_quit)
		return EXRD_WINDOW_CLOSED;

	return handle_disconnect_reason(deactivated, ext_disc_reason);

#endif
	if (g_redirect_username)
		xfree(g_redirect_username);

	xfree(g_username);
}
示例#17
0
/**
 * Main function
 */
int main(int argc, char **argv)
{
	int opt = 0;
	comm_plugin = communication_plugin();

	if (argc == 1) {
		opt = 1;
	} else if (argc == 2) {
                if (strstr(argv[1], "--help") != 0) {
                        print_help();
                        exit(0);
		} else if (strstr(argv[1], "pulseoximeter") != 0) {
			opt = 1;
		} else if (strstr(argv[1], "bloodpressure") != 0) {
			opt = 2;
		} else if (strstr(argv[1], "weightscale") != 0) {
			opt = 3;
		} else if (strstr(argv[1], "glucometer") != 0) {
			opt = 4;
		} else {
                        fprintf(stderr, "ERROR: invalid option: %s\n", argv[1]);
                        fprintf(stderr, "Try `%s --help'"
                                " for more information.\n", argv[0]);
                        exit(1);
		}
	} else {
		fprintf(stderr, "ERROR: invalid option: %s\n", argv[1]);
		fprintf(stderr, "Try `%s --help'"
				" for more information.\n", argv[0]);
		exit(1);
	}

	tcp_mode();

	fprintf(stderr, "\nIEEE 11073 sample agent\n");

	comm_plugin.timer_count_timeout = timer_count_timeout;
	comm_plugin.timer_reset_timeout = timer_reset_timeout;

	CommunicationPlugin *plugins[] = {&comm_plugin, 0};
	void *event_report_cb;
	int specialization;
	if (opt == 2) { /* Blood Pressure */
		fprintf(stderr, "Starting Blood Pressure Agent\n");
		event_report_cb = blood_pressure_event_report_cb;
		specialization = 0x02BC;
	} else if (opt == 3) { /* Weight Scale */
		fprintf(stderr, "Starting Weight Scale Agent\n");
		event_report_cb = weightscale_event_report_cb;
		specialization = 0x05DC;
	} else if (opt == 4) { /* Glucometer */
		fprintf(stderr, "Starting Glucometer Agent\n");
		event_report_cb = glucometer_event_report_cb;
		specialization = 0x06A4;
	} else { /* Default Pulse Oximeter */
		fprintf(stderr, "Starting Pulse Oximeter Agent\n");
		event_report_cb = oximeter_event_report_cb;
		// change to 0x0191 if you want timestamps
		specialization = 0x0190;
	}

	agent_init(plugins, specialization, event_report_cb, mds_data_cb);

	AgentListener listener = AGENT_LISTENER_EMPTY;
	listener.device_connected = &device_connected;
	listener.device_associated = &device_associated;
	listener.device_unavailable = &device_unavailable;

	agent_add_listener(listener);

	agent_start();

	signal(SIGALRM, sigalrm);
	agent_connection_loop(CONTEXT_ID);

	agent_finalize();

	return 0;
}