1 /* run_context -- stuff in which TESH runs a command */
3 /* Copyright (c) 2007, 2008, 2009, 2010. The SimGrid Team.
4 * All rights reserved. */
6 /* This program is free software; you can redistribute it and/or modify it
7 * under the terms of the license (GNU LGPL) which comes with this package. */
11 #include <sys/types.h>
16 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(tesh);
18 xbt_dynar_t bg_jobs = NULL;
19 rctx_t armageddon_initiator = NULL;
20 xbt_os_mutex_t armageddon_mutex = NULL;
26 static void kill_it(void *r)
28 rctx_t rctx = *(rctx_t *) r;
30 VERB2("Join thread %p which were running background cmd <%s>", rctx->runner,
32 xbt_os_thread_join(rctx->runner, NULL);
38 bg_jobs = xbt_dynar_new_sync(sizeof(rctx_t), kill_it);
39 armageddon_mutex = xbt_os_mutex_init();
40 armageddon_initiator = NULL;
46 /* Do not use xbt_dynar_free or it will lock the dynar, preventing armageddon from working */
47 while (xbt_dynar_length(bg_jobs)) {
49 xbt_dynar_pop(bg_jobs, &rctx);
52 xbt_dynar_free(&bg_jobs);
54 xbt_os_mutex_destroy(armageddon_mutex);
57 void rctx_wait_bg(void)
60 /* Do not use xbt_dynar_free or it will lock the dynar, preventing armageddon from working */
61 while (xbt_dynar_length(bg_jobs)) {
63 xbt_dynar_pop(bg_jobs, &rctx);
66 xbt_dynar_free(&bg_jobs);
68 bg_jobs = xbt_dynar_new_sync(sizeof(rctx_t), kill_it);
71 void rctx_armageddon(rctx_t initiator, int exitcode)
75 DEBUG2("Armageddon request by <%s> (exit=%d)", initiator->filepos,
77 xbt_os_mutex_acquire(armageddon_mutex);
78 if (armageddon_initiator != NULL) {
79 VERB0("Armageddon already started. Let it go");
80 xbt_os_mutex_release(initiator->interruption);
81 xbt_os_mutex_release(armageddon_mutex);
84 DEBUG1("Armageddon request by <%s> got the lock. Let's go amok",
86 armageddon_initiator = initiator;
87 xbt_os_mutex_release(armageddon_mutex);
89 /* Kill any background commands */
90 while (xbt_dynar_length(bg_jobs)) {
91 xbt_dynar_pop(bg_jobs, &rctx);
92 if (rctx != initiator) {
93 INFO2("Kill <%s> because <%s> failed", rctx->filepos,
95 xbt_os_mutex_acquire(rctx->interruption);
96 rctx->interrupted = 1;
97 xbt_os_mutex_release(rctx->interruption);
98 if (!rctx->reader_done) {
99 kill(rctx->pid, SIGTERM);
101 kill(rctx->pid, SIGKILL);
106 VERB0("Shut everything down!");
114 void rctx_empty(rctx_t rc)
117 char **env_it = environ;
127 for (i = 0; *env_it; i++, env_it++);
130 rc->env = malloc(i * sizeof(char *));
131 memcpy(rc->env, environ, i * sizeof(char *));
135 rc->is_background = 0;
136 rc->is_stoppable = 0;
137 rc->output = e_output_check;
141 xbt_strbuff_empty(rc->input);
142 xbt_strbuff_empty(rc->output_wanted);
143 xbt_strbuff_empty(rc->output_got);
149 rctx_t res = xbt_new0(s_rctx_t, 1);
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();
159 void rctx_free(rctx_t rctx)
161 DEBUG1("RCTX: Free %p", rctx);
162 rctx_dump(rctx, "free");
172 xbt_os_mutex_destroy(rctx->interruption);
173 xbt_strbuff_free(rctx->input);
174 xbt_strbuff_free(rctx->output_got);
175 xbt_strbuff_free(rctx->output_wanted);
179 void rctx_dump(rctx_t rctx, const char *str)
181 DEBUG9("%s RCTX %p={in%p={%d,%10s}, want={%d,%10s}, out={%d,%10s}}",
183 rctx->input, rctx->input->used, rctx->input->data,
184 rctx->output_wanted->used, rctx->output_wanted->data,
185 rctx->output_got->used, rctx->output_got->data);
186 DEBUG5("%s RCTX %p=[cmd%p=%10s, pid=%d]",
187 str, rctx, rctx->cmd, rctx->cmd, rctx->pid);
192 * Getting instructions from the file
195 void rctx_pushline(const char *filepos, char kind, char *line)
202 if (!rctx->is_empty) {
204 ("[%s] More than one command in this chunk of lines (previous: %s).\n"
205 " Cannot guess which input/output belongs to which command.",
207 ERROR1("Test suite `%s': NOK (syntax error)", testsuite_name);
208 rctx_armageddon(rctx, 1);
212 VERB1("[%s] More than one command in this chunk of lines", filepos);
215 rctx->is_background = 1;
217 rctx->is_background = 0;
219 rctx->cmd = xbt_strdup(line);
220 rctx->filepos = xbt_strdup(filepos);
221 INFO3("[%s] %s%s", filepos, rctx->cmd,
222 ((rctx->is_background) ? " (background command)" : ""));
228 xbt_strbuff_append(rctx->input, line);
229 xbt_strbuff_append(rctx->input, "\n");
234 xbt_strbuff_append(rctx->output_wanted, line);
235 xbt_strbuff_append(rctx->output_wanted, "\n");
242 if (!strncmp(line, "timeout no", strlen("timeout no"))) {
243 VERB1("[%s] (disable timeout)", filepos);
245 } else if (!strncmp(line, "timeout ", strlen("timeout "))) {
246 timeout_value = atoi(line + strlen("timeout"));
247 VERB2("[%s] (new timeout value: %d)", filepos, timeout_value);
249 } else if (!strncmp(line, "expect signal ", strlen("expect signal "))) {
250 rctx->expected_signal = strdup(line + strlen("expect signal "));
251 xbt_str_trim(rctx->expected_signal, " \n");
252 VERB2("[%s] (next command must raise signal %s)",
253 filepos, rctx->expected_signal);
255 } else if (!strncmp(line, "expect return ", strlen("expect return "))) {
256 rctx->expected_return = atoi(line + strlen("expect return "));
257 VERB2("[%s] (next command must return code %d)",
258 filepos, rctx->expected_return);
260 } else if (!strncmp(line, "output ignore", strlen("output ignore"))) {
261 rctx->output = e_output_ignore;
262 VERB1("[%s] (ignore output of next command)", filepos);
264 } else if (!strncmp(line, "output display", strlen("output display"))) {
265 rctx->output = e_output_display;
266 VERB1("[%s] (ignore output of next command)", filepos);
268 } else if (!strncmp(line, "setenv ", strlen("setenv "))) {
269 int len = strlen("setenv ");
270 char *eq = strchr(line + len, '=');
271 char *key = bprintf("%.*s", (int) (eq - line - len), line + len);
272 xbt_dict_set(env, key, xbt_strdup(eq + 1), xbt_free_f);
274 rctx->env = realloc(rctx->env, ++(rctx->env_size) * sizeof(char *));
275 rctx->env[rctx->env_size - 2] = xbt_strdup(line + len);
276 rctx->env[rctx->env_size - 1] = NULL;
277 VERB2("[%s] setenv %s", filepos, line + len);
280 ERROR2("%s: Malformed metacommand: %s", filepos, line);
281 ERROR1("Test suite `%s': NOK (syntax error)", testsuite_name);
282 rctx_armageddon(rctx, 1);
290 * Actually doing the job
293 /* The IO of the childs are handled by the two following threads
294 (one pair per child) */
296 static void *thread_writer(void *r)
299 rctx_t rctx = (rctx_t) r;
300 for (posw = 0; posw < rctx->input->used && !rctx->brokenpipe;) {
302 DEBUG1("Still %d chars to write", rctx->input->used - posw);
304 write(rctx->child_to, rctx->input->data + posw,
305 rctx->input->used - posw);
309 if (errno == EPIPE) {
310 rctx->brokenpipe = 1;
311 } else if (errno != EINTR && errno != EAGAIN && errno != EPIPE) {
312 perror("Error while writing input to child");
313 ERROR1("Test suite `%s': NOK (system error)", testsuite_name);
314 rctx_armageddon(rctx, 4);
318 DEBUG1("written %d chars so far", posw);
323 rctx->input->data[0] = '\0';
324 rctx->input->used = 0;
325 close(rctx->child_to);
330 static void *thread_reader(void *r)
332 rctx_t rctx = (rctx_t) r;
333 char *buffout = malloc(4096);
337 posr = read(rctx->child_from, buffout, 4095);
338 if (posr < 0 && errno != EINTR && errno != EAGAIN) {
339 perror("Error while reading output of child");
340 ERROR1("Test suite `%s': NOK (system error)", testsuite_name);
341 rctx_armageddon(rctx, 4);
345 buffout[posr] = '\0';
346 xbt_strbuff_append(rctx->output_got, buffout);
350 } while (!rctx->timeout && posr != 0);
353 /* let this thread wait for the child so that the main thread can detect the timeout without blocking on the wait */
354 got_pid = waitpid(rctx->pid, &rctx->status, 0);
355 if (got_pid != rctx->pid) {
356 perror(bprintf("(%s) Cannot wait for the child %s (got pid %d where pid %d were expected;status=%d)",
357 xbt_thread_self_name(), rctx->cmd, (int)got_pid, (int)rctx->pid,rctx->status));
358 ERROR1("Test suite `%s': NOK (system error)", testsuite_name);
359 rctx_armageddon(rctx, 4);
363 rctx->reader_done = 1;
367 /* Special command: mkfile is a building creating a file with the input data as content */
368 static void rctx_mkfile(void)
370 char *filename = xbt_strdup(rctx->cmd + strlen("mkfile "));
372 xbt_str_trim(filename, NULL);
373 OUT = fopen(filename, "w");
376 THROW3(system_error, errno, "%s: Cannot create file %s: %s",
377 rctx->filepos, filename, strerror(errno));
379 fprintf(OUT, "%s", rctx->input->data);
383 /* function to be called from the child to start the actual process */
384 static void start_command(rctx_t rctx)
386 xbt_dynar_t cmd = xbt_str_split_quoted(rctx->cmd);
387 char *binary_name = NULL;
390 xbt_dynar_get_cpy(cmd, 0, &binary_name);
391 char **args = xbt_new(char *, xbt_dynar_length(cmd) + 1);
394 if (!strncmp(rctx->cmd, "mkfile ", strlen("mkfile "))) {
396 exit(0); /* end the working child */
399 xbt_dynar_foreach(cmd, it, str) {
400 args[it] = xbt_strdup(str);
404 /* To search for the right executable path when not trivial */
405 struct stat stat_buf;
407 /* build the command line */
408 if (stat(binary_name, &stat_buf)) {
409 /* Damn. binary not in current dir. We'll have to dig the PATH to find it */
412 for (i = 0; environ[i]; i++) {
413 if (!strncmp("PATH=", environ[i], 5)) {
414 xbt_dynar_t path = xbt_str_split(environ[i] + 5, ":");
416 xbt_dynar_foreach(path, it, str) {
419 binary_name = bprintf("%s/%s", str, args[0]);
420 if (!stat(binary_name, &stat_buf)) {
422 DEBUG1("Looked in the PATH for the binary. Found %s",
424 xbt_dynar_free(&path);
428 xbt_dynar_free(&path);
429 if (stat(binary_name, &stat_buf)) {
431 printf("TESH_ERROR Command %s not found\n", args[0]);
438 binary_name = xbt_strdup(args[0]);
441 errcode = execve(binary_name, args, rctx->env);
442 printf("TESH_ERROR %s: Cannot start %s: %s\n", rctx->filepos, rctx->cmd,
447 /* Start a new child, plug the pipes as expected and fire up the
448 helping threads. Is also waits for the child to end if this is a
449 foreground job, or fire up a thread to wait otherwise. */
450 void rctx_start(void)
455 DEBUG1("Cmd before rewriting %s", rctx->cmd);
456 rctx->cmd = xbt_str_varsubst(rctx->cmd, env);
457 VERB2("Start %s %s", rctx->cmd,
458 (rctx->is_background ? "(background job)" : ""));
459 if (pipe(child_in) || pipe(child_out)) {
460 perror("Cannot open the pipes");
461 ERROR1("Test suite `%s': NOK (system error)", testsuite_name);
462 rctx_armageddon(rctx, 4);
467 perror("Cannot fork the command");
468 ERROR1("Test suite `%s': NOK (system error)", testsuite_name);
469 rctx_armageddon(rctx, 4);
473 if (rctx->pid) { /* father */
475 rctx->child_to = child_in[1];
478 rctx->child_from = child_out[0];
480 if (timeout_value > 0)
481 rctx->end_time = time(NULL) + timeout_value;
485 rctx->reader_done = 0;
487 xbt_os_thread_create("reader", thread_reader, (void *) rctx);
489 xbt_os_thread_create("writer", thread_writer, (void *) rctx);
494 dup2(child_in[0], 0);
498 dup2(child_out[1], 1);
499 dup2(child_out[1], 2);
505 rctx->is_stoppable = 1;
507 if (!rctx->is_background) {
510 /* Damn. Copy the rctx and launch a thread to handle it */
512 xbt_os_thread_t runner;
515 DEBUG2("RCTX: new bg=%p, new fg=%p", old, rctx);
517 DEBUG2("Launch a thread to wait for %s %d", old->cmd, old->pid);
518 runner = xbt_os_thread_create(old->cmd, rctx_wait, (void *) old);
519 old->runner = runner;
520 VERB3("Launched thread %p to wait for %s %d", runner, old->cmd, old->pid);
521 xbt_dynar_push(bg_jobs, &old);
525 /* Waits for the child to end (or to timeout), and check its
526 ending conditions. This is launched from rctx_start but either in main
527 thread (for foreground jobs) or in a separate one for background jobs.
528 That explains the prototype, forced by xbt_os_thread_create. */
530 void *rctx_wait(void *r)
532 rctx_t rctx = (rctx_t) r;
534 int now = time(NULL);
536 rctx_dump(rctx, "wait");
538 if (!rctx->is_stoppable)
539 THROW1(unknown_error, 0, "Cmd '%s' not started yet. Cannot wait it",
542 /* Wait for the child to die or the timeout to happen (or an armageddon to happen) */
543 while (!rctx->interrupted && !rctx->reader_done
544 && (rctx->end_time < 0 || rctx->end_time >= now)) {
549 xbt_os_mutex_acquire(rctx->interruption);
550 if (!rctx->interrupted && rctx->end_time > 0 && rctx->end_time < now) {
551 INFO1("<%s> timeouted. Kill the process.", rctx->filepos);
553 kill(rctx->pid, SIGTERM);
555 kill(rctx->pid, SIGKILL);
556 rctx->reader_done = 1;
559 /* Make sure helper threads die.
560 Cannot block since they wait for the child we just killed
561 if not already dead. */
562 xbt_os_thread_join(rctx->writer, NULL);
563 xbt_os_thread_join(rctx->reader, NULL);
565 /* xbt_os_mutex_release(rctx->interruption);
566 if (rctx->interrupted)
568 xbt_os_mutex_acquire(rctx->interruption); */
570 xbt_strbuff_chomp(rctx->output_got);
571 xbt_strbuff_chomp(rctx->output_wanted);
572 xbt_strbuff_trim(rctx->output_got);
573 xbt_strbuff_trim(rctx->output_wanted);
575 /* Check for broken pipe */
576 if (rctx->brokenpipe)
577 VERB0("Warning: Child did not consume all its input (I got broken pipe)");
579 /* Check for timeouts */
581 if (rctx->output_got->data[0])
582 INFO2("<%s> Output on timeout:\n%s",
583 rctx->filepos, rctx->output_got->data);
585 INFO1("<%s> No output before timeout", rctx->filepos);
586 ERROR3("Test suite `%s': NOK (<%s> timeout after %d sec)",
587 testsuite_name, rctx->filepos, timeout_value);
588 DEBUG2("<%s> Interrupted = %d", rctx->filepos, rctx->interrupted);
589 if (!rctx->interrupted) {
590 rctx_armageddon(rctx, 3);
595 DEBUG2("RCTX=%p (pid=%d)", rctx, rctx->pid);
596 DEBUG3("Status(%s|%d)=%d", rctx->cmd, rctx->pid, rctx->status);
598 if (!rctx->interrupted) {
599 if (WIFSIGNALED(rctx->status) && !rctx->expected_signal) {
600 ERROR3("Test suite `%s': NOK (<%s> got signal %s)",
601 testsuite_name, rctx->filepos,
602 signal_name(WTERMSIG(rctx->status), NULL));
603 errcode = WTERMSIG(rctx->status) + 4;
606 if (WIFSIGNALED(rctx->status) && rctx->expected_signal &&
607 strcmp(signal_name(WTERMSIG(rctx->status), rctx->expected_signal),
608 rctx->expected_signal)) {
609 ERROR4("Test suite `%s': NOK (%s got signal %s instead of %s)",
610 testsuite_name, rctx->filepos,
611 signal_name(WTERMSIG(rctx->status), rctx->expected_signal),
612 rctx->expected_signal);
613 errcode = WTERMSIG(rctx->status) + 4;
616 if (!WIFSIGNALED(rctx->status) && rctx->expected_signal) {
617 ERROR3("Test suite `%s': NOK (child %s expected signal %s)",
618 testsuite_name, rctx->filepos, rctx->expected_signal);
622 if (WIFEXITED(rctx->status)
623 && WEXITSTATUS(rctx->status) != rctx->expected_return) {
624 if (rctx->expected_return)
625 ERROR4("Test suite `%s': NOK (<%s> returned code %d instead of %d)",
626 testsuite_name, rctx->filepos,
627 WEXITSTATUS(rctx->status), rctx->expected_return);
629 ERROR3("Test suite `%s': NOK (<%s> returned code %d)",
630 testsuite_name, rctx->filepos, WEXITSTATUS(rctx->status));
631 errcode = 40 + WEXITSTATUS(rctx->status);
634 rctx->expected_return = 0;
636 if (rctx->expected_signal) {
637 free(rctx->expected_signal);
638 rctx->expected_signal = NULL;
641 while (rctx->output_got->used
642 && !strncmp(rctx->output_got->data, "TESH_ERROR ",
643 strlen("TESH_ERROR "))) {
644 int marklen = strlen("TESH_ERROR ");
645 char *endline = strchr(rctx->output_got->data, '\n');
647 CRITICAL2("%.*s", (int) (endline - rctx->output_got->data - marklen),
648 rctx->output_got->data + marklen);
649 memmove(rctx->output_got->data, rctx->output_got->data + marklen,
650 rctx->output_got->used - marklen);
651 rctx->output_got->used -= endline - rctx->output_got->data + 1;
652 rctx->output_got->data[rctx->output_got->used] = '\0';
656 if (rctx->output == e_output_check
657 && (rctx->output_got->used != rctx->output_wanted->used
658 || strcmp(rctx->output_got->data, rctx->output_wanted->data))) {
659 if (XBT_LOG_ISENABLED(tesh, xbt_log_priority_info)) {
661 xbt_str_diff(rctx->output_wanted->data, rctx->output_got->data);
662 ERROR2("Output of <%s> mismatch:\n%s", rctx->filepos, diff);
665 ERROR2("Test suite `%s': NOK (<%s> output mismatch)",
666 testsuite_name, rctx->filepos);
669 } else if (rctx->output == e_output_ignore) {
670 INFO1("(ignoring the output of <%s> as requested)", rctx->filepos);
671 } else if (rctx->output == e_output_display) {
672 xbt_dynar_t a = xbt_str_split(rctx->output_got->data, "\n");
673 char *out = xbt_str_join(a, "\n||");
675 INFO1("Here is the (ignored) command output: \n||%s", out);
677 } else if ((errcode && errcode != 1) || rctx->interrupted) {
678 /* checking output, and matching */
679 xbt_dynar_t a = xbt_str_split(rctx->output_got->data, "\n");
680 char *out = xbt_str_join(a, "\n||");
682 INFO2("Output of <%s> so far: \n||%s", rctx->filepos, out);
686 if (!rctx->is_background) {
690 if (!rctx->interrupted) {
691 rctx_armageddon(rctx, errcode);
696 xbt_os_mutex_release(rctx->interruption);