Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Error message pretty printing (to ease grepping on the automatic ranking of my studen...
[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
17 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(tesh);
18
19 xbt_dynar_t bg_jobs = NULL;
20
21 /* 
22  * Module management
23  */
24
25 static void join_it(void*t) {  
26   xbt_thread_t th = *(xbt_thread_t*)t;
27   VERB1("Join thread %p which were running a background cmd",th);
28   xbt_thread_join(th,NULL);
29 }
30
31 void rctx_init(void) {
32   bg_jobs = xbt_dynar_new(sizeof(xbt_thread_t),join_it);
33 }
34
35 void rctx_exit(void) {
36   xbt_dynar_free(&bg_jobs);
37 }
38
39 void rctx_wait_bg(void) {
40   xbt_dynar_free(&bg_jobs);
41   bg_jobs = xbt_dynar_new(sizeof(xbt_thread_t),join_it);
42 }
43
44 /*
45  * Memory management
46  */
47
48 void rctx_empty(rctx_t rc) {
49   if (rc->cmd)
50     free(rc->cmd);
51   rc->cmd = NULL;
52   rc->is_empty = 1;
53   rc->is_background = 0;
54   rc->is_stoppable = 0;
55   rc->output = e_output_check;
56   rc->brokenpipe = 0;
57   rc->timeout = 0;
58   buff_empty(rc->input);
59   buff_empty(rc->output_wanted);
60   buff_empty(rc->output_got);
61 }
62
63 rctx_t rctx_new() {
64   rctx_t res = xbt_new0(s_rctx_t,1);
65
66   res->input=buff_new();
67   res->output_wanted=buff_new();
68   res->output_got=buff_new();
69   rctx_empty(res);
70   return res;
71 }
72
73 void rctx_free(rctx_t rctx) {
74   DEBUG1("RCTX: Free %p", rctx);
75   rctx_dump(rctx,"free");
76   if (!rctx)
77     return;
78
79   if (rctx->cmd)
80     free(rctx->cmd);
81   buff_free(rctx->input);
82   buff_free(rctx->output_got);
83   buff_free(rctx->output_wanted);
84   free(rctx);
85 }
86
87 void rctx_dump(rctx_t rctx, const char *str) {
88   DEBUG9("%s RCTX %p={in%p={%d,%10s}, want={%d,%10s}, out={%d,%10s}}",
89          str, rctx,
90          rctx->input,              rctx->input->used,        rctx->input->data,
91          rctx->output_wanted->used,rctx->output_wanted->data,
92          rctx->output_got->used,   rctx->output_got->data);
93   DEBUG5("%s RCTX %p=[cmd%p=%10s, pid=%d]",
94          str,rctx,rctx->cmd,rctx->cmd,rctx->pid);
95
96 }
97
98 /*
99  * Getting instructions from the file
100  */
101
102 void rctx_pushline(const char* filepos, char kind, char *line) {
103   
104   switch (kind) {
105   case '$':
106   case '&':
107     if (rctx->cmd) {
108       if (!rctx->is_empty) {
109         ERROR2("[%s] More than one command in this chunk of lines (previous: %s).\n"
110                " Dunno which input/output belongs to which command.",
111                filepos,rctx->cmd);
112         ERROR1("Test suite `%s': NOK (syntax error)",testsuite_name);
113         exit(1);
114       }
115       rctx_start();
116       VERB1("[%s] More than one command in this chunk of lines",filepos);
117     }
118     if (kind == '&')
119       rctx->is_background = 1;
120     else
121       rctx->is_background = 0;
122       
123     rctx->cmd = xbt_strdup(line);
124     INFO3("[%s] %s%s",filepos,line,
125           ((rctx->is_background)?" (background command)":""));
126
127     break;
128     
129   case '<':
130     rctx->is_empty = 0;
131     buff_append(rctx->input,line);
132     buff_append(rctx->input,"\n");
133     break;
134
135   case '>':
136     rctx->is_empty = 0;
137     buff_append(rctx->output_wanted,line);
138     buff_append(rctx->output_wanted,"\n");
139     break;
140
141   case '!':
142     if (rctx->cmd)
143       rctx_start();
144
145     if (!strncmp(line,"set timeout ",strlen("set timeout "))) {
146       timeout_value=atoi(line+strlen("set timeout"));
147       VERB2("[%s] (new timeout value: %d)",
148              filepos,timeout_value);
149
150     } else if (!strncmp(line,"expect signal ",strlen("expect signal "))) {
151       rctx->expected_signal = strdup(line + strlen("expect signal "));
152       xbt_str_trim(rctx->expected_signal," \n");
153            VERB2("[%s] (next command must raise signal %s)", 
154                  filepos, rctx->expected_signal);
155
156     } else if (!strncmp(line,"expect return ",strlen("expect return "))) {
157       rctx->expected_return = atoi(line+strlen("expect return "));
158       VERB2("[%s] (next command must return code %d)",
159             filepos, rctx->expected_return);
160
161     } else if (!strncmp(line,"output ignore",strlen("output ignore"))) {
162       rctx->output = e_output_ignore;
163       VERB1("[%s] (ignore output of next command)", filepos);
164        
165     } else if (!strncmp(line,"output display",strlen("output display"))) {
166       rctx->output = e_output_display;
167       VERB1("[%s] (ignore output of next command)", filepos);
168        
169     } else {
170       ERROR2("%s: Malformed metacommand: %s",filepos,line);
171       ERROR1("Test suite `%s': NOK (syntax error)",testsuite_name);
172       exit(1);
173     }
174     break;
175   }
176 }
177
178 /* 
179  * Actually doing the job
180  */
181
182 /* The IO of the childs are handled by the two following threads
183    (one pair per child) */
184
185 static void* thread_writer(void *r) {
186   int posw;
187   rctx_t rctx = (rctx_t)r;
188   for (posw=0; posw<rctx->input->used && !rctx->brokenpipe; ) {
189     int got;
190     DEBUG1("Still %d chars to write",rctx->input->used-posw);
191     got=write(rctx->child_to,rctx->input->data+posw,rctx->input->used-posw);
192     if (got>0)
193       posw+=got;
194     if (got<0) {
195       if (errno == EPIPE) {
196         rctx->brokenpipe = 1;
197       } else if (errno!=EINTR && errno!=EAGAIN && errno!=EPIPE) {
198         perror("Error while writing input to child");
199         ERROR1("Test suite `%s': NOK (system error)",testsuite_name);
200         exit(4);
201       }
202     }
203     DEBUG1("written %d chars so far",posw);
204
205     if (got <= 0)
206       usleep(100);
207   }
208   rctx->input->data[0]='\0';
209   rctx->input->used=0;
210   close(rctx->child_to);
211
212   return NULL;
213 }
214 static void *thread_reader(void *r) {
215   rctx_t rctx = (rctx_t)r;
216   char *buffout=malloc(4096);
217   int posr, got_pid;
218
219   do {
220     posr=read(rctx->child_from,buffout,4095);
221     if (posr<0 && errno!=EINTR && errno!=EAGAIN) {
222       perror("Error while reading output of child");
223       ERROR1("Test suite `%s': NOK (system error)", testsuite_name);
224       exit(4);
225     }
226     if (posr>0) {
227       buffout[posr]='\0';
228       buff_append(rctx->output_got,buffout);
229     } else {
230       usleep(100);
231     }
232   } while (!rctx->timeout && posr!=0);
233   free(buffout);
234
235   /* let this thread wait for the child so that the main thread can detect the timeout without blocking on the wait */
236   got_pid = waitpid(rctx->pid,&rctx->status,0);
237   if (got_pid != rctx->pid) {
238     perror(bprintf("Cannot wait for the child %s",rctx->cmd));
239     ERROR1("Test suite `%s': NOK (system error)", testsuite_name);
240     exit(4);
241   }
242    
243   rctx->reader_done = 1;
244   return NULL;
245
246
247 /* Start a new child, plug the pipes as expected and fire up the 
248    helping threads. Is also waits for the child to end if this is a 
249    foreground job, or fire up a thread to wait otherwise. */
250
251 void rctx_start(void) {
252   int child_in[2];
253   int child_out[2];
254
255   VERB2("Start %s %s",rctx->cmd,(rctx->is_background?"(background job)":""));
256   if (pipe(child_in) || pipe(child_out)) {
257     perror("Cannot open the pipes");
258     ERROR1("Test suite `%s': NOK (system error)", testsuite_name);
259     exit(4);
260   }
261
262   rctx->pid=fork();
263   if (rctx->pid<0) {
264     perror("Cannot fork the command");
265     ERROR1("Test suite `%s': NOK (system error)", testsuite_name);
266     exit(4);
267   }
268
269   if (rctx->pid) { /* father */
270     close(child_in[0]);
271     rctx->child_to = child_in[1];
272
273     close(child_out[1]);
274     rctx->child_from = child_out[0];
275
276     rctx->end_time = time(NULL) + timeout_value;
277
278     rctx->reader_done = 0;
279     rctx->reader = xbt_thread_create(thread_reader,(void*)rctx);
280     rctx->writer = xbt_thread_create(thread_writer,(void*)rctx);
281
282   } else { /* child */
283
284     close(child_in[1]);
285     dup2(child_in[0],0);
286     close(child_in[0]);
287
288     close(child_out[0]);
289     dup2(child_out[1],1);
290     dup2(child_out[1],2);
291     close(child_out[1]);
292
293     execlp ("/bin/sh", "sh", "-c", rctx->cmd, NULL);
294   }
295
296   rctx->is_stoppable = 1;
297
298   if (!rctx->is_background) {
299     rctx_wait(rctx);
300   } else {
301     /* Damn. Copy the rctx and launch a thread to handle it */
302     rctx_t old = rctx;
303     xbt_thread_t runner;
304
305     rctx = rctx_new();
306     DEBUG2("RCTX: new bg=%p, new fg=%p",old,rctx);
307
308     DEBUG2("Launch a thread to wait for %s %d",old->cmd,old->pid);
309     runner = xbt_thread_create(rctx_wait,(void*)old);
310     VERB3("Launched thread %p to wait for %s %d",
311           runner,old->cmd, old->pid);
312     xbt_dynar_push(bg_jobs,&runner);
313   }
314 }
315
316 /* Waits for the child to end (or to timeout), and check its 
317    ending conditions. This is launched from rctx_start but either in main
318    thread (for foreground jobs) or in a separate one for background jobs. 
319    That explains the prototype, forced by xbt_thread_create. */
320
321 void *rctx_wait(void* r) {
322   rctx_t rctx = (rctx_t)r;
323   int errcode = 0;
324   int now = time(NULL);
325     
326   rctx_dump(rctx,"wait");
327
328   if (!rctx->is_stoppable) 
329     THROW1(unknown_error,0,"Cmd '%s' not started yet. Cannot wait it",
330            rctx->cmd);
331
332     usleep(100);
333   /* Wait for the child to die or the timeout to happen */
334   while (!rctx->reader_done && rctx->end_time >= now) {
335     usleep(100);
336     now = time(NULL);
337   }
338    
339   if (rctx->end_time < now) {
340     INFO1("Child '%s' timeouted. Kill it",rctx->cmd);
341     rctx->timeout = 1;
342     kill(rctx->pid,SIGTERM);
343     usleep(100);
344     kill(rctx->pid,SIGKILL);    
345   }
346    
347   /* Make sure helper threads die.
348      Cannot block since they wait for the child we just killed
349      if not already dead. */
350   xbt_thread_join(rctx->writer,NULL);
351   xbt_thread_join(rctx->reader,NULL);
352
353   /* Check for broken pipe */
354   if (rctx->brokenpipe)
355     VERB0("Warning: Child did not consume all its input (I got broken pipe)");
356
357   /* Check for timeouts */
358   if (rctx->timeout) {
359     ERROR2("Test suite `%s': NOK (timeout after %d sec)", testsuite_name,timeout_value);
360     exit(3);
361   }
362       
363   DEBUG2("RCTX=%p (pid=%d)",rctx,rctx->pid);
364   DEBUG3("Status(%s|%d)=%d",rctx->cmd,rctx->pid,rctx->status);
365
366   if (WIFSIGNALED(rctx->status) && !rctx->expected_signal) {
367     ERROR2("Test suite `%s': NOK (child got signal %s)", 
368            testsuite_name,
369            signal_name(WTERMSIG(rctx->status),NULL));
370     errcode = WTERMSIG(rctx->status)+4; 
371   }
372
373   if (WIFSIGNALED(rctx->status) && rctx->expected_signal &&
374       strcmp(signal_name(WTERMSIG(rctx->status),rctx->expected_signal),
375              rctx->expected_signal)) {
376     ERROR3("Test suite `%s': NOK (child got signal %s instead of %s)", testsuite_name,
377             signal_name(WTERMSIG(rctx->status),rctx->expected_signal),
378             rctx->expected_signal);
379     errcode = WTERMSIG(rctx->status)+4; 
380   }
381   
382   if (!WIFSIGNALED(rctx->status) && rctx->expected_signal) {
383     ERROR2("Test suite `%s': NOK (child expected signal %s)", testsuite_name,
384            rctx->expected_signal);
385     errcode = 5;
386   }
387
388   if (WIFEXITED(rctx->status) && WEXITSTATUS(rctx->status) != rctx->expected_return ) {
389     if (rctx->expected_return) 
390       ERROR3("Test suite `%s': NOK (child returned code %d instead of %d)", testsuite_name,
391              WEXITSTATUS(rctx->status), rctx->expected_return);
392     else
393       ERROR2("Test suite `%s': NOK (child returned code %d)", testsuite_name, WEXITSTATUS(rctx->status));
394     errcode = 40+WEXITSTATUS(rctx->status);
395     
396   }
397   rctx->expected_return = 0;
398   
399   if(rctx->expected_signal){
400     free(rctx->expected_signal);
401     rctx->expected_signal = NULL;
402   }
403
404   buff_chomp(rctx->output_got);
405   buff_chomp(rctx->output_wanted);
406   buff_trim(rctx->output_got);
407   buff_trim(rctx->output_wanted);
408
409   if (   rctx->output == e_output_check
410       && (    rctx->output_got->used != rctx->output_wanted->used
411            || strcmp(rctx->output_got->data, rctx->output_wanted->data))) {
412     if (XBT_LOG_ISENABLED(tesh,xbt_log_priority_info)) {
413        char *diff= xbt_str_diff(rctx->output_wanted->data,rctx->output_got->data);        
414        ERROR1("Output mismatch:\n%s",
415               diff);
416        free(diff);
417     }     
418     ERROR1("Test suite `%s': NOK (output mismatch)", testsuite_name);
419      
420     errcode=2;
421   } else if (rctx->output == e_output_ignore) {
422     INFO0("(ignoring the output as requested)");
423   } else if (rctx->output == e_output_display) {
424     xbt_dynar_t a = xbt_str_split(rctx->output_got->data, "\n");
425     char *out = xbt_str_join(a,"\n||");
426     xbt_dynar_free(&a);
427     INFO1("Here is the (ignored) command output: \n||%s",out);
428     free(out);
429   }
430
431   if (rctx->is_background)
432     rctx_free(rctx);
433   else
434     rctx_empty(rctx);
435   if (errcode) {
436     if (rctx->output == e_output_check)
437       INFO1("Here is the child's output:\n%s",rctx->output_got->data);
438     exit (errcode);
439   }
440
441   return NULL;
442 }
443