summaryrefslogtreecommitdiffstats
path: root/src/lib-test/test-subprocess.c
blob: eeaae801b3693ea160f6738bf28bb304a86e7140 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
/* Copyright (c) 2020 Dovecot authors, see the included COPYING file */

#include "lib.h"
#include "lib-signals.h"
#include "hostpid.h"
#include "array.h"
#include "ioloop.h"
#include "sleep.h"
#include "test-common.h"
#include "test-subprocess.h"

#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

struct test_subprocess {
	pid_t pid;
};

volatile sig_atomic_t test_subprocess_is_child = 0;
static bool test_subprocess_lib_init = FALSE;
static volatile bool test_subprocess_notification_signal_received[SIGUSR1 + 1];
static struct event *test_subprocess_event = NULL;
static ARRAY(struct test_subprocess *) test_subprocesses = ARRAY_INIT;
static void (*test_subprocess_cleanup_callback)(void) = NULL;

static void
test_subprocess_signal(const siginfo_t *si ATTR_UNUSED,
		       void *context ATTR_UNUSED)
{
	io_loop_stop(current_ioloop);
}

static void test_subprocess_free_all(void)
{
	struct test_subprocess *subp;

	array_foreach_elem(&test_subprocesses, subp)
		i_free(subp);
	array_free(&test_subprocesses);
}

static void ATTR_NORETURN
test_subprocess_child(int (*func)(void *context), void *context,
		      bool continue_test)
{
	int ret;

	if (!continue_test)
		test_forked_end();

	hostpid_init();

	lib_signals_deinit();
	lib_signals_init();

	lib_signals_set_handler(SIGTERM,
		LIBSIG_FLAG_DELAYED | LIBSIG_FLAG_IOLOOP_AUTOMOVE,
		test_subprocess_signal, NULL);
	lib_signals_set_handler(SIGQUIT,
		LIBSIG_FLAG_DELAYED | LIBSIG_FLAG_IOLOOP_AUTOMOVE,
		test_subprocess_signal, NULL);
	lib_signals_set_handler(SIGINT,
		LIBSIG_FLAG_DELAYED | LIBSIG_FLAG_IOLOOP_AUTOMOVE,
		test_subprocess_signal, NULL);

	ret = func(context);

	/* Prevent race condition */
	lib_signals_clear_handlers_and_ignore(SIGTERM);

	event_unref(&test_subprocess_event);
	lib_signals_deinit();

	if (!continue_test) {
		lib_deinit();
		lib_exit(ret);
	}
	test_exit((test_has_failed() ? 1 : 0));
}

#undef test_subprocess_fork
void test_subprocess_fork(int (*func)(void *context), void *context,
			  bool continue_test)
{
	struct test_subprocess *subprocess;

	subprocess = i_new(struct test_subprocess, 1);

	lib_signals_ioloop_detach();

	/* avoid races: fork the child process with test_subprocess_is_child
	   set to 1 in case it immediately receives a signal. */
	test_subprocess_is_child = 1;
	if ((subprocess->pid = fork()) == (pid_t)-1)
		i_fatal("test: sub-process: fork() failed: %m");
	if (subprocess->pid == 0) {
		/* cannot include this in the list to avoid accidental
		 * kill of PID 0, so just free it here explicitly. */
		i_free(subprocess);
		test_subprocess_free_all();

		test_subprocess_child(func, context, continue_test);
		i_unreached();
	}
	test_subprocess_is_child = 0;

	array_push_back(&test_subprocesses, &subprocess);
	lib_signals_ioloop_attach();
}

static void test_subprocess_verify_exit_status(int status)
{
	test_out_quiet("sub-process ended properly",
		       WIFEXITED(status) && WEXITSTATUS(status) == 0);
	if (WIFEXITED(status)) {
		if (WEXITSTATUS(status) != 0) {
			e_warning(test_subprocess_event,
				  "Sub-process exited with status %d",
				  WEXITSTATUS(status));
		}
	} else if (WIFSIGNALED(status)) {
		e_warning(test_subprocess_event,
			  "Sub-process forcibly terminated with signal %d",
		          WTERMSIG(status));
	} else if (WIFSTOPPED(status)) {
		e_warning(test_subprocess_event,
			  "Sub-process stopped with signal %d",
			  WSTOPSIG(status));
	} else {
		e_warning(test_subprocess_event,
			  "Sub-process terminated abnormally with status %d",
			  status);
	}
}

static void test_subprocess_kill_forced(struct test_subprocess *subp)
{
	i_assert(subp->pid > 0);
	(void)kill(subp->pid, SIGKILL);
	(void)waitpid(subp->pid, NULL, 0);
}

void test_subprocess_kill_all(unsigned int timeout_secs)
{
	struct test_subprocess **subps;
	unsigned int subps_count, subps_left, i;

	subps = array_get_modifiable(&test_subprocesses, &subps_count);

	/* Request children to terminate gently */
	for (i = 0; i < subps_count; i++) {
		if (subps[i] == NULL || subps[i]->pid == (pid_t)-1)
			continue;

		e_debug(test_subprocess_event,
			"Terminating sub-process [%u]", i);
		if (kill(subps[i]->pid, SIGTERM) < 0) {
			e_error(test_subprocess_event,
				"Failed to kill sub-process [%u] with SIGTERM: "
				"%m", i);
		}
	}

	/* Wait for children */
	subps_left = subps_count;
	while (subps_left > 0) {
		int status;
		pid_t wret = (pid_t)-1;

		alarm(timeout_secs);
		wret = waitpid(-1, &status, 0);
		alarm(0);

		test_assert(wret > 0);
		if (wret < 0 && errno == EINTR)
			e_warning(test_subprocess_event,
				  "Wait for sub-processes timed out");
		if (wret > 0)
			test_subprocess_verify_exit_status(status);

		if (wret == 0)
			break;
		if (wret < 0) {
			if (errno == ECHILD)
				continue;
			e_warning(test_subprocess_event,
				  "Wait for sub-processes failed: %m");
			break;
		}
		for (i = 0; i < subps_count; i++) {
			if (subps[i] == NULL || subps[i]->pid != wret)
				continue;
			e_debug(test_subprocess_event,
				"Terminated sub-process [%u]", i);
			i_free(subps[i]);
			subps_left--;
		}
	}

	/* Kill disobedient ones with fire */
	for (i = 0; i < subps_count; i++) {
		if (subps[i] == NULL || subps[i]->pid == (pid_t)-1)
			continue;
		e_warning(test_subprocess_event,
			  "Forcibly killed sub-process [%u]", i);
		test_subprocess_kill_forced(subps[i]);
		i_assert(subps_left > 0);
		i_free(subps[i]);
		subps_left--;
	}
	i_assert(subps_left == 0);

	array_clear(&test_subprocesses);
}

static void test_subprocess_kill_all_forced(void)
{
	struct test_subprocess **subps;
	unsigned int subps_count, i;

	if (!array_is_created(&test_subprocesses))
		return;

	/* This is also called from signal handler context, so no debug logging
	   here.
	 */

	subps = array_get_modifiable(&test_subprocesses, &subps_count);

	if (subps_count == 0)
		return;

	for (i = 0; i < subps_count; i++) {
		if (subps[i] == NULL || subps[i]->pid == (pid_t)-1)
			continue;
		test_subprocess_kill_forced(subps[i]);
		subps[i]->pid = (pid_t)-1;
	}
}

/*
 * Main
 */

volatile sig_atomic_t terminating = 0;

static void test_subprocess_cleanup(void)
{
	if (test_subprocess_is_child != 0) {
		/* Child processes must not execute the cleanups */
		return;
	}

	/* We get here when the test ended normally, badly failed, crashed,
	   terminated, or executed exit() unexpectedly. The cleanups performed
	   here are important and must be executed at all times. */

	/* While any unfreed memory will be handled by the system, lingering
	   child processes will not be handled so well. So, we need to make sure
	   here that we don't leave any pesky child processes alive. */
	test_subprocess_kill_all_forced();

	/* Perform any additional important cleanup specific to the test. */
	if (test_subprocess_cleanup_callback != NULL)
		test_subprocess_cleanup_callback();
}

static void
test_subprocess_alarm(const siginfo_t *si ATTR_UNUSED,
		      void *context ATTR_UNUSED)
{
	/* We use alarm() to implement a simple timeout on waitpid(), which will
	   exit with EINTR when SIGALRM is received. This handler overrides the
	   default SIGALRM handler, so that the process is not killed and no
	   messages are printed to terminal.
	 */
}

static void
test_subprocess_terminate(const siginfo_t *si, void *context ATTR_UNUSED)
{
	int signo = si->si_signo;

	if (terminating != 0)
		raise(signo);
	terminating = 1;

	/* Perform important cleanups */
	test_subprocess_cleanup();

	(void)signal(signo, SIG_DFL);
	if (signo == SIGTERM)
		_exit(0);
	else
		raise(signo);
}

static void test_atexit(void)
{
	/* NOTICE: This is also called by children, so be careful. */

	/* Perform important cleanups */
	test_subprocess_cleanup();
}

void test_subprocess_set_cleanup_callback(void (*callback)(void))
{
	test_subprocess_cleanup_callback = callback;
}

void test_subprocess_notify_signal_send(int signo, pid_t pid)
{
	if (kill(pid, signo) < 0)
		i_fatal("kill(%ld, SIGHUP) failed: %m", (long)pid);
}

void test_subprocess_notify_signal_send_parent(int signo)
{
	test_subprocess_notify_signal_send(signo, getppid());
}

void test_subprocess_notify_signal_reset(int signo)
{
	i_assert(signo >= 0 &&
		 (unsigned int)signo < N_ELEMENTS(test_subprocess_notification_signal_received));
	test_subprocess_notification_signal_received[signo] = FALSE;
}

void test_subprocess_notify_signal_wait(int signo, unsigned int timeout_msecs)
{
	unsigned int i, count = timeout_msecs / 10;

	for (i = 0; i < count; i++) {
		if (test_subprocess_notification_signal_received[signo])
			return;
		i_sleep_msecs(10);
	}
	i_fatal("Didn't receive wait notification signal from server");
}

static void
test_subprocess_notification_signal(const siginfo_t *si,
				    void *context ATTR_UNUSED)
{
	int signo = si->si_signo;

	i_assert(signo >= 0 &&
		 (unsigned int)signo < N_ELEMENTS(test_subprocess_notification_signal_received));
	test_subprocess_notification_signal_received[signo] = TRUE;
}

void test_subprocesses_init(bool debug)
{
	if (!lib_is_initialized()) {
		lib_init();
		test_subprocess_lib_init = TRUE;
	}
	lib_signals_init();

	atexit(test_atexit);
	lib_signals_ignore(SIGPIPE, TRUE);
	lib_signals_set_handler(SIGALRM, 0, test_subprocess_alarm, NULL);
	lib_signals_set_handler(SIGTERM, 0, test_subprocess_terminate, NULL);
	lib_signals_set_handler(SIGQUIT, 0, test_subprocess_terminate, NULL);
	lib_signals_set_handler(SIGINT, 0, test_subprocess_terminate, NULL);
	lib_signals_set_handler(SIGSEGV, 0, test_subprocess_terminate, NULL);
	lib_signals_set_handler(SIGABRT, 0, test_subprocess_terminate, NULL);
	lib_signals_set_handler(SIGHUP, LIBSIG_FLAG_RESTART,
				test_subprocess_notification_signal, NULL);
	lib_signals_set_handler(SIGUSR1, LIBSIG_FLAG_RESTART,
				test_subprocess_notification_signal, NULL);

	i_array_init(&test_subprocesses, 8);

	test_subprocess_event = event_create(NULL);
	event_set_forced_debug(test_subprocess_event, debug);
	event_set_append_log_prefix(test_subprocess_event, "test: ");
}

void test_subprocesses_deinit(void)
{
	test_subprocess_cleanup();
	test_subprocess_free_all();
	array_free(&test_subprocesses);

	event_unref(&test_subprocess_event);
	lib_signals_deinit();

	if (test_subprocess_lib_init)
		lib_deinit();
}