1 /* run_context -- stuff in which TESH runs a command */
3 /* Copyright (c) 2007 Martin Quinson. */
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("Cannot wait for the child %s", rctx->cmd));
357 ERROR1("Test suite `%s': NOK (system error)", testsuite_name);
358 rctx_armageddon(rctx, 4);
362 rctx->reader_done = 1;
366 /* Special command: mkfile is a building creating a file with the input data as content */
367 static void rctx_mkfile(void)
369 char *filename = xbt_strdup(rctx->cmd + strlen("mkfile "));
371 xbt_str_trim(filename, NULL);
372 OUT = fopen(filename, "w");
375 THROW3(system_error, errno, "%s: Cannot create file %s: %s",
376 rctx->filepos, filename, strerror(errno));
378 fprintf(OUT, "%s", rctx->input->data);
382 /* function to be called from the child to start the actual process */
383 static void start_command(rctx_t rctx)
385 xbt_dynar_t cmd = xbt_str_split_quoted(rctx->cmd);
386 char *binary_name = NULL;
389 xbt_dynar_get_cpy(cmd, 0, &binary_name);
390 char **args = xbt_new(char *, xbt_dynar_length(cmd) + 1);
393 if (!strncmp(rctx->cmd, "mkfile ", strlen("mkfile "))) {
395 exit(0); /* end the working child */
398 xbt_dynar_foreach(cmd, it, str) {
399 args[it] = xbt_strdup(str);
403 /* To search for the right executable path when not trivial */
404 struct stat stat_buf;
406 /* build the command line */
407 if (stat(binary_name, &stat_buf)) {
408 /* Damn. binary not in current dir. We'll have to dig the PATH to find it */
411 for (i = 0; environ[i]; i++) {
412 if (!strncmp("PATH=", environ[i], 5)) {
413 xbt_dynar_t path = xbt_str_split(environ[i] + 5, ":");
415 xbt_dynar_foreach(path, it, str) {
418 binary_name = bprintf("%s/%s", str, args[0]);
419 if (!stat(binary_name, &stat_buf)) {
421 DEBUG1("Looked in the PATH for the binary. Found %s",
423 xbt_dynar_free(&path);
427 xbt_dynar_free(&path);
428 if (stat(binary_name, &stat_buf)) {
430 printf("TESH_ERROR Command %s not found\n", args[0]);
437 binary_name = xbt_strdup(args[0]);
440 errcode = execve(binary_name, args, rctx->env);
441 printf("TESH_ERROR %s: Cannot start %s: %s\n", rctx->filepos, rctx->cmd,
446 /* Start a new child, plug the pipes as expected and fire up the
447 helping threads. Is also waits for the child to end if this is a
448 foreground job, or fire up a thread to wait otherwise. */
449 void rctx_start(void)
454 DEBUG1("Cmd before rewriting %s", rctx->cmd);
455 rctx->cmd = xbt_str_varsubst(rctx->cmd, env);
456 VERB2("Start %s %s", rctx->cmd,
457 (rctx->is_background ? "(background job)" : ""));
458 if (pipe(child_in) || pipe(child_out)) {
459 perror("Cannot open the pipes");
460 ERROR1("Test suite `%s': NOK (system error)", testsuite_name);
461 rctx_armageddon(rctx, 4);
466 perror("Cannot fork the command");
467 ERROR1("Test suite `%s': NOK (system error)", testsuite_name);
468 rctx_armageddon(rctx, 4);
472 if (rctx->pid) { /* father */
474 rctx->child_to = child_in[1];
477 rctx->child_from = child_out[0];
479 if (timeout_value > 0)
480 rctx->end_time = time(NULL) + timeout_value;
484 rctx->reader_done = 0;
486 xbt_os_thread_create("reader", thread_reader, (void *) rctx);
488 xbt_os_thread_create("writer", thread_writer, (void *) rctx);
493 dup2(child_in[0], 0);
497 dup2(child_out[1], 1);
498 dup2(child_out[1], 2);
504 rctx->is_stoppable = 1;
506 if (!rctx->is_background) {
509 /* Damn. Copy the rctx and launch a thread to handle it */
511 xbt_os_thread_t runner;
514 DEBUG2("RCTX: new bg=%p, new fg=%p", old, rctx);
516 DEBUG2("Launch a thread to wait for %s %d", old->cmd, old->pid);
517 runner = xbt_os_thread_create(old->cmd, rctx_wait, (void *) old);
518 old->runner = runner;
519 VERB3("Launched thread %p to wait for %s %d", runner, old->cmd, old->pid);
520 xbt_dynar_push(bg_jobs, &old);
524 /* Waits for the child to end (or to timeout), and check its
525 ending conditions. This is launched from rctx_start but either in main
526 thread (for foreground jobs) or in a separate one for background jobs.
527 That explains the prototype, forced by xbt_os_thread_create. */
529 void *rctx_wait(void *r)
531 rctx_t rctx = (rctx_t) r;
533 int now = time(NULL);
535 rctx_dump(rctx, "wait");
537 if (!rctx->is_stoppable)
538 THROW1(unknown_error, 0, "Cmd '%s' not started yet. Cannot wait it",
541 /* Wait for the child to die or the timeout to happen (or an armageddon to happen) */
542 while (!rctx->interrupted && !rctx->reader_done
543 && (rctx->end_time < 0 || rctx->end_time >= now)) {
548 xbt_os_mutex_acquire(rctx->interruption);
549 if (!rctx->interrupted && rctx->end_time > 0 && rctx->end_time < now) {
550 INFO1("<%s> timeouted. Kill the process.", rctx->filepos);
552 kill(rctx->pid, SIGTERM);
554 kill(rctx->pid, SIGKILL);
555 rctx->reader_done = 1;
558 /* Make sure helper threads die.
559 Cannot block since they wait for the child we just killed
560 if not already dead. */
561 xbt_os_thread_join(rctx->writer, NULL);
562 xbt_os_thread_join(rctx->reader, NULL);
564 /* xbt_os_mutex_release(rctx->interruption);
565 if (rctx->interrupted)
567 xbt_os_mutex_acquire(rctx->interruption); */
569 xbt_strbuff_chomp(rctx->output_got);
570 xbt_strbuff_chomp(rctx->output_wanted);
571 xbt_strbuff_trim(rctx->output_got);
572 xbt_strbuff_trim(rctx->output_wanted);
574 /* Check for broken pipe */
575 if (rctx->brokenpipe)
576 VERB0("Warning: Child did not consume all its input (I got broken pipe)");
578 /* Check for timeouts */
580 if (rctx->output_got->data[0])
581 INFO2("<%s> Output on timeout:\n%s",
582 rctx->filepos, rctx->output_got->data);
584 INFO1("<%s> No output before timeout", rctx->filepos);
585 ERROR3("Test suite `%s': NOK (<%s> timeout after %d sec)",
586 testsuite_name, rctx->filepos, timeout_value);
587 DEBUG2("<%s> Interrupted = %d", rctx->filepos, rctx->interrupted);
588 if (!rctx->interrupted) {
589 rctx_armageddon(rctx, 3);
594 DEBUG2("RCTX=%p (pid=%d)", rctx, rctx->pid);
595 DEBUG3("Status(%s|%d)=%d", rctx->cmd, rctx->pid, rctx->status);
597 if (!rctx->interrupted) {
598 if (WIFSIGNALED(rctx->status) && !rctx->expected_signal) {
599 ERROR3("Test suite `%s': NOK (<%s> got signal %s)",
600 testsuite_name, rctx->filepos,
601 signal_name(WTERMSIG(rctx->status), NULL));
602 errcode = WTERMSIG(rctx->status) + 4;
605 if (WIFSIGNALED(rctx->status) && rctx->expected_signal &&
606 strcmp(signal_name(WTERMSIG(rctx->status), rctx->expected_signal),
607 rctx->expected_signal)) {
608 ERROR4("Test suite `%s': NOK (%s got signal %s instead of %s)",
609 testsuite_name, rctx->filepos,
610 signal_name(WTERMSIG(rctx->status), rctx->expected_signal),
611 rctx->expected_signal);
612 errcode = WTERMSIG(rctx->status) + 4;
615 if (!WIFSIGNALED(rctx->status) && rctx->expected_signal) {
616 ERROR3("Test suite `%s': NOK (child %s expected signal %s)",
617 testsuite_name, rctx->filepos, rctx->expected_signal);
621 if (WIFEXITED(rctx->status)
622 && WEXITSTATUS(rctx->status) != rctx->expected_return) {
623 if (rctx->expected_return)
624 ERROR4("Test suite `%s': NOK (<%s> returned code %d instead of %d)",
625 testsuite_name, rctx->filepos,
626 WEXITSTATUS(rctx->status), rctx->expected_return);
628 ERROR3("Test suite `%s': NOK (<%s> returned code %d)",
629 testsuite_name, rctx->filepos, WEXITSTATUS(rctx->status));
630 errcode = 40 + WEXITSTATUS(rctx->status);
633 rctx->expected_return = 0;
635 if (rctx->expected_signal) {
636 free(rctx->expected_signal);
637 rctx->expected_signal = NULL;
640 while (rctx->output_got->used
641 && !strncmp(rctx->output_got->data, "TESH_ERROR ",
642 strlen("TESH_ERROR "))) {
643 int marklen = strlen("TESH_ERROR ");
644 char *endline = strchr(rctx->output_got->data, '\n');
646 CRITICAL2("%.*s", (int) (endline - rctx->output_got->data - marklen),
647 rctx->output_got->data + marklen);
648 memmove(rctx->output_got->data, rctx->output_got->data + marklen,
649 rctx->output_got->used - marklen);
650 rctx->output_got->used -= endline - rctx->output_got->data + 1;
651 rctx->output_got->data[rctx->output_got->used] = '\0';
655 if (rctx->output == e_output_check
656 && (rctx->output_got->used != rctx->output_wanted->used
657 || strcmp(rctx->output_got->data, rctx->output_wanted->data))) {
658 if (XBT_LOG_ISENABLED(tesh, xbt_log_priority_info)) {
660 xbt_str_diff(rctx->output_wanted->data, rctx->output_got->data);
661 ERROR2("Output of <%s> mismatch:\n%s", rctx->filepos, diff);
664 ERROR2("Test suite `%s': NOK (<%s> output mismatch)",
665 testsuite_name, rctx->filepos);
668 } else if (rctx->output == e_output_ignore) {
669 INFO1("(ignoring the output of <%s> as requested)", rctx->filepos);
670 } else if (rctx->output == e_output_display) {
671 xbt_dynar_t a = xbt_str_split(rctx->output_got->data, "\n");
672 char *out = xbt_str_join(a, "\n||");
674 INFO1("Here is the (ignored) command output: \n||%s", out);
676 } else if ((errcode && errcode != 1) || rctx->interrupted) {
677 /* checking output, and matching */
678 xbt_dynar_t a = xbt_str_split(rctx->output_got->data, "\n");
679 char *out = xbt_str_join(a, "\n||");
681 INFO2("Output of <%s> so far: \n||%s", rctx->filepos, out);
685 if (!rctx->is_background) {
689 if (!rctx->interrupted) {
690 rctx_armageddon(rctx, errcode);
695 xbt_os_mutex_release(rctx->interruption);