Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
1246e8903e1b7f0375ab54d59035a213e824438e
[simgrid.git] / tools / tesh / run_context.c
1 /* $Id$ */
2
3 /* run_context -- stuff in which TESH runs a command                        */
4
5 /* Copyright (c) 2007 Martin Quinson.                                       */
6 /* All rights reserved.                                                     */
7
8 /* This program is free software; you can redistribute it and/or modify it
9  * under the terms of the license (GNU LGPL) which comes with this package. */
10
11 #include "tesh.h"
12
13 #include <sys/types.h>
14 #include <sys/wait.h>
15
16 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(tesh);
17
18 xbt_dynar_t bg_jobs = NULL;
19 rctx_t armageddon_initiator = NULL;
20 xbt_os_mutex_t armageddon_mutex = NULL;
21
22 /*
23  * Module management
24  */
25
26 static void kill_it(void*r) {
27   rctx_t rctx = *(rctx_t*)r;
28
29   VERB2("Join thread %p which were running background cmd <%s>",rctx->runner,rctx->filepos);
30   xbt_os_thread_join(rctx->runner,NULL);
31   rctx_free(rctx);
32 }
33
34 void rctx_init(void) {
35   bg_jobs = xbt_dynar_new_sync(sizeof(rctx_t),kill_it);
36   armageddon_mutex = xbt_os_mutex_init();
37   armageddon_initiator = NULL;
38 }
39
40 void rctx_exit(void) {
41   if (bg_jobs) {
42     /* Do not use xbt_dynar_free or it will lock the dynar, preventing armageddon from working */
43     while (xbt_dynar_length(bg_jobs)) {
44        rctx_t rctx;
45        xbt_dynar_pop(bg_jobs,&rctx);
46        kill_it(&rctx);
47     }
48     xbt_dynar_free(&bg_jobs);
49   }
50   xbt_os_mutex_destroy(armageddon_mutex);
51 }
52
53 void rctx_wait_bg(void) {
54   if (bg_jobs) {
55     /* Do not use xbt_dynar_free or it will lock the dynar, preventing armageddon from working */
56     while (xbt_dynar_length(bg_jobs)) {
57        rctx_t rctx;
58        xbt_dynar_pop(bg_jobs,&rctx);
59        kill_it(&rctx);
60     }
61     xbt_dynar_free(&bg_jobs);
62   }
63   bg_jobs = xbt_dynar_new_sync(sizeof(rctx_t),kill_it);
64 }
65
66 void rctx_armageddon(rctx_t initiator, int exitcode) {
67   rctx_t rctx;
68
69   DEBUG2("Armageddon request by <%s> (exit=%d)",initiator->filepos,exitcode);
70   xbt_os_mutex_acquire(armageddon_mutex);
71   if (armageddon_initiator != NULL) {
72     VERB0("Armageddon already started. Let it go");
73     xbt_os_mutex_release(initiator->interruption);
74     xbt_os_mutex_release(armageddon_mutex);
75     return;
76   }
77   DEBUG1("Armageddon request by <%s> got the lock. Let's go amok",initiator->filepos);
78   armageddon_initiator = initiator;
79   xbt_os_mutex_release(armageddon_mutex);
80
81   /* Kill any background commands */
82   while (xbt_dynar_length(bg_jobs)) {
83     xbt_dynar_pop(bg_jobs,&rctx);
84     if (rctx != initiator) {
85       INFO2("Kill <%s> because <%s> failed",rctx->filepos,initiator->filepos);
86       xbt_os_mutex_acquire(rctx->interruption);
87       rctx->interrupted = 1;
88       xbt_os_mutex_release(rctx->interruption);
89       if (!rctx->reader_done) {
90         kill(rctx->pid,SIGTERM);
91         usleep(100);
92         kill(rctx->pid,SIGKILL);
93       }
94     }
95   }
96
97   VERB0("Shut everything down!");
98   exit(exitcode);
99 }
100
101 /*
102  * Memory management
103  */
104
105 # ifdef __APPLE__
106 /* under darwin, the environment gets added to the process at startup time. So, it's not defined at library link time, forcing us to extra tricks */
107 # include <crt_externs.h>
108 # define environ (*_NSGetEnviron())
109 # else
110  /* the environment, as specified by the opengroup, used to initialize the process properties */
111  extern char **environ;
112 # endif
113
114 void rctx_empty(rctx_t rc) {
115   int i;
116   char **env_it=environ;
117
118   if (rc->cmd)
119     free(rc->cmd);
120   rc->cmd = NULL;
121   if (rc->filepos)
122     free(rc->filepos);
123   if (rc->env)
124      free(rc->env);
125
126   for (i=0;*env_it;i++,env_it++);
127   i++;
128   rc->env_size = i;
129   rc->env = malloc(i*sizeof(char*));
130   memcpy(rc->env,environ,i*sizeof(char*));
131
132   rc->filepos = NULL;
133   rc->is_empty = 1;
134   rc->is_background = 0;
135   rc->is_stoppable = 0;
136   rc->output = e_output_check;
137   rc->brokenpipe = 0;
138   rc->timeout = 0;
139   rc->interrupted = 0;
140   xbt_strbuff_empty(rc->input);
141   xbt_strbuff_empty(rc->output_wanted);
142   xbt_strbuff_empty(rc->output_got);
143 }
144
145
146 rctx_t rctx_new() {
147   rctx_t res = xbt_new0(s_rctx_t,1);
148
149   res->input=xbt_strbuff_new();
150   res->output_wanted=xbt_strbuff_new();
151   res->output_got=xbt_strbuff_new();
152   res->interruption = xbt_os_mutex_init();
153   rctx_empty(res);
154   return res;
155 }
156
157 void rctx_free(rctx_t rctx) {
158   DEBUG1("RCTX: Free %p", rctx);
159   rctx_dump(rctx,"free");
160   if (!rctx)
161     return;
162
163   if (rctx->cmd)
164     free(rctx->cmd);
165   if (rctx->filepos)
166     free(rctx->filepos);
167   if (rctx->env)
168     free(rctx->env);
169   xbt_os_mutex_destroy(rctx->interruption);
170   xbt_strbuff_free(rctx->input);
171   xbt_strbuff_free(rctx->output_got);
172   xbt_strbuff_free(rctx->output_wanted);
173   free(rctx);
174 }
175
176 void rctx_dump(rctx_t rctx, const char *str) {
177   DEBUG9("%s RCTX %p={in%p={%d,%10s}, want={%d,%10s}, out={%d,%10s}}",
178          str, rctx,
179          rctx->input,              rctx->input->used,        rctx->input->data,
180          rctx->output_wanted->used,rctx->output_wanted->data,
181          rctx->output_got->used,   rctx->output_got->data);
182   DEBUG5("%s RCTX %p=[cmd%p=%10s, pid=%d]",
183          str,rctx,rctx->cmd,rctx->cmd,rctx->pid);
184
185 }
186
187 /*
188  * Getting instructions from the file
189  */
190
191 void rctx_pushline(const char* filepos, char kind, char *line) {
192
193   switch (kind) {
194   case '$':
195   case '&':
196     if (rctx->cmd) {
197       if (!rctx->is_empty) {
198         ERROR2("[%s] More than one command in this chunk of lines (previous: %s).\n"
199                " Dunno which input/output belongs to which command.",
200                filepos,rctx->cmd);
201         ERROR1("Test suite `%s': NOK (syntax error)",testsuite_name);
202         rctx_armageddon(rctx,1);
203         return;
204       }
205       rctx_start();
206       VERB1("[%s] More than one command in this chunk of lines",filepos);
207     }
208     if (kind == '&')
209       rctx->is_background = 1;
210     else
211       rctx->is_background = 0;
212
213     rctx->cmd = xbt_strdup(line);
214     rctx->filepos = xbt_strdup(filepos);
215     INFO3("[%s] %s%s",filepos,rctx->cmd,
216           ((rctx->is_background)?" (background command)":""));
217
218     break;
219
220   case '<':
221     rctx->is_empty = 0;
222     xbt_strbuff_append(rctx->input,line);
223     xbt_strbuff_append(rctx->input,"\n");
224     break;
225
226   case '>':
227     rctx->is_empty = 0;
228     xbt_strbuff_append(rctx->output_wanted,line);
229     xbt_strbuff_append(rctx->output_wanted,"\n");
230     break;
231
232   case '!':
233     if (rctx->cmd)
234       rctx_start();
235
236     if (!strncmp(line,"timeout no",strlen("timeout no"))) {
237       VERB1("[%s] (disable timeout)", filepos);
238       timeout_value = -1;
239     } else if (!strncmp(line,"timeout ",strlen("timeout "))) {
240       timeout_value=atoi(line+strlen("timeout"));
241       VERB2("[%s] (new timeout value: %d)",
242              filepos,timeout_value);
243
244     } else if (!strncmp(line,"expect signal ",strlen("expect signal "))) {
245       rctx->expected_signal = strdup(line + strlen("expect signal "));
246       xbt_str_trim(rctx->expected_signal," \n");
247            VERB2("[%s] (next command must raise signal %s)",
248                  filepos, rctx->expected_signal);
249
250     } else if (!strncmp(line,"expect return ",strlen("expect return "))) {
251       rctx->expected_return = atoi(line+strlen("expect return "));
252       VERB2("[%s] (next command must return code %d)",
253             filepos, rctx->expected_return);
254
255     } else if (!strncmp(line,"output ignore",strlen("output ignore"))) {
256       rctx->output = e_output_ignore;
257       VERB1("[%s] (ignore output of next command)", filepos);
258
259     } else if (!strncmp(line,"output display",strlen("output display"))) {
260       rctx->output = e_output_display;
261       VERB1("[%s] (ignore output of next command)", filepos);
262
263     } else if (!strncmp(line,"setenv ",strlen("setenv "))) {
264       rctx->env = realloc(rctx->env,++(rctx->env_size)*sizeof(char*));
265       rctx->env[rctx->env_size-2] = xbt_strdup(line+strlen("setenv "));
266       rctx->env[rctx->env_size-1] = NULL;
267       VERB1("[%s] (ignore output of next command)", filepos);
268
269     } else {
270       ERROR2("%s: Malformed metacommand: %s",filepos,line);
271       ERROR1("Test suite `%s': NOK (syntax error)",testsuite_name);
272       rctx_armageddon(rctx,1);
273       return;
274     }
275     break;
276   }
277 }
278
279 /*
280  * Actually doing the job
281  */
282
283 /* The IO of the childs are handled by the two following threads
284    (one pair per child) */
285
286 static void* thread_writer(void *r) {
287   int posw;
288   rctx_t rctx = (rctx_t)r;
289   for (posw=0; posw<rctx->input->used && !rctx->brokenpipe; ) {
290     int got;
291     DEBUG1("Still %d chars to write",rctx->input->used-posw);
292     got=write(rctx->child_to,rctx->input->data+posw,rctx->input->used-posw);
293     if (got>0)
294       posw+=got;
295     if (got<0) {
296       if (errno == EPIPE) {
297         rctx->brokenpipe = 1;
298       } else if (errno!=EINTR && errno!=EAGAIN && errno!=EPIPE) {
299         perror("Error while writing input to child");
300         ERROR1("Test suite `%s': NOK (system error)",testsuite_name);
301         rctx_armageddon(rctx,4);
302         return NULL;
303       }
304     }
305     DEBUG1("written %d chars so far",posw);
306
307     if (got <= 0)
308       usleep(100);
309   }
310   rctx->input->data[0]='\0';
311   rctx->input->used=0;
312   close(rctx->child_to);
313
314   return NULL;
315 }
316 static void *thread_reader(void *r) {
317   rctx_t rctx = (rctx_t)r;
318   char *buffout=malloc(4096);
319   int posr, got_pid;
320
321   do {
322     posr=read(rctx->child_from,buffout,4095);
323     if (posr<0 && errno!=EINTR && errno!=EAGAIN) {
324       perror("Error while reading output of child");
325       ERROR1("Test suite `%s': NOK (system error)", testsuite_name);
326       rctx_armageddon(rctx,4);
327       return NULL;
328     }
329     if (posr>0) {
330       buffout[posr]='\0';
331       xbt_strbuff_append(rctx->output_got,buffout);
332     } else {
333       usleep(100);
334     }
335   } while (!rctx->timeout && posr!=0);
336   free(buffout);
337
338   /* let this thread wait for the child so that the main thread can detect the timeout without blocking on the wait */
339   got_pid = waitpid(rctx->pid,&rctx->status,0);
340   if (got_pid != rctx->pid) {
341     perror(bprintf("Cannot wait for the child %s",rctx->cmd));
342     ERROR1("Test suite `%s': NOK (system error)", testsuite_name);
343     rctx_armageddon(rctx,4);
344     return NULL;
345   }
346
347   rctx->reader_done = 1;
348   return NULL;
349 }
350
351 /* Start a new child, plug the pipes as expected and fire up the
352    helping threads. Is also waits for the child to end if this is a
353    foreground job, or fire up a thread to wait otherwise. */
354
355 void rctx_start(void) {
356   int child_in[2];
357   int child_out[2];
358
359   VERB2("Start %s %s",rctx->cmd,(rctx->is_background?"(background job)":""));
360   if (pipe(child_in) || pipe(child_out)) {
361     perror("Cannot open the pipes");
362     ERROR1("Test suite `%s': NOK (system error)", testsuite_name);
363     rctx_armageddon(rctx,4);
364   }
365
366   rctx->pid=fork();
367   if (rctx->pid<0) {
368     perror("Cannot fork the command");
369     ERROR1("Test suite `%s': NOK (system error)", testsuite_name);
370     rctx_armageddon(rctx,4);
371     return;
372   }
373
374   if (rctx->pid) { /* father */
375     close(child_in[0]);
376     rctx->child_to = child_in[1];
377
378     close(child_out[1]);
379     rctx->child_from = child_out[0];
380
381     if (timeout_value > 0)
382        rctx->end_time = time(NULL) + timeout_value;
383     else
384        rctx->end_time = -1;
385
386     rctx->reader_done = 0;
387     rctx->reader = xbt_os_thread_create("reader",thread_reader,(void*)rctx);
388     rctx->writer = xbt_os_thread_create("writer",thread_writer,(void*)rctx);
389
390   } else { /* child */
391
392     close(child_in[1]);
393     dup2(child_in[0],0);
394     close(child_in[0]);
395
396     close(child_out[0]);
397     dup2(child_out[1],1);
398     dup2(child_out[1],2);
399     close(child_out[1]);
400
401         xbt_dynar_t cmd = xbt_str_split_quoted(rctx->cmd);
402         char *file;
403         unsigned int it;
404         char *str;
405         xbt_dynar_get_cpy(cmd,0,&file);
406         char **args = xbt_new(char*,xbt_dynar_length(cmd)+1);
407         xbt_dynar_foreach(cmd,it,str)
408                 args[it] = xbt_strdup(str);
409         args[it] = NULL;
410         execve(file, args, rctx->env);
411   }
412
413   rctx->is_stoppable = 1;
414
415   if (!rctx->is_background) {
416     rctx_wait(rctx);
417   } else {
418     /* Damn. Copy the rctx and launch a thread to handle it */
419     rctx_t old = rctx;
420     xbt_os_thread_t runner;
421
422     rctx = rctx_new();
423     DEBUG2("RCTX: new bg=%p, new fg=%p",old,rctx);
424
425     DEBUG2("Launch a thread to wait for %s %d",old->cmd,old->pid);
426     runner = xbt_os_thread_create(old->cmd,rctx_wait,(void*)old);
427     old->runner = runner;
428     VERB3("Launched thread %p to wait for %s %d",
429           runner,old->cmd, old->pid);
430     xbt_dynar_push(bg_jobs,&old);
431   }
432 }
433
434 /* Waits for the child to end (or to timeout), and check its
435    ending conditions. This is launched from rctx_start but either in main
436    thread (for foreground jobs) or in a separate one for background jobs.
437    That explains the prototype, forced by xbt_os_thread_create. */
438
439 void *rctx_wait(void* r) {
440   rctx_t rctx = (rctx_t)r;
441   int errcode = 0;
442   int now = time(NULL);
443
444   rctx_dump(rctx,"wait");
445
446   if (!rctx->is_stoppable)
447     THROW1(unknown_error,0,"Cmd '%s' not started yet. Cannot wait it",
448            rctx->cmd);
449
450   /* Wait for the child to die or the timeout to happen (or an armageddon to happen) */
451   while (!rctx->interrupted && !rctx->reader_done && (rctx->end_time <0 ||rctx->end_time >= now)) {
452     usleep(100);
453     now = time(NULL);
454   }
455
456   xbt_os_mutex_acquire(rctx->interruption);
457   if (!rctx->interrupted && rctx->end_time > 0 && rctx->end_time < now) {
458     INFO1("<%s> timeouted. Kill the process.",rctx->filepos);
459     rctx->timeout = 1;
460     kill(rctx->pid,SIGTERM);
461     usleep(100);
462     kill(rctx->pid,SIGKILL);
463     rctx->reader_done = 1;
464   }
465
466   /* Make sure helper threads die.
467      Cannot block since they wait for the child we just killed
468      if not already dead. */
469   xbt_os_thread_join(rctx->writer,NULL);
470   xbt_os_thread_join(rctx->reader,NULL);
471
472   /*  xbt_os_mutex_release(rctx->interruption);
473   if (rctx->interrupted)
474     return NULL;
475     xbt_os_mutex_acquire(rctx->interruption);*/
476
477   xbt_strbuff_chomp(rctx->output_got);
478   xbt_strbuff_chomp(rctx->output_wanted);
479   xbt_strbuff_trim(rctx->output_got);
480   xbt_strbuff_trim(rctx->output_wanted);
481
482   /* Check for broken pipe */
483   if (rctx->brokenpipe)
484     VERB0("Warning: Child did not consume all its input (I got broken pipe)");
485
486   /* Check for timeouts */
487   if (rctx->timeout) {
488     if (rctx->output_got->data[0])
489       INFO2("<%s> Output on timeout:\n%s",
490             rctx->filepos,rctx->output_got->data);
491     else
492       INFO1("<%s> No output before timeout",
493             rctx->filepos);
494     ERROR3("Test suite `%s': NOK (<%s> timeout after %d sec)",
495            testsuite_name,rctx->filepos,timeout_value);
496     DEBUG2("<%s> Interrupted = %d", rctx->filepos, rctx->interrupted);
497     if (!rctx->interrupted) {
498       rctx_armageddon(rctx, 3);
499       return NULL;
500     }
501   }
502
503   DEBUG2("RCTX=%p (pid=%d)",rctx,rctx->pid);
504   DEBUG3("Status(%s|%d)=%d",rctx->cmd,rctx->pid,rctx->status);
505
506   if (!rctx->interrupted) {
507     if (WIFSIGNALED(rctx->status) && !rctx->expected_signal) {
508       ERROR3("Test suite `%s': NOK (<%s> got signal %s)",
509              testsuite_name, rctx->filepos,
510              signal_name(WTERMSIG(rctx->status),NULL));
511       errcode = WTERMSIG(rctx->status)+4;
512     }
513
514     if (WIFSIGNALED(rctx->status) && rctx->expected_signal &&
515         strcmp(signal_name(WTERMSIG(rctx->status),rctx->expected_signal),
516                rctx->expected_signal)) {
517       ERROR4("Test suite `%s': NOK (%s got signal %s instead of %s)",
518              testsuite_name, rctx->filepos,
519              signal_name(WTERMSIG(rctx->status),rctx->expected_signal),
520              rctx->expected_signal);
521       errcode = WTERMSIG(rctx->status)+4;
522     }
523
524     if (!WIFSIGNALED(rctx->status) && rctx->expected_signal) {
525       ERROR3("Test suite `%s': NOK (child %s expected signal %s)",
526              testsuite_name, rctx->filepos,
527              rctx->expected_signal);
528       errcode = 5;
529     }
530
531     if (WIFEXITED(rctx->status) && WEXITSTATUS(rctx->status) != rctx->expected_return ) {
532       if (rctx->expected_return)
533         ERROR4("Test suite `%s': NOK (<%s> returned code %d instead of %d)",
534                testsuite_name, rctx->filepos,
535                WEXITSTATUS(rctx->status), rctx->expected_return);
536       else
537         ERROR3("Test suite `%s': NOK (<%s> returned code %d)",
538                testsuite_name, rctx->filepos, WEXITSTATUS(rctx->status));
539       errcode = 40+WEXITSTATUS(rctx->status);
540
541     }
542     rctx->expected_return = 0;
543
544     if(rctx->expected_signal){
545       free(rctx->expected_signal);
546       rctx->expected_signal = NULL;
547     }
548   }
549
550   if (   rctx->output == e_output_check
551       && (    rctx->output_got->used != rctx->output_wanted->used
552            || strcmp(rctx->output_got->data, rctx->output_wanted->data))) {
553     if (XBT_LOG_ISENABLED(tesh,xbt_log_priority_info)) {
554        char *diff= xbt_str_diff(rctx->output_wanted->data,rctx->output_got->data);
555        ERROR2("Output of <%s> mismatch:\n%s",rctx->filepos,diff);
556        free(diff);
557     }
558     ERROR2("Test suite `%s': NOK (<%s> output mismatch)",
559            testsuite_name,rctx->filepos);
560
561     errcode=2;
562   } else if (rctx->output == e_output_ignore) {
563     INFO1("(ignoring the output of <%s> as requested)",rctx->filepos);
564   } else if (rctx->output == e_output_display) {
565     xbt_dynar_t a = xbt_str_split(rctx->output_got->data, "\n");
566     char *out = xbt_str_join(a,"\n||");
567     xbt_dynar_free(&a);
568     INFO1("Here is the (ignored) command output: \n||%s",out);
569     free(out);
570   } else if (errcode || rctx->interrupted) {
571     /* checking output, and matching */
572     xbt_dynar_t a = xbt_str_split(rctx->output_got->data, "\n");
573     char *out = xbt_str_join(a,"\n||");
574     xbt_dynar_free(&a);
575     INFO2("Output of <%s> so far: \n||%s",rctx->filepos,out);
576     free(out);
577   }
578
579   if (!rctx->is_background) {
580     rctx_empty(rctx);
581   }
582   if (errcode) {
583     if (!rctx->interrupted) {
584       rctx_armageddon(rctx, errcode);
585       return NULL;
586     }
587   }
588
589   xbt_os_mutex_release(rctx->interruption);
590   return NULL;
591 }
592