Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Add a configure file and a Makefile to explain we now use cmake.
[simgrid.git] / tools / tesh / run_context.c
index 2c92bb7..41af0d5 100644 (file)
@@ -20,28 +20,49 @@ int fg_job = 0;
 xbt_dynar_t bg_jobs = NULL;
 rctx_t armageddon_initiator = NULL;
 xbt_os_mutex_t armageddon_mutex = NULL;
-pid_t father_pid;
 struct {
   int num;
   struct sigaction act;
 } oldact[3];                    /* SIGINT, SIGQUIT, SIGTERM */
 
+xbt_os_thread_t sigwaiter_thread;
+xbt_os_mutex_t sigwaiter_mutex;
+xbt_os_cond_t sigwaiter_cond;
+int armageddon_requested = 0;
+int caught_signum = 0;
+
 /*
  * Module management
  */
 
 static void armageddon_sighandler(int signum)
 {
-  if (getpid() == father_pid) {
-    ERROR2("Test suite `%s': caught signal %d", testsuite_name, signum);
+  xbt_os_mutex_acquire(sigwaiter_mutex);
+  caught_signum = signum;
+  armageddon_requested = 1;
+  xbt_os_cond_signal(sigwaiter_cond);
+  xbt_os_mutex_release(sigwaiter_mutex);
+}
+
+static void *armageddon_sigwaiter(_XBT_GNUC_UNUSED void *arg)
+{
+  xbt_os_mutex_acquire(sigwaiter_mutex);
+  /* Inform main thread that it started. */
+  xbt_os_cond_signal(sigwaiter_cond);
+  /* Wait for ending signal... */
+  xbt_os_cond_wait(sigwaiter_cond, sigwaiter_mutex);
+  if (armageddon_requested) {
+    ERROR2("Test suite `%s': caught signal %d", testsuite_name, caught_signum);
     rctx_armageddon(rctx, 3);
   }
+  xbt_os_mutex_release(sigwaiter_mutex);
+  return NULL;
 }
 
 static void wait_it(rctx_t rctx)
 {
-  VERB2("Join thread %p which were running background cmd <%s>", rctx->runner,
-        rctx->filepos);
+  VERB2("Join thread %p which were running background cmd <%s>",
+        rctx->runner, rctx->filepos);
   xbt_os_thread_join(rctx->runner, NULL);
 }
 
@@ -60,7 +81,14 @@ void rctx_init(void)
   bg_jobs = xbt_dynar_new_sync(sizeof(rctx_t), kill_it);
   armageddon_mutex = xbt_os_mutex_init();
   armageddon_initiator = NULL;
-  father_pid = getpid();
+  sigwaiter_mutex = xbt_os_mutex_init();
+  sigwaiter_cond = xbt_os_cond_init();
+  xbt_os_mutex_acquire(sigwaiter_mutex);
+  sigwaiter_thread = xbt_os_thread_create("Armaggedon request waiter",
+                                          armageddon_sigwaiter, NULL, NULL);
+  /* Wait for thread to start... */
+  xbt_os_cond_wait(sigwaiter_cond, sigwaiter_mutex);
+  xbt_os_mutex_release(sigwaiter_mutex);
   memset(&newact, 0, sizeof(newact));
   newact.sa_handler = armageddon_sighandler;
   oldact[0].num = SIGINT;
@@ -73,35 +101,27 @@ void rctx_init(void)
 void rctx_exit(void)
 {
   int i;
-  if (bg_jobs) {
-    /* Do not use xbt_dynar_free or it will lock the dynar, preventing armageddon from working */
-    while (xbt_dynar_length(bg_jobs)) {
-      rctx_t rctx = xbt_dynar_getlast_as(bg_jobs, rctx_t);
-      wait_it(rctx);
-      xbt_dynar_pop(bg_jobs, &rctx);
-      rctx_free(rctx);
-    }
-  }
   for (i = 0; i < 3; i++)
     sigaction(oldact[i].num, &oldact[i].act, NULL);
-  if (bg_jobs)
-    xbt_dynar_free(&bg_jobs);
+  xbt_os_cond_signal(sigwaiter_cond);
+  xbt_os_thread_join(sigwaiter_thread, NULL);
+  xbt_dynar_free(&bg_jobs);
+  xbt_os_cond_destroy(sigwaiter_cond);
+  xbt_os_mutex_destroy(sigwaiter_mutex);
   xbt_os_mutex_destroy(armageddon_mutex);
 }
 
 void rctx_wait_bg(void)
 {
-  if (bg_jobs) {
-    /* Do not use xbt_dynar_free or it will lock the dynar, preventing armageddon from working */
-    while (xbt_dynar_length(bg_jobs)) {
-      rctx_t rctx = xbt_dynar_getlast_as(bg_jobs, rctx_t);
-      wait_it(rctx);
-      xbt_dynar_pop(bg_jobs, &rctx);
-      rctx_free(rctx);
-    }
-    xbt_dynar_free(&bg_jobs);
+  /* Do not use xbt_dynar_free or it will lock the dynar, preventing armageddon
+   * from working */
+  while (xbt_dynar_length(bg_jobs)) {
+    rctx_t rctx = xbt_dynar_getlast_as(bg_jobs, rctx_t);
+    wait_it(rctx);
+    xbt_dynar_pop(bg_jobs, &rctx);
+    rctx_free(rctx);
   }
-  bg_jobs = xbt_dynar_new_sync(sizeof(rctx_t), kill_it);
+  xbt_dynar_reset(bg_jobs);
 }
 
 static void rctx_armageddon_kill_one(rctx_t initiator, const char *filepos,
@@ -131,11 +151,11 @@ void rctx_armageddon(rctx_t initiator, int exitcode)
   xbt_os_mutex_acquire(armageddon_mutex);
   if (armageddon_initiator != NULL) {
     VERB0("Armageddon already started. Let it go");
-    xbt_os_mutex_release(initiator->interruption);
     xbt_os_mutex_release(armageddon_mutex);
     return;
   }
-  DEBUG1("Armageddon request by <%s> got the lock. Let's go amok", filepos);
+  DEBUG1("Armageddon request by <%s> got the lock. Let's go amok",
+         filepos);
   armageddon_initiator = initiator;
   xbt_os_mutex_release(armageddon_mutex);
 
@@ -148,6 +168,13 @@ void rctx_armageddon(rctx_t initiator, int exitcode)
     rctx_armageddon_kill_one(initiator, filepos, job);
   }
 
+  /* Give runner threads a chance to acknowledge the processes deaths */
+  usleep(10000);
+  /* Ensure that nobody is running rctx_wait on exit */
+  if (fg_job)
+    xbt_os_mutex_acquire(rctx->interruption);
+  xbt_dynar_foreach(bg_jobs, cursor, job)
+    xbt_os_mutex_acquire(job->interruption);
   VERB0("Shut everything down!");
   exit(exitcode);
 }
@@ -159,7 +186,7 @@ void rctx_armageddon(rctx_t initiator, int exitcode)
 void rctx_empty(rctx_t rc)
 {
   int i;
-  char **env_it = environ;
+  char **env_it;
   void *filepos;
 
   if (rc->cmd)
@@ -170,19 +197,21 @@ void rctx_empty(rctx_t rc)
   rc->filepos = NULL;
   if (filepos)
     free(filepos);
-  if (rc->env)
+  for (i = 0, env_it = environ; *env_it; i++, env_it++);
+  if (rc->env) {
+    for (env_it = rctx->env + i; *env_it; env_it++)
+      free(*env_it);
     free(rc->env);
-
-  for (i = 0; *env_it; i++, env_it++);
-  i++;
-  rc->env_size = i;
-  rc->env = malloc(i * sizeof(char *));
-  memcpy(rc->env, environ, i * sizeof(char *));
+  }
+  rc->env_size = i + 1;
+  rc->env = malloc(rc->env_size * sizeof(char *));
+  memcpy(rc->env, environ, rc->env_size * sizeof(char *));
 
   rc->is_empty = 1;
   rc->is_background = 0;
   rc->is_stoppable = 0;
   rc->output = e_output_check;
+  rc->output_sort = 0;
   rc->brokenpipe = 0;
   rc->timeout = 0;
   rc->interrupted = 0;
@@ -197,6 +226,7 @@ rctx_t rctx_new()
   rctx_t res = xbt_new0(s_rctx_t, 1);
 
   res->input = xbt_strbuff_new();
+  res->output_sort = 0;
   res->output_wanted = xbt_strbuff_new();
   res->output_got = xbt_strbuff_new();
   res->interruption = xbt_os_mutex_init();
@@ -215,8 +245,14 @@ void rctx_free(rctx_t rctx)
     free(rctx->cmd);
   if (rctx->filepos)
     free(rctx->filepos);
-  if (rctx->env)
+  if (rctx->env) {
+    int i;
+    char **env_it;
+    for (i = 0, env_it = environ; *env_it; i++, env_it++);
+    for (env_it = rctx->env + i; *env_it; env_it++)
+      free(*env_it);
     free(rctx->env);
+  }
   xbt_os_mutex_destroy(rctx->interruption);
   xbt_strbuff_free(rctx->input);
   xbt_strbuff_free(rctx->output_got);
@@ -249,9 +285,9 @@ void rctx_pushline(const char *filepos, char kind, char *line)
     if (rctx->cmd) {
       if (!rctx->is_empty) {
         ERROR2
-          ("[%s] More than one command in this chunk of lines (previous: %s).\n"
-           " Cannot guess which input/output belongs to which command.",
-           filepos, rctx->cmd);
+            ("[%s] More than one command in this chunk of lines (previous: %s).\n"
+             " Cannot guess which input/output belongs to which command.",
+             filepos, rctx->cmd);
         ERROR1("Test suite `%s': NOK (syntax error)", testsuite_name);
         rctx_armageddon(rctx, 1);
         return;
@@ -305,6 +341,10 @@ void rctx_pushline(const char *filepos, char kind, char *line)
       VERB2("[%s] (next command must return code %d)",
             filepos, rctx->expected_return);
 
+    } else if (!strncmp(line, "output sort", strlen("output sort"))) {
+      rctx->output_sort = 1;
+      VERB1("[%s] (sort output of next command)", filepos);
+
     } else if (!strncmp(line, "output ignore", strlen("output ignore"))) {
       rctx->output = e_output_ignore;
       VERB1("[%s] (ignore output of next command)", filepos);
@@ -318,6 +358,7 @@ void rctx_pushline(const char *filepos, char kind, char *line)
       char *eq = strchr(line + len, '=');
       char *key = bprintf("%.*s", (int) (eq - line - len), line + len);
       xbt_dict_set(env, key, xbt_strdup(eq + 1), xbt_free_f);
+      free(key);
 
       rctx->env = realloc(rctx->env, ++(rctx->env_size) * sizeof(char *));
       rctx->env[rctx->env_size - 2] = xbt_strdup(line + len);
@@ -349,8 +390,8 @@ static void *thread_writer(void *r)
     int got;
     DEBUG1("Still %d chars to write", rctx->input->used - posw);
     got =
-      write(rctx->child_to, rctx->input->data + posw,
-            rctx->input->used - posw);
+        write(rctx->child_to, rctx->input->data + posw,
+              rctx->input->used - posw);
     if (got > 0)
       posw += got;
     if (got < 0) {
@@ -401,8 +442,10 @@ static void *thread_reader(void *r)
   /* let this thread wait for the child so that the main thread can detect the timeout without blocking on the wait */
   got_pid = waitpid(rctx->pid, &rctx->status, 0);
   if (got_pid != rctx->pid) {
-    perror(bprintf("(%s) Cannot wait for the child %s (got pid %d where pid %d were expected;status=%d)",
-                  xbt_thread_self_name(), rctx->cmd, (int)got_pid, (int)rctx->pid,rctx->status));
+    perror(bprintf
+           ("(%s) Cannot wait for the child %s (got pid %d where pid %d were expected;status=%d)",
+            xbt_thread_self_name(), rctx->cmd, (int) got_pid,
+            (int) rctx->pid, rctx->status));
     ERROR1("Test suite `%s': NOK (system error)", testsuite_name);
     rctx_armageddon(rctx, 4);
     return NULL;
@@ -412,42 +455,57 @@ static void *thread_reader(void *r)
   return NULL;
 }
 
-/* Special command: mkfile is a building creating a file with the input data as content */
+/* Special command: mkfile is a built-in creating a file with the input data as content */
 static void rctx_mkfile(void)
 {
   char *filename = xbt_strdup(rctx->cmd + strlen("mkfile "));
   FILE *OUT;
+  int err;
   xbt_str_trim(filename, NULL);
   OUT = fopen(filename, "w");
   if (!OUT) {
-    free(filename);
     THROW3(system_error, errno, "%s: Cannot create file %s: %s",
            rctx->filepos, filename, strerror(errno));
   }
-  fprintf(OUT, "%s", rctx->input->data);
-  fclose(OUT);
+  err = (fprintf(OUT, "%s", rctx->input->data) < 0);
+  err = (fclose(OUT) == -1) || err;
+  if (err) {
+    THROW3(system_error, errno, "%s: Cannot write file %s: %s",
+           rctx->filepos, filename, strerror(errno));
+  }
+  free(filename);
 }
 
 /* function to be called from the child to start the actual process */
 static void start_command(rctx_t rctx)
 {
-  xbt_dynar_t cmd = xbt_str_split_quoted(rctx->cmd);
+  xbt_dynar_t cmd;
   char *binary_name = NULL;
   unsigned int it;
   char *str;
-  xbt_dynar_get_cpy(cmd, 0, &binary_name);
-  char **args = xbt_new(char *, xbt_dynar_length(cmd) + 1);
+  char **args;
   int errcode;
 
   if (!strncmp(rctx->cmd, "mkfile ", strlen("mkfile "))) {
     rctx_mkfile();
+    /* Valgrind detects memory leaks here.
+     * To correct those leaks, we must free objects allocated in main() or in
+     * handle_suite(), but we have no more reference to them at this point.
+     * A quick and dirty hack to make valgrind happy it to uncomment the
+     * following line.
+     */
+    /* execlp("true", "true", (const char *)0); */
     exit(0);                    /* end the working child */
   }
 
+  cmd = xbt_str_split_quoted(rctx->cmd);
+  xbt_dynar_get_cpy(cmd, 0, &binary_name);
+  args = xbt_new(char *, xbt_dynar_length(cmd) + 1);
   xbt_dynar_foreach(cmd, it, str) {
     args[it] = xbt_strdup(str);
   }
   args[it] = NULL;
+  xbt_dynar_free_container(&cmd);
 
   /* To search for the right executable path when not trivial */
   struct stat stat_buf;
@@ -540,13 +598,11 @@ void rctx_start(void)
 
     rctx->reader_done = 0;
     rctx->reader =
-      xbt_os_thread_create("reader", thread_reader, (void *) rctx);
+        xbt_os_thread_create("reader", thread_reader, (void *) rctx, NULL);
     rctx->writer =
-      xbt_os_thread_create("writer", thread_writer, (void *) rctx);
+        xbt_os_thread_create("writer", thread_writer, (void *) rctx, NULL);
 
   } else {                      /* child */
-    xbt_os_mutex_release(armageddon_mutex);
-
     close(child_in[1]);
     dup2(child_in[0], 0);
     close(child_in[0]);
@@ -575,14 +631,32 @@ void rctx_start(void)
     DEBUG2("RCTX: new bg=%p, new fg=%p", old, rctx);
 
     DEBUG2("Launch a thread to wait for %s %d", old->cmd, old->pid);
-    runner = xbt_os_thread_create(old->cmd, rctx_wait, (void *) old);
+    runner = xbt_os_thread_create(old->cmd, rctx_wait, (void *) old, NULL);
     old->runner = runner;
-    VERB3("Launched thread %p to wait for %s %d", runner, old->cmd, old->pid);
+    VERB3("Launched thread %p to wait for %s %d", runner, old->cmd,
+          old->pid);
     xbt_dynar_push(bg_jobs, &old);
     xbt_os_mutex_release(armageddon_mutex);
   }
 }
 
+/* Helper function to sort the output */
+static int cmpstringp(const void *p1, const void *p2) {
+  /* Sort only using the 19 first chars (date+pid)
+   * If the dates are the same, then, sort using pointer address (be stable wrt output of each process)
+   */
+  const char *s1 = *((const char**) p1);
+  const char *s2 = *((const char**) p2);
+
+  DEBUG2("Compare strings '%s' and '%s'", s1, s2);
+
+  int res = strncmp(s1, s2, 19);
+  if (res == 0)
+    return p1>p2;
+  return res;
+}
+
+
 /* Waits for the child to end (or to timeout), and check its
    ending conditions. This is launched from rctx_start but either in main
    thread (for foreground jobs) or in a separate one for background jobs.
@@ -634,7 +708,8 @@ void *rctx_wait(void *r)
 
   /* Check for broken pipe */
   if (rctx->brokenpipe)
-    VERB0("Warning: Child did not consume all its input (I got broken pipe)");
+    VERB0
+        ("Warning: Child did not consume all its input (I got broken pipe)");
 
   /* Check for timeouts */
   if (rctx->timeout) {
@@ -647,6 +722,7 @@ void *rctx_wait(void *r)
            testsuite_name, rctx->filepos, timeout_value);
     DEBUG2("<%s> Interrupted = %d", rctx->filepos, rctx->interrupted);
     if (!rctx->interrupted) {
+      xbt_os_mutex_release(rctx->interruption);
       rctx_armageddon(rctx, 3);
       return NULL;
     }
@@ -682,9 +758,10 @@ void *rctx_wait(void *r)
     if (WIFEXITED(rctx->status)
         && WEXITSTATUS(rctx->status) != rctx->expected_return) {
       if (rctx->expected_return)
-        ERROR4("Test suite `%s': NOK (<%s> returned code %d instead of %d)",
-               testsuite_name, rctx->filepos,
-               WEXITSTATUS(rctx->status), rctx->expected_return);
+        ERROR4
+            ("Test suite `%s': NOK (<%s> returned code %d instead of %d)",
+             testsuite_name, rctx->filepos, WEXITSTATUS(rctx->status),
+             rctx->expected_return);
       else
         ERROR3("Test suite `%s': NOK (<%s> returned code %d)",
                testsuite_name, rctx->filepos, WEXITSTATUS(rctx->status));
@@ -713,6 +790,20 @@ void *rctx_wait(void *r)
     errcode = 1;
   }
 
+  if (rctx->output_sort) {
+    xbt_dynar_t a = xbt_str_split(rctx->output_got->data, "\n");
+    xbt_dynar_sort(a,cmpstringp);
+    char *sorted_output = xbt_str_join(a, "\n");
+    strcpy(rctx->output_got->data, sorted_output);
+    xbt_free(sorted_output);
+    xbt_dynar_free(&a);
+    /* If an empty line moved in first position, move it back to the end */
+    if (rctx->output_got->data[0]=='\n') {
+      fprintf(stderr,"XXX");
+      memmove(rctx->output_got->data,rctx->output_got->data+1,rctx->output_got->used-1);
+      rctx->output_got->data[rctx->output_got->used-1] = '\n';
+    }
+  }
   if ((errcode && errcode != 1) || rctx->interrupted) {
     /* checking output, and matching */
     xbt_dynar_t a = xbt_str_split(rctx->output_got->data, "\n");
@@ -721,11 +812,12 @@ void *rctx_wait(void *r)
     INFO2("Output of <%s> so far: \n||%s", rctx->filepos, out);
     free(out);
   } else if (rctx->output == e_output_check
-      && (rctx->output_got->used != rctx->output_wanted->used
-          || strcmp(rctx->output_got->data, rctx->output_wanted->data))) {
+             && (rctx->output_got->used != rctx->output_wanted->used
+                 || strcmp(rctx->output_got->data,
+                           rctx->output_wanted->data))) {
     if (XBT_LOG_ISENABLED(tesh, xbt_log_priority_info)) {
       char *diff =
-        xbt_str_diff(rctx->output_wanted->data, rctx->output_got->data);
+          xbt_str_diff(rctx->output_wanted->data, rctx->output_got->data);
       ERROR2("Output of <%s> mismatch:\n%s", rctx->filepos, diff);
       free(diff);
     }
@@ -752,8 +844,8 @@ void *rctx_wait(void *r)
   }
   if (errcode) {
     if (!rctx->interrupted) {
-      rctx_armageddon(rctx, errcode);
       xbt_os_mutex_release(rctx->interruption);
+      rctx_armageddon(rctx, errcode);
       return NULL;
     }
   }