1/*
2 * This file is part of the ZFS Event Daemon (ZED).
3 *
4 * Developed at Lawrence Livermore National Laboratory (LLNL-CODE-403049).
5 * Copyright (C) 2013-2014 Lawrence Livermore National Security, LLC.
6 * Refer to the OpenZFS git commit log for authoritative copyright attribution.
7 *
8 * The contents of this file are subject to the terms of the
9 * Common Development and Distribution License Version 1.0 (CDDL-1.0).
10 * You can obtain a copy of the license from the top-level file
11 * "OPENSOLARIS.LICENSE" or at <http://opensource.org/licenses/CDDL-1.0>.
12 * You may not use this file except in compliance with the license.
13 */
14
15#include <errno.h>
16#include <fcntl.h>
17#include <signal.h>
18#include <stdio.h>
19#include <stdlib.h>
20#include <string.h>
21#include <sys/mman.h>
22#include <sys/stat.h>
23#include <unistd.h>
24#include "zed.h"
25#include "zed_conf.h"
26#include "zed_event.h"
27#include "zed_file.h"
28#include "zed_log.h"
29
30static volatile sig_atomic_t _got_exit = 0;
31static volatile sig_atomic_t _got_hup = 0;
32
33/*
34 * Signal handler for SIGINT & SIGTERM.
35 */
36static void
37_exit_handler(int signum)
38{
39	_got_exit = 1;
40}
41
42/*
43 * Signal handler for SIGHUP.
44 */
45static void
46_hup_handler(int signum)
47{
48	_got_hup = 1;
49}
50
51/*
52 * Register signal handlers.
53 */
54static void
55_setup_sig_handlers(void)
56{
57	struct sigaction sa;
58
59	if (sigemptyset(&sa.sa_mask) < 0)
60		zed_log_die("Failed to initialize sigset");
61
62	sa.sa_flags = SA_RESTART;
63
64	sa.sa_handler = SIG_IGN;
65	if (sigaction(SIGPIPE, &sa, NULL) < 0)
66		zed_log_die("Failed to ignore SIGPIPE");
67
68	sa.sa_handler = _exit_handler;
69	if (sigaction(SIGINT, &sa, NULL) < 0)
70		zed_log_die("Failed to register SIGINT handler");
71
72	if (sigaction(SIGTERM, &sa, NULL) < 0)
73		zed_log_die("Failed to register SIGTERM handler");
74
75	sa.sa_handler = _hup_handler;
76	if (sigaction(SIGHUP, &sa, NULL) < 0)
77		zed_log_die("Failed to register SIGHUP handler");
78
79	(void) sigaddset(&sa.sa_mask, SIGCHLD);
80	if (pthread_sigmask(SIG_BLOCK, &sa.sa_mask, NULL) < 0)
81		zed_log_die("Failed to block SIGCHLD");
82}
83
84/*
85 * Lock all current and future pages in the virtual memory address space.
86 * Access to locked pages will never be delayed by a page fault.
87 *
88 * EAGAIN is tested up to max_tries in case this is a transient error.
89 *
90 * Note that memory locks are not inherited by a child created via fork()
91 * and are automatically removed during an execve().  As such, this must
92 * be called after the daemon fork()s (when running in the background).
93 */
94static void
95_lock_memory(void)
96{
97#if HAVE_MLOCKALL
98	int i = 0;
99	const int max_tries = 10;
100
101	for (i = 0; i < max_tries; i++) {
102		if (mlockall(MCL_CURRENT | MCL_FUTURE) == 0) {
103			zed_log_msg(LOG_INFO, "Locked all pages in memory");
104			return;
105		}
106		if (errno != EAGAIN)
107			break;
108	}
109	zed_log_die("Failed to lock memory pages: %s", strerror(errno));
110
111#else /* HAVE_MLOCKALL */
112	zed_log_die("Failed to lock memory pages: mlockall() not supported");
113#endif /* HAVE_MLOCKALL */
114}
115
116/*
117 * Start daemonization of the process including the double fork().
118 *
119 * The parent process will block here until _finish_daemonize() is called
120 * (in the grandchild process), at which point the parent process will exit.
121 * This prevents the parent process from exiting until initialization is
122 * complete.
123 */
124static void
125_start_daemonize(void)
126{
127	pid_t pid;
128	struct sigaction sa;
129
130	/* Create pipe for communicating with child during daemonization. */
131	zed_log_pipe_open();
132
133	/* Background process and ensure child is not process group leader. */
134	pid = fork();
135	if (pid < 0) {
136		zed_log_die("Failed to create child process: %s",
137		    strerror(errno));
138	} else if (pid > 0) {
139
140		/* Close writes since parent will only read from pipe. */
141		zed_log_pipe_close_writes();
142
143		/* Wait for notification that daemonization is complete. */
144		zed_log_pipe_wait();
145
146		zed_log_pipe_close_reads();
147		_exit(EXIT_SUCCESS);
148	}
149
150	/* Close reads since child will only write to pipe. */
151	zed_log_pipe_close_reads();
152
153	/* Create independent session and detach from terminal. */
154	if (setsid() < 0)
155		zed_log_die("Failed to create new session: %s",
156		    strerror(errno));
157
158	/* Prevent child from terminating on HUP when session leader exits. */
159	if (sigemptyset(&sa.sa_mask) < 0)
160		zed_log_die("Failed to initialize sigset");
161
162	sa.sa_flags = 0;
163	sa.sa_handler = SIG_IGN;
164
165	if (sigaction(SIGHUP, &sa, NULL) < 0)
166		zed_log_die("Failed to ignore SIGHUP");
167
168	/* Ensure process cannot re-acquire terminal. */
169	pid = fork();
170	if (pid < 0) {
171		zed_log_die("Failed to create grandchild process: %s",
172		    strerror(errno));
173	} else if (pid > 0) {
174		_exit(EXIT_SUCCESS);
175	}
176}
177
178/*
179 * Finish daemonization of the process by closing stdin/stdout/stderr.
180 *
181 * This must be called at the end of initialization after all external
182 * communication channels are established and accessible.
183 */
184static void
185_finish_daemonize(void)
186{
187	int devnull;
188
189	/* Preserve fd 0/1/2, but discard data to/from stdin/stdout/stderr. */
190	devnull = open("/dev/null", O_RDWR);
191	if (devnull < 0)
192		zed_log_die("Failed to open /dev/null: %s", strerror(errno));
193
194	if (dup2(devnull, STDIN_FILENO) < 0)
195		zed_log_die("Failed to dup /dev/null onto stdin: %s",
196		    strerror(errno));
197
198	if (dup2(devnull, STDOUT_FILENO) < 0)
199		zed_log_die("Failed to dup /dev/null onto stdout: %s",
200		    strerror(errno));
201
202	if (dup2(devnull, STDERR_FILENO) < 0)
203		zed_log_die("Failed to dup /dev/null onto stderr: %s",
204		    strerror(errno));
205
206	if ((devnull > STDERR_FILENO) && (close(devnull) < 0))
207		zed_log_die("Failed to close /dev/null: %s", strerror(errno));
208
209	/* Notify parent that daemonization is complete. */
210	zed_log_pipe_close_writes();
211}
212
213/*
214 * ZFS Event Daemon (ZED).
215 */
216int
217main(int argc, char *argv[])
218{
219	struct zed_conf zcp;
220	uint64_t saved_eid;
221	int64_t saved_etime[2];
222
223	zed_log_init(argv[0]);
224	zed_log_stderr_open(LOG_NOTICE);
225	zed_conf_init(&zcp);
226	zed_conf_parse_opts(&zcp, argc, argv);
227	if (zcp.do_verbose)
228		zed_log_stderr_open(LOG_INFO);
229
230	if (geteuid() != 0)
231		zed_log_die("Must be run as root");
232
233	zed_file_close_from(STDERR_FILENO + 1);
234
235	(void) umask(0);
236
237	if (chdir("/") < 0)
238		zed_log_die("Failed to change to root directory");
239
240	if (zed_conf_scan_dir(&zcp) < 0)
241		exit(EXIT_FAILURE);
242
243	if (!zcp.do_foreground) {
244		_start_daemonize();
245		zed_log_syslog_open(LOG_DAEMON);
246	}
247	_setup_sig_handlers();
248
249	if (zcp.do_memlock)
250		_lock_memory();
251
252	if ((zed_conf_write_pid(&zcp) < 0) && (!zcp.do_force))
253		exit(EXIT_FAILURE);
254
255	if (!zcp.do_foreground)
256		_finish_daemonize();
257
258	zed_log_msg(LOG_NOTICE,
259	    "ZFS Event Daemon %s-%s (PID %d)",
260	    ZFS_META_VERSION, ZFS_META_RELEASE, (int)getpid());
261
262	if (zed_conf_open_state(&zcp) < 0)
263		exit(EXIT_FAILURE);
264
265	if (zed_conf_read_state(&zcp, &saved_eid, saved_etime) < 0)
266		exit(EXIT_FAILURE);
267
268idle:
269	/*
270	 * If -I is specified, attempt to open /dev/zfs repeatedly until
271	 * successful.
272	 */
273	do {
274		if (!zed_event_init(&zcp))
275			break;
276		/* Wait for some time and try again. tunable? */
277		sleep(30);
278	} while (!_got_exit && zcp.do_idle);
279
280	if (_got_exit)
281		goto out;
282
283	zed_event_seek(&zcp, saved_eid, saved_etime);
284
285	while (!_got_exit) {
286		int rv;
287		if (_got_hup) {
288			_got_hup = 0;
289			(void) zed_conf_scan_dir(&zcp);
290		}
291		rv = zed_event_service(&zcp);
292
293		/* ENODEV: When kernel module is unloaded (osx) */
294		if (rv == ENODEV)
295			break;
296	}
297
298	zed_log_msg(LOG_NOTICE, "Exiting");
299	zed_event_fini(&zcp);
300
301	if (zcp.do_idle && !_got_exit)
302		goto idle;
303
304out:
305	zed_conf_destroy(&zcp);
306	zed_log_fini();
307	exit(EXIT_SUCCESS);
308}
309