Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
keep up with lastest diff computation changes
[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->check_output = 1;
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         exit(1);
113       }
114       rctx_start();
115       VERB1("[%s] More than one command in this chunk of lines",filepos);
116     }
117     if (kind == '&')
118       rctx->is_background = 1;
119     else
120       rctx->is_background = 0;
121       
122     rctx->cmd = xbt_strdup(line);
123     INFO3("[%s] %s%s",filepos,line,
124           ((rctx->is_background)?" (background command)":""));
125
126     break;
127     
128   case '<':
129     rctx->is_empty = 0;
130     buff_append(rctx->input,line);
131     buff_append(rctx->input,"\n");
132     break;
133
134   case '>':
135     rctx->is_empty = 0;
136     buff_append(rctx->output_wanted,line);
137     buff_append(rctx->output_wanted,"\n");
138     break;
139
140   case '!':
141     if (rctx->cmd)
142       rctx_start();
143
144     if (!strncmp(line,"set timeout ",strlen("set timeout "))) {
145       timeout_value=atoi(line+strlen("set timeout"));
146       VERB2("[%s] (new timeout value: %d)",
147              filepos,timeout_value);
148
149     } else if (!strncmp(line,"expect signal ",strlen("expect signal "))) {
150       rctx->expected_signal = strdup(line + strlen("expect signal "));
151       xbt_str_trim(rctx->expected_signal," \n");
152            VERB2("[%s] (next command must raise signal %s)", 
153                  filepos, rctx->expected_signal);
154
155     } else if (!strncmp(line,"expect return ",strlen("expect return "))) {
156       rctx->expected_return = atoi(line+strlen("expect return "));
157       VERB2("[%s] (next command must return code %d)",
158             filepos, rctx->expected_return);
159
160     } else if (!strncmp(line,"ignore output",strlen("ignore output"))) {
161       rctx->check_output = 0;
162       VERB1("[%s] (ignore output of next command)", filepos);
163        
164     } else {
165       ERROR2("%s: Malformed metacommand: %s",filepos,line);
166       exit(1);
167     }
168     break;
169   }
170 }
171
172 /* 
173  * Actually doing the job
174  */
175
176 /* The IO of the childs are handled by the two following threads
177    (one pair per child) */
178
179 static void* thread_writer(void *r) {
180   int posw;
181   rctx_t rctx = (rctx_t)r;
182   for (posw=0; posw<rctx->input->used && !rctx->brokenpipe; ) {
183     int got;
184     DEBUG1("Still %d chars to write",rctx->input->used-posw);
185     got=write(rctx->child_to,rctx->input->data+posw,rctx->input->used-posw);
186     if (got>0)
187       posw+=got;
188     if (got<0) {
189       if (errno == EPIPE) {
190         rctx->brokenpipe = 1;
191       } else if (errno!=EINTR && errno!=EAGAIN && errno!=EPIPE) {
192         perror("Error while writing input to child");
193           exit(4);
194       }
195     }
196     DEBUG1("written %d chars so far",posw);
197
198     if (got <= 0)
199       usleep(100);
200   }
201   rctx->input->data[0]='\0';
202   rctx->input->used=0;
203   close(rctx->child_to);
204
205   return NULL;
206 }
207 static void *thread_reader(void *r) {
208   rctx_t rctx = (rctx_t)r;
209   char *buffout=malloc(4096);
210   int posr;
211
212   do {
213     posr=read(rctx->child_from,buffout,4095);
214     if (posr<0 && errno!=EINTR && errno!=EAGAIN) {
215       perror("Error while reading output of child");
216       exit(4);
217     }
218     if (posr>0) {
219       buffout[posr]='\0';
220       buff_append(rctx->output_got,buffout);
221     } else {
222       usleep(100);
223     }
224   } while (!rctx->timeout && posr!=0);
225   free(buffout);
226   rctx->reader_done = 1;
227   return NULL;
228
229
230 /* Start a new child, plug the pipes as expected and fire up the 
231    helping threads. Is also waits for the child to end if this is a 
232    foreground job, or fire up a thread to wait otherwise. */
233
234 void rctx_start(void) {
235   int child_in[2];
236   int child_out[2];
237
238   VERB2("Start %s %s",rctx->cmd,(rctx->is_background?"(background job)":""));
239   if (pipe(child_in) || pipe(child_out)) {
240     perror("Cannot open the pipes");
241     exit(4);
242   }
243
244   rctx->pid=fork();
245   if (rctx->pid<0) {
246     perror("Cannot fork the command");
247     exit(4);
248   }
249
250   if (rctx->pid) { /* father */
251     close(child_in[0]);
252     rctx->child_to = child_in[1];
253
254     close(child_out[1]);
255     rctx->child_from = child_out[0];
256
257     rctx->end_time = time(NULL) + timeout_value;
258
259     rctx->reader = xbt_thread_create(thread_reader,(void*)rctx);
260     rctx->writer = xbt_thread_create(thread_writer,(void*)rctx);
261
262   } else { /* child */
263
264     close(child_in[1]);
265     dup2(child_in[0],0);
266     close(child_in[0]);
267
268     close(child_out[0]);
269     dup2(child_out[1],1);
270     dup2(child_out[1],2);
271     close(child_out[1]);
272
273     execlp ("/bin/sh", "sh", "-c", rctx->cmd, NULL);
274   }
275
276   rctx->is_stoppable = 1;
277
278   if (!rctx->is_background) {
279     rctx_wait(rctx);
280   } else {
281     /* Damn. Copy the rctx and launch a thread to handle it */
282     rctx_t old = rctx;
283     xbt_thread_t runner;
284
285     rctx = rctx_new();
286     DEBUG2("RCTX: new bg=%p, new fg=%p",old,rctx);
287
288     DEBUG2("Launch a thread to wait for %s %d",old->cmd,old->pid);
289     runner = xbt_thread_create(rctx_wait,(void*)old);
290     VERB3("Launched thread %p to wait for %s %d",
291           runner,old->cmd, old->pid);
292     xbt_dynar_push(bg_jobs,&runner);
293   }
294 }
295
296 /* Waits for the child to end (or to timeout), and check its 
297    ending conditions. This is launched from rctx_start but either in main
298    thread (for foreground jobs) or in a separate one for background jobs. 
299    That explains the prototype, forced by xbt_thread_create. */
300
301 void *rctx_wait(void* r) {
302   rctx_t rctx = (rctx_t)r;
303   int errcode = 0;
304   int res;
305   int status;
306     
307   rctx_dump(rctx,"wait");
308
309   if (!rctx->is_stoppable) 
310     THROW1(unknown_error,0,"Cmd '%s' not started yet. Cannot wait it",
311            rctx->cmd);
312
313   /* Wait for the child to die or the timeout to happen */
314   while (!rctx->reader_done && rctx->end_time > time(NULL)) {
315     usleep(100);
316   }
317
318   if (!rctx->reader_done) {
319     INFO1("Child '%s' timeouted. Kill it",rctx->cmd);
320     rctx->timeout = 1;
321     kill(rctx->pid,SIGKILL);
322   }
323   /* Make sure helper threads die.
324      Cannot block since they wait for the child we just killed
325      if not already dead. */
326   xbt_thread_join(rctx->writer,NULL);
327   xbt_thread_join(rctx->reader,NULL);
328
329   /* Check for broken pipe */
330   if (rctx->brokenpipe)
331     VERB0("Warning: Child did not consume all its input (I got broken pipe)");
332
333   /* Check for timeouts */
334   if (rctx->timeout) {
335     ERROR1("Child timeouted (waited %d sec)",timeout_value);
336     exit(3);
337   }
338       
339   DEBUG2("Wait for %s (%d)",rctx->cmd,rctx->pid);
340   res = waitpid(rctx->pid,&status,0);
341   if (res != rctx->pid) {
342     perror(bprintf("Cannot wait for the child %s",rctx->cmd));
343     exit(1);
344   }
345   DEBUG2("RCTX=%p (pid=%d)",rctx,rctx->pid);
346   DEBUG3("Status(%s|%d)=%d",rctx->cmd,rctx->pid,status);
347
348   if (WIFSIGNALED(status) && !rctx->expected_signal) {
349     ERROR2("Child \"%s\" got signal %s.", rctx->cmd,
350             signal_name(WTERMSIG(status),NULL));
351     errcode = WTERMSIG(status)+4;       
352   }
353
354   if (WIFSIGNALED(status) && rctx->expected_signal &&
355       strcmp(signal_name(WTERMSIG(status),rctx->expected_signal),
356              rctx->expected_signal)) {
357     ERROR3("Child \"%s\" got signal %s instead of signal %s", rctx->cmd,
358             signal_name(WTERMSIG(status),rctx->expected_signal),
359             rctx->expected_signal);
360     errcode = WTERMSIG(status)+4;       
361   }
362   
363   if (!WIFSIGNALED(status) && rctx->expected_signal) {
364     ERROR2("Child \"%s\" didn't got expected signal %s",
365            rctx->cmd, rctx->expected_signal);
366     errcode = 5;
367   }
368
369   if (WIFEXITED(status) && WEXITSTATUS(status) != rctx->expected_return ) {
370     if (rctx->expected_return) 
371       ERROR3("Child \"%s\" returned code %d instead of %d", rctx->cmd,
372              WEXITSTATUS(status), rctx->expected_return);
373     else
374       ERROR2("Child \"%s\" returned code %d", rctx->cmd, WEXITSTATUS(status));
375     errcode = 40+WEXITSTATUS(status);
376   }
377   rctx->expected_return = 0;
378   
379   if(rctx->expected_signal){
380     free(rctx->expected_signal);
381     rctx->expected_signal = NULL;
382   }
383
384   buff_chomp(rctx->output_got);
385   buff_chomp(rctx->output_wanted);
386   buff_trim(rctx->output_got);
387   buff_trim(rctx->output_wanted);
388
389   if (   rctx->check_output 
390       && (    rctx->output_got->used != rctx->output_wanted->used
391            || strcmp(rctx->output_got->data, rctx->output_wanted->data))) {
392     char *diff= xbt_str_diff(rctx->output_wanted->data,rctx->output_got->data);
393     ERROR2("Output of child \"%s\" don't match expectations. Here is a diff between expected and got output:\n%s",
394            rctx->cmd,diff);
395     free(diff);
396     errcode=2;
397   } else if (!rctx->check_output) {
398     INFO0("(ignoring the output as requested)");
399   }
400
401   if (rctx->is_background)
402     rctx_free(rctx);
403   else
404     rctx_empty(rctx);
405   if (errcode)
406     exit (errcode);
407
408   return NULL;
409 }
410