Exemple #1
0
int main(int argc, char *argv[])
{
   bool failed = false;

   lInit(nmv);

   if (!failed) {
      failed = check_range_get_all_ids();
   }
   if (!failed) {
      failed = check_range_set_all_ids();
   }

   /*
    * EB: TEST: add additional tests
    */

   if (failed) {
      printf("failed\n");
   }
   else {
      printf("successful\n");
   }
   
   return failed ? 1 : 0;
}
Exemple #2
0
/****** test_sge_calendar/main() ***********************************************
*  NAME
*     main() -- calendar test
*
*  SYNOPSIS
*     int main(int argc, char* argv[]) 
*
*  FUNCTION
*     calendar test
*
*  INPUTS
*     int argc     - nr. of args 
*     char* argv[] - args
*
*  RESULT
*     int -  nr of failed tests
*
*******************************************************************************/
int main(int argc, char* argv[])
{
   int test_counter = 0;
   int failed = 0;

   prof_mt_init();

   lInit(nmv);
   
   printf("==> category test <==\n");
   printf("---------------------\n");


   while (tests[test_counter].test_nr != -1) {
      if (test(&(tests[test_counter]), 
               result_category[test_counter], 
               test_counter) != 0) {
         failed++; 
      }   
      test_counter++;
   }

   if (failed == 0) {
      printf("\n==> All tests are okay <==\n");
   }
   else {
      printf("\n==> %d/%d test(s) failed <==\n", failed, test_counter);
   }
   
   return failed;
}
int main(int argc, char *argv[])
{
   int num_objects;
   int num_names;
   int i;
   bool uh, nuh;

   if (argc != 1 && argc < 5) {
      usage(argv[0]);
   }

   /* initialize globals */
   lInit(my_nmv);
   clk_tck = sysconf(_SC_CLK_TCK); /* JG: TODO: sge_sysconf? */
   prof_mt_init();

   /* we need random numbers */
   srand(time(0));

   if (argc == 1) {
      num_objects = 1000;
      num_names   = 10;
      uh          = true;
      nuh         = true;
   } else {
      /* parse commandline options */
      num_objects = atoi(argv[1]);
      num_names   = atoi(argv[2]);
      uh          = atoi(argv[3]) == 0 ? false : true;
      nuh         = atoi(argv[4]) == 0 ? false : true;
   }

   /* create name array */
   names = sge_malloc (num_names * sizeof(const char *));

   /* build random names */
   for (i = 0; i < num_names; i++) {
      const char *name = random_string(10);
      names[i] = name;
   }

   /* output header */
   printf(HEADER_FORMAT, "uh ", "nuh", 
          "create", "copy", "rau", "inu", "curo", "cnuro", 
          "dru", "(objs)", "dinu", "(objs)", "mem(kB)");

   /* do tests */
   do_test(uh, nuh, num_objects, num_names);
   
   /* free names */
   for (i = 0; i < num_names; i++) {
      sge_free(&(names[i]));
   }

   return EXIT_SUCCESS;
}
int main(int argc, char *argv[]) 
{
   int ret = 0;

   DENTER_MAIN(TOP_LAYER, "test_resource_utilization");

   sge_mt_init();

   lInit(nmv);

   ret += test_normal_utilization();
   ret += test_extensive_utilization();

   if (ret != 0) {
      printf("\ntest failed!\n");
   }

   return ret;
}
int main(int argc, char *argv[])
{
   lInit(nmv);
   prof_mt_init();

   printf("lWhat() ... %s\n", 
          test_lWhat() ? "Ok" : "Failed");
   printf("lCountWhat(...) ... %s\n", 
          test_lCountWhat() ? "Ok" : "Failed");
   printf("lReduceDescr(...) ... %s\n", 
          test_lReduceDescr() ? "Ok" : "Failed");
   printf("lCopyWhat() ... %s\n", 
          test_lCopyWhat() ? "Ok" : "Failed");
   printf("lIntVector2What() ... %s\n", 
          test_lIntVector2What() ? "Ok" : "Failed");
   printf("lSelect() ... %s\n", 
          test_lWhat_lSelect() ? "Ok" : "Failed");

   return EXIT_SUCCESS;
}
Exemple #6
0
/****** qmaster/setup_qmaster/sge_qmaster_thread_init() ************************
*  NAME
*     sge_qmaster_thread_init() -- Initialize a qmaster thread.
*
*  SYNOPSIS
*     int sge_qmaster_thread_init(bool switch_to_admin_user)
*
*  FUNCTION
*     Subsume functions which need to be called immediately after thread
*     startup. This function does make sure that the thread local data
*     structures do contain reasonable values.
*
*  INPUTS
*     bool switch_to_admin_user - become admin user if set to true
*
*  RESULT
*     0 - success
*
*  NOTES
*     MT-NOTE: sge_qmaster_thread_init() is MT safe
*     MT-NOTE:
*     MT-NOTE: sge_qmaster_thread_init() should be invoked at the beginning
*     MT-NOTE: of a thread function.
*
*******************************************************************************/
int
sge_qmaster_thread_init(sge_gdi_ctx_class_t **ctx_ref, u_long32 prog_id,
                        u_long32 thread_id, bool switch_to_admin_user)
{
    const char *admin_user = NULL;
    lList *alp = NULL;
    sge_gdi_ctx_class_t *ctx = NULL;

    DENTER(TOP_LAYER, "sge_qmaster_thread_init");

    lInit(nmv);

    if (sge_setup2(ctx_ref, prog_id, thread_id, &alp, true) != AE_OK) {
        answer_list_output(&alp);
        SGE_EXIT((void**)ctx_ref, 1);
    }
    ctx = *ctx_ref;
    ctx->reresolve_qualified_hostname(ctx);
    DEBUG((SGE_EVENT,"%s: qualified hostname \"%s\"\n", SGE_FUNC, ctx->get_qualified_hostname(ctx)));
    admin_user = ctx->get_admin_user(ctx);

    if (switch_to_admin_user == true) {
        char str[MAX_STRING_SIZE];
        if (sge_set_admin_username(admin_user, str) == -1) {
            CRITICAL((SGE_EVENT, SFNMAX, str));
            SGE_EXIT((void**)ctx_ref, 1);
        }

        if (sge_switch2admin_user()) {
            CRITICAL((SGE_EVENT, SFNMAX, MSG_ERROR_CANTSWITCHTOADMINUSER));
            SGE_EXIT((void**)ctx_ref, 1);
        }
    }

    DEXIT;
    return 0;
} /* sge_qmaster_thread_init() */
int main(int argc, char *argv[])
{
   lListElem *queue, *copy;
   const lDescr *descr;
   spooling_field *fields;

   dstring queue_str = DSTRING_INIT;
   dstring copy_str  = DSTRING_INIT;

   lList *answer_list;

   int i;

   lInit(nmv);

   descr = QU_Type;
   copy  = lCreateElem(descr);

/*    lWriteElemTo(queue, stdout); */

   for(i = 0; mt_get_type(descr[i].mt) != lEndT; i++) {
      int nm;
      const char *name;
      const char *value, *reread_value;

      nm = descr[i].nm;
      name = lNm2Str(nm);
      value = object_append_field_to_dstring(queue, &answer_list, 
                                             &queue_str, nm, '\0');
      reread_value = NULL;

      if(value != NULL) {
         if(!object_parse_field_from_string(copy, &answer_list, nm, value)) {
            fprintf(stderr, "setting value for field %s failed\n", name);
         } else {
            reread_value = object_append_field_to_dstring(copy, &answer_list, 
                                                          &copy_str, nm, '\0');
         }
      }

#if 1
      printf("%s\t%s\t%s\n", name, 
             value == NULL ? "<null>" : value,
             reread_value == NULL ? "<null>" : reread_value);
#endif

      if(sge_strnullcmp(value, reread_value) != 0) {
         fprintf(stderr, "regression test for object_[gs]et_field_contents failed for attribute "SFQ": "SFQ" != "SFQ"\n", 
                 name, 
                 value != NULL ? value : "<null>", 
                 reread_value != NULL ? reread_value : "<null>");
      }
   }

   fields = spool_get_fields_to_spool(&answer_list, QU_Type, &spool_config_instr);
   printf("\nthe following fields will be spooled:");
   for(i = 0; fields[i].nm != NoName; i++) {
      printf(" %s", lNm2Str(fields[i].nm));
   }
   printf("\n");
   fields = spool_free_spooling_fields(fields);

   /* cleanup */
   lFreeElem(&queue);
   lFreeElem(&copy);

   sge_dstring_free(&queue_str);
   sge_dstring_free(&copy_str);

   return EXIT_SUCCESS;
}
int main(int argc, char *argv[])
{
   int pos_tests_failed = 0;
   int neg_tests_failed = 0;
   int i = 0;
   lList *answer_list = NULL;


   filter_test_t positiv_test[] = {
      {"num_proc", 4}, 
      {"$num_proc", 4},
      {"$num_proc*2", 8},
      {"$num_proc*0.5", 2.0},
      {"num_proc*2", 8},
      {"num_proc+1", 5}, 
      {"$num_proc-2", 2}, 
      {"$num_proc+0.1", 4.1}, 
      {"1+$num_proc+0.1", 5.1}, 
      {NULL, 0}
   };

   filter_test_t negativ_test[] = {
      {"2*num_proc", 0}, 
      {"2,0+num_proc", 0}, 
      {"none", 0}, 
      {NULL, 0}
   };

   lList *centry_list;
   lList *host_centry_list;
   lListElem *centry;
   lListElem *host;

   DENTER_MAIN(TOP_LAYER, "test_sge_load_formula");

   lInit(nmv);

   /* set up centry */
   centry_list = lCreateList("", CE_Type);
   centry = lCreateElem(CE_Type);
   lSetString(centry, CE_name, "num_proc");
   lSetString(centry, CE_stringval, "4");
   lSetDouble(centry, CE_doubleval, 4);
   lAppendElem(centry_list, centry);

   /* set up host */
   host_centry_list = lCreateList("", CE_Type);
   lAppendElem(host_centry_list, lCopyElem(centry));
   host = lCreateElem(EH_Type);
   lSetList(host, EH_consumable_config_list, host_centry_list);

   for (i=0; ; i++){
      double val;
      if (positiv_test[i].formula == NULL) {
         break;
      }
      if (!validate_load_formula(positiv_test[i].formula, &answer_list, centry_list, "load_formula")) {
         answer_list_output(&answer_list);
         pos_tests_failed++;
      }

      val = scaled_mixed_load(positiv_test[i].formula, NULL, host, centry_list);
      if (val != positiv_test[i].value) {
         printf("got %f, but expected %f(%g,%g)\n", val, positiv_test[i].value, val, positiv_test[i].value);
         pos_tests_failed++;
      }
   }
   
   for (i=0; ; i++){
     if (negativ_test[i].formula == NULL) {
         break;
      }
      if (validate_load_formula(negativ_test[i].formula, &answer_list, centry_list, "load_formula") == true) {
         printf("load_formula \"%s\" returned no error\n", negativ_test[i].formula);
         neg_tests_failed++;
      }
      lFreeList(&answer_list);
   }

   lFreeList(&centry_list);
   lFreeElem(&host);

   printf("\n");
   printf("%d positiv test(s) failed\n", pos_tests_failed);
   printf("%d negativ test(s) failed\n", neg_tests_failed);

   DRETURN(pos_tests_failed + neg_tests_failed);
}
int main(int argc, char *argv[])
{
   lListElem *queue, *copy;
   lList *queue_list;
   lList *answer_list = NULL;
   const lDescr *descr;
   spooling_field *fields;
   const char *filepath;
   int i;
   int width;
   char format[100];

   lInit(nmv);

   queue = queue_create_template();
   lSetString(queue, QU_terminate_method, "/tmp/myterminate_method.sh");
   lAddSubStr(queue, CE_name, "foo", QU_suspend_thresholds, CE_Type);
   lAddSubStr(queue, CE_name, "bar", QU_suspend_thresholds, CE_Type);
   copy  = lCreateElem(QU_Type);

   queue_list = lCreateList("queue_list", QU_Type);
   lAppendElem(queue_list, queue);
   lAppendElem(queue_list, copy);

   descr = lGetElemDescr(queue);
   
   fields = spool_get_fields_to_spool(&answer_list, QU_Type, &spool_config_instr);
   printf("\nthe following fields are spooled:");
   for(i = 0; fields[i].nm != NoName; i++) {
      printf(" %s", lNm2Str(fields[i].nm));
   }
   printf("\n");

   spool_flatfile_align_object(&answer_list, fields);
   width = fields[0].width;
   printf("alignment for attribute names is %d\n", width);

   spool_flatfile_align_list(&answer_list, queue_list, fields);
   printf("field widths for list output is as follows:\n");
   
   sprintf(format, "%%%ds: %%d\n", width);

   for(i = 0; fields[i].nm != NoName; i++) {
      printf(format, lNm2Str(fields[i].nm), fields[i].width);
   }

   filepath = spool_flatfile_write_object(&answer_list, queue,
                                          NULL,
                                          &spool_flatfile_instr_config,
                                          SP_DEST_STDOUT, SP_FORM_ASCII, NULL);
   if(filepath != NULL) {
      printf("\ndata successfully written to stdout\n");
      FREE(filepath);
   } else {
      answer_list_print_err_warn(&answer_list, NULL, NULL);
   }
                               
   printf("\n");

   filepath = spool_flatfile_write_object(&answer_list, queue,
                               NULL,
                               &spool_flatfile_instr_config,
                               SP_DEST_TMP, SP_FORM_ASCII, NULL);
   if(filepath != NULL) {
      printf("temporary file %s successfully written\n", filepath);
      sge_unlink(NULL, filepath);
      FREE(filepath);
   } else {
      answer_list_print_err_warn(&answer_list, NULL, NULL);
   }
                               
   filepath = spool_flatfile_write_object(&answer_list, queue,
                               NULL,
                               &spool_flatfile_instr_config,
                               SP_DEST_SPOOL, SP_FORM_ASCII, 
                               "test_sge_spooling_flatfile.dat");
   if(filepath != NULL) {
      lListElem *reread_queue;

      printf("spool file %s successfully written\n", filepath);

      /* reread queue from file */
      reread_queue = spool_flatfile_read_object(&answer_list, QU_Type, NULL, NULL,
                                                &spool_flatfile_instr_config, 
                                                SP_FORM_ASCII, NULL, 
                                                "test_sge_spooling_flatfile.dat");
     
      if(reread_queue == NULL) {
         answer_list_print_err_warn(&answer_list, NULL, NULL);
      } else {
         lWriteElemTo(reread_queue, stdout);
         lFreeElem(&reread_queue);
      }
     
      sge_unlink(NULL, filepath);
      FREE(filepath);
   } else {
      answer_list_print_err_warn(&answer_list, NULL, NULL);
   }
   
   filepath = spool_flatfile_write_list(&answer_list, queue_list,
                                        NULL,
                                        &spool_flatfile_instr_config_list,
                                        SP_DEST_STDOUT, SP_FORM_ASCII, 
                                        NULL);
   if(filepath != NULL) {
      printf("\ndata successfully written to stdout\n");
      FREE(filepath);
   } else {
      answer_list_print_err_warn(&answer_list, NULL, NULL);
   }
   
   filepath = spool_flatfile_write_list(&answer_list, queue_list,
                                        NULL,
                                        &spool_flatfile_instr_config_list,
                                        SP_DEST_SPOOL, SP_FORM_ASCII, 
                                        "test_sge_spooling_flatfile.dat");
   if(filepath != NULL) {
      lList *reread_list;

      printf("spool file %s successfully written\n", filepath);

      reread_list = spool_flatfile_read_list(&answer_list, QU_Type, NULL, NULL, &spool_flatfile_instr_config_list, SP_FORM_ASCII, NULL, "test_sge_spooling_flatfile.dat");
      if (reread_list == NULL) {
         answer_list_print_err_warn(&answer_list, NULL, NULL);
      } else {
         lWriteListTo(reread_list, stdout);
         lFreeList(&reread_list);
      }
/*       sge_unlink(NULL, filepath); */
      FREE(filepath);
   } else {
      answer_list_print_err_warn(&answer_list, NULL, NULL);
   }

   /* test reading object */
   /* test nonexisting filename */
   
   /* test behaviour with NULL-pointer passed */
   printf("\n\ntesting error handling, the next calls have to fail\n");
   spool_flatfile_align_object(&answer_list, NULL);
   spool_flatfile_align_list(&answer_list, NULL, fields);
   spool_flatfile_align_list(&answer_list, queue_list, NULL);
   answer_list_print_err_warn(&answer_list, NULL, NULL);

   /* cleanup */
   lFreeList(&queue_list);

   fields = spool_free_spooling_fields(fields);

   fprintf(stdout, "file handle stdout still alive\n");
   fprintf(stderr, "file handle stderr still alive\n");

   return EXIT_SUCCESS;
}
Exemple #10
0
int main(int argc, char *argv[])
{
   lList *queuelist = NULL, *joblist = NULL;

   enum {
      MATCH_REQUEST,
      LOOP_JOBS_QUEUES
/*                              SUBWHERE */
   };
   int scene, fulfilled, numdiddeldum;

   lList *erglist = NULL;
   lListElem *job, *queue;
   lCondition *where = NULL;

   lEnumeration *w0, *w1, *nothing, *all;
   lList *queuecomplexes = NULL, *attributes = NULL;
   lListElem *attribute, *request;
   const char *operator;

   DENTER_MAIN(TOP_LAYER, "example2");

   if (argc != 3)
      usage();

   sscanf(argv[1], "%d", &scene);
   sscanf(argv[2], "%d", &numdiddeldum);

   /* neccessary for comfortable output  */
   lInit(nmv);

   queuelist = buildQueueList();
   printf("\n\nQUEUELIST\n\n");
   lWriteList(queuelist);

   COMPLEXLIST = buildComplexList();
   printf("\n\nCOMPLEXLIST\n\n");
   lWriteList(COMPLEXLIST);

   joblist = buildJobList(numdiddeldum);
   printf("\n\nJOBLIST\n\n");
   lWriteList(joblist);

   printf("\n******** BEGIN PROCESSING *********\n\n");

   switch (scene) {

   case MATCH_REQUEST:

      /* 
         find for each job in the joblist all queues that 
         suffer the request of this job 
         ( implemented with quick list functions )
       */

      for_each(job, joblist) {

         printf("\n-------------------------------"
                "-------------------------------\n");
         printf("*** job %s may get started in the following queues ***\n\n",
                lGetString(job, J_name));

         for_each(queue, queuelist) {
            if (matchRequest(lGetList(queue, Q_complexname),
                             lGetList(job, J_hardrequest))) {
               if (!erglist)
                  if (!(erglist = lCreateList("erglist", QueueT))) {
                     printf("case MATCH_REQUEST: lCreateList"
                            " failure\n");
                     exit(-1);
                  }
               lAppendElem(erglist, lCopyElem(queue));
            }
         }
         printf("\n\n**** ERGLIST ****\n\n");
         if (erglist) {
            lWriteList(erglist);
            lFreeList(&erglist);
            erglist = NULL;
         }
      }

      break;

   case LOOP_JOBS_QUEUES:

      /* 
         find for each job in the joblist all queues that 
         suffer the request of this job 
         ( implemented with mighty database-like functions )
       */

      for_each(job, joblist) {

         printf("\n--------------------------------------------------------------\n");
         printf("*** job %s may get started in the following queues ***\n\n",
                lGetString(job, J_name));

         for_each(queue, queuelist) {

            /*
               build a list of the complexes of the queue

               therefore: build a subset of the complex list 
               with the queues complex name list as a selector

               join the complex name list of the queue      
               ( join field: N_complexname) 
               with the global complex list                                         
               ( join field: C_name )

               select nothing from the queue's complex name list (w0)
               and only the attributes of the global complex list (w1)

               every valid combination is needed, so the 
               where parameter is NULL for both lists 
             */

            w0 = lWhat("%T(NONE)", ComplexNameT);       /* NIX */
            w1 = lWhat("%T(%I)", ComplexT, C_attribute);

            queuecomplexes = lJoin("queuecomplexes",
                 N_complexname, lGetList(queue, Q_complexname), NULL, w0,
                                   C_name, COMPLEXLIST, NULL, w1);

            lFreeWhat(&w0);
            lFreeWhat(&w1);

            /* 
               try to find a hard request of this job 
               that is not fulfilled by the queue's complexes
             */
            fulfilled = 1;

            for_each(request, lGetList(job, J_hardrequest)) {

               /* 
                  build a flat complex attribute list with only
                  these attributes of the request

                  this produces a attribute list of all complexes 
                */

               nothing = lWhat("%T(NONE)", lGetListDescr(queuecomplexes));
               all = lWhat("%T(ALL)", ComplexAttributeT);
               where = lWhere("%T( %I == %s )", ComplexAttributeT,
                              A_name,
                              lGetString(request, R_name));

               attributes = lJoinSublist("attributelist",
                              C_attribute, queuecomplexes, NULL, nothing,
                                         ComplexAttributeT, where, all);

               lFreeWhere(&where);
               lFreeWhat(&nothing);
               lFreeWhat(&all);

               /* 
                  if we get an empty list then the queue has 
                  no complex fulfilling the request of this job
                */
               /* 
                  right now the lJoinSublist function returns
                  an empty list (no elements) if there was no sublist
                */
               if (lGetNumberOfElem(attributes) == 0) {
                  fulfilled = 0;
                  break;        /* leave request loop */
               }

               /* 
                  if there are attributes the values of at least one
                  complex of the queue must fulfill the request
                */
               for_each(attribute, attributes) {

                  operator = lGetString(request, R_operator);

                  if (strcmp(operator, "==") == 0) {
                     fulfilled = (!strcmp(
                                          lGetString(attribute, A_value),
                                          lGetString(request, R_value)));

                  }
                  else if (strcmp(operator, "!=") == 0) {
                     fulfilled = (strcmp(
                                           lGetString(attribute, A_value),
                                           lGetString(request, R_value)));

                  }             /* else if .. ( for all operators ) */

                  if (fulfilled)
                     break;     /* leave attribute loop */
               }
Exemple #11
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);
}
int main(int argc, char* argv[])
{
	thread_t command_t;
	char* tmp;
	int i;

	logger_set_limit(1);
	logger_set_instant_func(print_message_cli);

	if((timer = timer_init()) == NULL)
	{
		printf("Failed to create timer!\n");
		return 1;
	}

	common_init();
	
	read_config();

#ifdef USE_READLINE

	rl_catch_signals = 0;

#endif
	
	for(i = 1 ; i < argc ; i++)
	{
		if(!strcmp(argv[i], "-h"))
			help();
		else if(!strcmp(argv[i], "-c"))
		{
			information();
			exit(0);
		}
	}
	
	signal(SIGINT , &ctrl_c);//&signalHandler);
	exit_time = 0;

#ifndef DISABLE_PHYSICS

	space = NULL;
	staticBody = NULL;
	
	lInit(&to_remove_array, NULL);
	lInit(&chipmunk_data_array, NULL);
	pthread_mutex_init(&text_lock, NULL);
	
	physics_exit_time = 0;

	simple_lock_init(&physics_lock);

#endif

#ifndef DISABLE_PHYSICS

	/* Set the functions for the network_lib library. */
	nlServerSetFuncs(&send_server_name,
					 &fill_info,
					 &new_chipmunk_data,
					 &mark_for_delete,
					 &key_press,
					 &key_release,
					 &get_exit_state,
					 NULL,
					 &logger_new_message);

#else

	nlServerSetFuncs(&send_server_name,
	                 NULL,
			 NULL,
			 NULL,
			 NULL,
			 NULL,
			 &get_exit_state,
			 NULL,
			 &logger_new_message);

#endif

	nlServerInit();
	
	if(argc > 2)
	{
		int i;
		
		for(i = 1; i < argc ; i++)
		{
			if(!strcmp(argv[i], "-u") && i+1 < argc)
			{
				mfree(IGD_URL);
				IGD_URL = m_strdup(argv[++i]);
				LOG("IGD Path: %s", IGD_URL);
			}
			else if(!strcmp(argv[i], "-p") && i+1 < argc)
			{
				#warning Check for errors.
				int port = 0;
				
				sscanf(argv[++i], "%d", &port);
				LOG("New port: %d", port);
				nlServerBindPort(port);
			}
		}
	}
		
	/* Start everything that has to do with the thread starting! */
	nlServerStart();

#ifndef DISABLE_PHYSICS

	pthread_create(&command_t, NULL, command_thread, NULL);
	physics_thread();
	
	/* If we arrive here, it is that an exit demand was
	 * performed (certainly ^C or ^D).
	 * We now clean everything up. */
	pthread_cancel(command_t);

#else

	command_thread(NULL);

#endif

	quit();

	return 0;
}
static void* command_thread(void* unused)
{
	lList words;
	lInit(&words, NULL);
	
	(void)unused;

	INIT_INPUT;

	while(1)
	{
		char* command;
		void* remember;
		char* newline;

		INPUT_DECLARE;

		lDestroy(&words, free);

		if(READ_INPUT("Enter a command: ") == NULL)
			break;
		
		if((newline = strchr(input, '\n')) != NULL)
			*newline = '\0';
		
		getWords(&words, input);
		command = (char*)lGet(&words, FIRST, &remember);
		//LOG_DEBUG("Command: %s\n", command);

		if(!strcmp(command, ".") || !strcmp(command, "quit") 
		|| !strcmp(command, "q") || !strcmp(command, "exit"))
		{
			//LOG("\n");
			break;
		}
		/* 
		 * Command: send (client) (filename) 
		 */
		else if(!strcmp(command, "send") || !strcmp(command, "snd")) /* Send a file directly to a client */
		{
			ERROR_ENOUGH_ARGUMENTS(3);

			char* who = NEXT_WORD;
			char* filename = NEXT_WORD;
		
			nlServerSendFile(who, filename);
			
			WARN_TOO_MUCH_ARGUMENTS(3);
		}
		else if(!strcmp(command, "wget")) /* Tell a client to download a file at the given URL */
		{
			ERROR_ENOUGH_ARGUMENTS(4);
			
			                           /* Example: */
			char* who = NEXT_WORD;     /*   who: Client */
			char* address = NEXT_WORD; /*   address: http://some_site.org/some_file.tar.gz */
			char* where = NEXT_WORD;   /*   where: pouet.tgz */

			nlServerSendMessage(who, "W %s$%s", address, where);

			WARN_TOO_MUCH_ARGUMENTS(4);
		}
		else if(!strcmp(command, "ip")) /* Get our ip */
		{
			LOG("LAN IP: %s on port %d.", UPnPgetLanAddr(), getServerPort());
//			LOG("External IP: %s.", UPnPgetExternalAddress());
		}
		else if(!strcmp(command, "list") || !strcmp(command, "ls")) /* List all connected clients */
		{
			nlServerList();
		}
		else if(!strcmp(command, "register")) /* Register on the main server. */
		{
			if(!nlServerStartRegister())
				LOG("Unable to reach the register.");
			else
				LOG("Registered.");
		}
		else if(!strcmp(command, "h")
		     || !strcmp(command, "help"))
		{
			LOG("Non exaustive list of commands:\n"
				"\tls:\tList connected players.\n"
				"\tip:\tPrint local IP address with bound port.\n"
				"\tsend:\tSend to the given client the given file.\n"
				"\tquit:\tExit program.");
		}
		else
			LOG("Sorry, unimplemented command: %s.", cmd);	

		AFTER_INPUT;
	}
	
	lFree(&words);
	signalHandler(0);
	
	UNINIT_INPUT;

#ifndef DISABLE_PHYSICS

	thread_exit();

#else

	quit();
	return NULL;

#endif
}