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. */
12 #include <sys/types.h>
17 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(tesh);
20 xbt_dynar_t bg_jobs = NULL;
21 rctx_t armageddon_initiator = NULL;
22 xbt_os_mutex_t armageddon_mutex = NULL;
27 } oldact[3]; /* SIGINT, SIGQUIT, SIGTERM */
33 static void armageddon_sighandler(int signum)
35 if (getpid() == father_pid) {
36 ERROR2("Test suite `%s': caught signal %d", testsuite_name, signum);
37 rctx_armageddon(rctx, 3);
41 static void wait_it(rctx_t rctx)
43 VERB2("Join thread %p which were running background cmd <%s>",
44 rctx->runner, rctx->filepos);
45 xbt_os_thread_join(rctx->runner, NULL);
48 static void kill_it(void *r)
50 rctx_t rctx = *(rctx_t *) r;
57 struct sigaction newact;
60 bg_jobs = xbt_dynar_new_sync(sizeof(rctx_t), kill_it);
61 armageddon_mutex = xbt_os_mutex_init();
62 armageddon_initiator = NULL;
63 father_pid = getpid();
64 memset(&newact, 0, sizeof(newact));
65 newact.sa_handler = armageddon_sighandler;
66 oldact[0].num = SIGINT;
67 oldact[1].num = SIGQUIT;
68 oldact[2].num = SIGTERM;
69 for (i = 0; i < 3; i++)
70 sigaction(oldact[i].num, &newact, &oldact[i].act);
77 /* Do not use xbt_dynar_free or it will lock the dynar, preventing armageddon from working */
78 while (xbt_dynar_length(bg_jobs)) {
79 rctx_t rctx = xbt_dynar_getlast_as(bg_jobs, rctx_t);
81 xbt_dynar_pop(bg_jobs, &rctx);
85 for (i = 0; i < 3; i++)
86 sigaction(oldact[i].num, &oldact[i].act, NULL);
88 xbt_dynar_free(&bg_jobs);
89 xbt_os_mutex_destroy(armageddon_mutex);
92 void rctx_wait_bg(void)
95 /* Do not use xbt_dynar_free or it will lock the dynar, preventing armageddon from working */
96 while (xbt_dynar_length(bg_jobs)) {
97 rctx_t rctx = xbt_dynar_getlast_as(bg_jobs, rctx_t);
99 xbt_dynar_pop(bg_jobs, &rctx);
102 xbt_dynar_free(&bg_jobs);
104 bg_jobs = xbt_dynar_new_sync(sizeof(rctx_t), kill_it);
107 static void rctx_armageddon_kill_one(rctx_t initiator, const char *filepos,
110 if (rctx != initiator) {
111 INFO2("Kill <%s> because <%s> failed", rctx->filepos, filepos);
112 xbt_os_mutex_acquire(rctx->interruption);
113 if (!rctx->reader_done) {
114 rctx->interrupted = 1;
115 kill(rctx->pid, SIGTERM);
117 kill(rctx->pid, SIGKILL);
119 xbt_os_mutex_release(rctx->interruption);
123 void rctx_armageddon(rctx_t initiator, int exitcode)
127 const char *filepos = initiator && initiator->filepos ?
128 initiator->filepos : "(master)";
130 DEBUG2("Armageddon request by <%s> (exit=%d)", filepos, exitcode);
131 xbt_os_mutex_acquire(armageddon_mutex);
132 if (armageddon_initiator != NULL) {
133 VERB0("Armageddon already started. Let it go");
134 xbt_os_mutex_release(initiator->interruption);
135 xbt_os_mutex_release(armageddon_mutex);
138 DEBUG1("Armageddon request by <%s> got the lock. Let's go amok",
140 armageddon_initiator = initiator;
141 xbt_os_mutex_release(armageddon_mutex);
143 /* Kill foreground command */
145 rctx_armageddon_kill_one(initiator, filepos, rctx);
147 /* Kill any background commands */
148 xbt_dynar_foreach(bg_jobs, cursor, job) {
149 rctx_armageddon_kill_one(initiator, filepos, job);
152 VERB0("Shut everything down!");
160 void rctx_empty(rctx_t rc)
163 char **env_it = environ;
169 /* avoid race with rctx_armageddon log messages */
170 filepos = rc->filepos;
177 for (i = 0; *env_it; i++, env_it++);
180 rc->env = malloc(i * sizeof(char *));
181 memcpy(rc->env, environ, i * sizeof(char *));
184 rc->is_background = 0;
185 rc->is_stoppable = 0;
186 rc->output = e_output_check;
190 xbt_strbuff_empty(rc->input);
191 xbt_strbuff_empty(rc->output_wanted);
192 xbt_strbuff_empty(rc->output_got);
198 rctx_t res = xbt_new0(s_rctx_t, 1);
200 res->input = xbt_strbuff_new();
201 res->output_wanted = xbt_strbuff_new();
202 res->output_got = xbt_strbuff_new();
203 res->interruption = xbt_os_mutex_init();
208 void rctx_free(rctx_t rctx)
210 DEBUG1("RCTX: Free %p", rctx);
211 rctx_dump(rctx, "free");
221 xbt_os_mutex_destroy(rctx->interruption);
222 xbt_strbuff_free(rctx->input);
223 xbt_strbuff_free(rctx->output_got);
224 xbt_strbuff_free(rctx->output_wanted);
228 void rctx_dump(rctx_t rctx, const char *str)
230 DEBUG9("%s RCTX %p={in%p={%d,%10s}, want={%d,%10s}, out={%d,%10s}}",
232 rctx->input, rctx->input->used, rctx->input->data,
233 rctx->output_wanted->used, rctx->output_wanted->data,
234 rctx->output_got->used, rctx->output_got->data);
235 DEBUG5("%s RCTX %p=[cmd%p=%10s, pid=%d]",
236 str, rctx, rctx->cmd, rctx->cmd, rctx->pid);
241 * Getting instructions from the file
244 void rctx_pushline(const char *filepos, char kind, char *line)
251 if (!rctx->is_empty) {
253 ("[%s] More than one command in this chunk of lines (previous: %s).\n"
254 " Cannot guess which input/output belongs to which command.",
256 ERROR1("Test suite `%s': NOK (syntax error)", testsuite_name);
257 rctx_armageddon(rctx, 1);
261 VERB1("[%s] More than one command in this chunk of lines", filepos);
264 rctx->is_background = 1;
266 rctx->is_background = 0;
268 rctx->cmd = xbt_strdup(line);
269 rctx->filepos = xbt_strdup(filepos);
270 INFO3("[%s] %s%s", filepos, rctx->cmd,
271 ((rctx->is_background) ? " (background command)" : ""));
277 xbt_strbuff_append(rctx->input, line);
278 xbt_strbuff_append(rctx->input, "\n");
283 xbt_strbuff_append(rctx->output_wanted, line);
284 xbt_strbuff_append(rctx->output_wanted, "\n");
291 if (!strncmp(line, "timeout no", strlen("timeout no"))) {
292 VERB1("[%s] (disable timeout)", filepos);
294 } else if (!strncmp(line, "timeout ", strlen("timeout "))) {
295 timeout_value = atoi(line + strlen("timeout"));
296 VERB2("[%s] (new timeout value: %d)", filepos, timeout_value);
298 } else if (!strncmp(line, "expect signal ", strlen("expect signal "))) {
299 rctx->expected_signal = strdup(line + strlen("expect signal "));
300 xbt_str_trim(rctx->expected_signal, " \n");
301 VERB2("[%s] (next command must raise signal %s)",
302 filepos, rctx->expected_signal);
304 } else if (!strncmp(line, "expect return ", strlen("expect return "))) {
305 rctx->expected_return = atoi(line + strlen("expect return "));
306 VERB2("[%s] (next command must return code %d)",
307 filepos, rctx->expected_return);
309 } else if (!strncmp(line, "output ignore", strlen("output ignore"))) {
310 rctx->output = e_output_ignore;
311 VERB1("[%s] (ignore output of next command)", filepos);
313 } else if (!strncmp(line, "output display", strlen("output display"))) {
314 rctx->output = e_output_display;
315 VERB1("[%s] (ignore output of next command)", filepos);
317 } else if (!strncmp(line, "setenv ", strlen("setenv "))) {
318 int len = strlen("setenv ");
319 char *eq = strchr(line + len, '=');
320 char *key = bprintf("%.*s", (int) (eq - line - len), line + len);
321 xbt_dict_set(env, key, xbt_strdup(eq + 1), xbt_free_f);
323 rctx->env = realloc(rctx->env, ++(rctx->env_size) * sizeof(char *));
324 rctx->env[rctx->env_size - 2] = xbt_strdup(line + len);
325 rctx->env[rctx->env_size - 1] = NULL;
326 VERB2("[%s] setenv %s", filepos, line + len);
329 ERROR2("%s: Malformed metacommand: %s", filepos, line);
330 ERROR1("Test suite `%s': NOK (syntax error)", testsuite_name);
331 rctx_armageddon(rctx, 1);
339 * Actually doing the job
342 /* The IO of the childs are handled by the two following threads
343 (one pair per child) */
345 static void *thread_writer(void *r)
348 rctx_t rctx = (rctx_t) r;
349 for (posw = 0; posw < rctx->input->used && !rctx->brokenpipe;) {
351 DEBUG1("Still %d chars to write", rctx->input->used - posw);
353 write(rctx->child_to, rctx->input->data + posw,
354 rctx->input->used - posw);
358 if (errno == EPIPE) {
359 rctx->brokenpipe = 1;
360 } else if (errno != EINTR && errno != EAGAIN && errno != EPIPE) {
361 perror("Error while writing input to child");
362 ERROR1("Test suite `%s': NOK (system error)", testsuite_name);
363 rctx_armageddon(rctx, 4);
367 DEBUG1("written %d chars so far", posw);
372 rctx->input->data[0] = '\0';
373 rctx->input->used = 0;
374 close(rctx->child_to);
379 static void *thread_reader(void *r)
381 rctx_t rctx = (rctx_t) r;
382 char *buffout = malloc(4096);
386 posr = read(rctx->child_from, buffout, 4095);
387 if (posr < 0 && errno != EINTR && errno != EAGAIN) {
388 perror("Error while reading output of child");
389 ERROR1("Test suite `%s': NOK (system error)", testsuite_name);
390 rctx_armageddon(rctx, 4);
394 buffout[posr] = '\0';
395 xbt_strbuff_append(rctx->output_got, buffout);
399 } while (!rctx->timeout && posr != 0);
402 /* let this thread wait for the child so that the main thread can detect the timeout without blocking on the wait */
403 got_pid = waitpid(rctx->pid, &rctx->status, 0);
404 if (got_pid != rctx->pid) {
406 ("(%s) Cannot wait for the child %s (got pid %d where pid %d were expected;status=%d)",
407 xbt_thread_self_name(), rctx->cmd, (int) got_pid,
408 (int) rctx->pid, rctx->status));
409 ERROR1("Test suite `%s': NOK (system error)", testsuite_name);
410 rctx_armageddon(rctx, 4);
414 rctx->reader_done = 1;
418 /* Special command: mkfile is a building creating a file with the input data as content */
419 static void rctx_mkfile(void)
421 char *filename = xbt_strdup(rctx->cmd + strlen("mkfile "));
423 xbt_str_trim(filename, NULL);
424 OUT = fopen(filename, "w");
427 THROW3(system_error, errno, "%s: Cannot create file %s: %s",
428 rctx->filepos, filename, strerror(errno));
430 fprintf(OUT, "%s", rctx->input->data);
434 /* function to be called from the child to start the actual process */
435 static void start_command(rctx_t rctx)
437 xbt_dynar_t cmd = xbt_str_split_quoted(rctx->cmd);
438 char *binary_name = NULL;
441 xbt_dynar_get_cpy(cmd, 0, &binary_name);
442 char **args = xbt_new(char *, xbt_dynar_length(cmd) + 1);
445 if (!strncmp(rctx->cmd, "mkfile ", strlen("mkfile "))) {
447 exit(0); /* end the working child */
450 xbt_dynar_foreach(cmd, it, str) {
451 args[it] = xbt_strdup(str);
455 /* To search for the right executable path when not trivial */
456 struct stat stat_buf;
458 /* build the command line */
459 if (stat(binary_name, &stat_buf)) {
460 /* Damn. binary not in current dir. We'll have to dig the PATH to find it */
463 for (i = 0; environ[i]; i++) {
464 if (!strncmp("PATH=", environ[i], 5)) {
465 xbt_dynar_t path = xbt_str_split(environ[i] + 5, ":");
467 xbt_dynar_foreach(path, it, str) {
470 binary_name = bprintf("%s/%s", str, args[0]);
471 if (!stat(binary_name, &stat_buf)) {
473 DEBUG1("Looked in the PATH for the binary. Found %s",
475 xbt_dynar_free(&path);
479 xbt_dynar_free(&path);
480 if (stat(binary_name, &stat_buf)) {
482 printf("TESH_ERROR Command %s not found\n", args[0]);
489 binary_name = xbt_strdup(args[0]);
492 errcode = execve(binary_name, args, rctx->env);
493 printf("TESH_ERROR %s: Cannot start %s: %s\n", rctx->filepos, rctx->cmd,
498 /* Start a new child, plug the pipes as expected and fire up the
499 helping threads. Is also waits for the child to end if this is a
500 foreground job, or fire up a thread to wait otherwise. */
501 void rctx_start(void)
506 DEBUG1("Cmd before rewriting %s", rctx->cmd);
507 rctx->cmd = xbt_str_varsubst(rctx->cmd, env);
508 VERB2("Start %s %s", rctx->cmd,
509 (rctx->is_background ? "(background job)" : ""));
510 xbt_os_mutex_acquire(armageddon_mutex);
511 if (armageddon_initiator) {
512 VERB0("Armageddon in progress. Do not start job.");
513 xbt_os_mutex_release(armageddon_mutex);
516 if (pipe(child_in) || pipe(child_out)) {
517 perror("Cannot open the pipes");
518 ERROR1("Test suite `%s': NOK (system error)", testsuite_name);
519 xbt_os_mutex_release(armageddon_mutex);
520 rctx_armageddon(rctx, 4);
525 perror("Cannot fork the command");
526 ERROR1("Test suite `%s': NOK (system error)", testsuite_name);
527 xbt_os_mutex_release(armageddon_mutex);
528 rctx_armageddon(rctx, 4);
532 if (rctx->pid) { /* father */
534 rctx->child_to = child_in[1];
537 rctx->child_from = child_out[0];
539 if (timeout_value > 0)
540 rctx->end_time = time(NULL) + timeout_value;
544 rctx->reader_done = 0;
546 xbt_os_thread_create("reader", thread_reader, (void *) rctx);
548 xbt_os_thread_create("writer", thread_writer, (void *) rctx);
551 xbt_os_mutex_release(armageddon_mutex);
554 dup2(child_in[0], 0);
558 dup2(child_out[1], 1);
559 dup2(child_out[1], 2);
565 rctx->is_stoppable = 1;
567 if (!rctx->is_background) {
569 xbt_os_mutex_release(armageddon_mutex);
573 /* Damn. Copy the rctx and launch a thread to handle it */
575 xbt_os_thread_t runner;
578 DEBUG2("RCTX: new bg=%p, new fg=%p", old, rctx);
580 DEBUG2("Launch a thread to wait for %s %d", old->cmd, old->pid);
581 runner = xbt_os_thread_create(old->cmd, rctx_wait, (void *) old);
582 old->runner = runner;
583 VERB3("Launched thread %p to wait for %s %d", runner, old->cmd,
585 xbt_dynar_push(bg_jobs, &old);
586 xbt_os_mutex_release(armageddon_mutex);
590 /* Waits for the child to end (or to timeout), and check its
591 ending conditions. This is launched from rctx_start but either in main
592 thread (for foreground jobs) or in a separate one for background jobs.
593 That explains the prototype, forced by xbt_os_thread_create. */
595 void *rctx_wait(void *r)
597 rctx_t rctx = (rctx_t) r;
599 int now = time(NULL);
601 rctx_dump(rctx, "wait");
603 if (!rctx->is_stoppable)
604 THROW1(unknown_error, 0, "Cmd '%s' not started yet. Cannot wait it",
607 /* Wait for the child to die or the timeout to happen (or an armageddon to happen) */
608 while (!rctx->reader_done
609 && (rctx->end_time < 0 || rctx->end_time >= now)) {
614 xbt_os_mutex_acquire(rctx->interruption);
615 if (!rctx->interrupted && rctx->end_time > 0 && rctx->end_time < now) {
616 INFO1("<%s> timeouted. Kill the process.", rctx->filepos);
618 kill(rctx->pid, SIGTERM);
620 kill(rctx->pid, SIGKILL);
623 /* Make sure helper threads die.
624 Cannot block since they wait for the child we just killed
625 if not already dead. */
626 xbt_os_thread_join(rctx->writer, NULL);
627 xbt_os_thread_join(rctx->reader, NULL);
629 /* xbt_os_mutex_release(rctx->interruption);
630 if (rctx->interrupted)
632 xbt_os_mutex_acquire(rctx->interruption); */
634 xbt_strbuff_chomp(rctx->output_got);
635 xbt_strbuff_chomp(rctx->output_wanted);
636 xbt_strbuff_trim(rctx->output_got);
637 xbt_strbuff_trim(rctx->output_wanted);
639 /* Check for broken pipe */
640 if (rctx->brokenpipe)
642 ("Warning: Child did not consume all its input (I got broken pipe)");
644 /* Check for timeouts */
646 if (rctx->output_got->data[0])
647 INFO2("<%s> Output on timeout:\n%s",
648 rctx->filepos, rctx->output_got->data);
650 INFO1("<%s> No output before timeout", rctx->filepos);
651 ERROR3("Test suite `%s': NOK (<%s> timeout after %d sec)",
652 testsuite_name, rctx->filepos, timeout_value);
653 DEBUG2("<%s> Interrupted = %d", rctx->filepos, rctx->interrupted);
654 if (!rctx->interrupted) {
655 rctx_armageddon(rctx, 3);
660 DEBUG2("RCTX=%p (pid=%d)", rctx, rctx->pid);
661 DEBUG3("Status(%s|%d)=%d", rctx->cmd, rctx->pid, rctx->status);
663 if (!rctx->interrupted) {
664 if (WIFSIGNALED(rctx->status) && !rctx->expected_signal) {
665 ERROR3("Test suite `%s': NOK (<%s> got signal %s)",
666 testsuite_name, rctx->filepos,
667 signal_name(WTERMSIG(rctx->status), NULL));
668 errcode = WTERMSIG(rctx->status) + 4;
671 if (WIFSIGNALED(rctx->status) && rctx->expected_signal &&
672 strcmp(signal_name(WTERMSIG(rctx->status), rctx->expected_signal),
673 rctx->expected_signal)) {
674 ERROR4("Test suite `%s': NOK (%s got signal %s instead of %s)",
675 testsuite_name, rctx->filepos,
676 signal_name(WTERMSIG(rctx->status), rctx->expected_signal),
677 rctx->expected_signal);
678 errcode = WTERMSIG(rctx->status) + 4;
681 if (!WIFSIGNALED(rctx->status) && rctx->expected_signal) {
682 ERROR3("Test suite `%s': NOK (child %s expected signal %s)",
683 testsuite_name, rctx->filepos, rctx->expected_signal);
687 if (WIFEXITED(rctx->status)
688 && WEXITSTATUS(rctx->status) != rctx->expected_return) {
689 if (rctx->expected_return)
691 ("Test suite `%s': NOK (<%s> returned code %d instead of %d)",
692 testsuite_name, rctx->filepos, WEXITSTATUS(rctx->status),
693 rctx->expected_return);
695 ERROR3("Test suite `%s': NOK (<%s> returned code %d)",
696 testsuite_name, rctx->filepos, WEXITSTATUS(rctx->status));
697 errcode = 40 + WEXITSTATUS(rctx->status);
700 rctx->expected_return = 0;
702 if (rctx->expected_signal) {
703 free(rctx->expected_signal);
704 rctx->expected_signal = NULL;
707 while (rctx->output_got->used
708 && !strncmp(rctx->output_got->data, "TESH_ERROR ",
709 strlen("TESH_ERROR "))) {
710 int marklen = strlen("TESH_ERROR ");
711 char *endline = strchr(rctx->output_got->data, '\n');
713 CRITICAL2("%.*s", (int) (endline - rctx->output_got->data - marklen),
714 rctx->output_got->data + marklen);
715 memmove(rctx->output_got->data, rctx->output_got->data + marklen,
716 rctx->output_got->used - marklen);
717 rctx->output_got->used -= endline - rctx->output_got->data + 1;
718 rctx->output_got->data[rctx->output_got->used] = '\0';
722 if ((errcode && errcode != 1) || rctx->interrupted) {
723 /* checking output, and matching */
724 xbt_dynar_t a = xbt_str_split(rctx->output_got->data, "\n");
725 char *out = xbt_str_join(a, "\n||");
727 INFO2("Output of <%s> so far: \n||%s", rctx->filepos, out);
729 } else if (rctx->output == e_output_check
730 && (rctx->output_got->used != rctx->output_wanted->used
731 || strcmp(rctx->output_got->data,
732 rctx->output_wanted->data))) {
733 if (XBT_LOG_ISENABLED(tesh, xbt_log_priority_info)) {
735 xbt_str_diff(rctx->output_wanted->data, rctx->output_got->data);
736 ERROR2("Output of <%s> mismatch:\n%s", rctx->filepos, diff);
739 ERROR2("Test suite `%s': NOK (<%s> output mismatch)",
740 testsuite_name, rctx->filepos);
743 } else if (rctx->output == e_output_ignore) {
744 INFO1("(ignoring the output of <%s> as requested)", rctx->filepos);
745 } else if (rctx->output == e_output_display) {
746 xbt_dynar_t a = xbt_str_split(rctx->output_got->data, "\n");
747 char *out = xbt_str_join(a, "\n||");
749 INFO1("Here is the (ignored) command output: \n||%s", out);
753 if (!rctx->is_background) {
754 xbt_os_mutex_acquire(armageddon_mutex);
755 /* Don't touch rctx if armageddon is in progress. */
756 if (!armageddon_initiator)
758 xbt_os_mutex_release(armageddon_mutex);
761 if (!rctx->interrupted) {
762 rctx_armageddon(rctx, errcode);
763 xbt_os_mutex_release(rctx->interruption);
768 xbt_os_mutex_release(rctx->interruption);