Logo AND Algorithmique Numérique Distribuée

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