Beispiel #1
0
int main(int argc, char **argv)
{
	int res;
	const SBVersionStatus * compiled = sbGetCompiledVersion(); 
	unsigned int objSizeStatus = sbValidateObjectSize(compiled);

	ros::init(argc, argv, "coax_server");
	ROS_INFO("Object size status: %04x",objSizeStatus);
	assert(objSizeStatus == 0);

	SBApiSimpleContext simple;
	SBController api(&simple);


	CRITICAL(res = api.initialise((argc<2)?("localhost"):(argv[1])));

	ros::NodeHandle n("/coax_server");

	std::vector<ros::ServiceServer> services;
	services.push_back(n.advertiseService("get_version", &SBController::get_version, &api));
	services.push_back(n.advertiseService("configure_comm", &SBController::configure_comm, &api));
	services.push_back(n.advertiseService("configure_control", &SBController::configure_control, &api));
	services.push_back(n.advertiseService("configure_oamode", &SBController::configure_oamode, &api));
	services.push_back(n.advertiseService("get_control_parameters", &SBController::get_control_parameters, &api));
	services.push_back(n.advertiseService("set_control_parameters", &SBController::set_control_parameters, &api));
	services.push_back(n.advertiseService("get_trim_mode", &SBController::get_trim_mode, &api));
	services.push_back(n.advertiseService("set_trim_mode", &SBController::set_trim_mode, &api));
	services.push_back(n.advertiseService("get_sensor_list", &SBController::get_sensor_list, &api));
	services.push_back(n.advertiseService("reach_nav_state", &SBController::reach_nav_state, &api));
	services.push_back(n.advertiseService("request_state", &SBController::request_state, &api));
	services.push_back(n.advertiseService("send_string", &SBController::send_string, &api));
	services.push_back(n.advertiseService("set_verbose", &SBController::set_verbose, &api));
	services.push_back(n.advertiseService("set_ack_mode", &SBController::set_ack_mode, &api));
	services.push_back(n.advertiseService("set_timeout", &SBController::set_timeout, &api));
	services.push_back(n.advertiseService("set_control", &SBController::set_control, &api));
	services.push_back(n.advertiseService("set_raw_control", &SBController::set_raw_control, &api));
	services.push_back(n.advertiseService("reset", &SBController::reset, &api));
	services.push_back(n.advertiseService("set_light", &SBController::set_light, &api));

	// Publishing the state
	ros::Publisher coax_pub = n.advertise<coax_msgs::CoaxState>("state",1);
	api.registerPublisher(&coax_pub);

	// Subscribing to control message (without acknowledgement)
#if 1
	ros::TransportHints hints1,hints2;
	ros::Subscriber control_sub = n.subscribe("control",1,&SBController::control_callback,&api,hints1.udp());
	ros::Subscriber rawcontrol_sub = n.subscribe("rawcontrol",1,&SBController::raw_control_callback,&api,hints2.udp());
#else
	ros::Subscriber control_sub = n.subscribe("control",1,&SBController::control_callback,&api);
	ros::Subscriber rawcontrol_sub = n.subscribe("rawcontrol",1,&SBController::raw_control_callback,&api);
	ros::Subscriber external_state_sub = n.subscribe("external_state",1,&SBController::external_state_callback,&api);
#endif

#ifdef REPEAT_STRINGS
	ros::Subscriber repeat_sub = n.subscribe("torepeat",1,&SBController::repeat_ros_callback,&api);
	ros::Publisher repeat_pub = n.advertise<std_msgs::String>("repeated",1);
#else
	ros::Subscriber repeat_sub = n.subscribe("torepeat",1,&SBController::repeat_ros_callback,&api);
	ros::Publisher repeat_pub = n.advertise<coax_msgs::CoaxRepeat>("repeated",1);
#endif
    api.setupRepeatIO(&repeat_pub,&repeat_sub);

	ROS_INFO("Coax Server ready");
	ros::spin();

	DEBUG(res = api.terminate());
	return 0;
}
/****** uti/spool/sge_get_management_entry() *************************************
*  NAME
*     sge_get_management_entry() - Read management.properties file entries
*
*  SYNOPSIS
*     int sge_get_management_entry(const char *fname, int n, 
*                               const char *name[], 
*                               char value[][1025],
*                               dstring *error_dstring) 
*
*  FUNCTION
*     Reads in an array of configuration file entries
*
*  RESULT
*     int - 0 on success
*
*  BUGS
*     Function can not differ multiple similar named entries.
*
*  NOTES
*     MT-NOTE: sge_get_management_entry() is MT safe
******************************************************************************/
int sge_get_management_entry(const char *fname, int n, int nmissing, bootstrap_entry_t name[], 
                          char value[][SGE_PATH_MAX], dstring *error_dstring) 
{
   FILE *fp;
   char buf[SGE_PATH_MAX], *cp;
   int i;
   bool *is_found = NULL;
   
   DENTER(TOP_LAYER, "sge_get_management_entry");

   if (!(fp = fopen(fname, "r"))) {
      if (error_dstring == NULL){
         CRITICAL((SGE_EVENT, MSG_FILE_FOPENFAILED_SS, fname, strerror(errno)));
      }
      else {
         sge_dstring_sprintf(error_dstring, MSG_FILE_FOPENFAILED_SS, 
                             fname, strerror(errno));
      }
      DEXIT;
      return n;
   }
   is_found = malloc(sizeof(bool) * n);
   memset(is_found, false, n * sizeof(bool));
   
   while (fgets(buf, sizeof(buf), fp)) {
      char *pos = NULL;

      /* set chrptr to the first non blank character
       * If line is empty continue with next line
       */
      if(!(cp = strtok_r(buf, " \t\n", &pos))) {
          continue;
      }    

      /* allow commentaries */
      if (cp[0] == '#') {
          continue;
      }    
  
      /* search for all requested configuration values */ 
      for (i=0; i<n; i++) {
         char *nam = strtok_r(cp, "=", &pos);
         char *val = strtok_r(NULL, "\n", &pos);
         if (nam != NULL && strcasecmp(name[i].name, nam) == 0) {
                DPRINTF(("nam = %s\n", nam));
                if (val != NULL) {
                   DPRINTF(("val = %s\n", val));
                   sge_strlcpy(value[i], val, SGE_PATH_MAX);
                } else {
                   sge_strlcpy(value[i], "", SGE_PATH_MAX);
                }
                is_found[i] = true;
                if (name[i].is_required) {
                  --nmissing; 
                }
                break;
         }
      }
   }
   if (nmissing != 0) {
      for (i=0; i<n; i++) {
         if (!is_found[i] && name[i].is_required) {
            if (error_dstring == NULL){
               CRITICAL((SGE_EVENT, MSG_UTI_CANNOTLOCATEATTRIBUTEMAN_SS, name[i].name, fname));
            }
            else {
               sge_dstring_sprintf(error_dstring, MSG_UTI_CANNOTLOCATEATTRIBUTEMAN_SS, 
                                   name[i].name, fname);
            }
            
            break;
         }
      }
   }
   
   sge_free(&is_found);
   FCLOSE(fp);
   DEXIT;
   return nmissing;
FCLOSE_ERROR:
   DEXIT;
   return 0;
} /* sge_get_management_entry() */
/****** qmaster/ckpt/sge_del_ckpt() *******************************************
*
*  NAME
*     sge_del_ckpt -- delete ckpt object in Master_Ckpt_List 
*
*  SYNOPSIS
*     int sge_del_ckpt(lListElem *ep, lList **alpp, char *ruser, char *rhost);
* 
*  FUNCTION
*     This function will be called from the framework which will
*     add/modify/delete generic gdi objects.
*     The purpose of this function is it to delete ckpt objects. 
*
*
*  INPUTS
*     ep          - element which should be deleted
*     alpp        - reference to an answer list.
*     ruser       - username of person who invoked this gdi request
*     rhost       - hostname of the host where someone initiated an gdi call
*
*  RESULT
*     [alpp] - error messages will be added to this list
*     0 - success
*     STATUS_EUNKNOWN - an error occured
******************************************************************************/ 
int sge_del_ckpt(sge_gdi_ctx_class_t *ctx, lListElem *ep, lList **alpp, char *ruser, char *rhost) 
{
   lListElem *found;
   int pos;
   const char *ckpt_name;
   lList **lpp = object_type_get_master_list(SGE_TYPE_CKPT);

   DENTER(TOP_LAYER, "sge_del_ckpt");

   if ( !ep || !ruser || !rhost ) {
      CRITICAL((SGE_EVENT, MSG_SGETEXT_NULLPTRPASSED_S, SGE_FUNC));
      answer_list_add(alpp, SGE_EVENT, STATUS_EUNKNOWN, ANSWER_QUALITY_ERROR);
      DEXIT;
      return STATUS_EUNKNOWN;
   }

   /* ep is no ckpt element, if ep has no CK_name */
   if ((pos = lGetPosViaElem(ep, CK_name, SGE_NO_ABORT)) < 0) {
      CRITICAL((SGE_EVENT, MSG_SGETEXT_MISSINGCULLFIELD_SS,
            lNm2Str(CK_name), SGE_FUNC));
      answer_list_add(alpp, SGE_EVENT, STATUS_EUNKNOWN, ANSWER_QUALITY_ERROR);
      DEXIT;
      return STATUS_EUNKNOWN;
   }

   ckpt_name = lGetPosString(ep, pos);
   if (!ckpt_name) {
      CRITICAL((SGE_EVENT, MSG_SGETEXT_NULLPTRPASSED_S, SGE_FUNC));
      answer_list_add(alpp, SGE_EVENT, STATUS_EUNKNOWN, ANSWER_QUALITY_ERROR);
      DEXIT;
      return STATUS_EUNKNOWN;
   }                    
   found = ckpt_list_locate(*lpp, ckpt_name);

   if (!found) {
      ERROR((SGE_EVENT, MSG_SGETEXT_DOESNOTEXIST_SS, MSG_OBJ_CKPT, ckpt_name));
      answer_list_add(alpp, SGE_EVENT, STATUS_EEXIST, ANSWER_QUALITY_ERROR);
      DEXIT;
      return STATUS_EEXIST;
   }

   /* 
    * Try to find references in other objects
    */
   {
      lList *local_answer_list = NULL;

      if (ckpt_is_referenced(found, &local_answer_list, *(object_type_get_master_list(SGE_TYPE_JOB)),
                             *(object_type_get_master_list(SGE_TYPE_CQUEUE)))) {
         lListElem *answer = lFirst(local_answer_list);

         ERROR((SGE_EVENT, "denied: %s", lGetString(answer, AN_text)));
         answer_list_add(alpp, SGE_EVENT, STATUS_EUNKNOWN,
                         ANSWER_QUALITY_ERROR);
         lFreeList(&local_answer_list);
         DEXIT;
         return STATUS_EUNKNOWN;
      }
   }

   /* remove ckpt file 1st */
   if (!sge_event_spool(ctx, alpp, 0, sgeE_CKPT_DEL, 0, 0, ckpt_name, NULL, NULL,
                        NULL, NULL, NULL, true, true)) {
      ERROR((SGE_EVENT, MSG_CANTSPOOL_SS, MSG_OBJ_CKPT, ckpt_name));
      answer_list_add(alpp, SGE_EVENT, STATUS_EEXIST, ANSWER_QUALITY_ERROR);
      DEXIT;
      return STATUS_EDISK;
   }

   /* now we can remove the element */
   lRemoveElem(*lpp, &found);

   INFO((SGE_EVENT, MSG_SGETEXT_REMOVEDFROMLIST_SSSS,
            ruser, rhost, ckpt_name, MSG_OBJ_CKPT));
   answer_list_add(alpp, SGE_EVENT, STATUS_OK, ANSWER_QUALITY_INFO);
   DEXIT;
   return STATUS_OK;
}                     
Beispiel #4
0
/****** sge_manop_qmaster/sge_del_manop() **************************************
*  NAME
*     sge_del_manop() -- delete manager or operator
*
*  SYNOPSIS
*     int 
*     sge_del_manop(sge_gdi_ctx_class_t *ctx, lListElem *ep, lList **alpp, 
*                   char *ruser, char *rhost, u_long32 target) 
*
*  FUNCTION
*     Deletes a manager or an operator from the corresponding master list.
*
*  INPUTS
*     sge_gdi_ctx_class_t *ctx - gdi context
*     lListElem *ep            - the manager/operator to delete
*     lList **alpp             - answer list to return messages
*     char *ruser              - user having triggered the action
*     char *rhost              - host from which the action has been triggered
*     u_long32 target          - SGE_UM_LIST or SGE_UO_LIST
*
*  RESULT
*     int - STATUS_OK or STATUS_* error code
*
*  NOTES
*     MT-NOTE: sge_del_manop() is MT safe - if we hold the global lock.
*******************************************************************************/
int sge_del_manop(sge_gdi_ctx_class_t *ctx, lListElem *ep, lList **alpp, char *ruser, char *rhost, u_long32 target)
{
   lListElem *found;
   int pos;
   const char *manop_name;
   const char *object_name;
   lList **lpp = NULL;
   int key = NoName;
   ev_event eve = sgeE_EVENTSIZE;

   DENTER(TOP_LAYER, "sge_del_manop");

   if (ep == NULL || ruser == NULL || rhost == NULL) {
      CRITICAL((SGE_EVENT, MSG_SGETEXT_NULLPTRPASSED_S, SGE_FUNC));
      answer_list_add(alpp, SGE_EVENT, STATUS_EUNKNOWN, ANSWER_QUALITY_ERROR);
      DRETURN(STATUS_EUNKNOWN);
   }

   switch (target) {
      case SGE_UM_LIST:
         lpp = object_type_get_master_list(SGE_TYPE_MANAGER);
         object_name = MSG_OBJ_MANAGER;
         key = UM_name;
         eve = sgeE_MANAGER_DEL;
         break;
      case SGE_UO_LIST:
         lpp = object_type_get_master_list(SGE_TYPE_OPERATOR);
         object_name = MSG_OBJ_OPERATOR;
         key = UO_name;
         eve = sgeE_OPERATOR_DEL;
         break;
      default :
         DPRINTF(("unknown target passed to %s\n", SGE_FUNC));
         DRETURN(STATUS_EUNKNOWN);
   }

   /* ep is no manop element, if ep has no UM_name/UO_name */
   if ((pos = lGetPosViaElem(ep, key, SGE_NO_ABORT)) < 0) {
      CRITICAL((SGE_EVENT, MSG_SGETEXT_MISSINGCULLFIELD_SS, lNm2Str(key), SGE_FUNC));
      answer_list_add(alpp, SGE_EVENT, STATUS_EUNKNOWN, ANSWER_QUALITY_ERROR);
      DRETURN(STATUS_EUNKNOWN);
   }

   manop_name = lGetPosString(ep, pos);
   if (manop_name == NULL) {
      CRITICAL((SGE_EVENT, MSG_SGETEXT_NULLPTRPASSED_S, SGE_FUNC));
      answer_list_add(alpp, SGE_EVENT, STATUS_EUNKNOWN, ANSWER_QUALITY_ERROR);
      DRETURN(STATUS_EUNKNOWN);
   }

   /* prevent removing of root from man/op-list */
   if (strcmp(manop_name, "root") == 0) {
      ERROR((SGE_EVENT, MSG_SGETEXT_MAY_NOT_REMOVE_USER_FROM_LIST_SS, "root", object_name));  
      answer_list_add(alpp, SGE_EVENT, STATUS_EEXIST, ANSWER_QUALITY_ERROR);
      DRETURN(STATUS_EEXIST);
   }

   /* prevent removing the admin user from man/op-list */
   if (strcmp(manop_name, ctx->get_admin_user(ctx)) == 0) {
      ERROR((SGE_EVENT, MSG_SGETEXT_MAY_NOT_REMOVE_USER_FROM_LIST_SS,
             ctx->get_admin_user(ctx), object_name));  
      answer_list_add(alpp, SGE_EVENT, STATUS_EEXIST, ANSWER_QUALITY_ERROR);
      DRETURN(STATUS_EEXIST);
   }

   found = lGetElemStr(*lpp, key, manop_name);
   if (!found) {
      ERROR((SGE_EVENT, MSG_SGETEXT_DOESNOTEXIST_SS, object_name, manop_name));
      answer_list_add(alpp, SGE_EVENT, STATUS_EEXIST, ANSWER_QUALITY_ERROR);
      DRETURN(STATUS_EEXIST);
   }
   
   lDechainElem(*lpp, found);

   /* update on file */
   if (!sge_event_spool(ctx, alpp, 0, eve,
                        0, 0, manop_name, NULL, NULL,
                        NULL, NULL, NULL, true, true)) {
      ERROR((SGE_EVENT, MSG_CANTSPOOL_SS, object_name, manop_name));
      answer_list_add(alpp, SGE_EVENT, STATUS_EDISK, ANSWER_QUALITY_ERROR);
   
      /* chain in again */
      lAppendElem(*lpp, found);

      DRETURN(STATUS_EDISK);
   }
   lFreeElem(&found);

   INFO((SGE_EVENT, MSG_SGETEXT_REMOVEDFROMLIST_SSSS, ruser, rhost, manop_name, object_name));
   answer_list_add(alpp, SGE_EVENT, STATUS_OK, ANSWER_QUALITY_INFO);
   DRETURN(STATUS_OK);
}
Beispiel #5
0
static Boolean
setTime (ClockDriver *self, TimeInternal *time, Boolean force) {

	GET_CONFIG_CLOCKDRIVER(self, myConfig, unix);

	TimeInternal oldTime, delta;

	getTime(self, &oldTime);

	subTime(&delta, &oldTime, time);

	if(self->config.readOnly) {
		return FALSE;
	}

	if(force) {
	    self->lockedUp = FALSE;
	}

	if(!force && !self->config.negativeStep && isTimeNegative(&delta)) {
		CRITICAL(THIS_COMPONENT"Cannot step Unix clock %s backwards\n", self->name);
		CRITICAL(THIS_COMPONENT"Manual intervention required or SIGUSR1 to force %s clock step\n", self->name);
		self->lockedUp = TRUE;
		self->setState(self, CS_NEGSTEP);
		return FALSE;
	}

#if defined(_POSIX_TIMERS) && (_POSIX_TIMERS > 0)

	struct timespec tp;
	tp.tv_sec = time->seconds;
	tp.tv_nsec = time->nanoseconds;

	if(tp.tv_sec == 0) {
	    ERROR(THIS_COMPONENT"Unix clock driver %s: cannot set time to zero seconds\n", self->name);
	    return FALSE;
	}

	if(tp.tv_sec <= 0) {
	    ERROR(THIS_COMPONENT"Unic clock driver %s: cannot set time to a negative value %d\n", self->name, tp.tv_sec);
	    return FALSE;
	}

#else

	struct timeval tv;
	tv.tv_sec = time->seconds;
	tv.tv_usec = time->nanoseconds / 1000;

	if(tv.tv_sec == 0) {
	    ERROR(THIS_COMPONENT"Unix clock %s: cannot set time to zero seconds\n", self->name);
	    return FALSE;
	}

	if(tv.tv_sec < 0) {
	    ERROR(THIS_COMPONENT"Unic clock %s: cannot set time to a negative value %d\n", self->name, tv.tv_sec);
	    return FALSE;
	}


#endif /* _POSIX_TIMERS */

#if defined(_POSIX_TIMERS) && (_POSIX_TIMERS > 0)
	if (clock_settime(CLOCK_REALTIME, &tp) < 0) {
		PERROR(THIS_COMPONENT"Could not set system time");
		return FALSE;
	}
	addTime(&_stepAccumulator, &_stepAccumulator, &delta);
#else

	settimeofday(&tv, 0);
	addTime(&_stepAccumulator, &_stepAccumulator, &delta);
#endif /* _POSIX_TIMERS */

	if(oldTime.seconds != time->seconds) {
	    updateXtmp_unix(oldTime, *time);
	    if(myConfig->setRtc) {
		setRtc(self, time);
	    }
	}

	self->_stepped = TRUE;

	struct timespec tmpTs = { time->seconds,0 };

	char timeStr[MAXTIMESTR];
	strftime(timeStr, MAXTIMESTR, "%x %X", localtime(&tmpTs.tv_sec));
	NOTICE(THIS_COMPONENT"Unix clock %s: stepped the system clock to: %s.%d\n", self->name,
	       timeStr, time->nanoseconds);

	self->setState(self, CS_FREERUN);

	return TRUE;

}
Beispiel #6
0
int ewk_init(void)
{
    if (_ewkInitCount)
        return ++_ewkInitCount;

    if (!eina_init())
        goto error_eina;

    _ewk_log_dom = eina_log_domain_register("ewebkit", EINA_COLOR_ORANGE);
    if (_ewk_log_dom < 0) {
        EINA_LOG_CRIT("could not register log domain 'ewebkit'");
        goto error_log_domain;
    }

    if (!evas_init()) {
        CRITICAL("could not init evas.");
        goto error_evas;
    }

    if (!ecore_init()) {
        CRITICAL("could not init ecore.");
        goto error_ecore;
    }

    if (!ecore_evas_init()) {
        CRITICAL("could not init ecore_evas.");
        goto error_ecore_evas;
    }

    if (!edje_init()) {
        CRITICAL("could not init edje.");
        goto error_edje;
    }

#ifdef HAVE_ECORE_X
    if (!ecore_x_init(0)) {
        CRITICAL("could not init ecore_x.");
        goto error_ecore_x;
    }
#endif

    if (!_ewk_init_body()) {
        CRITICAL("could not init body");
        goto error_edje;
    }

    return ++_ewkInitCount;

#ifdef HAVE_ECORE_X
error_ecore_x:
    edje_shutdown();
#endif
error_edje:
    ecore_evas_shutdown();
error_ecore_evas:
    ecore_shutdown();
error_ecore:
    evas_shutdown();
error_evas:
    eina_log_domain_unregister(_ewk_log_dom);
    _ewk_log_dom = -1;
error_log_domain:
    eina_shutdown();
error_eina:
    return 0;
}
Beispiel #7
0
/* MAIN entry point */
int main(int argc, char *argv[]) {
    int i, n, ret = 0;
    int config_loop;
    int verbosity;
    int detach;
    kstr *err_msg;
    struct kdsignal_info sigs[] = { {SIGALRM, kd_SIGALRM_handler },
                                    {SIGINT,  kd_SIGINT_handler  },
                                    {SIGTERM, kd_SIGTERM_handler },
                                    {SIGCHLD, kd_SIGCHLD_handler },
                                    {SIGUSR1, kd_SIGUSR1_handler },
                                    {SIGHUP,  kd_SIGHUP_handler  } };
    int ignored_sigs[] = {SIGPIPE, 0};
    apr_pool_t *server_pool;

    printf("Teambox Sign-On Server daemon\n");
    printf("Copyright (C) 2006-2012 Opersys inc.\n\n");

    ktools_initialize();
    kmem_set_handler(NULL, NULL, NULL, NULL, kd_abort_handler, NULL);

    /* Configuration and option setup.
       1 - Load the internal defaults.  They have the least priority.
       2 - Load the configuration file.
       3 - Load the command line options, overriding 2 and 1. */

    /* Initializes APR. */
    apr_initialize();
    apr_pool_create(&main_pool, NULL);

    /* Configuration. */
    do {
        log_open(main_pool);
        log_set_all_level("syslog", 0);

        if (options_load(main_pool, 
                         opts_tbl, 
                         opts_tbl_cnt, 
                         CONFIG_PATH "/tbxsosd.conf",
                         kd_options_error_handler,
                         0) < 0) {
	    kstr str;
	    kstr_init(&str);
	    format_current_error_for_user(&str);
	    fprintf(stderr, "config read error: %s.\n", str.data);
	    kstr_clean(&str);
            break;
        }

        kd_init_logging();

        /* Command line stuff. */
        if (kd_options_parse(argc, argv) < 0) {
            ret = -1;
            break;
        }      

        /* Load options for local use.  No need to check the return
           value since the values should have been set earlier when
           parsing the command line. */
        detach = options_get_bool("server.detach");
        verbosity = options_get_uint32("server.log_verbosity");

        log_set_verbosity(verbosity);

        /* Proceed to static initialization of modules. */
        if (kdssl_static_init(main_pool) < 0) {
            kd_dump_error();
            err_msg = kerror_str_n(0);
            CRITICAL(_log_server_, "SSL initialization failed: %s.", err_msg->data);
            kstr_destroy(err_msg);
            ret = -1;
            break;
        }        
        if (kdclient_static_init(main_pool) < 0) {
            kd_dump_error();
            err_msg = kerror_str_n(0);
            ERROR(_log_server_, "Basic initialization failed: %s", err_msg->data);
            kstr_destroy(err_msg);
            ret = -1;
            break;
        }
        if (kdkey_static_init() < 0) {
            kd_dump_error();
            err_msg = kerror_str_n(0);
            ERROR(_log_server_, "Basic initialization failed: %s", err_msg->data);
            kstr_destroy(err_msg);
            ret = -1;
            break;
        }
   
        /* Spawn the master process. */
        if (detach && kd_spawn(main_pool) == 0) break;        

        kdsignal_handled(sizeof(sigs) / sizeof(struct kdsignal_info), sigs);
        kdsignal_ignored(ignored_sigs);

        apr_pool_create(&server_pool, main_pool);
        
        /* Block all signals we say we are handling since it's the job
           of the server object to handle them. */
        kdsignal_block_all_handled();

        /* Create the new server object. */
        if ((server = kdserver_new(server_pool)) == NULL) {
            kd_dump_error();
            err_msg = kerror_str_n(0);
            CRITICAL(_log_server_, "Error initializing the server: %s", err_msg->data);
            kstr_destroy(err_msg);
            ret = -1;
            break;
        }        
           
        /* At this point, the expected behavior in signal handling can
           resume. */
        kdsignal_unblock_all_handled();

        for (i = 0; i < server->ssl_sock_count; i++)
            INFO(_log_server_, "Listening for SSL on %s:%ld.",
                 inet_ntoa(server->ssl_sock_addr[i]->sin_addr),
                 ntohs(server->ssl_sock_addr[i]->sin_port));
        for (i = 0; i < server->n_sock_count; i++)
            INFO(_log_server_, "Listening on %s:%ld.",
                 inet_ntoa(server->n_sock_addr[i]->sin_addr),
                 ntohs(server->n_sock_addr[i]->sin_port));

        /* Loop in the server.  This will block until the server
           quits. */
        config_loop = 1;
        while (config_loop && !ret) {
            n = kdserver_main(server, main_pool);

            if (n < 0) {
                err_msg = kerror_str_n(0);
                CRITICAL(_log_server_, "Server error: %s", err_msg->data);
		kstr_destroy(err_msg);
                ret = - 1;
                break;
            } 
            /* Reloading configuration was demanded. */
            else if (n == 0 && server->sig_flag & FLAG_REHASH) {
                INFO(_log_server_, "Reloading configuration.");

                /* Get rid of this block. */
                kdsignal_block_all_handled();

                apr_pool_destroy(server_pool);
                server = NULL;

                kdsignal_unblock_all_handled();

                if (options_reload(main_pool, CONFIG_PATH "/tbxsosd.conf") < 0) {
                    kd_dump_error();
                    CRITICAL(_log_server_, "config read error");
                    ret = -1;
                }
               
                if (kdclient_static_init(main_pool) < 0) {
                    kd_dump_error();
                    err_msg = kerror_str_n(0);
                    CRITICAL(_log_server_, "Basic initialization failed: %s", err_msg->data);
                    kstr_destroy(err_msg);
                    ret = -1;
                }    

                apr_pool_create(&server_pool, main_pool);

                /* Block all signals we say we are handling since it's the job
                   of the server object to handle them. */
                kdsignal_block_all_handled();

                /* Create the new server object. */
                if ((server = kdserver_new(server_pool)) == NULL) {
                    kd_dump_error();
                    err_msg = kerror_str_n(0);
                    CRITICAL(_log_server_, "Error initializing the server: %s", err_msg->data);
                    kstr_destroy(err_msg);
                    ret = -1;
                    break;
                }        
           
                /* At this point, the expected behavior in signal handling can
                   resume. */
                kdsignal_unblock_all_handled();
            }
            /* Clean quit. */
            else if (n == 0) {
                INFO(_log_server_, "Server terminating.");
                config_loop = 0;
            }
        }

    } while (0);

    kdkey_static_clean();

    apr_pool_destroy(main_pool);

    apr_terminate();    
    ktools_finalize();

    return ret;
}
/************************************************************
  sge_mod_sharetree - Master code

  Modify a share tree
  lListElem *ep,   This is the new share tree 
  lList **lpp,     list to change 
 ************************************************************/
int sge_mod_sharetree(sge_gdi_ctx_class_t *ctx,
                      lListElem *ep, lList **lpp, lList **alpp, 
                      char *ruser, char *rhost ) 
{
   int ret;
   int prev_version;
   int adding; 
   lList *found = NULL;
   object_description *object_base = object_type_get_object_description();

   DENTER(TOP_LAYER, "sge_mod_sharetree");

   /* do some checks */
   if (!ep || !ruser || !rhost) {
      CRITICAL((SGE_EVENT, MSG_SGETEXT_NULLPTRPASSED_S, SGE_FUNC));
      answer_list_add(alpp, SGE_EVENT, STATUS_EUNKNOWN, ANSWER_QUALITY_ERROR);
      DEXIT;
      return STATUS_EUNKNOWN;
   }

   ret = check_sharetree(alpp, ep, *object_base[SGE_TYPE_USER].list, 
                         *object_base[SGE_TYPE_PROJECT].list, 
                         NULL, &found);
   lFreeList(&found);
   if (ret) {
      /* alpp gets filled by check_sharetree() */
      DRETURN(STATUS_EUNKNOWN);
   }

   /* check for presence of sharetree list and create if neccesary */
   if (!*lpp) {
      prev_version = 0;
      *lpp = lCreateList("sharetree list", STN_Type);
      adding = 1;
   } else if (lGetNumberOfElem(*lpp) == 0) {
      prev_version = 0;
      adding = 1;
   } else {
      lListElem *first = lFirst(*lpp);
      /* real action: change user or project
         We simply replace the old element with the new one. If there is no
         old we simle add the new. */
     
      prev_version = lGetUlong(lFirst(*lpp), STN_version); 
      lRemoveElem(*lpp, &first);
      adding = 0;
   }

   lSetUlong(ep, STN_version, prev_version+1);

   id_sharetree(alpp, ep, 0, NULL);

   /* now insert new element */
   lAppendElem(*lpp, lCopyElem(ep));
  
   /* write sharetree to file */
   if (!sge_event_spool(ctx,
                        alpp, 0, sgeE_NEW_SHARETREE,
                        0, 0, NULL, NULL, NULL,
                        ep, NULL, NULL, true, true)) {

      /* answer list gets filled in sge_event_spool() */
      DEXIT;
      return ret;
   }

   if (adding) {
      INFO((SGE_EVENT, MSG_STREE_ADDSTREE_SSII, 
         ruser, rhost, lGetNumberOfNodes(ep, NULL, STN_children), lGetNumberOfLeafs(ep, NULL, STN_children)));
   } else {
      INFO((SGE_EVENT, MSG_STREE_MODSTREE_SSII, 
         ruser, rhost, lGetNumberOfNodes(ep, NULL, STN_children), lGetNumberOfLeafs(ep, NULL, STN_children)));
   }

   answer_list_add(alpp, SGE_EVENT, STATUS_OK, ANSWER_QUALITY_INFO);

   DEXIT;
   return STATUS_OK;
}
Beispiel #9
0
/*----------------------------------------------------------------------------*/
int 
main(int argc, char **argv)
{
   int heartbeat        = 0;
   int last_heartbeat   = 0;
   int latest_heartbeat = 0;
   int ret              = 0;
   int delay            = 0;
   time_t now, last;
/*    const char *cp; */
   char err_str[MAX_STRING_SIZE];
   char shadowd_pidfile[SGE_PATH_MAX];
   dstring ds;
   char buffer[256];
   pid_t shadowd_pid;

#if 1

static int check_interval = CHECK_INTERVAL;
static int get_active_interval = GET_ACTIVE_INTERVAL;
static int delay_time = DELAY_TIME;
static int sge_test_heartbeat = 0;

char binpath[SGE_PATH_MAX];
char oldqmaster[SGE_PATH_MAX];

char shadow_err_file[SGE_PATH_MAX];
char qmaster_out_file[SGE_PATH_MAX];

#endif

   lList *alp = NULL;
   sge_gdi_ctx_class_t *ctx = NULL;

   DENTER_MAIN(TOP_LAYER, "sge_shadowd");
   
   sge_dstring_init(&ds, buffer, sizeof(buffer));
   /* initialize recovery control variables */
   {
      char *s;
      int val;
      if ((s=getenv("SGE_CHECK_INTERVAL")) &&
          sscanf(s, "%d", &val) == 1)
         check_interval = val;
      if ((s=getenv("SGE_GET_ACTIVE_INTERVAL")) &&
          sscanf(s, "%d", &val) == 1)
         get_active_interval = val;
      if ((s=getenv("SGE_DELAY_TIME")) &&
          sscanf(s, "%d", &val) == 1)
         delay_time = val;
      if ((s=getenv("SGE_TEST_HEARTBEAT_TIMEOUT")) &&
          sscanf(s, "%d", &val) == 1)
         sge_test_heartbeat = val;
   }
         
   /* This needs a better solution */
   umask(022);

#ifdef __SGE_COMPILE_WITH_GETTEXT__  
   /* init language output for gettext() , it will use the right language */
   sge_init_language_func((gettext_func_type)        gettext,
                         (setlocale_func_type)      setlocale,
                         (bindtextdomain_func_type) bindtextdomain,
                         (textdomain_func_type)     textdomain);
   sge_init_language(NULL,NULL);   
#endif /* __SGE_COMPILE_WITH_GETTEXT__  */

   log_state_set_log_file(TMP_ERR_FILE_SHADOWD);

   if (sge_setup2(&ctx, SHADOWD, MAIN_THREAD, &alp, false) != AE_OK) {
      answer_list_output(&alp);
      SGE_EXIT((void**)&ctx, 1);
   }

   /* AA: TODO: change this */
   ctx->set_exit_func(ctx, shadowd_exit_func);
   sge_setup_sig_handlers(SHADOWD);
   
#if defined(SOLARIS)
   /* Init shared SMF libs if necessary */
   if (sge_smf_used() == 1 && sge_smf_init_libs() != 0) {
       SGE_EXIT((void**)&ctx, 1);
   }
#endif

   if (ctx->get_qmaster_spool_dir(ctx) != NULL) {
      char *shadowd_name = SGE_SHADOWD;

      /* is there a running shadowd on this host (with unqualified name) */
      sprintf(shadowd_pidfile, "%s/"SHADOWD_PID_FILE, ctx->get_qmaster_spool_dir(ctx), 
              ctx->get_unqualified_hostname(ctx));

      DPRINTF(("pidfilename: %s\n", shadowd_pidfile));
      if ((shadowd_pid = sge_readpid(shadowd_pidfile))) {
         DPRINTF(("shadowd_pid: "sge_U32CFormat"\n", sge_u32c(shadowd_pid)));
         if (!sge_checkprog(shadowd_pid, shadowd_name, PSCMD)) {
            CRITICAL((SGE_EVENT, MSG_SHADOWD_FOUNDRUNNINGSHADOWDWITHPIDXNOTSTARTING_I, (int) shadowd_pid));
            SGE_EXIT((void**)&ctx, 1);
         }
      }

      ctx->prepare_enroll(ctx);

      /* is there a running shadowd on this host (with aliased name) */
      sprintf(shadowd_pidfile, "%s/"SHADOWD_PID_FILE, ctx->get_qmaster_spool_dir(ctx), 
              ctx->get_qualified_hostname(ctx));
      DPRINTF(("pidfilename: %s\n", shadowd_pidfile));
      if ((shadowd_pid = sge_readpid(shadowd_pidfile))) {
         DPRINTF(("shadowd_pid: "sge_U32CFormat"\n", sge_u32c(shadowd_pid)));
         if (!sge_checkprog(shadowd_pid, shadowd_name, PSCMD)) {
            CRITICAL((SGE_EVENT, MSG_SHADOWD_FOUNDRUNNINGSHADOWDWITHPIDXNOTSTARTING_I, (int) shadowd_pid));
            SGE_EXIT((void**)&ctx, 1);
         }
      }  
   } else {
      ctx->prepare_enroll(ctx);
   }

   if (parse_cmdline_shadowd(argc, argv) == 1) {
      SGE_EXIT((void**)&ctx, 0);
   }
   
   if (ctx->get_qmaster_spool_dir(ctx) == NULL) {
      CRITICAL((SGE_EVENT, MSG_SHADOWD_CANTREADQMASTERSPOOLDIRFROMX_S, ctx->get_bootstrap_file(ctx)));
      SGE_EXIT((void**)&ctx, 1);
   }

   if (chdir(ctx->get_qmaster_spool_dir(ctx))) {
      CRITICAL((SGE_EVENT, MSG_SHADOWD_CANTCHANGETOQMASTERSPOOLDIRX_S, ctx->get_qmaster_spool_dir(ctx)));
      SGE_EXIT((void**)&ctx, 1);
   }

   if (sge_set_admin_username(ctx->get_admin_user(ctx), err_str)) {
      CRITICAL((SGE_EVENT, SFNMAX, err_str));
      SGE_EXIT((void**)&ctx, 1);
   }

   if (sge_switch2admin_user()) {
      CRITICAL((SGE_EVENT, SFNMAX, MSG_SHADOWD_CANTSWITCHTOADMIN_USER));
      SGE_EXIT((void**)&ctx, 1);
   }

   sprintf(shadow_err_file, "messages_shadowd.%s", ctx->get_unqualified_hostname(ctx));
   sprintf(qmaster_out_file, "messages_qmaster.%s", ctx->get_unqualified_hostname(ctx));
   sge_copy_append(TMP_ERR_FILE_SHADOWD, shadow_err_file, SGE_MODE_APPEND);
   unlink(TMP_ERR_FILE_SHADOWD);
   log_state_set_log_as_admin_user(1);
   log_state_set_log_file(shadow_err_file);

   {
      int* tmp_fd_array = NULL;
      unsigned long tmp_fd_count = 0;

      if (cl_com_set_handle_fds(cl_com_get_handle(prognames[SHADOWD] ,0), &tmp_fd_array, &tmp_fd_count) == CL_RETVAL_OK) {
         sge_daemonize(tmp_fd_array, tmp_fd_count, ctx);
         if (tmp_fd_array != NULL) {
            sge_free(&tmp_fd_array);
         }
      } else {
         sge_daemonize(NULL, 0, ctx);
      }
   }

   /* shadowd pid file will contain aliased name */
   sge_write_pid(shadowd_pidfile);

   starting_up();
   
   sge_setup_sig_handlers(SHADOWD);

   last_heartbeat = get_qmaster_heartbeat(QMASTER_HEARTBEAT_FILE, 30);

   last = (time_t) sge_get_gmt(); /* set time of last check time */

   delay = 0;
   while (!shut_me_down) {
      sleep(check_interval);

      /* get current heartbeat file content */
      heartbeat = get_qmaster_heartbeat(QMASTER_HEARTBEAT_FILE, 30);

      now = (time_t) sge_get_gmt();


      /* Only check when we could read the heartbeat file at least two times
       * (last_heartbeat and heartbeat) without error 
       */
      if (last_heartbeat > 0 && heartbeat > 0) {

         /*
          * OK we have to heartbeat entries to check. Check times ...
          * now  = current time
          * last = last check time
          */
         if ( (now - last) >= (get_active_interval + delay) ) {

            delay = 0;
            if (last_heartbeat == heartbeat) {
               DPRINTF(("heartbeat not changed since seconds: "sge_U32CFormat"\n", sge_u32c(now - last)));
               delay = delay_time; /* set delay time */

               /*
                * check if we are a possible new qmaster host (lock file of qmaster active, etc.)
                */
               ret = check_if_valid_shadow(binpath, oldqmaster, 
                                           ctx->get_act_qmaster_file(ctx), 
                                           ctx->get_shadow_master_file(ctx), 
                                           ctx->get_qualified_hostname(ctx), 
                                           ctx->get_binary_path(ctx));

               if (ret == 0) {
                  /* we can start a qmaster on this host */
                  if (qmaster_lock(QMASTER_LOCK_FILE)) {
                     ERROR((SGE_EVENT, SFNMAX, MSG_SHADOWD_FAILEDTOLOCKQMASTERSOMBODYWASFASTER));
                  } else {
                     int out, err;

                     /* still the old qmaster name in act_qmaster file and still the old heartbeat */
                     latest_heartbeat = get_qmaster_heartbeat( QMASTER_HEARTBEAT_FILE, 30);
                     /* TODO: what do we when there is a timeout ??? */
                     DPRINTF(("old qmaster name in act_qmaster and old heartbeat\n"));
                     if (!compare_qmaster_names(ctx->get_act_qmaster_file(ctx), oldqmaster) &&
                         !shadowd_is_old_master_enrolled(sge_test_heartbeat, sge_get_qmaster_port(NULL), oldqmaster) && 
                         (latest_heartbeat == heartbeat)) {
                        char qmaster_name[256];

                        strcpy(qmaster_name, SGE_PREFIX);
                        strcat(qmaster_name, prognames[QMASTER]); 
                        DPRINTF(("qmaster_name: "SFN"\n", qmaster_name)); 

                        /*
                         * open logfile as admin user for initial qmaster/schedd 
                         * startup messages
                         */
                        out = SGE_OPEN3(qmaster_out_file, O_CREAT|O_WRONLY|O_APPEND, 
                                   0644);
                        err = out;
                        if (out == -1) {
                           /*
                            * First priority is the master restart
                            * => ignore this error
                            */
                           out = 1;
                           err = 2;
                        } 

                        sge_switch2start_user();
                        ret = startprog(out, err, NULL, binpath, qmaster_name, NULL);
                        sge_switch2admin_user();
                        if (ret) {
                           ERROR((SGE_EVENT, SFNMAX, MSG_SHADOWD_CANTSTARTQMASTER));
                        }
                        close(out);
                     } else {
                        qmaster_unlock(QMASTER_LOCK_FILE);
                     }
                  }      
               } else {
                  if (ret == -1) {
                     /* just log the more important failures */    
                     WARNING((SGE_EVENT, MSG_SHADOWD_DELAYINGSHADOWFUNCFORXSECONDS_U, sge_u32c(delay) ));
                  }
               } 
            }
            /* Begin a new interval, set timers and hearbeat to current values */
            last = now;
            last_heartbeat = heartbeat;
         }
      } else {
         if (last_heartbeat < 0 || heartbeat < 0) {
            /* There was an error reading heartbeat or last_heartbeat */
            DPRINTF(("can't read heartbeat file. last_heartbeat="sge_U32CFormat", heartbeat="sge_U32CFormat"\n",
                     sge_u32c(last_heartbeat), sge_u32c(heartbeat)));
         } else {
            DPRINTF(("have to read the heartbeat file twice to check time differences\n"));
         }
      }
   }

   sge_shutdown((void**)&ctx, 0);

   DRETURN(EXIT_SUCCESS);
}
Beispiel #10
0
int main(int argc, char *argv[])
{
        QtSingleApplication a(argc, argv);
        int retcode;
        if(a.isRunning())
        {
            QMessageBox::critical(NULL, QObject::tr("Running instance detected"), QObject::tr("ScreenCloud is already running. Please close the running instance before starting a new one."));
            return 1;
        }
        a.setOrganizationName("screencloud");
        a.setApplicationName("ScreenCloud");
        a.setQuitOnLastWindowClosed(false);
        //Create data location for storing plugins if it dosen't exist
        QDir d;
        d.mkpath(QDesktopServices::storageLocation(QDesktopServices::DataLocation) + "/plugins");
        //Prepare settings
        QSettings settings("screencloud", "ScreenCloud");
        settings.setValue("config-version", "1.1");
        bool firstRun = settings.value("first-run", true).toBool();
        //Parse command line switches
        QStringList cmdline_args = a.arguments();
        if(cmdline_args.contains("--help") || cmdline_args.contains("-h") )
        {
            INFO(QObject::tr("USAGE: screencloud [-v|-c|-s|-w|-a]"));
            return 0;
        }
        if(cmdline_args.contains("--version") || cmdline_args.contains("-v") )
        {
            INFO(QObject::tr("ScreenCloud version ") + QString(VERSION) + "(" + QString(OPERATING_SYSTEM) + ")");
            return 0;
        }
        //Setup the python interpreter
        PythonQt::init();
        PythonQt_init_QtBindings();
        PythonQt::self()->addSysPath(a.applicationDirPath() + QDir::separator() + "modules");
        PythonQt::self()->addSysPath(a.applicationDirPath() + QDir::separator() + "modules"  + QDir::separator() + "python-stdlib");
        //Global vars
        if(cmdline_args.contains("--cli") || cmdline_args.contains("-c"))
        {
            //Running in CLI mode, do not show GUI
            if(firstRun)
            {
                CRITICAL(QObject::tr("This is the first time you're running ScreenCloud. Refusing to run in CLI mode."));
                return 1;
            }
            ScreenShooter screenShooter;
            QImage screenshot;
            if(cmdline_args.contains("--area") || cmdline_args.contains("-a"))
            {
                int areaGeomIndex = cmdline_args.indexOf("--area");
                if(areaGeomIndex == -1)
                {
                    areaGeomIndex = cmdline_args.indexOf("-a");
                }
                areaGeomIndex += 1;
                if(areaGeomIndex > 0 && areaGeomIndex < cmdline_args.count())
                {
                    QString areaString = cmdline_args.at(areaGeomIndex);
                    INFO("Grabbing area (" + areaString + ")");
                    QRect area(QPoint(areaString.split(",")[0].toUInt(), areaString.split(",")[1].toUInt()), QSize(areaString.split(",")[2].toUInt(), areaString.split(",")[3].toUInt()));
                    screenshot = screenShooter.captureSelection(area);
                }else
                {
                    CRITICAL("No area provided. Format: --area x,y,width,height. Example: --area 0,0,640,480");
                    return 1;
                }
            }
            else if(cmdline_args.contains("--window") || cmdline_args.contains("-w"))
            {
                //Get the window id
                int winIdIndex = cmdline_args.indexOf("--window");
                if(winIdIndex == -1)
                {
                    winIdIndex = cmdline_args.indexOf("-w");
                }
                winIdIndex += 1;
                if(winIdIndex > 0 && winIdIndex < cmdline_args.count())
                {
                    WId windowId = (WId)cmdline_args.at(winIdIndex).toInt();
                    INFO("Grabbing window with id " + QString::number((int)windowId));
                    screenshot = screenShooter.captureWindow(windowId);
                }else
                {
                    CRITICAL("No window id provided.");
                    return 1;
                }
            }
            else
            {
                //Default to fullscreen
                if(!cmdline_args.contains("--fullscreen") && !cmdline_args.contains("-f"))
                {
                    INFO("No --area or --window set. Defaulting to fullscreen.");
                }else
                {
                    INFO("Capturing fullscreen.")
                }
                screenshot = screenShooter.captureFullscreen();
            }
            UploadManager up;
            QString serviceShortname = up.getDefaultService();
            if(serviceShortname.isEmpty())
            {
                if(cmdline_args.contains("--service") || cmdline_args.contains("-s"))
                {
                    int serviceNameIndex = cmdline_args.indexOf("--service");
                    if(serviceNameIndex == -1)
                    {
                        serviceNameIndex = cmdline_args.indexOf("-s");
                    }
                    serviceNameIndex += 1;
                    serviceShortname = cmdline_args.at(serviceNameIndex);
                }else
                {
                    CRITICAL("No --service set and no default was found.");
                    return 1;
                }
            }
            up.upload(screenshot, serviceShortname, up.getUploader(serviceShortname)->getFilename(), true);
            retcode = 0;
        }else
        {
            //Show GUI
            if(firstRun)
Beispiel #11
0
static void
gdkevent_dispatcher (GdkEvent *event,
                     gpointer  data)
{
	GDBusMessage *message;
	GError *error = NULL;

	message = g_dbus_message_new_method_call(NULL, "/",
	                                         "org.perfkit.Agent.GdkEvent",
	                                         "Event");

	switch (event->type) {
   case GDK_TOUCH_BEGIN:
   case GDK_TOUCH_END:
   case GDK_TOUCH_UPDATE:
   case GDK_TOUCH_CANCEL:
	case GDK_NOTHING:
		break;
	case GDK_DELETE:
		gdkevent_handle_any(event, connection);
		break;
	case GDK_DESTROY:
		gdkevent_handle_destroy(event, connection);
		break;
	case GDK_EXPOSE:
		gdkevent_handle_expose(event, message, connection);
		break;
	case GDK_MOTION_NOTIFY:
		gdkevent_handle_motion_notfiy(event, connection);
		break;
	case GDK_BUTTON_PRESS:
	case GDK_2BUTTON_PRESS:
	case GDK_3BUTTON_PRESS:
	case GDK_BUTTON_RELEASE:
		gdkevent_handle_button(event, connection);
		break;
	case GDK_KEY_PRESS:
	case GDK_KEY_RELEASE:
		gdkevent_handle_key(event, connection);
		break;
	case GDK_ENTER_NOTIFY:
	case GDK_LEAVE_NOTIFY:
		gdkevent_handle_crossing(event, connection);
		break;
	case GDK_FOCUS_CHANGE:
		gdkevent_handle_focus(event, connection);
		break;
	case GDK_CONFIGURE:
		gdkevent_handle_configure(event, connection);
		break;
	case GDK_MAP:
	case GDK_UNMAP:
		gdkevent_handle_any(event, connection);
		break;
	case GDK_PROPERTY_NOTIFY:
	case GDK_SELECTION_CLEAR:
	case GDK_SELECTION_REQUEST:
	case GDK_SELECTION_NOTIFY:
	case GDK_PROXIMITY_IN:
	case GDK_PROXIMITY_OUT:
	case GDK_DRAG_ENTER:
	case GDK_DRAG_LEAVE:
	case GDK_DRAG_MOTION:
	case GDK_DRAG_STATUS:
	case GDK_DROP_START:
	case GDK_DROP_FINISHED:
	case GDK_CLIENT_EVENT:
	case GDK_VISIBILITY_NOTIFY:
#if !GTK_CHECK_VERSION(2, 91, 0)
	case GDK_NO_EXPOSE:
#endif
	case GDK_SCROLL:
	case GDK_WINDOW_STATE:
	case GDK_SETTING:
	case GDK_OWNER_CHANGE:
	case GDK_GRAB_BROKEN:
	case GDK_DAMAGE:
	case GDK_EVENT_LAST:
	default:
		/*
		 * TODO: Handle more of these specificaly.
		 */
		gdkevent_handle_any(event, connection);
		break;
	}

	if (!g_dbus_connection_send_message(connection, message,
	                                    G_DBUS_SEND_MESSAGE_FLAGS_NONE,
	                                    NULL, &error)) {
		CRITICAL(Gdk, "Error sending message: %s", error->message);
		g_error_free(error);
	}

	gtk_main_do_event(event);
}
Beispiel #12
0
int EwkMain::initialize()
{
    if (m_initCount)
        return ++m_initCount;

    if (!eina_init()) {
        EINA_LOG_CRIT("could not init eina.");
        return 0;
    }

    m_logDomainId = eina_log_domain_register("ewebkit2", EINA_COLOR_ORANGE);
    if (m_logDomainId < 0) {
        EINA_LOG_CRIT("could not register log domain 'ewebkit2'");
        shutdownInitializedEFLModules(EFLModuleInitFailure::EinaLog);
        return 0;
    }

    if (!evas_init()) {
        CRITICAL("could not init evas.");
        shutdownInitializedEFLModules(EFLModuleInitFailure::Evas);
        return 0;
    }

    if (!ecore_init()) {
        CRITICAL("could not init ecore.");
        shutdownInitializedEFLModules(EFLModuleInitFailure::Ecore);
        return 0;
    }

    if (!ecore_evas_init()) {
        CRITICAL("could not init ecore_evas.");
        shutdownInitializedEFLModules(EFLModuleInitFailure::EcoreEvas);
        return 0;
    }

    if (!ecore_imf_init()) {
        CRITICAL("could not init ecore_imf.");
        shutdownInitializedEFLModules(EFLModuleInitFailure::EcoreImf);
        return 0;
    }

    if (!efreet_init()) {
        CRITICAL("could not init efreet.");
        shutdownInitializedEFLModules(EFLModuleInitFailure::Efreet);
        return 0;
    }

#ifdef HAVE_ECORE_X
    if (!ecore_x_init(0)) {
        CRITICAL("could not init ecore_x.");
        shutdownInitializedEFLModules(EFLModuleInitFailure::EcoreX);
        return 0;
    }
#endif

    if (!edje_init()) {
        CRITICAL("Could not init edje.");
        shutdownInitializedEFLModules(EFLModuleInitFailure::Edje);
        return 0;
    }

    if (!ecore_main_loop_glib_integrate()) {
        WARN("Ecore was not compiled with GLib support, some plugins will not "
            "work (ie: Adobe Flash)");
    }

    return ++m_initCount;
}
Beispiel #13
0
/*-------------------------------------------------------------------------*/
int main(int argc, char **argv)
{
   int ret;
   int my_pid;
   int ret_val;
   int printed_points = 0;
   int max_enroll_tries;
   static char tmp_err_file_name[SGE_PATH_MAX];
   time_t next_prof_output = 0;
   int execd_exit_state = 0;
   lList **master_job_list = NULL;
   sge_gdi_ctx_class_t *ctx = NULL;
   lList *alp = NULL;

   DENTER_MAIN(TOP_LAYER, "execd");

#if defined(LINUX)
   gen_procList ();
#endif

   prof_mt_init();

   set_thread_name(pthread_self(),"Execd Thread");

   prof_set_level_name(SGE_PROF_CUSTOM1, "Execd Thread", NULL); 
   prof_set_level_name(SGE_PROF_CUSTOM2, "Execd Dispatch", NULL); 

#ifdef __SGE_COMPILE_WITH_GETTEXT__  
   /* init language output for gettext() , it will use the right language */
   sge_init_language_func((gettext_func_type)        gettext,
                         (setlocale_func_type)      setlocale,
                         (bindtextdomain_func_type) bindtextdomain,
                         (textdomain_func_type)     textdomain);
   sge_init_language(NULL,NULL);   
#endif /* __SGE_COMPILE_WITH_GETTEXT__  */

   /* This needs a better solution */
   umask(022);
      
   /* Initialize path for temporary logging until we chdir to spool */
   my_pid = getpid();
   sprintf(tmp_err_file_name,"%s."sge_U32CFormat"", TMP_ERR_FILE_EXECD, sge_u32c(my_pid));
   log_state_set_log_file(tmp_err_file_name);

   /* exit func for SGE_EXIT() */
   sge_sig_handler_in_main_loop = 0;
   sge_setup_sig_handlers(EXECD);

   if (sge_setup2(&ctx, EXECD, MAIN_THREAD, &alp, false) != AE_OK) {
      answer_list_output(&alp);
      SGE_EXIT((void**)&ctx, 1);
   }
   ctx->set_exit_func(ctx, execd_exit_func);
   
#if defined(SOLARIS)
   /* Init shared SMF libs if necessary */
   if (sge_smf_used() == 1 && sge_smf_init_libs() != 0) {
       SGE_EXIT((void**)&ctx, 1);
   }
#endif

   /* prepare daemonize */
   if (!getenv("SGE_ND")) {
      sge_daemonize_prepare(ctx);
   }

   if ((ret=sge_occupy_first_three())>=0) {
      CRITICAL((SGE_EVENT, MSG_FILE_REDIRECTFD_I, ret));
      SGE_EXIT((void**)&ctx, 1);
   }

   lInit(nmv);

   /* unset XAUTHORITY if set */
   if (getenv("XAUTHORITY") != NULL) {
      sge_unsetenv("XAUTHORITY");
   }

   parse_cmdline_execd(argv);   
   
   /* exit if we can't get communication handle (bind port) */
   max_enroll_tries = 30;
   while (cl_com_get_handle(prognames[EXECD],1) == NULL) {
      ctx->prepare_enroll(ctx);
      max_enroll_tries--;

      if (max_enroll_tries <= 0 || shut_me_down) {
         /* exit after 30 seconds */
         if (printed_points != 0) {
            printf("\n");
         }
         CRITICAL((SGE_EVENT, MSG_COM_ERROR));
         SGE_EXIT((void**)&ctx, 1);
      }
      if (cl_com_get_handle(prognames[EXECD],1) == NULL) {
        /* sleep when prepare_enroll() failed */
        sleep(1);
        if (max_enroll_tries < 27) {
           printf(".");
           printed_points++;
           fflush(stdout);
        }
      }
   }

   if (printed_points != 0) {
      printf("\n");
   }

   /*
    * now the commlib up and running. Set execd application status function 
    * ( commlib callback function for qping status information response 
    *   messages (SIRM) )
    */
   ret_val = cl_com_set_status_func(sge_execd_application_status);
   if (ret_val != CL_RETVAL_OK) {
      ERROR((SGE_EVENT, cl_get_error_text(ret_val)) );
   }

   /* test connection */
   {
      cl_com_SIRM_t* status = NULL;
      ret_val = cl_commlib_get_endpoint_status(ctx->get_com_handle(ctx),
                                               (char *)ctx->get_master(ctx, true),
                                               (char*)prognames[QMASTER], 1, &status);
      if (ret_val != CL_RETVAL_OK) {
         ERROR((SGE_EVENT, cl_get_error_text(ret_val)));
         ERROR((SGE_EVENT, MSG_CONF_NOCONFBG));
      }
      cl_com_free_sirm_message(&status);
   }
   
   /* finalize daeamonize */
   if (!getenv("SGE_ND")) {
      sge_daemonize_finalize(ctx);
   }

   /* daemonizes if qmaster is unreachable */   
   sge_setup_sge_execd(ctx, tmp_err_file_name);

   /* are we using qidle or not */
   sge_ls_qidle(mconf_get_use_qidle());
   sge_ls_gnu_ls(1);
   
   DPRINTF(("use_qidle: %d\n", mconf_get_use_qidle()));

   /* test load sensor (internal or external) */
   {
      lList *report_list = sge_build_load_report(ctx->get_qualified_hostname(ctx), ctx->get_binary_path(ctx));
      lFreeList(&report_list);
   }
   
   /* here we have to wait for qmaster registration */
   while (sge_execd_register_at_qmaster(ctx, false) != 0) {
      if (sge_get_com_error_flag(EXECD, SGE_COM_ACCESS_DENIED, true)) {
         /* This is no error */
         DPRINTF(("*****  got SGE_COM_ACCESS_DENIED from qmaster  *****\n"));
      }
      if (sge_get_com_error_flag(EXECD, SGE_COM_ENDPOINT_NOT_UNIQUE, false)) {
         execd_exit_state = SGE_COM_ENDPOINT_NOT_UNIQUE;
         break;
      }
      if (shut_me_down != 0) {
         break;
      }
      sleep(30);
   }

   /* 
    * Terminate on SIGTERM or hard communication error
    */
   if (execd_exit_state != 0 || shut_me_down != 0) {
      sge_shutdown((void**)&ctx, execd_exit_state);
      DRETURN(execd_exit_state);
   }

   /*
    * We write pid file when we are connected to qmaster. Otherwise an old
    * execd might overwrite our pidfile.
    */
   sge_write_pid(EXECD_PID_FILE);

   /*
    * At this point we are sure we are the only sge_execd and we are connected
    * to the current qmaster. First we have to report any reaped children
    * that might exist.
    */
   starting_up();

   /*
    * Log a warning message if execd hasn't been started by a superuser
    */
   if (!sge_is_start_user_superuser()) {
      WARNING((SGE_EVENT, MSG_SWITCH_USER_NOT_ROOT));
   }   

#ifdef COMPILE_DC
   if (ptf_init()) {
      CRITICAL((SGE_EVENT, MSG_EXECD_NOSTARTPTF));
      SGE_EXIT((void**)&ctx, 1);
   }
   INFO((SGE_EVENT, MSG_EXECD_STARTPDCANDPTF));
#endif

   master_job_list = object_type_get_master_list(SGE_TYPE_JOB);
   *master_job_list = lCreateList("Master_Job_List", JB_Type);
   job_list_read_from_disk(master_job_list, "Master_Job_List",
                           0, SPOOL_WITHIN_EXECD, 
                          job_initialize_job);
   

   /* clean up jobs hanging around (look in active_dir) */
   clean_up_old_jobs(ctx, 1);
   execd_trash_load_report();
   sge_set_flush_lr_flag(true);

   sge_sig_handler_in_main_loop = 1;

   if (thread_prof_active_by_id(pthread_self())) {
      prof_start(SGE_PROF_CUSTOM1, NULL);
      prof_start(SGE_PROF_CUSTOM2, NULL);
      prof_start(SGE_PROF_GDI_REQUEST, NULL);
   } else {
      prof_stop(SGE_PROF_CUSTOM1, NULL);
      prof_stop(SGE_PROF_CUSTOM2, NULL);
      prof_stop(SGE_PROF_GDI_REQUEST, NULL);
   }

   PROF_START_MEASUREMENT(SGE_PROF_CUSTOM1);

   /* Start dispatching */
   execd_exit_state = sge_execd_process_messages(ctx);


   /*
    * This code is only reached when dispatcher terminates and execd goes down.
    */

   /* log if we received SIGPIPE signal */
   if (sge_sig_handler_sigpipe_received) {
       sge_sig_handler_sigpipe_received = 0;
       INFO((SGE_EVENT, "SIGPIPE received\n"));
   }

#if defined(LINUX)
   free_procList();
#endif
   lFreeList(master_job_list);

   PROF_STOP_MEASUREMENT(SGE_PROF_CUSTOM1);
   if (prof_is_active(SGE_PROF_ALL)) {
     time_t now = (time_t)sge_get_gmt();

      if (now > next_prof_output) {
         prof_output_info(SGE_PROF_ALL, false, "profiling summary:\n");
         prof_reset(SGE_PROF_ALL,NULL);
         next_prof_output = now + 60;
      }
   }
   sge_prof_cleanup();

   sge_shutdown((void**)&ctx, execd_exit_state);
   DRETURN(execd_exit_state);
}
/****** qmaster/sge_qmaster_main/main() ****************************************
*  NAME
*     main() -- qmaster entry point 
*
*  SYNOPSIS
*     int main(int argc, char* argv[]) 
*
*  FUNCTION
*     Qmaster entry point.
*
*     NOTE: The main thread must block all signals before any additional thread
*     is created. Failure to do so will ruin signal handling!
*
*  INPUTS
*     int argc     - number of commandline arguments 
*     char* argv[] - commandline arguments 
*
*  RESULT
*     0 - success 
*
*  NOTES
*     We check whether 'SGE_ROOT' is set before we daemonize. Once qmaster is
*     a daemon, we are no longer connected to a terminal and hence can not
*     output an error message to stdout or stderr.
*
*     We need to inovke 'prepare_enroll()' *before* the user id is switched via
*     'become_admin_user()'. This is because qmaster must be able to bind a so
*     called reserved port (requires root privileges) if configured to do so.
*
*******************************************************************************/
int main(int argc, char* argv[])
{
   int max_enroll_tries;
   int ret_val;
   int file_descriptor_settings_result = 0;
   bool has_daemonized = false;
   sge_gdi_ctx_class_t *ctx = NULL;
   u_long32 start_time = sge_get_gmt();
   monitoring_t monitor;

   DENTER_MAIN(TOP_LAYER, "qmaster");

   sge_monitor_init(&monitor, "MAIN", NONE_EXT, MT_WARNING, MT_ERROR);
   prof_mt_init();

   sge_get_root_dir(true, NULL, 0, true);
   
#ifdef __SGE_COMPILE_WITH_GETTEXT__  
   sge_init_language_func((gettext_func_type)gettext, (setlocale_func_type)setlocale, (bindtextdomain_func_type)bindtextdomain, (textdomain_func_type)textdomain);
   sge_init_language(NULL,NULL);   
#endif 

   /* 
    * qmaster doesn't support any commandline anymore,
    * but we should show version string and -help option 
    */
   if (argc != 1) {
      sigset_t sig_set;
      sigfillset(&sig_set);
      pthread_sigmask(SIG_SETMASK, &sig_set, NULL);
      sge_qmaster_thread_init(&ctx, QMASTER, MAIN_THREAD, true);
      sge_process_qmaster_cmdline(argv);
      SGE_EXIT((void**)&ctx, 1);
   }

   /*
    * daemonize qmaster
    * set file descriptor limits
    * and initialize libraries to be used in multi threaded environment
    * also take care that finished child processed of this process become
    * zombie jobs
    */
   has_daemonized = sge_daemonize_qmaster();
   file_descriptor_settings_result = set_file_descriptor_limit();
#if !defined(INTERIX) && !defined(CYGWIN)
   init_sig_action_and_mask();
#endif

   /* init qmaster threads without becomming admin user */
   sge_qmaster_thread_init(&ctx, QMASTER, MAIN_THREAD, false);

   ctx->set_daemonized(ctx, has_daemonized);

   /* this must be done as root user to be able to bind ports < 1024 */
   max_enroll_tries = 30;
   while (cl_com_get_handle(prognames[QMASTER],1) == NULL) {
      ctx->prepare_enroll(ctx);
      max_enroll_tries--;
      if (max_enroll_tries <= 0) {
         /* exit after 30 seconds */
         CRITICAL((SGE_EVENT, MSG_QMASTER_COMMUNICATION_ERRORS ));
         SGE_EXIT((void**)&ctx, 1);
      }
      if (cl_com_get_handle(prognames[QMASTER],1) == NULL) {
        /* sleep when prepare_enroll() failed */
        sleep(1);
      }
   }

   /*
    * now the commlib up and running. Set qmaster application status function 
    * (commlib callback function for qping status information response 
    *  messages (SIRM))
    */
   ret_val = cl_com_set_status_func(sge_qmaster_application_status);
   if (ret_val != CL_RETVAL_OK) {
      ERROR((SGE_EVENT, cl_get_error_text(ret_val)));
   }

   /* 
    * now we become admin user change into the correct root directory set the
    * the target for logging messages
    */
   sge_become_admin_user(ctx->get_admin_user(ctx));
   sge_chdir_exit(ctx->get_qmaster_spool_dir(ctx), 1);
   log_state_set_log_file(ERR_FILE);
   ctx->set_exit_func(ctx, sge_exit_func);

#if defined(SOLARIS)
   /* Init shared SMF libs if necessary */
   if (sge_smf_used() == 1 && sge_smf_init_libs() != 0) {
       SGE_EXIT((void**)&ctx, 1);
   }
#endif

   /*
    * We do increment the heartbeat manually here. This is the 'startup heartbeat'. 
    * The first time the hearbeat will be incremented through the heartbeat event 
    * handler is after about HEARTBEAT_INTERVAL seconds. The hardbeat event handler
    * is setup during the initialisazion of the timer thread.
    */
   inc_qmaster_heartbeat(QMASTER_HEARTBEAT_FILE, HEARTBEAT_INTERVAL, NULL);
     
   /*
    * Event master module has to be initialized already here because
    * sge_setup_qmaster() might already access it although event delivery
    * thread is not running.
    *
    * Corresponding shutdown is done in sge_event_master_terminate();
    *
    * EB: In my opinion the init function should called in
    * sge_event_master_initialize(). Is it possible to move that call?
    */ 
   sge_event_master_init();

   sge_setup_qmaster(ctx, argv);

#ifndef USE_POLL
   if (file_descriptor_settings_result == 1) {
      WARNING((SGE_EVENT, MSG_QMASTER_FD_SETSIZE_LARGER_THAN_LIMIT_U, sge_u32c(FD_SETSIZE)));
      WARNING((SGE_EVENT, MSG_QMASTER_FD_SETSIZE_COMPILE_MESSAGE1_U, sge_u32c(FD_SETSIZE - 20)));
      WARNING((SGE_EVENT, MSG_QMASTER_FD_SETSIZE_COMPILE_MESSAGE2));
      WARNING((SGE_EVENT, MSG_QMASTER_FD_SETSIZE_COMPILE_MESSAGE3));
   }
#endif

   /*
    * Setup all threads and initialize corresponding modules. 
    * Order is important!
    */
   sge_signaler_initialize(ctx);
   sge_event_master_initialize(ctx);
   sge_timer_initialize(ctx, &monitor);
   sge_worker_initialize(ctx);
#if 0
   sge_test_initialize(ctx);
#endif
   sge_listener_initialize(ctx);
   sge_scheduler_initialize(ctx, NULL);
#ifndef NO_JNI
   sge_jvm_initialize(ctx, NULL);
#endif

   INFO((SGE_EVENT, "qmaster startup took "sge_u32" seconds", sge_get_gmt() - start_time));

   /*
    * Block till signal from signal thread arrives us
    */
   sge_thread_wait_for_signal();

   /* 
    * Shutdown all threads and shutdown corresponding modules.
    * Order is important!
    */
#ifndef NO_JNI
   sge_jvm_terminate(ctx, NULL);
#endif
   sge_scheduler_terminate(ctx, NULL);
   sge_listener_terminate();
#if 0
   sge_test_terminate(ctx);
#endif
   sge_worker_terminate(ctx);
   sge_timer_terminate();
   sge_event_master_terminate();
   sge_signaler_terminate();

   /*
    * Remaining shutdown operations
    */
   sge_clean_lists();
   sge_monitor_free(&monitor);

   sge_shutdown((void**)&ctx, sge_qmaster_get_exit_state());
   sge_prof_cleanup();

   DEXIT;
   return 0;
} /* main() */
Beispiel #15
0
void
applyConfig(dictionary *baseConfig, RunTimeOpts *rtOpts, PtpClock *ptpClock)
{

	Boolean reloadSuccessful = TRUE;


	/* Load default config to fill in the blanks in the config file */
	RunTimeOpts tmpOpts;
	loadDefaultSettings(&tmpOpts);

	/* Check the new configuration for errors, fill in the blanks from defaults */
	if( ( rtOpts->candidateConfig = parseConfig(CFGOP_PARSE, NULL, baseConfig, &tmpOpts)) == NULL ) {
	    WARNING("Configuration has errors, reload aborted\n");
	    return;
	}

	/* Check for changes between old and new configuration */
	if(compareConfig(rtOpts->candidateConfig,rtOpts->currentConfig)) {
	    INFO("Configuration unchanged\n");
	    goto cleanup;
	}

	/*
	 * Mark which subsystems have to be restarted. Most of this will be picked up by doState()
	 * If there are errors past config correctness (such as non-existent NIC,
	 * or lock file clashes if automatic lock files used - abort the mission
	 */

	rtOpts->restartSubsystems =
	    checkSubsystemRestart(rtOpts->candidateConfig, rtOpts->currentConfig, rtOpts);

	/* If we're told to re-check lock files, do it: tmpOpts already has what rtOpts should */
	if( (rtOpts->restartSubsystems & PTPD_CHECK_LOCKS) &&
	    tmpOpts.autoLockFile && !checkOtherLocks(&tmpOpts)) {
		reloadSuccessful = FALSE;
	}

	/* If the network configuration has changed, check if the interface is OK */
	if(rtOpts->restartSubsystems & PTPD_RESTART_NETWORK) {
		INFO("Network configuration changed - checking interface(s)\n");
		if(!testInterface(tmpOpts.primaryIfaceName, &tmpOpts)) {
		    reloadSuccessful = FALSE;
		    ERROR("Error: Cannot use %s interface\n",tmpOpts.primaryIfaceName);
		}
		if(rtOpts->backupIfaceEnabled && !testInterface(tmpOpts.backupIfaceName, &tmpOpts)) {
		    rtOpts->restartSubsystems = -1;
		    ERROR("Error: Cannot use %s interface as backup\n",tmpOpts.backupIfaceName);
		}
	}
#if (defined(linux) && defined(HAVE_SCHED_H)) || defined(HAVE_SYS_CPUSET_H) || defined(__QNXNTO__)
        /* Changing the CPU affinity mask */
        if(rtOpts->restartSubsystems & PTPD_CHANGE_CPUAFFINITY) {
                NOTIFY("Applying CPU binding configuration: changing selected CPU core\n");

                if(setCpuAffinity(tmpOpts.cpuNumber) < 0) {
                        if(tmpOpts.cpuNumber == -1) {
                                ERROR("Could not unbind from CPU core %d\n", rtOpts->cpuNumber);
                        } else {
                                ERROR("Could bind to CPU core %d\n", tmpOpts.cpuNumber);
                        }
			reloadSuccessful = FALSE;
                } else {
                        if(tmpOpts.cpuNumber > -1)
                                INFO("Successfully bound "PTPD_PROGNAME" to CPU core %d\n", tmpOpts.cpuNumber);
                        else
                                INFO("Successfully unbound "PTPD_PROGNAME" from cpu core CPU core %d\n", rtOpts->cpuNumber);
                }
         }
#endif

	if(!reloadSuccessful) {
		ERROR("New configuration cannot be applied - aborting reload\n");
		rtOpts->restartSubsystems = 0;
		goto cleanup;
	}


		/**
		 * Commit changes to rtOpts and currentConfig
		 * (this should never fail as the config has already been checked if we're here)
		 * However if this DOES fail, some default has been specified out of range -
		 * this is the only situation where parse will succeed but commit not:
		 * disable quiet mode to show what went wrong, then die.
		 */
		if (rtOpts->currentConfig) {
			dictionary_del(&rtOpts->currentConfig);
		}
		if ( (rtOpts->currentConfig = parseConfig(CFGOP_PARSE_QUIET, NULL, rtOpts->candidateConfig,rtOpts)) == NULL) {
			CRITICAL("************ "PTPD_PROGNAME": parseConfig returned NULL during config commit"
				 "  - this is a BUG - report the following: \n");

			if ((rtOpts->currentConfig = parseConfig(CFGOP_PARSE, NULL, rtOpts->candidateConfig,rtOpts)) == NULL)
			    CRITICAL("*****************" PTPD_PROGNAME" shutting down **********************\n");
			/*
			 * Could be assert(), but this should be done any time this happens regardless of
			 * compile options. Anyhow, if we're here, the daemon will no doubt segfault soon anyway
			 */
			abort();
		}

	/* clean up */
	cleanup:

		dictionary_del(&rtOpts->candidateConfig);
}
bool sge_bootstrap(const char *bootstrap_file, dstring *error_dstring) 
{
   bool ret = true;
   int i = 0;
   /*const char **/
   bootstrap_entry_t name[NUM_BOOTSTRAP] = { {"admin_user", true},
                                             {"default_domain", true},
                                             {"ignore_fqdn", true},
                                             {"spooling_method", true},
                                             {"spooling_lib", true}, 
                                             {"spooling_params", true},
                                             {"binary_path", true}, 
                                             {"qmaster_spool_dir", true},
                                             {"security_mode", true},
                                             {"job_spooling", false},
                                             {"listener_threads", false},
                                             {"worker_threads", false},
                                             {"scheduler_threads", false},
                                             {"jvm_threads", false}
                                     };
   char value[NUM_BOOTSTRAP][1025];

   DENTER(TOP_LAYER, "sge_bootstrap");

   for (i = 0; i < NUM_BOOTSTRAP; i++) {
      value[i][0] = '\0';
   }

   /* get filepath of bootstrap file */
   if (bootstrap_file == NULL) {
      if (error_dstring == NULL) {
         CRITICAL((SGE_EVENT, SFNMAX, MSG_UTI_CANNOTRESOLVEBOOTSTRAPFILE));
      } else {
         sge_dstring_sprintf(error_dstring, "%s", MSG_UTI_CANNOTRESOLVEBOOTSTRAPFILE);
      }
      ret = false;
   /* read bootstrapping information */   
   } else if (sge_get_confval_array(bootstrap_file, NUM_BOOTSTRAP, NUM_REQ_BOOTSTRAP, name, 
                                    value, error_dstring)) {
      ret = false;
   } else {
      /* store bootstrapping information */
      bootstrap_set_admin_user(value[0]);
      bootstrap_set_default_domain(value[1]);
      {
         u_long32 uval;
         parse_ulong_val(NULL, &uval, TYPE_BOO, value[2], 
                         NULL, 0);
         bootstrap_set_ignore_fqdn(uval ? true : false);
      }
      bootstrap_set_spooling_method(value[3]);
      bootstrap_set_spooling_lib(value[4]);
      bootstrap_set_spooling_params(value[5]);
      bootstrap_set_binary_path(value[6]);
      bootstrap_set_qmaster_spool_dir(value[7]);
      bootstrap_set_security_mode(value[8]);
      if (strcmp(value[9], "")) {
         u_long32 uval = 0;
         parse_ulong_val(NULL, &uval, TYPE_BOO, value[9], 
                         NULL, 0);
         bootstrap_set_job_spooling(uval ? true : false);
      } else {
         bootstrap_set_job_spooling(true);
      }   
      {
         u_long32 uval = 0;
         parse_ulong_val(NULL, &uval, TYPE_INT, value[10], NULL, 0);
         bootstrap_set_listener_thread_count(uval);
      }
      {
         u_long32 uval = 0;
         parse_ulong_val(NULL, &uval, TYPE_INT, value[11], NULL, 0);
         bootstrap_set_worker_thread_count(uval);
      }
      {
         u_long32 uval = 0;
         parse_ulong_val(NULL, &uval, TYPE_INT, value[12], NULL, 0);
         bootstrap_set_scheduler_thread_count(uval);
      }
      {
         u_long32 uval = 0;
         parse_ulong_val(NULL, &uval, TYPE_INT, value[13], NULL, 0);
         bootstrap_set_jvm_thread_count(uval);
      }

      DPRINTF(("admin_user          >%s<\n", bootstrap_get_admin_user()));
      DPRINTF(("default_domain      >%s<\n", bootstrap_get_default_domain()));
      DPRINTF(("ignore_fqdn         >%s<\n", bootstrap_get_ignore_fqdn() ? 
                                             "true" : "false"));
      DPRINTF(("spooling_method     >%s<\n", bootstrap_get_spooling_method()));
      DPRINTF(("spooling_lib        >%s<\n", bootstrap_get_spooling_lib()));
      DPRINTF(("spooling_params     >%s<\n", bootstrap_get_spooling_params()));
      DPRINTF(("binary_path         >%s<\n", bootstrap_get_binary_path()));
      DPRINTF(("qmaster_spool_dir   >%s<\n", bootstrap_get_qmaster_spool_dir()));
      DPRINTF(("security_mode       >%s<\n", bootstrap_get_security_mode()));
      DPRINTF(("job_spooling        >%s<\n", bootstrap_get_job_spooling() ? 
                                             "true":"false"));
      DPRINTF(("listener_threads    >%d<\n", bootstrap_get_listener_thread_count()));
      DPRINTF(("worker_threads      >%d<\n", bootstrap_get_worker_thread_count()));
      DPRINTF(("scheduler_threads   >%d<\n", bootstrap_get_scheduler_thread_count()));
      DPRINTF(("jvm_threads         >%d<\n", bootstrap_get_jvm_thread_count()));
   } 

   DEXIT;
   return ret;
}
Beispiel #17
0
/**
 * Signal handler for HUP which tells us to swap the log file
 * and reload configuration file if specified
 *
 * @param sig
 */
void
do_signal_sighup(RunTimeOpts * rtOpts, PtpClock * ptpClock)
{

    NOTIFY("SIGHUP received\n");

#ifdef RUNTIME_DEBUG
    if(rtOpts->transport == UDP_IPV4 && rtOpts->ip_mode != IPMODE_UNICAST) {
        DBG("SIGHUP - running an ipv4 multicast based mode, re-sending IGMP joins\n");
        netRefreshIGMP(&ptpClock->netPath, rtOpts, ptpClock);
    }
#endif /* RUNTIME_DEBUG */


    /* if we don't have a config file specified, we're done - just reopen log files*/
    if(strlen(rtOpts->configFile) ==  0)
        goto end;

    dictionary* tmpConfig = dictionary_new(0);
    /* Try reloading the config file */
    NOTIFY("Reloading configuration file: %s\n",rtOpts->configFile);
    if(!loadConfigFile(&tmpConfig, rtOpts)) {
        dictionary_del(tmpConfig);
        goto end;
    }
    dictionary_merge(rtOpts->cliConfig, tmpConfig, 1, "from command line");
    /* Load default config to fill in the blanks in the config file */
    RunTimeOpts tmpOpts;
    loadDefaultSettings(&tmpOpts);

    /* Check the new configuration for errors, fill in the blanks from defaults */
    if( ( rtOpts->candidateConfig = parseConfig(tmpConfig,&tmpOpts)) == NULL ) {
        WARNING("Configuration file has errors, reload aborted\n");
        dictionary_del(tmpConfig);
        goto end;
    }

    /* Check for changes between old and new configuration */
    if(compareConfig(rtOpts->candidateConfig,rtOpts->currentConfig)) {
        INFO("Configuration unchanged\n");
        goto cleanup;
    }

    /*
     * Mark which subsystems have to be restarted. Most of this will be picked up by doState()
     * If there are errors past config correctness (such as non-existent NIC,
     * or lock file clashes if automatic lock files used - abort the mission
     */

    rtOpts->restartSubsystems =
        checkSubsystemRestart(rtOpts->candidateConfig, rtOpts->currentConfig);

    /* If we're told to re-check lock files, do it: tmpOpts already has what rtOpts should */
    if( (rtOpts->restartSubsystems & PTPD_CHECK_LOCKS) &&
            tmpOpts.autoLockFile && !checkOtherLocks(&tmpOpts)) {
        rtOpts->restartSubsystems = -1;
    }

    /* If the network configuration has changed, check if the interface is OK */
    if(rtOpts->restartSubsystems & PTPD_RESTART_NETWORK) {
        INFO("Network configuration changed - checking interface\n");
        if(!testInterface(tmpOpts.ifaceName, &tmpOpts)) {
            rtOpts->restartSubsystems = -1;
            ERROR("Error: Cannot use %s interface\n",tmpOpts.ifaceName);
        }

    }


#if defined(linux) && defined(HAVE_SCHED_H)
    /* Changing the CPU affinity mask */
    if(rtOpts->restartSubsystems & PTPD_CHANGE_CPUAFFINITY) {
        NOTIFY("Applying CPU binding configuration: changing selected CPU core\n");
        cpu_set_t mask;
        CPU_ZERO(&mask);
        if(tmpOpts.cpuNumber > -1) {
            CPU_SET(tmpOpts.cpuNumber,&mask);
        } else {
            int i;
            for(i = 0;  i < CPU_SETSIZE; i++) {
                CPU_SET(i, &mask);
            }
        }
        if(sched_setaffinity(0, sizeof(mask), &mask) < 0) {
            if(tmpOpts.cpuNumber == -1) {
                PERROR("Could not unbind from CPU core %d", rtOpts->cpuNumber);
            } else {
                PERROR("Could bind to CPU core %d", tmpOpts.cpuNumber);
            }
            rtOpts->restartSubsystems = -1;
        } else {
            if(tmpOpts.cpuNumber > -1)
                INFO("Successfully bound "PTPD_PROGNAME" to CPU core %d\n", tmpOpts.cpuNumber);
            else
                INFO("Successfully unbound "PTPD_PROGNAME" from cpu core CPU core %d\n", rtOpts->cpuNumber);
        }
    }
#endif /* linux && HAVE_SCHED_H */

#ifdef HAVE_SYS_CPUSET_H
    /* Changing the CPU affinity mask */
    if (rtOpts->restartSubsystems & PTPD_CHANGE_CPUAFFINITY) {
        NOTIFY("Applying CPU binding configuration:"
               "changing selected CPU core\n");
        cpuset_t mask;
        CPU_ZERO(&mask);
        if (tmpOpts.cpuNumber < 0) {
            if (cpuset_getaffinity(CPU_LEVEL_ROOT, CPU_WHICH_CPUSET, 1,
                                   sizeof(mask), &mask) < 0)
                PERROR("Could not get affinity.");
            if (cpuset_setaffinity(CPU_LEVEL_WHICH, CPU_WHICH_PID,
                                   -1, sizeof(mask), &mask) < 0)
                PERROR("Could not unbind from CPU core %d",
                       rtOpts->cpuNumber);
            else
                INFO("Successfully unbound "
                     PTPD_PROGNAME" from cpu core CPU core %d\n",
                     rtOpts->cpuNumber);
        } else {
            CPU_SET(tmpOpts.cpuNumber,&mask);
            if (cpuset_setaffinity(CPU_LEVEL_WHICH, CPU_WHICH_PID,
                                   -1, sizeof(mask), &mask) < 0)  {
                PERROR("Could not bind to CPU core %d",
                       tmpOpts.cpuNumber);
                rtOpts->restartSubsystems = -1;
            } else {
                INFO("Successfully bound "
                     PTPD_PROGNAME" to CPU core %d\n",
                     tmpOpts.cpuNumber);
            }
        }
    }
#endif

    if(rtOpts->restartSubsystems == -1) {
        ERROR("New configuration cannot be applied - aborting reload\n");
        rtOpts->restartSubsystems = 0;
        goto cleanup;
    }


    /* Tell parseConfig to shut up - it's had its chance already */
    dictionary_set(rtOpts->candidateConfig,"%quiet%:%quiet%","Y");

    /**
     * Commit changes to rtOpts and currentConfig
     * (this should never fail as the config has already been checked if we're here)
     * However if this DOES fail, some default has been specified out of range -
     * this is the only situation where parse will succeed but commit not:
     * disable quiet mode to show what went wrong, then die.
     */
    if (rtOpts->currentConfig) {
        dictionary_del(rtOpts->currentConfig);
    }
    if ( (rtOpts->currentConfig = parseConfig(rtOpts->candidateConfig,rtOpts)) == NULL) {
        CRITICAL("************ "PTPD_PROGNAME": parseConfig returned NULL during config commit"
                 "  - this is a BUG - report the following: \n");

        dictionary_unset(rtOpts->candidateConfig,"%quiet%:%quiet%");

        if ((rtOpts->currentConfig = parseConfig(rtOpts->candidateConfig,rtOpts)) == NULL)
            CRITICAL("*****************" PTPD_PROGNAME" shutting down **********************\n");
        /*
         * Could be assert(), but this should be done any time this happens regardless of
         * compile options. Anyhow, if we're here, the daemon will no doubt segfault soon anyway
         */
        abort();
    }

    /* clean up */
cleanup:

    dictionary_del(tmpConfig);
    dictionary_del(rtOpts->candidateConfig);

end:

    if(rtOpts->recordLog.logEnabled ||
            rtOpts->eventLog.logEnabled ||
            (rtOpts->statisticsLog.logEnabled))
        INFO("Reopening log files\n");

    restartLogging(rtOpts);

    if(rtOpts->statisticsLog.logEnabled)
        ptpClock->resetStatisticsLog = TRUE;


}
Beispiel #18
0
/*-------------------------------------------------------------------*/
void sge_setup_sge_execd(sge_gdi_ctx_class_t *ctx, const char* tmp_err_file_name)
{
   char err_str[MAX_STRING_SIZE];
   int allowed_get_conf_errors     = 5;
   char* spool_dir = NULL;
   const char *unqualified_hostname = ctx->get_unqualified_hostname(ctx);
   const char *admin_user = ctx->get_admin_user(ctx);

   DENTER(TOP_LAYER, "sge_setup_sge_execd");

   /* TODO: is this the right place to switch the user ?
            ports below 1024 ok */
   /*
   ** switch to admin user
   */
   if (sge_set_admin_username(admin_user, err_str)) {
      CRITICAL((SGE_EVENT, SFNMAX, err_str));
      /* TODO: remove */
      SGE_EXIT(NULL, 1);
   }

   if (sge_switch2admin_user()) {
      CRITICAL((SGE_EVENT, SFNMAX, MSG_ERROR_CANTSWITCHTOADMINUSER));
      /* TODO: remove */
      SGE_EXIT(NULL, 1);
   }

   while (gdi2_wait_for_conf(ctx, &Execd_Config_List)) {
      if (allowed_get_conf_errors-- <= 0) {
         CRITICAL((SGE_EVENT, SFNMAX, MSG_EXECD_CANT_GET_CONFIGURATION_EXIT));
         /* TODO: remove */
         SGE_EXIT(NULL, 1);
      }
      sleep(1);
      ctx->get_master(ctx, true);
   }
   sge_show_conf();         


   /* get aliased hostname */
   /* TODO: is this call needed ? */
   ctx->reresolve_qualified_hostname(ctx);
   spool_dir = mconf_get_execd_spool_dir();

   DPRINTF(("chdir(\"/\")----------------------------\n"));
   sge_chdir_exit("/",1);
   DPRINTF(("Making directories----------------------------\n"));
   sge_mkdir(spool_dir, 0755, 1, 0);
   DPRINTF(("chdir(\"%s\")----------------------------\n", spool_dir));
   sge_chdir_exit(spool_dir,1);
   sge_mkdir(unqualified_hostname, 0755, 1, 0);
   DPRINTF(("chdir(\"%s\",me.unqualified_hostname)--------------------------\n",
            unqualified_hostname));
   sge_chdir_exit(unqualified_hostname, 1); 
   /* having passed the  previous statement we may 
      log messages into the ERR_FILE  */
   if ( tmp_err_file_name != NULL) {
      sge_copy_append((char*)tmp_err_file_name, ERR_FILE, SGE_MODE_APPEND);
   }
   sge_switch2start_user();
   if ( tmp_err_file_name != NULL) {
      unlink(tmp_err_file_name);
   }
   sge_switch2admin_user();
   log_state_set_log_as_admin_user(1);
   sprintf(execd_messages_file, "%s/%s/%s", spool_dir, 
           unqualified_hostname, ERR_FILE);
   log_state_set_log_file(execd_messages_file);

   sprintf(execd_spool_dir, "%s/%s", spool_dir, 
           unqualified_hostname);
   
   DPRINTF(("Making directories----------------------------\n"));
   sge_mkdir(EXEC_DIR, 0775, 1, 0);
   sge_mkdir(JOB_DIR, 0775, 1, 0);
   sge_mkdir(ACTIVE_DIR,  0775, 1, 0);

#if defined(PLPA_LINUX) || defined(SOLARIS86) || defined(SOLARISAMD64)
   /* initialize processor topology */
   if (initialize_topology() != true) {
      DPRINTF(("Couldn't initizalize topology-----------------------\n"));
   }
#endif

   sge_free(&spool_dir);
   DRETURN_VOID;
}
/*
 * Delete configuration 'confp' from cluster configuration.
 *
 * TODO: A fix for IZ issue #79 is needed. For this to be done it may be 
 * necessary to introduce something like 'protected' configuration entries.
 */
int 
sge_del_configuration(sge_gdi_ctx_class_t *ctx,
                      lListElem *aConf, lList **anAnswer, 
                      char *aUser, char *aHost)
{
   const char *tmp_name = NULL;
   char unique_name[CL_MAXHOSTLEN];
   int ret = -1;

   DENTER(TOP_LAYER, "sge_del_configuration");

   if (!aConf || !aUser || !aHost) {
      CRITICAL((SGE_EVENT, MSG_SGETEXT_NULLPTRPASSED_S, SGE_FUNC));
      answer_list_add(anAnswer, SGE_EVENT, 
                      STATUS_EUNKNOWN, ANSWER_QUALITY_ERROR);
      DRETURN(STATUS_EUNKNOWN);
   }
   
   if ((tmp_name = lGetHost(aConf, CONF_name)) == NULL) {
      CRITICAL((SGE_EVENT, MSG_SGETEXT_MISSINGCULLFIELD_SS, 
                lNm2Str(CONF_name), SGE_FUNC));
      answer_list_add(anAnswer, SGE_EVENT, 
                      STATUS_EUNKNOWN, ANSWER_QUALITY_ERROR);
      DRETURN(STATUS_EUNKNOWN);
   }

   /*
    * Due to CR 6319231 IZ 1760:
    *    try to resolve the hostname
    *    if it is not resolveable then
    *       ignore this and use the hostname stored in the configuration obj
    *       or use the given name if no object can be found
    */
   ret = sge_resolve_hostname(tmp_name, unique_name, EH_name, sizeof(unique_name));
   if (ret != CL_RETVAL_OK) {
      lListElem *conf_obj = NULL;
 
      DPRINTF(("%s: error %s resolving host %s\n", SGE_FUNC,
               cl_get_error_text(ret), tmp_name));
 
      conf_obj = sge_get_configuration_for_host(tmp_name);
      if (conf_obj != NULL) {
         DPRINTF(("using hostname stored in configuration object\n"));
         strcpy(unique_name, lGetHost(conf_obj, CONF_name));
         lFreeElem(&conf_obj);
      } else {
         ERROR((SGE_EVENT, MSG_SGETEXT_CANT_DEL_CONFIG2_S, tmp_name));
         answer_list_add(anAnswer, SGE_EVENT,
                         STATUS_EEXIST, ANSWER_QUALITY_ERROR);
         DRETURN(STATUS_EEXIST);
      }
   }

   /* Do not allow to delete global configuration */
   if (!strcasecmp(SGE_GLOBAL_NAME, unique_name)) {
      ERROR((SGE_EVENT, MSG_SGETEXT_CANT_DEL_CONFIG_S, unique_name));
      answer_list_add(anAnswer, SGE_EVENT, STATUS_EEXIST, ANSWER_QUALITY_ERROR);
      DRETURN(STATUS_EEXIST);
   }

   sge_event_spool(ctx, anAnswer, 0, sgeE_CONFIG_DEL, 0, 0, unique_name, NULL, NULL, NULL, NULL, NULL, true, true);
    
   remove_conf_by_name(unique_name);
   
   INFO((SGE_EVENT, MSG_SGETEXT_REMOVEDFROMLIST_SSSS, aUser, aHost, unique_name, MSG_OBJ_CONF ));
   answer_list_add(anAnswer, SGE_EVENT, STATUS_OK, ANSWER_QUALITY_INFO);
   
   update_reschedule_unknown_timout_values(unique_name);

   /* invalidate cached configuration values */
   mconf_set_new_config(true);
    
   DRETURN(STATUS_OK);
}
Beispiel #20
0
static Boolean
stepTime (ClockDriver *self, TimeInternal *delta, Boolean force) {

	GET_CONFIG_CLOCKDRIVER(self, myConfig, unix);

	if(isTimeZero(delta)) {
	    return TRUE;
	}

	struct timespec nts;

	TimeInternal oldTime,newTime;
	getTime(self, &oldTime);
	addTime(&newTime, &oldTime, delta);

	if(self->config.readOnly) {
		return FALSE;
	}

	if(force) {
	    self->lockedUp = FALSE;
	}

	if(!force && !self->config.negativeStep && isTimeNegative(delta)) {
		CRITICAL(THIS_COMPONENT"Cannot step Unix clock %s backwards\n", self->name);
		CRITICAL(THIS_COMPONENT"Manual intervention required or SIGUSR1 to force %s clock step\n", self->name);
		self->lockedUp = TRUE;
		self->setState(self, CS_NEGSTEP);
		return FALSE;
	}

#ifdef ADJ_SETOFFSET
	struct timex tmx;
	memset(&tmx, 0, sizeof(tmx));
	tmx.modes = ADJ_SETOFFSET | ADJ_NANO;

	tmx.time.tv_sec = delta->seconds;
	tmx.time.tv_usec = delta->nanoseconds;

	getTime(self, &newTime);
	addTime(&newTime, &newTime, delta);

	nts.tv_sec = newTime.seconds;

	if(nts.tv_sec == 0) {
	    ERROR(THIS_COMPONENT"Unix clock %s: cannot step time to zero seconds\n", self->name);
	    return FALSE;
	}

	if(nts.tv_sec < 0) {
	    ERROR(THIS_COMPONENT"Unix clock %s: cannot step time to a negative value %d\n", self->name, nts.tv_sec);
	    return FALSE;
	}

	if(adjtimex(&tmx) < 0) {
	    DBG("Could not set clock offset of Unix clock %s\n", self->name);
	    return setTime(self, &newTime, force);
	}

	NOTICE(THIS_COMPONENT"Unix clock %s: stepped clock by %s%d.%09d seconds\n", self->name,
		    (delta->seconds <0 || delta->nanoseconds <0) ? "-":"", delta->seconds, delta->nanoseconds);

	addTime(&_stepAccumulator, &_stepAccumulator, delta);

	self->_stepped = TRUE;

	self->setState(self, CS_FREERUN);

	if(oldTime.seconds != newTime.seconds) {
	    updateXtmp_unix(oldTime, newTime);
	    if(myConfig->setRtc) {
		setRtc(self, &newTime);
	    }
	}

	return TRUE;
#else
	return setTime(self, &newTime, force);
#endif


}
/****** qmaster/sge_mod_configuration() ****************************************
*  NAME
*     sge_mod_configuration() -- modify cluster configuration
*
*  SYNOPSIS
*     int sge_mod_configuration(lListElem *aConf, lList **anAnswer, char *aUser,
*                               char *aHost)
*
*  FUNCTION
*     Modify cluster configuration. 'confp' is a pointer to a 'CONF_Type' list
*     element and does contain the modified configuration entry. Adding a new
*     configuration entry is also viewed as a modification.
*
*  INPUTS
*     lListElem *aConf  - CONF_Type element containing the modified conf
*     lList **anAnswer  - answer list
*     char *aUser       - target user
*     char *aHost       - target host
*
*  RESULT
*     int - 0 success
*          -1 error
*
*  NOTES
*     MT-NOTE: sge_mod_configuration() is MT safe 
*
*******************************************************************************/
int sge_mod_configuration(sge_gdi_ctx_class_t *ctx, lListElem *aConf, lList **anAnswer, char *aUser, char *aHost)
{
   lListElem *old_conf;
   const char *tmp_name = NULL;
   char unique_name[CL_MAXHOSTLEN];
   int ret = -1;
   const char *cell_root = ctx->get_cell_root(ctx);
   const char *qualified_hostname = ctx->get_qualified_hostname(ctx);
   u_long32 progid = ctx->get_who(ctx);

   DENTER(TOP_LAYER, "sge_mod_configuration");

   if (!aConf || !aUser || !aHost) {
      CRITICAL((SGE_EVENT, MSG_SGETEXT_NULLPTRPASSED_S, SGE_FUNC));
      answer_list_add(anAnswer, SGE_EVENT, STATUS_EUNKNOWN, ANSWER_QUALITY_ERROR);
      DRETURN(STATUS_EUNKNOWN);
   }

   if ((tmp_name = lGetHost(aConf, CONF_name)) == NULL) {
      CRITICAL((SGE_EVENT, MSG_SGETEXT_MISSINGCULLFIELD_SS, lNm2Str(CONF_name), SGE_FUNC));
      answer_list_add(anAnswer, SGE_EVENT, STATUS_EUNKNOWN, ANSWER_QUALITY_ERROR);
      DRETURN(STATUS_EUNKNOWN);
   }

   if ((ret = sge_resolve_hostname(tmp_name, unique_name, EH_name, sizeof(unique_name)))
       != CL_RETVAL_OK) {
      DPRINTF(("%s: error %s resolving host %s\n", SGE_FUNC, cl_get_error_text(ret), tmp_name));
      ERROR((SGE_EVENT, MSG_SGETEXT_CANTRESOLVEHOST_S, tmp_name));
      answer_list_add(anAnswer, SGE_EVENT, STATUS_EUNKNOWN, ANSWER_QUALITY_ERROR);
      DRETURN(STATUS_EUNKNOWN);
   }
   
   if ((ret = check_config(anAnswer, aConf))) {
      DRETURN(ret); 
   }

   if ((old_conf = sge_get_configuration_for_host(unique_name)) != NULL) {
      int ret = -1;
      
      ret = do_mod_config(ctx, unique_name, old_conf, aConf, anAnswer);
      
      lFreeElem(&old_conf);
      
      if (ret == 0) {    
         INFO((SGE_EVENT, MSG_SGETEXT_MODIFIEDINLIST_SSSS, aUser, aHost, unique_name, MSG_OBJ_CONF));
         answer_list_add(anAnswer, SGE_EVENT, STATUS_OK, ANSWER_QUALITY_INFO);
      } else {
         DRETURN(STATUS_EUNKNOWN);
      }
   } else {
      do_add_config(ctx, unique_name, aConf, anAnswer);
            
      INFO((SGE_EVENT, MSG_SGETEXT_ADDEDTOLIST_SSSS, aUser, aHost, unique_name, MSG_OBJ_CONF));            
      answer_list_add(anAnswer, SGE_EVENT, STATUS_OK, ANSWER_QUALITY_INFO);
   }
   
   if (strcmp(SGE_GLOBAL_NAME, unique_name) == 0) {
      sge_add_event(0, sgeE_GLOBAL_CONFIG, 0, 0, NULL, NULL, NULL, NULL);
   }

   /*
   ** is the configuration change relevant for the qmaster itsself?
   ** if so, initialise conf struct anew
   */
   if (strcmp(unique_name, SGE_GLOBAL_NAME) == 0 || sge_hostcmp(unique_name, qualified_hostname) == 0) {
      lListElem *local = NULL;
      lListElem *global = NULL;
      lList *answer_list = NULL;
      char* qmaster_params = NULL;
      int accounting_flush_time = mconf_get_accounting_flush_time();

      if ((local = sge_get_configuration_for_host(qualified_hostname)) == NULL) {
         WARNING((SGE_EVENT, MSG_CONF_NOLOCAL_S, qualified_hostname));
      }
      
      if ((global = sge_get_configuration_for_host(SGE_GLOBAL_NAME)) == NULL) {
         ERROR((SGE_EVENT, SFNMAX, MSG_CONF_NOGLOBAL));
      }
            
      if (merge_configuration(&answer_list, progid, cell_root, global, local, NULL) != 0) {
         ERROR((SGE_EVENT, MSG_CONF_CANTMERGECONFIGURATIONFORHOST_S, qualified_hostname));
      }
      answer_list_output(&answer_list);

      /* Restart the accounting flush event if needed. */
      if ((accounting_flush_time == 0) &&
          (mconf_get_accounting_flush_time() != 0)) {
         te_event_t ev = te_new_event(time(NULL), TYPE_ACCOUNTING_TRIGGER, ONE_TIME_EVENT, 1, 0, NULL);
         te_add_event(ev);
         te_free_event(&ev);
      }
      
      lFreeElem(&local);
      lFreeElem(&global);
      
      sge_show_conf();

      /* 'max_unheard' may have changed */
      cl_commlib_set_connection_param(cl_com_get_handle("qmaster", 1), HEARD_FROM_TIMEOUT, mconf_get_max_unheard());

      /* fetching qmaster_params and begin to parse */
      qmaster_params = mconf_get_qmaster_params();

      /* updating the commlib paramterlist and gdi_timeout with new or changed parameters */
      cl_com_update_parameter_list(qmaster_params);

      sge_free(&qmaster_params);
   }
    
   /* invalidate configuration cache */
   mconf_set_new_config(true);
   
   DRETURN(STATUS_OK);
}
Beispiel #22
0
/**
 * Client request entry point
 */
void SoundPlayer::play(const std::string& filePath, const std::string& streamClass, bool repeat, int duration)
{
	WARNING("SoundPlayer::play(%s): %p: filePath: %s, streamClass: %s, repeat: %d, duration: %d",
			  getStateName(), this, filePath.c_str(), streamClass.c_str(), repeat, duration);

	if (m_state == eState_Dead)
	{
		CRITICAL("SoundPlayer::play(%s): This player can not be reused!", getStateName());
		return;
	}

	if (m_state != eState_Init)
		stop();

	// recycling? move state machine back
	if (m_state == eState_Finished)
		setState(eState_Connected);

	m_filePath = filePath;
	m_streamClass = streamClass;
	m_audioStreamClass = kAudioStreamMedia;

	if (!m_streamClass.empty())
	{
		if (m_streamClass == "ringtones")
			m_audioStreamClass = kAudioStreamRingtone;

		else if (m_streamClass == "alarm")
			m_audioStreamClass = kAudioStreamAlarm;

		else if (m_streamClass == "alerts")
			m_audioStreamClass = kAudioStreamAlert;

		else if (m_streamClass == "notifications")
			m_audioStreamClass = kAudioStreamNotification;

		else if (m_streamClass == "calendar")
			m_audioStreamClass = kAudioStreamCalendar;

		else if (m_streamClass == "media")
			m_audioStreamClass = kAudioStreamMedia;

		else if (m_streamClass == "voicedial")
			m_audioStreamClass = kAudioStreamVoicedial;

		else if (m_streamClass == "flash")
			m_audioStreamClass = kAudioStreamFlash;

		else if (m_streamClass == "navigation")
			m_audioStreamClass = kAudioStreamNavigation;

		else if (m_streamClass == "defaultapp")
			m_audioStreamClass = kAudioStreamDefaultapp;

		else if (m_streamClass == "feedback")
			m_audioStreamClass = kAudioStreamFeedback;

		else
		{
			WARNING("SoundPlayer::play: unrecognized media class '%s' for '%s'. Will use media class.", streamClass.c_str(), filePath.c_str());
			m_audioStreamClass = kAudioStreamMedia;
		}
	}

	m_repeat = repeat;
	m_duration = float(duration) / 1000.f;	// integer ms to float seconds
	checkForNextStep();
}
Beispiel #23
0
int ewk_init(void)
{
    if (_ewk_init_count)
        return ++_ewk_init_count;

    if (!eina_init())
        goto error_eina;

    _ewk_log_dom = eina_log_domain_register("ewebkit", EINA_COLOR_ORANGE);
    if (_ewk_log_dom < 0) {
        EINA_LOG_CRIT("could not register log domain 'ewebkit'");
        goto error_log_domain;
    }

    if (!evas_init()) {
        CRITICAL("could not init evas.");
        goto error_evas;
    }

    if (!ecore_init()) {
        CRITICAL("could not init ecore.");
        goto error_ecore;
    }

    if (!ecore_evas_init()) {
        CRITICAL("could not init ecore_evas.");
        goto error_ecore_evas;
    }

    if (!edje_init()) {
        CRITICAL("could not init edje.");
        goto error_edje;
    }

#ifdef ENABLE_GLIB_SUPPORT
    g_type_init();

    if (!g_thread_supported())
        g_thread_init(0);

#ifdef ENABLE_GTK_PLUGINS_SUPPORT
    gdk_threads_init();
    if (!gtk_init_check(0, 0))
        WRN("Could not initialize GTK support.");
#endif

    if (!ecore_main_loop_glib_integrate())
        WRN("Ecore was not compiled with GLib support, some plugins will not "
            "work (ie: Adobe Flash)");
#endif

    JSC::initializeThreading();
    WTF::initializeMainThread();
    WebCore::InitializeLoggingChannelsIfNecessary();

    // Page cache capacity (in pages). Comment from Mac port:
    // (Research indicates that value / page drops substantially after 3 pages.)
    // FIXME: Expose this with an API and/or calculate based on available resources
    WebCore::pageCache()->setCapacity(3);
    WebCore::PageGroup::setShouldTrackVisitedLinks(true);

    // TODO: this should move to WebCore, already reported to webkit-gtk folks:
    if (1) {
        SoupSession* session = WebCore::ResourceHandle::defaultSession();
        soup_session_add_feature_by_type(session, SOUP_TYPE_CONTENT_SNIFFER);
    }

    return ++_ewk_init_count;

error_edje:
    ecore_evas_shutdown();
error_ecore_evas:
    ecore_shutdown();
error_ecore:
    evas_shutdown();
error_evas:
    eina_log_domain_unregister(_ewk_log_dom);
    _ewk_log_dom = -1;
error_log_domain:
    eina_shutdown();
error_eina:
    return 0;
}
Beispiel #24
0
int ewk_init(void)
{
    if (_ewkInitCount)
        return ++_ewkInitCount;

    if (!eina_init())
        goto error_eina;

    _ewk_log_dom = eina_log_domain_register("ewebkit2", EINA_COLOR_ORANGE);
    if (_ewk_log_dom < 0) {
        EINA_LOG_CRIT("could not register log domain 'ewebkit2'");
        goto error_log_domain;
    }

    if (!evas_init()) {
        CRITICAL("could not init evas.");
        goto error_evas;
    }

    if (!ecore_init()) {
        CRITICAL("could not init ecore.");
        goto error_ecore;
    }

    if (!ecore_evas_init()) {
        CRITICAL("could not init ecore_evas.");
        goto error_ecore_evas;
    }

#ifdef HAVE_ECORE_X
    if (!ecore_x_init(0)) {
        CRITICAL("could not init ecore_x.");
        goto error_ecore_x;
    }
#endif

    g_type_init();

    if (!ecore_main_loop_glib_integrate()) {
        WARN("Ecore was not compiled with GLib support, some plugins will not "
            "work (ie: Adobe Flash)");
    }

    return ++_ewkInitCount;

#ifdef HAVE_ECORE_X
error_ecore_x:
    ecore_evas_shutdown();
#endif
error_ecore_evas:
    ecore_shutdown();
error_ecore:
    evas_shutdown();
error_evas:
    eina_log_domain_unregister(_ewk_log_dom);
    _ewk_log_dom = -1;
error_log_domain:
    eina_shutdown();
error_eina:
    return 0;
}
Beispiel #25
0
void KinectOpenNI::setDeviceid(int id)
{
	try{
    if(id==_deviceid)
    {
        return;
    }

    if(_kinectlist.contains(id))
    {
        return;
    }

	disconnect();

    QMutexLocker locker(&_mutex);

    XnStatus status = g_context.Init();

    checkXnError(status, "Initialize context");



    //XnStatus status;
    xn::NodeInfoList device_node_info_list;
    status = g_context.EnumerateProductionTrees(XN_NODE_TYPE_DEVICE, NULL, device_node_info_list);
    checkXnError(status, "Cannot enumerate devices.");
    xn::NodeInfoList::Iterator nodeIt = device_node_info_list.Begin();
    int current_id = 0;
    for (; current_id < id && nodeIt != device_node_info_list.End (); ++nodeIt, ++current_id) {}
    
    xn::NodeInfo deviceInfo = *nodeIt;


	
    status = g_context.CreateProductionTree(deviceInfo, g_device);
    checkXnError(status, "Create Device Node");

    const XnProductionNodeDescription& description = deviceInfo.GetDescription();

	


    #ifdef UNIX_BUILD
        _serial = getKinectSerial(id);
    #else
    char* infoChr = (char*)deviceInfo.GetCreationInfo();
    if(0!=infoChr)
    {
        QString info(infoChr);
        QStringList list = info.split('#');
        if(list.count()>2)
        {
            _serial = list[2].toUpper();
            //eebug() << description.strVendor << description.strName << deviceInfo.GetInstanceName() << _serial ;
        }else{
            _serial = info;
        }

    }else{
        _serial = "Unknown";
    }
    #endif
   // //qDebug() << "Brk" << infoChr;


    xn::Query query;
    query.AddNeededNode(deviceInfo.GetInstanceName());

    status = g_depth.Create(g_context, &query);
    checkXnError(status, "Create depth generator");
    XnMapOutputMode depth_mode;
    depth_mode.nXRes = 640;
    depth_mode.nYRes = 480;
    _fps = depth_mode.nFPS = 30;
    g_depth.SetMapOutputMode(depth_mode);

    status = g_image.Create(g_context, &query);
    checkXnError(status, "Create image generator");

    status = g_image.SetIntProperty ("Resolution", 1);
    checkXnError(status, "Resolution");

    status = g_context.SetGlobalMirror(m_mirrored);
    checkXnError(status, "Mirror");

    XnMapOutputMode rgb_mode;
    if (m_high_resolution)
    {
        _fps = rgb_mode.nFPS = 15;
        rgb_mode.nXRes = 1280;
        rgb_mode.nYRes = 1024;
    }
    else
    {
        rgb_mode.nXRes = 640;
        rgb_mode.nYRes = 480;
        _fps = rgb_mode.nFPS = 30;
    }
    g_image.SetMapOutputMode(rgb_mode);

    status = g_depth.GetAlternativeViewPointCap().SetViewPoint(g_image);
  //  status = g_image.GetAlternativeViewPointCap().SetViewPoint(g_depth);
    checkXnError(status, "Depth::GetAlternativeViewPointCap");

    status = g_depth.StartGenerating();
    checkXnError(status, "Depth::StartGenerating");

    status = g_image.StartGenerating();
    checkXnError(status, "RGB::StartGenerating");

    //Preallocation of memory for converting
    if(_proj){
        delete _proj;
        _proj = 0;

    }
    if(_real){
        delete _real;
        _real = 0;
    }
    _proj = new XnPoint3D[depth_mode.nXRes*depth_mode.nYRes];
    for( int y = 0; y < depth_mode.nYRes; y++ )
    {
        for( int x = 0; x < depth_mode.nXRes; x++ )
        {
            int ind = y*depth_mode.nXRes+x;
            _proj[ind].X = (float)x;
            _proj[ind].Y = (float)y;
            _proj[ind].Z = 0;
            //_proj[ind].Z = depth.at<unsigned short>( y, x);
        }
    }

    _real = new XnPoint3D[depth_mode.nXRes*depth_mode.nYRes];

	g_context.WaitAndUpdateAll();

	_deviceid = id;
	_connected = true;
    _kinectlist.push_back(_deviceid);
	}catch(std::exception &ex){
		CRITICAL(ex.what());
	}catch(...){
		CRITICAL("Unknown exception");
	}

}
Beispiel #26
0
/* ------------------------------------------------------------

   sge_add_manop() - adds an manop list to the global manager/operator
                     list

   if the invoking process is the qmaster 
   the added manop list is spooled in the MANAGER_FILE/OPERATOR_FILE

*/
int sge_add_manop(
sge_gdi_ctx_class_t *ctx,
lListElem *ep,
lList **alpp,
char *ruser,
char *rhost,
u_long32 target  /* may be SGE_UM_LIST or SGE_UO_LIST */
) {
   const char *manop_name;
   const char *object_name;
   lList **lpp = NULL;
   lListElem *added;
   int pos;
   int key;
   lDescr *descr = NULL;
   ev_event eve = sgeE_EVENTSIZE; 

   DENTER(TOP_LAYER, "sge_add_manop");

   if ( !ep || !ruser || !rhost ) {
      CRITICAL((SGE_EVENT, MSG_SGETEXT_NULLPTRPASSED_S, SGE_FUNC));
      answer_list_add(alpp, SGE_EVENT, STATUS_EUNKNOWN, ANSWER_QUALITY_ERROR);
      DEXIT;
      return STATUS_EUNKNOWN;
   }

   switch (target) {
   case SGE_UM_LIST:
      lpp = object_type_get_master_list(SGE_TYPE_MANAGER);
      object_name = MSG_OBJ_MANAGER;
      key = UM_name;
      descr = UM_Type;
      eve = sgeE_MANAGER_ADD;
      break;
   case SGE_UO_LIST:
      lpp = object_type_get_master_list(SGE_TYPE_OPERATOR);
      object_name = MSG_OBJ_OPERATOR;
      key = UO_name;
      descr = UO_Type;
      eve = sgeE_OPERATOR_ADD;
      break;
   default :
      DPRINTF(("unknown target passed to %s\n", SGE_FUNC));
      DEXIT;
      return STATUS_EUNKNOWN;
   }

   /* ep is no acl element, if ep has no UM_name/UO_name */
   if ((pos = lGetPosViaElem(ep, key, SGE_NO_ABORT)) < 0) {
      CRITICAL((SGE_EVENT, MSG_SGETEXT_MISSINGCULLFIELD_SS,
            lNm2Str(key), SGE_FUNC));
      answer_list_add(alpp, SGE_EVENT, STATUS_EUNKNOWN, ANSWER_QUALITY_ERROR);
      DEXIT;
      return STATUS_EUNKNOWN;
   }

   manop_name = lGetPosString(ep, pos);
   if (!manop_name) {
      CRITICAL((SGE_EVENT, MSG_SGETEXT_NULLPTRPASSED_S, SGE_FUNC));
      answer_list_add(alpp, SGE_EVENT, STATUS_EUNKNOWN, ANSWER_QUALITY_ERROR);
      DEXIT;
      return STATUS_EUNKNOWN;
   }

   if (lGetElemStr(*lpp, key, manop_name)) {
      ERROR((SGE_EVENT, MSG_SGETEXT_ALREADYEXISTS_SS, object_name, manop_name));
      answer_list_add(alpp, SGE_EVENT, STATUS_EEXIST, ANSWER_QUALITY_ERROR);
      DEXIT;
      return STATUS_EEXIST;
   }

   /* update in interal lists */
   added = lAddElemStr(lpp, key, manop_name, descr);

   /* update on file */
   if(!sge_event_spool(ctx, alpp, 0, eve, 
                       0, 0, manop_name, NULL, NULL,
                       added, NULL, NULL, true, true)) {
      ERROR((SGE_EVENT, MSG_CANTSPOOL_SS, object_name, manop_name));
      answer_list_add(alpp, SGE_EVENT, STATUS_EDISK, ANSWER_QUALITY_ERROR);
   
      /* remove element from list */
      lRemoveElem(*lpp, &added);

      DEXIT;
      return STATUS_EDISK;
   }

   INFO((SGE_EVENT, MSG_SGETEXT_ADDEDTOLIST_SSSS,
            ruser, rhost, manop_name, object_name));
   answer_list_add(alpp, SGE_EVENT, STATUS_OK, ANSWER_QUALITY_INFO);
   DEXIT;
   return STATUS_OK;
}
Beispiel #27
0
void
updateClock(RunTimeOpts * rtOpts, PtpClock * ptpClock)
{

	/* updates paused, leap second pending - do nothing */
        if(ptpClock->leapSecondInProgress)
            return;
	DBGV("==> updateClock\n");

	if(ptpClock->panicMode) {
	    DBG("Panic mode - skipping updateClock");
	}



/*
if(rtOpts->delayMSOutlierFilterEnabled && rtOpts->delayMSOutlierFilterDiscard && ptpClock->delayMSoutlier)
	    goto display;
*/
	if (rtOpts->maxReset) { /* If maxReset is 0 then it's OFF */
		if (ptpClock->offsetFromMaster.seconds && rtOpts->maxReset) {
			INFO("updateClock aborted, offset greater than 1"
			     " second.");
			if (rtOpts->displayPackets)
				msgDump(ptpClock);
			goto display;
		}

		if (ptpClock->offsetFromMaster.nanoseconds > rtOpts->maxReset) {
			INFO("updateClock aborted, offset %d greater than "
			     "administratively set maximum %d\n",
			     ptpClock->offsetFromMaster.nanoseconds, 
			     rtOpts->maxReset);
			if (rtOpts->displayPackets)
				msgDump(ptpClock);
			goto display;
		}
	}

	if (ptpClock->offsetFromMaster.seconds) {
		/* if secs, reset clock or set freq adjustment to max */
		
		/* 
		  if offset from master seconds is non-zero, then this is a "big jump:
		  in time.  Check Run Time options to see if we will reset the clock or
		  set frequency adjustment to max to adjust the time
		*/

		/*
		 * noAdjust     = cannot do any change to clock
		 * noResetClock = if can change the clock, can we also step it?
		 */
		if (!rtOpts->noAdjust) {


	if(rtOpts->enablePanicMode && !ptpClock->panicOver) {

		if(ptpClock->panicMode)
		    goto display;

		if(ptpClock->panicOver) {
		    ptpClock->panicMode = FALSE;
		    ptpClock->panicOver = FALSE;
#ifdef PTPD_STATISTICS
		    ptpClock->isCalibrated = FALSE;
#endif /* PTPD_STATISTICS */
		    goto display;
		}

		CRITICAL("Offset above 1 second - entering panic mode\n");

		ptpClock->panicMode = TRUE;
		ptpClock->panicModeTimeLeft = 2 * rtOpts->panicModeDuration;
		timerStart(PANIC_MODE_TIMER, 30, ptpClock->itimer);

#ifdef PTPD_NTPDC

/* Trigger NTP failover as part of panic mode */

if(rtOpts->ntpOptions.enableEngine && rtOpts->panicModeNtp) {

				/* Make sure we log ntp control errors now */
				ptpClock->ntpControl.requestFailed = FALSE;
                                /* We have a timeout defined */
                                if(rtOpts->ntpOptions.failoverTimeout) {
                                        DBG("NTP failover timer started - panic mode\n");
                                        timerStart(NTPD_FAILOVER_TIMER,
                                                    rtOpts->ntpOptions.failoverTimeout,
                                                    ptpClock->itimer);
                                /* Fail over to NTP straight away */
                                } else {
                                        DBG("Initiating NTP failover\n");
                                        ptpClock->ntpControl.isRequired = TRUE;
                                        ptpClock->ntpControl.isFailOver = TRUE;
                                        if(!ntpdControl(&rtOpts->ntpOptions, &ptpClock->ntpControl, FALSE))
                                                DBG("PANIC MODE instant NTP failover - could not fail over\n");
                                }

}

#endif /* PTPD_NTPDC */
		goto display;

	}

			if(rtOpts->enablePanicMode) {
				if(ptpClock->panicOver)
					CRITICAL("Panic mode timeout - accepting current offset. Clock will jump\n");
				ptpClock->panicOver = FALSE;
				timerStop(PANIC_MODE_TIMER, ptpClock->itimer);

#ifdef PTPD_NTPDC
/* Exiting ntp failover - getting out of panic mode */
	if(rtOpts->ntpOptions.enableEngine && rtOpts->panicModeNtp) {
                            timerStop(NTPD_FAILOVER_TIMER, ptpClock->itimer);
			    ptpClock->ntpControl.isRequired = FALSE;
			    ptpClock->ntpControl.isFailOver = FALSE;
                            if(!ntpdControl(&rtOpts->ntpOptions, &ptpClock->ntpControl, FALSE))
                                DBG("NTPdcontrol - could not return from NTP panic mode\n");
	}
#endif /* PTPD_NTPDC */

			}
			if (!rtOpts->noResetClock) {
				servo_perform_clock_step(rtOpts, ptpClock);
			} else {
#ifdef HAVE_SYS_TIMEX_H
				if(ptpClock->offsetFromMaster.nanoseconds > 0)
				    ptpClock->servo.observedDrift = rtOpts->servoMaxPpb;
				else
				    ptpClock->servo.observedDrift = -rtOpts->servoMaxPpb;
				warn_operator_slow_slewing(rtOpts, ptpClock);
				adjFreq_wrapper(rtOpts, ptpClock, -ptpClock->servo.observedDrift);
				/* its not clear how the APPLE case works for large jumps */
#endif /* HAVE_SYS_TIMEX_H */
			}
		}
	} else {

	    /* If we're in panic mode, either exit if no threshold configured, or exit if we're outside the exit threshold */
	    if(rtOpts->enablePanicMode && 
		((ptpClock->panicMode && ( rtOpts->panicModeExitThreshold == 0 || ((rtOpts->panicModeExitThreshold > 0) &&  ((ptpClock->offsetFromMaster.seconds == 0) && (ptpClock->offsetFromMaster.nanoseconds < rtOpts->panicModeExitThreshold))))   ) || ptpClock->panicOver)) {
		    ptpClock->panicMode = FALSE;
		    ptpClock->panicOver = FALSE;
		    timerStop(PANIC_MODE_TIMER, ptpClock->itimer);
		    NOTICE("Offset below 1 second again: exiting panic mode\n");
#ifdef PTPD_NTPDC
/* exiting ntp failover - panic mode over */
	if(rtOpts->ntpOptions.enableEngine && rtOpts->panicModeNtp) {
                            timerStop(NTPD_FAILOVER_TIMER, ptpClock->itimer);
			    ptpClock->ntpControl.isRequired = FALSE;
			    ptpClock->ntpControl.isFailOver = FALSE;
                            if(!ntpdControl(&rtOpts->ntpOptions, &ptpClock->ntpControl, FALSE))
                                DBG("NTPdcontrol - could not return from NTP panic mode\n");
	}
#endif /* PTPD_NTPDC */

	    }

	/* Servo dT is the log sync interval */
	/* TODO: if logsyincinterval is 127 [unicast], switch to measured */
	if(rtOpts->servoDtMethod == DT_CONSTANT)
		ptpClock->servo.logdT = ptpClock->logSyncInterval;

/* If the last delayMS was an outlier and filter action is discard, skip servo run */
#ifdef PTPD_STATISTICS
	if(rtOpts->delayMSOutlierFilterEnabled && rtOpts->delayMSOutlierFilterDiscard && ptpClock->delayMSoutlier)
		goto statistics;
#endif /* PTPD_STATISTICS */

#ifndef HAVE_SYS_TIMEX_H
			adjTime(ptpClock->offsetFromMaster.nanoseconds);
#else

#ifdef PTPD_STATISTICS
	/* if statistics are enabled, only run the servo if we are calibrted - if calibration delay configured */
	if(!rtOpts->calibrationDelay || ptpClock->isCalibrated)
#endif /*PTPD_STATISTICS */
		/* Adjust the clock first -> the PI controller runs here */
		adjFreq_wrapper(rtOpts, ptpClock, runPIservo(&ptpClock->servo, ptpClock->offsetFromMaster.nanoseconds));
		/* Unset STA_UNSYNC */
		unsetTimexFlags(STA_UNSYNC, TRUE);
		/* "Tell" the clock about maxerror, esterror etc. */
		informClockSource(ptpClock);
#endif /* HAVE_SYS_TIMEX_H */
	}

/* Update relevant statistics containers, feed outlier filter thresholds etc. */
#ifdef PTPD_STATISTICS
statistics:
                        if (rtOpts->delayMSOutlierFilterEnabled) {
                        	double dDelayMS = timeInternalToDouble(&ptpClock->rawDelayMS);
                        	if(ptpClock->delayMSoutlier) {
				/* Allow [weight] * [deviation from mean] to influence std dev in the next outlier checks */
                        		DBG("DelayMS Outlier: %.09f\n", dDelayMS);
                        		dDelayMS = ptpClock->delayMSRawStats->meanContainer->mean + 
						    rtOpts->delayMSOutlierWeight * ( dDelayMS - ptpClock->delayMSRawStats->meanContainer->mean);
                        	}
                                feedDoubleMovingStdDev(ptpClock->delayMSRawStats, dDelayMS);
                                feedDoubleMovingMean(ptpClock->delayMSFiltered, timeInternalToDouble(&ptpClock->delayMS));
                        }
                        feedDoublePermanentStdDev(&ptpClock->slaveStats.ofmStats, timeInternalToDouble(&ptpClock->offsetFromMaster));
                        feedDoublePermanentStdDev(&ptpClock->servo.driftStats, ptpClock->servo.observedDrift);
#endif /* PTPD_STATISTICS */

display:
		logStatistics(rtOpts, ptpClock);

	DBGV("\n--Offset Correction-- \n");
	DBGV("Raw offset from master:  %10ds %11dns\n",
	    ptpClock->delayMS.seconds,
	    ptpClock->delayMS.nanoseconds);

	DBGV("\n--Offset and Delay filtered-- \n");

	if (ptpClock->delayMechanism == P2P) {
		DBGV("one-way delay averaged (P2P):  %10ds %11dns\n",
		    ptpClock->peerMeanPathDelay.seconds, 
		    ptpClock->peerMeanPathDelay.nanoseconds);
	} else if (ptpClock->delayMechanism == E2E) {
		DBGV("one-way delay averaged (E2E):  %10ds %11dns\n",
		    ptpClock->meanPathDelay.seconds, 
		    ptpClock->meanPathDelay.nanoseconds);
	}

	DBGV("offset from master:      %10ds %11dns\n",
	    ptpClock->offsetFromMaster.seconds, 
	    ptpClock->offsetFromMaster.nanoseconds);
	DBGV("observed drift:          %10d\n", ptpClock->servo.observedDrift);
}
Beispiel #28
0
/****** uti/monitor/sge_monitor_init() *****************************************
*  NAME
*     sge_monitor_init() -- init the monitoring structure
*
*  SYNOPSIS
*     void sge_monitor_init(monitoring_t *monitor, const char *thread_name, 
*     extension_t ext, thread_warning_t warning_timeout, thread_error_t 
*     error_timeout) 
*
*  FUNCTION
*     Sets the default values and inits the structure, finds the line pos
*     for the comlib output
*
*  INPUTS
*     monitoring_t *monitor            - monitoring strucutre
*     const char *thread_name          - the thread name
*     extension_t ext                  - the extension time (-> enum)
*     thread_warning_t warning_timeout - the warning timeout (-> enum)
*     thread_error_t error_timeout     - the error timeout (-> enum)
*
*  NOTES
*     MT-NOTE: sge_monitor_init() is MT safe 
*
*******************************************************************************/
void
sge_monitor_init(monitoring_t *monitor, const char *thread_name, extension_t ext, 
                 thread_warning_t warning_timeout, thread_error_t error_timeout)
{
   DENTER(GDI_LAYER, "sge_monitor_init");

   /*
    * initialize the mallinfo function pointer if it is available
    */
#if defined(LINUX) || defined(AIX43) || defined(AIX51) || defined(IRIX) || defined(SOLARIS) || defined(HP11)
   sge_mutex_lock("sge_monitor_status", SGE_FUNC, __LINE__, &global_mutex);
   if (mallinfo_initialized == false) {
      const char *function_name = "mallinfo";

      mallinfo_initialized = true;
#  ifdef RTLD_NODELETE
      mallinfo_shlib_handle = dlopen(NULL, RTLD_LAZY | RTLD_NODELETE);
#  else
      mallinfo_shlib_handle = dlopen(NULL, RTLD_LAZY );
#  endif /* RTLD_NODELETE */

      if (mallinfo_shlib_handle != NULL) {
         mallinfo_func_pointer = (struct mallinfo (*)(void)) dlsym(mallinfo_shlib_handle, function_name);
      }
   }
   sge_mutex_unlock("sge_monitor_status", SGE_FUNC, __LINE__, &global_mutex);
#endif

   monitor->thread_name = thread_name;
 
   monitor->output_line1 = (dstring*) malloc(sizeof(dstring));
   monitor->output_line2 = (dstring*) malloc(sizeof(dstring));
   
   if (monitor->output_line1 == NULL || monitor->output_line2 == NULL) {
      CRITICAL((SGE_EVENT, SFNMAX, MSG_UTI_MONITOR_MEMERROR));
      exit(1);
   } 

   memset(monitor->output_line1, 0, sizeof(dstring));
   memset(monitor->output_line2, 0, sizeof(dstring));
   
   sge_dstring_append(monitor->output_line1, thread_name);
   sge_dstring_append(monitor->output_line1, MSG_UTI_MONITOR_NODATA);
   sge_dstring_clear(monitor->output_line2);
   monitor->work_line = monitor->output_line2;
 
   switch(ext) {
      case SCH_EXT :
            monitor->ext_data = malloc(sizeof(m_sch_t));
            if (monitor->ext_data != NULL) {
               monitor->ext_type = SCH_EXT;
               monitor->ext_data_size = sizeof(m_sch_t);
               monitor->ext_output = &ext_sch_output;
            } else {
               monitor->ext_type = NONE_EXT;
               ERROR((SGE_EVENT, SFNMAX, MSG_UTI_MONITOR_MEMERROREXT));
            }
         break;

      case GDI_EXT :
            monitor->ext_data = malloc(sizeof(m_gdi_t));
            if (monitor->ext_data != NULL) {
               monitor->ext_type = GDI_EXT;
               monitor->ext_data_size = sizeof(m_gdi_t);
               monitor->ext_output = &ext_gdi_output;
            } else {
               monitor->ext_type = NONE_EXT;
               ERROR((SGE_EVENT, SFNMAX, MSG_UTI_MONITOR_MEMERROREXT));
            }
         break;

      case LIS_EXT :
            monitor->ext_data = malloc(sizeof(m_lis_t));
            if (monitor->ext_data != NULL) {
               monitor->ext_type = LIS_EXT;
               monitor->ext_data_size = sizeof(m_lis_t);
               monitor->ext_output = &ext_lis_output;
            } else {
               monitor->ext_type = NONE_EXT;
               ERROR((SGE_EVENT, SFNMAX, MSG_UTI_MONITOR_MEMERROREXT));
            }
         break;
         
      case EDT_EXT : 
            monitor->ext_data = malloc(sizeof(m_edt_t));
            if (monitor->ext_data != NULL) {
               monitor->ext_type = EDT_EXT;
               monitor->ext_data_size = sizeof(m_edt_t);
               monitor->ext_output = &ext_edt_output;
            } else {
               monitor->ext_type = NONE_EXT;
               ERROR((SGE_EVENT, SFNMAX, MSG_UTI_MONITOR_MEMERROREXT));
            }
         break;
       
      case TET_EXT : 
            monitor->ext_data = malloc(sizeof(m_tet_t));
            if (monitor->ext_data != NULL) {
               monitor->ext_type = TET_EXT;
               monitor->ext_data_size = sizeof(m_tet_t);
               monitor->ext_output = &ext_tet_output;
            } else {
               monitor->ext_type = NONE_EXT;
               ERROR((SGE_EVENT, SFNMAX, MSG_UTI_MONITOR_MEMERROREXT));
            }
         break;
         
      case NONE_EXT :
            monitor->ext_type = NONE_EXT;
         break;
         
      default : 
            monitor->ext_type = NONE_EXT;
            ERROR((SGE_EVENT, MSG_UTI_MONITOR_UNSUPPORTEDEXT_D, ext));
   };

   if (monitor->ext_type == NONE_EXT) {
      monitor->ext_data_size = 0;
      monitor->ext_data = NULL;
      monitor->ext_output = NULL;
   }
   
   sge_monitor_reset(monitor);
   
   { 
      int i;
      struct timeval time;
      monitor->pos = -1; 

      gettimeofday(&time, NULL);
      
      for (i = 0; i < MAX_OUTPUT_LINES; i++) {
         sge_mutex_lock("sge_monitor_init", SGE_FUNC, __LINE__, &(Output[i].Output_Mutex));
         if (Output[i].name == NULL) {
            monitor->pos = i;
            Output[i].output = monitor->output_line1;
            Output[i].name = thread_name;
            Output[i].warning_timeout = warning_timeout;
            Output[i].error_timeout = error_timeout;
            Output[i].update_time = time.tv_sec; 
            sge_mutex_unlock("sge_monitor_init", SGE_FUNC, __LINE__, &(Output[i].Output_Mutex));
            break;
         }      
         sge_mutex_unlock("sge_monitor_init", SGE_FUNC, __LINE__, &(Output[i].Output_Mutex));
      }
      
      sge_set_last_wait_time(monitor, time);
   }
  
   if (monitor->pos == -1) {
      ERROR((SGE_EVENT, MSG_UTI_MONITOR_NOLINES_S, monitor->thread_name));
   }
   
   DEXIT;
}
/****** uti/spool/sge_get_confval_array() *************************************
*  NAME
*     sge_get_confval_array() - Read configuration file entries
*
*  SYNOPSIS
*     int sge_get_confval_array(const char *fname, int n, 
*                               const char *name[], 
*                               char value[][1025],
*                               dstring *error_dstring) 
*
*  FUNCTION
*     Reads in an array of configuration file entries
*
*  RESULT
*     int - 0 on success
*
*  BUGS
*     Function can not differ multiple similar named entries.
*
*  NOTES
*     MT-NOTE: sge_get_confval_array() is MT safe
******************************************************************************/
int sge_get_confval_array(const char *fname, int n, int nmissing, bootstrap_entry_t name[], 
                          char value[][1025], dstring *error_dstring) 
{
   FILE *fp;
   char buf[1024], *cp;
   int i;
   bool *is_found = NULL;
   
   DENTER(TOP_LAYER, "sge_get_confval_array");

   if (!(fp = fopen(fname, "r"))) {
      if (error_dstring == NULL){
         CRITICAL((SGE_EVENT, MSG_FILE_FOPENFAILED_SS, fname, strerror(errno)));
      }
      else {
         sge_dstring_sprintf(error_dstring, MSG_FILE_FOPENFAILED_SS, 
                             fname, strerror(errno));
      }
      DEXIT;
      return n;
   }
   is_found = malloc(sizeof(bool) * n);
   memset(is_found, false, n * sizeof(bool));
   
   while (fgets(buf, sizeof(buf), fp)) {
      char *pos = NULL;

      /* set chrptr to the first non blank character
       * If line is empty continue with next line
       */
      if(!(cp = strtok_r(buf, " \t\n", &pos))) {
          continue;
      }    

      /* allow commentaries */
      if (cp[0] == '#') {
          continue;
      }    
  
      /* search for all requested configuration values */ 
      for (i=0; i<n; i++) {
         if (cp && (strcasecmp(name[i].name, cp) == 0) &&
             ((cp = strtok_r(NULL, " \t\n", &pos)) != NULL)) {
             if (!cp) break;
             /* fixme value elements are 1025 long in caller */
             strncpy(value[i], cp, 512);
             cp = value[i];
             is_found[i] = true;
             if (name[i].is_required) {
               --nmissing; 
             }
             break;
         }
      }
   }
   if (nmissing != 0) {
      for (i=0; i<n; i++) {
         if (!is_found[i] && name[i].is_required) {
            if (error_dstring == NULL){
               CRITICAL((SGE_EVENT, MSG_UTI_CANNOTLOCATEATTRIBUTE_SS, name[i].name, fname));
            }
            else {
               sge_dstring_sprintf(error_dstring, MSG_UTI_CANNOTLOCATEATTRIBUTE_SS, 
                                   name[i].name, fname);
            }
            
            break;
         }
      }
   }
   
   sge_free(&is_found);
   FCLOSE(fp);
   DEXIT;
   return nmissing;
FCLOSE_ERROR:
   DEXIT;
   return 0;
} /* sge_get_confval_array() */