hastd.c revision 229509
1204076Spjd/*-
2204076Spjd * Copyright (c) 2009-2010 The FreeBSD Foundation
3219351Spjd * Copyright (c) 2010-2011 Pawel Jakub Dawidek <pawel@dawidek.net>
4204076Spjd * All rights reserved.
5204076Spjd *
6204076Spjd * This software was developed by Pawel Jakub Dawidek under sponsorship from
7204076Spjd * the FreeBSD Foundation.
8204076Spjd *
9204076Spjd * Redistribution and use in source and binary forms, with or without
10204076Spjd * modification, are permitted provided that the following conditions
11204076Spjd * are met:
12204076Spjd * 1. Redistributions of source code must retain the above copyright
13204076Spjd *    notice, this list of conditions and the following disclaimer.
14204076Spjd * 2. Redistributions in binary form must reproduce the above copyright
15204076Spjd *    notice, this list of conditions and the following disclaimer in the
16204076Spjd *    documentation and/or other materials provided with the distribution.
17204076Spjd *
18204076Spjd * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
19204076Spjd * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20204076Spjd * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21204076Spjd * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
22204076Spjd * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23204076Spjd * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24204076Spjd * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25204076Spjd * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26204076Spjd * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27204076Spjd * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28204076Spjd * SUCH DAMAGE.
29204076Spjd */
30204076Spjd
31204076Spjd#include <sys/cdefs.h>
32204076Spjd__FBSDID("$FreeBSD: stable/9/sbin/hastd/hastd.c 229509 2012-01-04 17:22:10Z trociny $");
33204076Spjd
34204076Spjd#include <sys/param.h>
35204076Spjd#include <sys/linker.h>
36204076Spjd#include <sys/module.h>
37218044Spjd#include <sys/stat.h>
38204076Spjd#include <sys/wait.h>
39204076Spjd
40204076Spjd#include <err.h>
41204076Spjd#include <errno.h>
42204076Spjd#include <libutil.h>
43204076Spjd#include <signal.h>
44204076Spjd#include <stdbool.h>
45204076Spjd#include <stdio.h>
46204076Spjd#include <stdlib.h>
47204076Spjd#include <string.h>
48204076Spjd#include <sysexits.h>
49219813Spjd#include <time.h>
50204076Spjd#include <unistd.h>
51204076Spjd
52204076Spjd#include <activemap.h>
53204076Spjd#include <pjdlog.h>
54204076Spjd
55204076Spjd#include "control.h"
56212038Spjd#include "event.h"
57204076Spjd#include "hast.h"
58204076Spjd#include "hast_proto.h"
59204076Spjd#include "hastd.h"
60211977Spjd#include "hooks.h"
61204076Spjd#include "subr.h"
62204076Spjd
63204076Spjd/* Path to configuration file. */
64210886Spjdconst char *cfgpath = HAST_CONFIG;
65204076Spjd/* Hastd configuration. */
66204076Spjdstatic struct hastd_config *cfg;
67204076Spjd/* Was SIGINT or SIGTERM signal received? */
68204076Spjdbool sigexit_received = false;
69204076Spjd/* PID file handle. */
70204076Spjdstruct pidfh *pfh;
71204076Spjd
72211977Spjd/* How often check for hooks running for too long. */
73213430Spjd#define	REPORT_INTERVAL	5
74211977Spjd
75204076Spjdstatic void
76204076Spjdusage(void)
77204076Spjd{
78204076Spjd
79204076Spjd	errx(EX_USAGE, "[-dFh] [-c config] [-P pidfile]");
80204076Spjd}
81204076Spjd
82204076Spjdstatic void
83204076Spjdg_gate_load(void)
84204076Spjd{
85204076Spjd
86204076Spjd	if (modfind("g_gate") == -1) {
87204076Spjd		/* Not present in kernel, try loading it. */
88204076Spjd		if (kldload("geom_gate") == -1 || modfind("g_gate") == -1) {
89204076Spjd			if (errno != EEXIST) {
90204076Spjd				pjdlog_exit(EX_OSERR,
91204076Spjd				    "Unable to load geom_gate module");
92204076Spjd			}
93204076Spjd		}
94204076Spjd	}
95204076Spjd}
96204076Spjd
97218041Spjdvoid
98218041Spjddescriptors_cleanup(struct hast_resource *res)
99218041Spjd{
100218041Spjd	struct hast_resource *tres;
101222108Spjd	struct hastd_listen *lst;
102218041Spjd
103218041Spjd	TAILQ_FOREACH(tres, &cfg->hc_resources, hr_next) {
104218041Spjd		if (tres == res) {
105218041Spjd			PJDLOG_VERIFY(res->hr_role == HAST_ROLE_SECONDARY ||
106218041Spjd			    (res->hr_remotein == NULL &&
107218041Spjd			     res->hr_remoteout == NULL));
108218041Spjd			continue;
109218041Spjd		}
110218041Spjd		if (tres->hr_remotein != NULL)
111218041Spjd			proto_close(tres->hr_remotein);
112218041Spjd		if (tres->hr_remoteout != NULL)
113218041Spjd			proto_close(tres->hr_remoteout);
114218370Spjd		if (tres->hr_ctrl != NULL)
115218370Spjd			proto_close(tres->hr_ctrl);
116218370Spjd		if (tres->hr_event != NULL)
117218370Spjd			proto_close(tres->hr_event);
118218370Spjd		if (tres->hr_conn != NULL)
119218370Spjd			proto_close(tres->hr_conn);
120218041Spjd	}
121218041Spjd	if (cfg->hc_controlin != NULL)
122218041Spjd		proto_close(cfg->hc_controlin);
123218041Spjd	proto_close(cfg->hc_controlconn);
124222108Spjd	TAILQ_FOREACH(lst, &cfg->hc_listen, hl_next) {
125222108Spjd		if (lst->hl_conn != NULL)
126222108Spjd			proto_close(lst->hl_conn);
127222108Spjd	}
128218041Spjd	(void)pidfile_close(pfh);
129218041Spjd	hook_fini();
130218041Spjd	pjdlog_fini();
131218041Spjd}
132218041Spjd
133218044Spjdstatic const char *
134218044Spjddtype2str(mode_t mode)
135218044Spjd{
136218044Spjd
137218044Spjd	if (S_ISBLK(mode))
138218044Spjd		return ("block device");
139219864Spjd	else if (S_ISCHR(mode))
140218044Spjd		return ("character device");
141219864Spjd	else if (S_ISDIR(mode))
142218044Spjd		return ("directory");
143218044Spjd	else if (S_ISFIFO(mode))
144218044Spjd		return ("pipe or FIFO");
145219864Spjd	else if (S_ISLNK(mode))
146218044Spjd		return ("symbolic link");
147219864Spjd	else if (S_ISREG(mode))
148218044Spjd		return ("regular file");
149218044Spjd	else if (S_ISSOCK(mode))
150218044Spjd		return ("socket");
151219864Spjd	else if (S_ISWHT(mode))
152218044Spjd		return ("whiteout");
153218044Spjd	else
154218044Spjd		return ("unknown");
155218044Spjd}
156218044Spjd
157218044Spjdvoid
158218044Spjddescriptors_assert(const struct hast_resource *res, int pjdlogmode)
159218044Spjd{
160218044Spjd	char msg[256];
161218044Spjd	struct stat sb;
162218044Spjd	long maxfd;
163218044Spjd	bool isopen;
164218044Spjd	mode_t mode;
165218044Spjd	int fd;
166218044Spjd
167218044Spjd	/*
168218044Spjd	 * At this point descriptor to syslog socket is closed, so if we want
169218044Spjd	 * to log assertion message, we have to first store it in 'msg' local
170218044Spjd	 * buffer and then open syslog socket and log it.
171218044Spjd	 */
172218044Spjd	msg[0] = '\0';
173218044Spjd
174218044Spjd	maxfd = sysconf(_SC_OPEN_MAX);
175218044Spjd	if (maxfd < 0) {
176218373Spjd		pjdlog_init(pjdlogmode);
177218373Spjd		pjdlog_prefix_set("[%s] (%s) ", res->hr_name,
178218373Spjd		    role2str(res->hr_role));
179218044Spjd		pjdlog_errno(LOG_WARNING, "sysconf(_SC_OPEN_MAX) failed");
180218373Spjd		pjdlog_fini();
181218044Spjd		maxfd = 16384;
182218044Spjd	}
183218044Spjd	for (fd = 0; fd <= maxfd; fd++) {
184218044Spjd		if (fstat(fd, &sb) == 0) {
185218044Spjd			isopen = true;
186218044Spjd			mode = sb.st_mode;
187218044Spjd		} else if (errno == EBADF) {
188218044Spjd			isopen = false;
189218044Spjd			mode = 0;
190218044Spjd		} else {
191218375Spjd			(void)snprintf(msg, sizeof(msg),
192218044Spjd			    "Unable to fstat descriptor %d: %s", fd,
193218044Spjd			    strerror(errno));
194218374Spjd			break;
195218044Spjd		}
196218044Spjd		if (fd == STDIN_FILENO || fd == STDOUT_FILENO ||
197218044Spjd		    fd == STDERR_FILENO) {
198218044Spjd			if (!isopen) {
199218375Spjd				(void)snprintf(msg, sizeof(msg),
200218044Spjd				    "Descriptor %d (%s) is closed, but should be open.",
201218044Spjd				    fd, (fd == STDIN_FILENO ? "stdin" :
202218044Spjd				    (fd == STDOUT_FILENO ? "stdout" : "stderr")));
203218044Spjd				break;
204218044Spjd			}
205218044Spjd		} else if (fd == proto_descriptor(res->hr_event)) {
206218044Spjd			if (!isopen) {
207218375Spjd				(void)snprintf(msg, sizeof(msg),
208218044Spjd				    "Descriptor %d (event) is closed, but should be open.",
209218044Spjd				    fd);
210218044Spjd				break;
211218044Spjd			}
212218044Spjd			if (!S_ISSOCK(mode)) {
213218375Spjd				(void)snprintf(msg, sizeof(msg),
214218044Spjd				    "Descriptor %d (event) is %s, but should be %s.",
215218044Spjd				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
216218044Spjd				break;
217218044Spjd			}
218218044Spjd		} else if (fd == proto_descriptor(res->hr_ctrl)) {
219218044Spjd			if (!isopen) {
220218375Spjd				(void)snprintf(msg, sizeof(msg),
221218044Spjd				    "Descriptor %d (ctrl) is closed, but should be open.",
222218044Spjd				    fd);
223218044Spjd				break;
224218044Spjd			}
225218044Spjd			if (!S_ISSOCK(mode)) {
226218375Spjd				(void)snprintf(msg, sizeof(msg),
227218044Spjd				    "Descriptor %d (ctrl) is %s, but should be %s.",
228218044Spjd				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
229218044Spjd				break;
230218044Spjd			}
231219900Spjd		} else if (res->hr_role == HAST_ROLE_PRIMARY &&
232219900Spjd		    fd == proto_descriptor(res->hr_conn)) {
233218218Spjd			if (!isopen) {
234218375Spjd				(void)snprintf(msg, sizeof(msg),
235218218Spjd				    "Descriptor %d (conn) is closed, but should be open.",
236218218Spjd				    fd);
237218218Spjd				break;
238218218Spjd			}
239218218Spjd			if (!S_ISSOCK(mode)) {
240218375Spjd				(void)snprintf(msg, sizeof(msg),
241218218Spjd				    "Descriptor %d (conn) is %s, but should be %s.",
242218218Spjd				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
243218218Spjd				break;
244218218Spjd			}
245218044Spjd		} else if (res->hr_role == HAST_ROLE_SECONDARY &&
246219900Spjd		    res->hr_conn != NULL &&
247219900Spjd		    fd == proto_descriptor(res->hr_conn)) {
248219900Spjd			if (isopen) {
249219900Spjd				(void)snprintf(msg, sizeof(msg),
250219900Spjd				    "Descriptor %d (conn) is open, but should be closed.",
251219900Spjd				    fd);
252219900Spjd				break;
253219900Spjd			}
254219900Spjd		} else if (res->hr_role == HAST_ROLE_SECONDARY &&
255218044Spjd		    fd == proto_descriptor(res->hr_remotein)) {
256218044Spjd			if (!isopen) {
257218375Spjd				(void)snprintf(msg, sizeof(msg),
258218044Spjd				    "Descriptor %d (remote in) is closed, but should be open.",
259218044Spjd				    fd);
260218044Spjd				break;
261218044Spjd			}
262218044Spjd			if (!S_ISSOCK(mode)) {
263218375Spjd				(void)snprintf(msg, sizeof(msg),
264218044Spjd				    "Descriptor %d (remote in) is %s, but should be %s.",
265218044Spjd				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
266218044Spjd				break;
267218044Spjd			}
268218044Spjd		} else if (res->hr_role == HAST_ROLE_SECONDARY &&
269218044Spjd		    fd == proto_descriptor(res->hr_remoteout)) {
270218044Spjd			if (!isopen) {
271218375Spjd				(void)snprintf(msg, sizeof(msg),
272218044Spjd				    "Descriptor %d (remote out) is closed, but should be open.",
273218044Spjd				    fd);
274218044Spjd				break;
275218044Spjd			}
276218044Spjd			if (!S_ISSOCK(mode)) {
277218375Spjd				(void)snprintf(msg, sizeof(msg),
278218044Spjd				    "Descriptor %d (remote out) is %s, but should be %s.",
279218044Spjd				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
280218044Spjd				break;
281218044Spjd			}
282218044Spjd		} else {
283218044Spjd			if (isopen) {
284218375Spjd				(void)snprintf(msg, sizeof(msg),
285218044Spjd				    "Descriptor %d is open (%s), but should be closed.",
286218044Spjd				    fd, dtype2str(mode));
287218044Spjd				break;
288218044Spjd			}
289218044Spjd		}
290218044Spjd	}
291218044Spjd	if (msg[0] != '\0') {
292218044Spjd		pjdlog_init(pjdlogmode);
293218044Spjd		pjdlog_prefix_set("[%s] (%s) ", res->hr_name,
294218044Spjd		    role2str(res->hr_role));
295218044Spjd		PJDLOG_ABORT("%s", msg);
296218044Spjd	}
297218044Spjd}
298218044Spjd
299204076Spjdstatic void
300207372Spjdchild_exit_log(unsigned int pid, int status)
301207372Spjd{
302207372Spjd
303207372Spjd	if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
304207372Spjd		pjdlog_debug(1, "Worker process exited gracefully (pid=%u).",
305207372Spjd		    pid);
306207372Spjd	} else if (WIFSIGNALED(status)) {
307207372Spjd		pjdlog_error("Worker process killed (pid=%u, signal=%d).",
308207372Spjd		    pid, WTERMSIG(status));
309207372Spjd	} else {
310207372Spjd		pjdlog_error("Worker process exited ungracefully (pid=%u, exitcode=%d).",
311207372Spjd		    pid, WIFEXITED(status) ? WEXITSTATUS(status) : -1);
312207372Spjd	}
313207372Spjd}
314207372Spjd
315207372Spjdstatic void
316204076Spjdchild_exit(void)
317204076Spjd{
318204076Spjd	struct hast_resource *res;
319204076Spjd	int status;
320204076Spjd	pid_t pid;
321204076Spjd
322204076Spjd	while ((pid = wait3(&status, WNOHANG, NULL)) > 0) {
323204076Spjd		/* Find resource related to the process that just exited. */
324204076Spjd		TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
325204076Spjd			if (pid == res->hr_workerpid)
326204076Spjd				break;
327204076Spjd		}
328204076Spjd		if (res == NULL) {
329204076Spjd			/*
330204076Spjd			 * This can happen when new connection arrives and we
331211977Spjd			 * cancel child responsible for the old one or if this
332211977Spjd			 * was hook which we executed.
333204076Spjd			 */
334211977Spjd			hook_check_one(pid, status);
335204076Spjd			continue;
336204076Spjd		}
337204076Spjd		pjdlog_prefix_set("[%s] (%s) ", res->hr_name,
338204076Spjd		    role2str(res->hr_role));
339207372Spjd		child_exit_log(pid, status);
340213006Spjd		child_cleanup(res);
341204076Spjd		if (res->hr_role == HAST_ROLE_PRIMARY) {
342207372Spjd			/*
343207372Spjd			 * Restart child process if it was killed by signal
344207372Spjd			 * or exited because of temporary problem.
345207372Spjd			 */
346207372Spjd			if (WIFSIGNALED(status) ||
347207372Spjd			    (WIFEXITED(status) &&
348207372Spjd			     WEXITSTATUS(status) == EX_TEMPFAIL)) {
349207348Spjd				sleep(1);
350207348Spjd				pjdlog_info("Restarting worker process.");
351207348Spjd				hastd_primary(res);
352207348Spjd			} else {
353207348Spjd				res->hr_role = HAST_ROLE_INIT;
354207348Spjd				pjdlog_info("Changing resource role back to %s.",
355207348Spjd				    role2str(res->hr_role));
356207348Spjd			}
357204076Spjd		}
358204076Spjd		pjdlog_prefix_set("%s", "");
359204076Spjd	}
360204076Spjd}
361204076Spjd
362210886Spjdstatic bool
363210886Spjdresource_needs_restart(const struct hast_resource *res0,
364210886Spjd    const struct hast_resource *res1)
365210886Spjd{
366210886Spjd
367218138Spjd	PJDLOG_ASSERT(strcmp(res0->hr_name, res1->hr_name) == 0);
368210886Spjd
369210886Spjd	if (strcmp(res0->hr_provname, res1->hr_provname) != 0)
370210886Spjd		return (true);
371210886Spjd	if (strcmp(res0->hr_localpath, res1->hr_localpath) != 0)
372210886Spjd		return (true);
373210886Spjd	if (res0->hr_role == HAST_ROLE_INIT ||
374210886Spjd	    res0->hr_role == HAST_ROLE_SECONDARY) {
375210886Spjd		if (strcmp(res0->hr_remoteaddr, res1->hr_remoteaddr) != 0)
376210886Spjd			return (true);
377219818Spjd		if (strcmp(res0->hr_sourceaddr, res1->hr_sourceaddr) != 0)
378219818Spjd			return (true);
379210886Spjd		if (res0->hr_replication != res1->hr_replication)
380210886Spjd			return (true);
381219351Spjd		if (res0->hr_checksum != res1->hr_checksum)
382219351Spjd			return (true);
383219354Spjd		if (res0->hr_compression != res1->hr_compression)
384219354Spjd			return (true);
385210886Spjd		if (res0->hr_timeout != res1->hr_timeout)
386210886Spjd			return (true);
387211886Spjd		if (strcmp(res0->hr_exec, res1->hr_exec) != 0)
388211886Spjd			return (true);
389229509Strociny		/*
390229509Strociny		 * When metaflush has changed we don't really need restart,
391229509Strociny		 * but it is just easier this way.
392229509Strociny		 */
393229509Strociny		if (res0->hr_metaflush != res1->hr_metaflush)
394229509Strociny			return (true);
395210886Spjd	}
396210886Spjd	return (false);
397210886Spjd}
398210886Spjd
399210886Spjdstatic bool
400210886Spjdresource_needs_reload(const struct hast_resource *res0,
401210886Spjd    const struct hast_resource *res1)
402210886Spjd{
403210886Spjd
404218138Spjd	PJDLOG_ASSERT(strcmp(res0->hr_name, res1->hr_name) == 0);
405218138Spjd	PJDLOG_ASSERT(strcmp(res0->hr_provname, res1->hr_provname) == 0);
406218138Spjd	PJDLOG_ASSERT(strcmp(res0->hr_localpath, res1->hr_localpath) == 0);
407210886Spjd
408210886Spjd	if (res0->hr_role != HAST_ROLE_PRIMARY)
409210886Spjd		return (false);
410210886Spjd
411210886Spjd	if (strcmp(res0->hr_remoteaddr, res1->hr_remoteaddr) != 0)
412210886Spjd		return (true);
413219818Spjd	if (strcmp(res0->hr_sourceaddr, res1->hr_sourceaddr) != 0)
414219818Spjd		return (true);
415210886Spjd	if (res0->hr_replication != res1->hr_replication)
416210886Spjd		return (true);
417219351Spjd	if (res0->hr_checksum != res1->hr_checksum)
418219351Spjd		return (true);
419219354Spjd	if (res0->hr_compression != res1->hr_compression)
420219354Spjd		return (true);
421210886Spjd	if (res0->hr_timeout != res1->hr_timeout)
422210886Spjd		return (true);
423211886Spjd	if (strcmp(res0->hr_exec, res1->hr_exec) != 0)
424211886Spjd		return (true);
425229509Strociny	if (res0->hr_metaflush != res1->hr_metaflush)
426229509Strociny		return (true);
427210886Spjd	return (false);
428210886Spjd}
429210886Spjd
430204076Spjdstatic void
431217784Spjdresource_reload(const struct hast_resource *res)
432217784Spjd{
433217784Spjd	struct nv *nvin, *nvout;
434217784Spjd	int error;
435217784Spjd
436218138Spjd	PJDLOG_ASSERT(res->hr_role == HAST_ROLE_PRIMARY);
437217784Spjd
438217784Spjd	nvout = nv_alloc();
439221076Strociny	nv_add_uint8(nvout, CONTROL_RELOAD, "cmd");
440217784Spjd	nv_add_string(nvout, res->hr_remoteaddr, "remoteaddr");
441219818Spjd	nv_add_string(nvout, res->hr_sourceaddr, "sourceaddr");
442217784Spjd	nv_add_int32(nvout, (int32_t)res->hr_replication, "replication");
443219351Spjd	nv_add_int32(nvout, (int32_t)res->hr_checksum, "checksum");
444219354Spjd	nv_add_int32(nvout, (int32_t)res->hr_compression, "compression");
445217784Spjd	nv_add_int32(nvout, (int32_t)res->hr_timeout, "timeout");
446217784Spjd	nv_add_string(nvout, res->hr_exec, "exec");
447229509Strociny	nv_add_int32(nvout, (int32_t)res->hr_metaflush, "metaflush");
448217784Spjd	if (nv_error(nvout) != 0) {
449217784Spjd		nv_free(nvout);
450217784Spjd		pjdlog_error("Unable to allocate header for reload message.");
451217784Spjd		return;
452217784Spjd	}
453217784Spjd	if (hast_proto_send(res, res->hr_ctrl, nvout, NULL, 0) < 0) {
454217784Spjd		pjdlog_errno(LOG_ERR, "Unable to send reload message");
455217784Spjd		nv_free(nvout);
456217784Spjd		return;
457217784Spjd	}
458217784Spjd	nv_free(nvout);
459217784Spjd
460217784Spjd	/* Receive response. */
461217784Spjd	if (hast_proto_recv_hdr(res->hr_ctrl, &nvin) < 0) {
462217784Spjd		pjdlog_errno(LOG_ERR, "Unable to receive reload reply");
463217784Spjd		return;
464217784Spjd	}
465217784Spjd	error = nv_get_int16(nvin, "error");
466217784Spjd	nv_free(nvin);
467217784Spjd	if (error != 0) {
468217784Spjd		pjdlog_common(LOG_ERR, 0, error, "Reload failed");
469217784Spjd		return;
470217784Spjd	}
471217784Spjd}
472217784Spjd
473217784Spjdstatic void
474204076Spjdhastd_reload(void)
475204076Spjd{
476210886Spjd	struct hastd_config *newcfg;
477210886Spjd	struct hast_resource *nres, *cres, *tres;
478222108Spjd	struct hastd_listen *nlst, *clst;
479229509Strociny	struct pidfh *newpfh;
480222108Spjd	unsigned int nlisten;
481210886Spjd	uint8_t role;
482229509Strociny	pid_t otherpid;
483204076Spjd
484210886Spjd	pjdlog_info("Reloading configuration...");
485210886Spjd
486229509Strociny	newpfh = NULL;
487229509Strociny
488210886Spjd	newcfg = yy_config_parse(cfgpath, false);
489210886Spjd	if (newcfg == NULL)
490210886Spjd		goto failed;
491210886Spjd
492210886Spjd	/*
493210886Spjd	 * Check if control address has changed.
494210886Spjd	 */
495210886Spjd	if (strcmp(cfg->hc_controladdr, newcfg->hc_controladdr) != 0) {
496210886Spjd		if (proto_server(newcfg->hc_controladdr,
497210886Spjd		    &newcfg->hc_controlconn) < 0) {
498210886Spjd			pjdlog_errno(LOG_ERR,
499210886Spjd			    "Unable to listen on control address %s",
500210886Spjd			    newcfg->hc_controladdr);
501210886Spjd			goto failed;
502210886Spjd		}
503210886Spjd	}
504210886Spjd	/*
505222108Spjd	 * Check if any listen address has changed.
506210886Spjd	 */
507222108Spjd	nlisten = 0;
508222108Spjd	TAILQ_FOREACH(nlst, &newcfg->hc_listen, hl_next) {
509222108Spjd		TAILQ_FOREACH(clst, &cfg->hc_listen, hl_next) {
510222108Spjd			if (strcmp(nlst->hl_addr, clst->hl_addr) == 0)
511222108Spjd				break;
512210886Spjd		}
513222108Spjd		if (clst != NULL && clst->hl_conn != NULL) {
514222108Spjd			pjdlog_info("Keep listening on address %s.",
515222108Spjd			    nlst->hl_addr);
516222108Spjd			nlst->hl_conn = clst->hl_conn;
517222108Spjd			nlisten++;
518222108Spjd		} else if (proto_server(nlst->hl_addr, &nlst->hl_conn) == 0) {
519222108Spjd			pjdlog_info("Listening on new address %s.",
520222108Spjd			    nlst->hl_addr);
521222108Spjd			nlisten++;
522222108Spjd		} else {
523222108Spjd			pjdlog_errno(LOG_WARNING,
524222108Spjd			    "Unable to listen on address %s", nlst->hl_addr);
525222108Spjd		}
526210886Spjd	}
527222108Spjd	if (nlisten == 0) {
528222108Spjd		pjdlog_error("No addresses to listen on.");
529222108Spjd		goto failed;
530222108Spjd	}
531229509Strociny	/*
532229509Strociny	 * Check if pidfile's path has changed.
533229509Strociny	 */
534229509Strociny	if (strcmp(cfg->hc_pidfile, newcfg->hc_pidfile) != 0) {
535229509Strociny		newpfh = pidfile_open(newcfg->hc_pidfile, 0600, &otherpid);
536229509Strociny		if (newpfh == NULL) {
537229509Strociny			if (errno == EEXIST) {
538229509Strociny				pjdlog_errno(LOG_WARNING,
539229509Strociny				    "Another hastd is already running, pidfile: %s, pid: %jd.",
540229509Strociny				    newcfg->hc_pidfile, (intmax_t)otherpid);
541229509Strociny			} else {
542229509Strociny				pjdlog_errno(LOG_WARNING,
543229509Strociny				    "Unable to open or create pidfile %s",
544229509Strociny				    newcfg->hc_pidfile);
545229509Strociny			}
546229509Strociny		} else if (pidfile_write(newpfh) < 0) {
547229509Strociny			/* Write PID to a file. */
548229509Strociny			pjdlog_errno(LOG_WARNING,
549229509Strociny			    "Unable to write PID to file %s",
550229509Strociny			    newcfg->hc_pidfile);
551229509Strociny		} else {
552229509Strociny			pjdlog_debug(1, "PID stored in %s.",
553229509Strociny			    newcfg->hc_pidfile);
554229509Strociny		}
555229509Strociny	}
556222108Spjd
557222108Spjd	/* No failures from now on. */
558222108Spjd
559210886Spjd	/*
560222108Spjd	 * Switch to new control socket.
561210886Spjd	 */
562210886Spjd	if (newcfg->hc_controlconn != NULL) {
563210886Spjd		pjdlog_info("Control socket changed from %s to %s.",
564210886Spjd		    cfg->hc_controladdr, newcfg->hc_controladdr);
565210886Spjd		proto_close(cfg->hc_controlconn);
566210886Spjd		cfg->hc_controlconn = newcfg->hc_controlconn;
567210886Spjd		newcfg->hc_controlconn = NULL;
568210886Spjd		strlcpy(cfg->hc_controladdr, newcfg->hc_controladdr,
569210886Spjd		    sizeof(cfg->hc_controladdr));
570210886Spjd	}
571222108Spjd	/*
572229509Strociny	 * Switch to new pidfile.
573229509Strociny	 */
574229509Strociny	(void)pidfile_remove(pfh);
575229509Strociny	pfh = newpfh;
576229509Strociny	(void)strlcpy(cfg->hc_pidfile, newcfg->hc_pidfile,
577229509Strociny	    sizeof(cfg->hc_pidfile));
578229509Strociny	/*
579222108Spjd	 * Switch to new listen addresses. Close all that were removed.
580222108Spjd	 */
581222108Spjd	while ((clst = TAILQ_FIRST(&cfg->hc_listen)) != NULL) {
582222108Spjd		TAILQ_FOREACH(nlst, &newcfg->hc_listen, hl_next) {
583222108Spjd			if (strcmp(nlst->hl_addr, clst->hl_addr) == 0)
584222108Spjd				break;
585222108Spjd		}
586222108Spjd		if (nlst == NULL && clst->hl_conn != NULL) {
587222108Spjd			proto_close(clst->hl_conn);
588222108Spjd			pjdlog_info("No longer listening on address %s.",
589222108Spjd			    clst->hl_addr);
590222108Spjd		}
591222108Spjd		TAILQ_REMOVE(&cfg->hc_listen, clst, hl_next);
592222108Spjd		free(clst);
593210886Spjd	}
594222108Spjd	TAILQ_CONCAT(&cfg->hc_listen, &newcfg->hc_listen, hl_next);
595210886Spjd
596210886Spjd	/*
597210886Spjd	 * Stop and remove resources that were removed from the configuration.
598210886Spjd	 */
599210886Spjd	TAILQ_FOREACH_SAFE(cres, &cfg->hc_resources, hr_next, tres) {
600210886Spjd		TAILQ_FOREACH(nres, &newcfg->hc_resources, hr_next) {
601210886Spjd			if (strcmp(cres->hr_name, nres->hr_name) == 0)
602210886Spjd				break;
603210886Spjd		}
604210886Spjd		if (nres == NULL) {
605210886Spjd			control_set_role(cres, HAST_ROLE_INIT);
606210886Spjd			TAILQ_REMOVE(&cfg->hc_resources, cres, hr_next);
607210886Spjd			pjdlog_info("Resource %s removed.", cres->hr_name);
608210886Spjd			free(cres);
609210886Spjd		}
610210886Spjd	}
611210886Spjd	/*
612210886Spjd	 * Move new resources to the current configuration.
613210886Spjd	 */
614210886Spjd	TAILQ_FOREACH_SAFE(nres, &newcfg->hc_resources, hr_next, tres) {
615210886Spjd		TAILQ_FOREACH(cres, &cfg->hc_resources, hr_next) {
616210886Spjd			if (strcmp(cres->hr_name, nres->hr_name) == 0)
617210886Spjd				break;
618210886Spjd		}
619210886Spjd		if (cres == NULL) {
620210886Spjd			TAILQ_REMOVE(&newcfg->hc_resources, nres, hr_next);
621210886Spjd			TAILQ_INSERT_TAIL(&cfg->hc_resources, nres, hr_next);
622210886Spjd			pjdlog_info("Resource %s added.", nres->hr_name);
623210886Spjd		}
624210886Spjd	}
625210886Spjd	/*
626210886Spjd	 * Deal with modified resources.
627210886Spjd	 * Depending on what has changed exactly we might want to perform
628210886Spjd	 * different actions.
629210886Spjd	 *
630210886Spjd	 * We do full resource restart in the following situations:
631210886Spjd	 * Resource role is INIT or SECONDARY.
632210886Spjd	 * Resource role is PRIMARY and path to local component or provider
633210886Spjd	 * name has changed.
634210886Spjd	 * In case of PRIMARY, the worker process will be killed and restarted,
635210886Spjd	 * which also means removing /dev/hast/<name> provider and
636210886Spjd	 * recreating it.
637210886Spjd	 *
638210886Spjd	 * We do just reload (send SIGHUP to worker process) if we act as
639229509Strociny	 * PRIMARY, but only if remote address, source address, replication
640229509Strociny	 * mode, timeout, execution path or metaflush has changed.
641229509Strociny	 * For those, there is no need to restart worker process.
642210886Spjd	 * If PRIMARY receives SIGHUP, it will reconnect if remote address or
643229509Strociny	 * source address has changed or it will set new timeout if only timeout
644229509Strociny	 * has changed or it will update metaflush if only metaflush has
645229509Strociny	 * changed.
646210886Spjd	 */
647210886Spjd	TAILQ_FOREACH_SAFE(nres, &newcfg->hc_resources, hr_next, tres) {
648210886Spjd		TAILQ_FOREACH(cres, &cfg->hc_resources, hr_next) {
649210886Spjd			if (strcmp(cres->hr_name, nres->hr_name) == 0)
650210886Spjd				break;
651210886Spjd		}
652218138Spjd		PJDLOG_ASSERT(cres != NULL);
653210886Spjd		if (resource_needs_restart(cres, nres)) {
654210886Spjd			pjdlog_info("Resource %s configuration was modified, restarting it.",
655210886Spjd			    cres->hr_name);
656210886Spjd			role = cres->hr_role;
657210886Spjd			control_set_role(cres, HAST_ROLE_INIT);
658210886Spjd			TAILQ_REMOVE(&cfg->hc_resources, cres, hr_next);
659210886Spjd			free(cres);
660210886Spjd			TAILQ_REMOVE(&newcfg->hc_resources, nres, hr_next);
661210886Spjd			TAILQ_INSERT_TAIL(&cfg->hc_resources, nres, hr_next);
662210886Spjd			control_set_role(nres, role);
663210886Spjd		} else if (resource_needs_reload(cres, nres)) {
664210886Spjd			pjdlog_info("Resource %s configuration was modified, reloading it.",
665210886Spjd			    cres->hr_name);
666210886Spjd			strlcpy(cres->hr_remoteaddr, nres->hr_remoteaddr,
667210886Spjd			    sizeof(cres->hr_remoteaddr));
668219818Spjd			strlcpy(cres->hr_sourceaddr, nres->hr_sourceaddr,
669219818Spjd			    sizeof(cres->hr_sourceaddr));
670210886Spjd			cres->hr_replication = nres->hr_replication;
671219351Spjd			cres->hr_checksum = nres->hr_checksum;
672219354Spjd			cres->hr_compression = nres->hr_compression;
673210886Spjd			cres->hr_timeout = nres->hr_timeout;
674217729Spjd			strlcpy(cres->hr_exec, nres->hr_exec,
675217729Spjd			    sizeof(cres->hr_exec));
676229509Strociny			cres->hr_metaflush = nres->hr_metaflush;
677217784Spjd			if (cres->hr_workerpid != 0)
678217784Spjd				resource_reload(cres);
679210886Spjd		}
680210886Spjd	}
681210886Spjd
682210886Spjd	yy_config_free(newcfg);
683210886Spjd	pjdlog_info("Configuration reloaded successfully.");
684210886Spjd	return;
685210886Spjdfailed:
686210886Spjd	if (newcfg != NULL) {
687210886Spjd		if (newcfg->hc_controlconn != NULL)
688210886Spjd			proto_close(newcfg->hc_controlconn);
689222108Spjd		while ((nlst = TAILQ_FIRST(&newcfg->hc_listen)) != NULL) {
690222108Spjd			if (nlst->hl_conn != NULL) {
691222108Spjd				TAILQ_FOREACH(clst, &cfg->hc_listen, hl_next) {
692222108Spjd					if (strcmp(nlst->hl_addr,
693222108Spjd					    clst->hl_addr) == 0) {
694222108Spjd						break;
695222108Spjd					}
696222108Spjd				}
697222108Spjd				if (clst == NULL || clst->hl_conn == NULL)
698222108Spjd					proto_close(nlst->hl_conn);
699222108Spjd			}
700222108Spjd			TAILQ_REMOVE(&newcfg->hc_listen, nlst, hl_next);
701222108Spjd			free(nlst);
702222108Spjd		}
703210886Spjd		yy_config_free(newcfg);
704210886Spjd	}
705229509Strociny	if (newpfh != NULL)
706229509Strociny		(void)pidfile_remove(newpfh);
707210886Spjd	pjdlog_warning("Configuration not reloaded.");
708204076Spjd}
709204076Spjd
710204076Spjdstatic void
711211899Spjdterminate_workers(void)
712211899Spjd{
713211899Spjd	struct hast_resource *res;
714211899Spjd
715211899Spjd	pjdlog_info("Termination signal received, exiting.");
716211899Spjd	TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
717211899Spjd		if (res->hr_workerpid == 0)
718211899Spjd			continue;
719211899Spjd		pjdlog_info("Terminating worker process (resource=%s, role=%s, pid=%u).",
720211899Spjd		    res->hr_name, role2str(res->hr_role), res->hr_workerpid);
721211899Spjd		if (kill(res->hr_workerpid, SIGTERM) == 0)
722211899Spjd			continue;
723211899Spjd		pjdlog_errno(LOG_WARNING,
724211899Spjd		    "Unable to send signal to worker process (resource=%s, role=%s, pid=%u).",
725211899Spjd		    res->hr_name, role2str(res->hr_role), res->hr_workerpid);
726211899Spjd	}
727211899Spjd}
728211899Spjd
729211899Spjdstatic void
730222108Spjdlisten_accept(struct hastd_listen *lst)
731204076Spjd{
732204076Spjd	struct hast_resource *res;
733204076Spjd	struct proto_conn *conn;
734204076Spjd	struct nv *nvin, *nvout, *nverr;
735204076Spjd	const char *resname;
736204076Spjd	const unsigned char *token;
737204076Spjd	char laddr[256], raddr[256];
738204076Spjd	size_t size;
739204076Spjd	pid_t pid;
740204076Spjd	int status;
741204076Spjd
742222108Spjd	proto_local_address(lst->hl_conn, laddr, sizeof(laddr));
743204076Spjd	pjdlog_debug(1, "Accepting connection to %s.", laddr);
744204076Spjd
745222108Spjd	if (proto_accept(lst->hl_conn, &conn) < 0) {
746204076Spjd		pjdlog_errno(LOG_ERR, "Unable to accept connection %s", laddr);
747204076Spjd		return;
748204076Spjd	}
749204076Spjd
750204076Spjd	proto_local_address(conn, laddr, sizeof(laddr));
751204076Spjd	proto_remote_address(conn, raddr, sizeof(raddr));
752209185Spjd	pjdlog_info("Connection from %s to %s.", raddr, laddr);
753204076Spjd
754207371Spjd	/* Error in setting timeout is not critical, but why should it fail? */
755207371Spjd	if (proto_timeout(conn, HAST_TIMEOUT) < 0)
756207371Spjd		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
757207371Spjd
758204076Spjd	nvin = nvout = nverr = NULL;
759204076Spjd
760204076Spjd	/*
761204076Spjd	 * Before receiving any data see if remote host have access to any
762204076Spjd	 * resource.
763204076Spjd	 */
764204076Spjd	TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
765204076Spjd		if (proto_address_match(conn, res->hr_remoteaddr))
766204076Spjd			break;
767204076Spjd	}
768204076Spjd	if (res == NULL) {
769204076Spjd		pjdlog_error("Client %s isn't known.", raddr);
770204076Spjd		goto close;
771204076Spjd	}
772204076Spjd	/* Ok, remote host can access at least one resource. */
773204076Spjd
774204076Spjd	if (hast_proto_recv_hdr(conn, &nvin) < 0) {
775204076Spjd		pjdlog_errno(LOG_ERR, "Unable to receive header from %s",
776204076Spjd		    raddr);
777204076Spjd		goto close;
778204076Spjd	}
779204076Spjd
780204076Spjd	resname = nv_get_string(nvin, "resource");
781204076Spjd	if (resname == NULL) {
782204076Spjd		pjdlog_error("No 'resource' field in the header received from %s.",
783204076Spjd		    raddr);
784204076Spjd		goto close;
785204076Spjd	}
786204076Spjd	pjdlog_debug(2, "%s: resource=%s", raddr, resname);
787204076Spjd	token = nv_get_uint8_array(nvin, &size, "token");
788204076Spjd	/*
789204076Spjd	 * NULL token means that this is first conection.
790204076Spjd	 */
791204076Spjd	if (token != NULL && size != sizeof(res->hr_token)) {
792204076Spjd		pjdlog_error("Received token of invalid size from %s (expected %zu, got %zu).",
793204076Spjd		    raddr, sizeof(res->hr_token), size);
794204076Spjd		goto close;
795204076Spjd	}
796204076Spjd
797204076Spjd	/*
798204076Spjd	 * From now on we want to send errors to the remote node.
799204076Spjd	 */
800204076Spjd	nverr = nv_alloc();
801204076Spjd
802204076Spjd	/* Find resource related to this connection. */
803204076Spjd	TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
804204076Spjd		if (strcmp(resname, res->hr_name) == 0)
805204076Spjd			break;
806204076Spjd	}
807204076Spjd	/* Have we found the resource? */
808204076Spjd	if (res == NULL) {
809204076Spjd		pjdlog_error("No resource '%s' as requested by %s.",
810204076Spjd		    resname, raddr);
811204076Spjd		nv_add_stringf(nverr, "errmsg", "Resource not configured.");
812204076Spjd		goto fail;
813204076Spjd	}
814204076Spjd
815204076Spjd	/* Now that we know resource name setup log prefix. */
816204076Spjd	pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
817204076Spjd
818204076Spjd	/* Does the remote host have access to this resource? */
819204076Spjd	if (!proto_address_match(conn, res->hr_remoteaddr)) {
820204076Spjd		pjdlog_error("Client %s has no access to the resource.", raddr);
821204076Spjd		nv_add_stringf(nverr, "errmsg", "No access to the resource.");
822204076Spjd		goto fail;
823204076Spjd	}
824204076Spjd	/* Is the resource marked as secondary? */
825204076Spjd	if (res->hr_role != HAST_ROLE_SECONDARY) {
826220890Spjd		pjdlog_warning("We act as %s for the resource and not as %s as requested by %s.",
827204076Spjd		    role2str(res->hr_role), role2str(HAST_ROLE_SECONDARY),
828204076Spjd		    raddr);
829204076Spjd		nv_add_stringf(nverr, "errmsg",
830204076Spjd		    "Remote node acts as %s for the resource and not as %s.",
831204076Spjd		    role2str(res->hr_role), role2str(HAST_ROLE_SECONDARY));
832220898Spjd		if (res->hr_role == HAST_ROLE_PRIMARY) {
833220898Spjd			/*
834220898Spjd			 * If we act as primary request the other side to wait
835220899Spjd			 * for us a bit, as we might be finishing cleanups.
836220898Spjd			 */
837220898Spjd			nv_add_uint8(nverr, 1, "wait");
838220898Spjd		}
839204076Spjd		goto fail;
840204076Spjd	}
841204076Spjd	/* Does token (if exists) match? */
842204076Spjd	if (token != NULL && memcmp(token, res->hr_token,
843204076Spjd	    sizeof(res->hr_token)) != 0) {
844204076Spjd		pjdlog_error("Token received from %s doesn't match.", raddr);
845209185Spjd		nv_add_stringf(nverr, "errmsg", "Token doesn't match.");
846204076Spjd		goto fail;
847204076Spjd	}
848204076Spjd	/*
849204076Spjd	 * If there is no token, but we have half-open connection
850204076Spjd	 * (only remotein) or full connection (worker process is running)
851204076Spjd	 * we have to cancel those and accept the new connection.
852204076Spjd	 */
853204076Spjd	if (token == NULL) {
854218138Spjd		PJDLOG_ASSERT(res->hr_remoteout == NULL);
855204076Spjd		pjdlog_debug(1, "Initial connection from %s.", raddr);
856204076Spjd		if (res->hr_workerpid != 0) {
857218138Spjd			PJDLOG_ASSERT(res->hr_remotein == NULL);
858204076Spjd			pjdlog_debug(1,
859204076Spjd			    "Worker process exists (pid=%u), stopping it.",
860204076Spjd			    (unsigned int)res->hr_workerpid);
861204076Spjd			/* Stop child process. */
862204076Spjd			if (kill(res->hr_workerpid, SIGINT) < 0) {
863204076Spjd				pjdlog_errno(LOG_ERR,
864204076Spjd				    "Unable to stop worker process (pid=%u)",
865204076Spjd				    (unsigned int)res->hr_workerpid);
866204076Spjd				/*
867204076Spjd				 * Other than logging the problem we
868204076Spjd				 * ignore it - nothing smart to do.
869204076Spjd				 */
870204076Spjd			}
871204076Spjd			/* Wait for it to exit. */
872204076Spjd			else if ((pid = waitpid(res->hr_workerpid,
873204076Spjd			    &status, 0)) != res->hr_workerpid) {
874207372Spjd				/* We can only log the problem. */
875204076Spjd				pjdlog_errno(LOG_ERR,
876204076Spjd				    "Waiting for worker process (pid=%u) failed",
877204076Spjd				    (unsigned int)res->hr_workerpid);
878204076Spjd			} else {
879207372Spjd				child_exit_log(res->hr_workerpid, status);
880204076Spjd			}
881213006Spjd			child_cleanup(res);
882204076Spjd		} else if (res->hr_remotein != NULL) {
883204076Spjd			char oaddr[256];
884204076Spjd
885213981Spjd			proto_remote_address(res->hr_remotein, oaddr,
886213981Spjd			    sizeof(oaddr));
887204076Spjd			pjdlog_debug(1,
888204076Spjd			    "Canceling half-open connection from %s on connection from %s.",
889204076Spjd			    oaddr, raddr);
890204076Spjd			proto_close(res->hr_remotein);
891204076Spjd			res->hr_remotein = NULL;
892204076Spjd		}
893204076Spjd	}
894204076Spjd
895204076Spjd	/*
896204076Spjd	 * Checks and cleanups are done.
897204076Spjd	 */
898204076Spjd
899204076Spjd	if (token == NULL) {
900204076Spjd		arc4random_buf(res->hr_token, sizeof(res->hr_token));
901204076Spjd		nvout = nv_alloc();
902204076Spjd		nv_add_uint8_array(nvout, res->hr_token,
903204076Spjd		    sizeof(res->hr_token), "token");
904204076Spjd		if (nv_error(nvout) != 0) {
905204076Spjd			pjdlog_common(LOG_ERR, 0, nv_error(nvout),
906204076Spjd			    "Unable to prepare return header for %s", raddr);
907204076Spjd			nv_add_stringf(nverr, "errmsg",
908204076Spjd			    "Remote node was unable to prepare return header: %s.",
909204076Spjd			    strerror(nv_error(nvout)));
910204076Spjd			goto fail;
911204076Spjd		}
912204076Spjd		if (hast_proto_send(NULL, conn, nvout, NULL, 0) < 0) {
913204076Spjd			int error = errno;
914204076Spjd
915204076Spjd			pjdlog_errno(LOG_ERR, "Unable to send response to %s",
916204076Spjd			    raddr);
917204076Spjd			nv_add_stringf(nverr, "errmsg",
918204076Spjd			    "Remote node was unable to send response: %s.",
919204076Spjd			    strerror(error));
920204076Spjd			goto fail;
921204076Spjd		}
922204076Spjd		res->hr_remotein = conn;
923204076Spjd		pjdlog_debug(1, "Incoming connection from %s configured.",
924204076Spjd		    raddr);
925204076Spjd	} else {
926204076Spjd		res->hr_remoteout = conn;
927204076Spjd		pjdlog_debug(1, "Outgoing connection to %s configured.", raddr);
928204076Spjd		hastd_secondary(res, nvin);
929204076Spjd	}
930204076Spjd	nv_free(nvin);
931204076Spjd	nv_free(nvout);
932204076Spjd	nv_free(nverr);
933204076Spjd	pjdlog_prefix_set("%s", "");
934204076Spjd	return;
935204076Spjdfail:
936204076Spjd	if (nv_error(nverr) != 0) {
937204076Spjd		pjdlog_common(LOG_ERR, 0, nv_error(nverr),
938204076Spjd		    "Unable to prepare error header for %s", raddr);
939204076Spjd		goto close;
940204076Spjd	}
941204076Spjd	if (hast_proto_send(NULL, conn, nverr, NULL, 0) < 0) {
942204076Spjd		pjdlog_errno(LOG_ERR, "Unable to send error to %s", raddr);
943204076Spjd		goto close;
944204076Spjd	}
945204076Spjdclose:
946204076Spjd	if (nvin != NULL)
947204076Spjd		nv_free(nvin);
948204076Spjd	if (nvout != NULL)
949204076Spjd		nv_free(nvout);
950204076Spjd	if (nverr != NULL)
951204076Spjd		nv_free(nverr);
952204076Spjd	proto_close(conn);
953204076Spjd	pjdlog_prefix_set("%s", "");
954204076Spjd}
955204076Spjd
956204076Spjdstatic void
957218218Spjdconnection_migrate(struct hast_resource *res)
958218218Spjd{
959218218Spjd	struct proto_conn *conn;
960218218Spjd	int16_t val = 0;
961218218Spjd
962219814Spjd	pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
963219814Spjd
964219900Spjd	PJDLOG_ASSERT(res->hr_role == HAST_ROLE_PRIMARY);
965219900Spjd
966218218Spjd	if (proto_recv(res->hr_conn, &val, sizeof(val)) < 0) {
967218218Spjd		pjdlog_errno(LOG_WARNING,
968218218Spjd		    "Unable to receive connection command");
969218218Spjd		return;
970218218Spjd	}
971219818Spjd	if (proto_client(res->hr_sourceaddr[0] != '\0' ? res->hr_sourceaddr : NULL,
972219818Spjd	    res->hr_remoteaddr, &conn) < 0) {
973218218Spjd		val = errno;
974218218Spjd		pjdlog_errno(LOG_WARNING,
975218218Spjd		    "Unable to create outgoing connection to %s",
976218218Spjd		    res->hr_remoteaddr);
977218218Spjd		goto out;
978218218Spjd	}
979218218Spjd	if (proto_connect(conn, -1) < 0) {
980218218Spjd		val = errno;
981218218Spjd		pjdlog_errno(LOG_WARNING, "Unable to connect to %s",
982218218Spjd		    res->hr_remoteaddr);
983218218Spjd		proto_close(conn);
984218218Spjd		goto out;
985218218Spjd	}
986218218Spjd	val = 0;
987218218Spjdout:
988218218Spjd	if (proto_send(res->hr_conn, &val, sizeof(val)) < 0) {
989218218Spjd		pjdlog_errno(LOG_WARNING,
990218218Spjd		    "Unable to send reply to connection request");
991218218Spjd	}
992218218Spjd	if (val == 0 && proto_connection_send(res->hr_conn, conn) < 0)
993218218Spjd		pjdlog_errno(LOG_WARNING, "Unable to send connection");
994219814Spjd
995219814Spjd	pjdlog_prefix_set("%s", "");
996218218Spjd}
997218218Spjd
998218218Spjdstatic void
999219837Spjdcheck_signals(void)
1000204076Spjd{
1001213009Spjd	struct timespec sigtimeout;
1002213009Spjd	sigset_t mask;
1003219837Spjd	int signo;
1004204076Spjd
1005213009Spjd	sigtimeout.tv_sec = 0;
1006213009Spjd	sigtimeout.tv_nsec = 0;
1007211977Spjd
1008213009Spjd	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
1009213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0);
1010213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
1011213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
1012213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGCHLD) == 0);
1013213009Spjd
1014219837Spjd	while ((signo = sigtimedwait(&mask, NULL, &sigtimeout)) != -1) {
1015219837Spjd		switch (signo) {
1016219837Spjd		case SIGINT:
1017219837Spjd		case SIGTERM:
1018219837Spjd			sigexit_received = true;
1019219837Spjd			terminate_workers();
1020219837Spjd			proto_close(cfg->hc_controlconn);
1021219837Spjd			exit(EX_OK);
1022219837Spjd			break;
1023219837Spjd		case SIGCHLD:
1024219837Spjd			child_exit();
1025219837Spjd			break;
1026219837Spjd		case SIGHUP:
1027219837Spjd			hastd_reload();
1028219837Spjd			break;
1029219837Spjd		default:
1030219837Spjd			PJDLOG_ABORT("Unexpected signal (%d).", signo);
1031219837Spjd		}
1032219837Spjd	}
1033219837Spjd}
1034219837Spjd
1035219837Spjdstatic void
1036219837Spjdmain_loop(void)
1037219837Spjd{
1038219837Spjd	struct hast_resource *res;
1039222108Spjd	struct hastd_listen *lst;
1040219837Spjd	struct timeval seltimeout;
1041219837Spjd	int fd, maxfd, ret;
1042219837Spjd	time_t lastcheck, now;
1043219837Spjd	fd_set rfds;
1044219837Spjd
1045219864Spjd	lastcheck = time(NULL);
1046219837Spjd	seltimeout.tv_sec = REPORT_INTERVAL;
1047219837Spjd	seltimeout.tv_usec = 0;
1048219837Spjd
1049204076Spjd	for (;;) {
1050219837Spjd		check_signals();
1051204076Spjd
1052209177Spjd		/* Setup descriptors for select(2). */
1053204076Spjd		FD_ZERO(&rfds);
1054212038Spjd		maxfd = fd = proto_descriptor(cfg->hc_controlconn);
1055218138Spjd		PJDLOG_ASSERT(fd >= 0);
1056212038Spjd		FD_SET(fd, &rfds);
1057222108Spjd		TAILQ_FOREACH(lst, &cfg->hc_listen, hl_next) {
1058222108Spjd			if (lst->hl_conn == NULL)
1059222108Spjd				continue;
1060222108Spjd			fd = proto_descriptor(lst->hl_conn);
1061222108Spjd			PJDLOG_ASSERT(fd >= 0);
1062222108Spjd			FD_SET(fd, &rfds);
1063222108Spjd			maxfd = fd > maxfd ? fd : maxfd;
1064222108Spjd		}
1065212038Spjd		TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
1066212038Spjd			if (res->hr_event == NULL)
1067212038Spjd				continue;
1068212038Spjd			fd = proto_descriptor(res->hr_event);
1069218138Spjd			PJDLOG_ASSERT(fd >= 0);
1070212038Spjd			FD_SET(fd, &rfds);
1071212038Spjd			maxfd = fd > maxfd ? fd : maxfd;
1072218218Spjd			if (res->hr_role == HAST_ROLE_PRIMARY) {
1073218218Spjd				/* Only primary workers asks for connections. */
1074219900Spjd				PJDLOG_ASSERT(res->hr_conn != NULL);
1075218218Spjd				fd = proto_descriptor(res->hr_conn);
1076218218Spjd				PJDLOG_ASSERT(fd >= 0);
1077218218Spjd				FD_SET(fd, &rfds);
1078218218Spjd				maxfd = fd > maxfd ? fd : maxfd;
1079219900Spjd			} else {
1080219900Spjd				PJDLOG_ASSERT(res->hr_conn == NULL);
1081218218Spjd			}
1082212038Spjd		}
1083204076Spjd
1084218138Spjd		PJDLOG_ASSERT(maxfd + 1 <= (int)FD_SETSIZE);
1085213009Spjd		ret = select(maxfd + 1, &rfds, NULL, NULL, &seltimeout);
1086219813Spjd		now = time(NULL);
1087219813Spjd		if (lastcheck + REPORT_INTERVAL <= now) {
1088213429Spjd			hook_check();
1089219813Spjd			lastcheck = now;
1090219813Spjd		}
1091219813Spjd		if (ret == 0) {
1092219813Spjd			/*
1093219813Spjd			 * select(2) timed out, so there should be no
1094219813Spjd			 * descriptors to check.
1095219813Spjd			 */
1096219813Spjd			continue;
1097219813Spjd		} else if (ret == -1) {
1098204076Spjd			if (errno == EINTR)
1099204076Spjd				continue;
1100204076Spjd			KEEP_ERRNO((void)pidfile_remove(pfh));
1101204076Spjd			pjdlog_exit(EX_OSERR, "select() failed");
1102204076Spjd		}
1103204076Spjd
1104219837Spjd		/*
1105219837Spjd		 * Check for signals before we do anything to update our
1106219837Spjd		 * info about terminated workers in the meantime.
1107219837Spjd		 */
1108219837Spjd		check_signals();
1109219837Spjd
1110212038Spjd		if (FD_ISSET(proto_descriptor(cfg->hc_controlconn), &rfds))
1111204076Spjd			control_handle(cfg);
1112222108Spjd		TAILQ_FOREACH(lst, &cfg->hc_listen, hl_next) {
1113222108Spjd			if (lst->hl_conn == NULL)
1114222108Spjd				continue;
1115222108Spjd			if (FD_ISSET(proto_descriptor(lst->hl_conn), &rfds))
1116222108Spjd				listen_accept(lst);
1117222108Spjd		}
1118212038Spjd		TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
1119212038Spjd			if (res->hr_event == NULL)
1120212038Spjd				continue;
1121212038Spjd			if (FD_ISSET(proto_descriptor(res->hr_event), &rfds)) {
1122212038Spjd				if (event_recv(res) == 0)
1123212038Spjd					continue;
1124212038Spjd				/* The worker process exited? */
1125212038Spjd				proto_close(res->hr_event);
1126212038Spjd				res->hr_event = NULL;
1127219900Spjd				if (res->hr_conn != NULL) {
1128219900Spjd					proto_close(res->hr_conn);
1129219900Spjd					res->hr_conn = NULL;
1130219900Spjd				}
1131218218Spjd				continue;
1132212038Spjd			}
1133219900Spjd			if (res->hr_role == HAST_ROLE_PRIMARY) {
1134219900Spjd				PJDLOG_ASSERT(res->hr_conn != NULL);
1135219900Spjd				if (FD_ISSET(proto_descriptor(res->hr_conn),
1136219900Spjd				    &rfds)) {
1137219900Spjd					connection_migrate(res);
1138219900Spjd				}
1139219900Spjd			} else {
1140219900Spjd				PJDLOG_ASSERT(res->hr_conn == NULL);
1141218218Spjd			}
1142212038Spjd		}
1143204076Spjd	}
1144204076Spjd}
1145204076Spjd
1146213428Spjdstatic void
1147213428Spjddummy_sighandler(int sig __unused)
1148213428Spjd{
1149213428Spjd	/* Nothing to do. */
1150213428Spjd}
1151213428Spjd
1152204076Spjdint
1153204076Spjdmain(int argc, char *argv[])
1154204076Spjd{
1155222108Spjd	struct hastd_listen *lst;
1156204076Spjd	const char *pidfile;
1157204076Spjd	pid_t otherpid;
1158204076Spjd	bool foreground;
1159204076Spjd	int debuglevel;
1160213009Spjd	sigset_t mask;
1161204076Spjd
1162204076Spjd	foreground = false;
1163204076Spjd	debuglevel = 0;
1164229509Strociny	pidfile = NULL;
1165204076Spjd
1166204076Spjd	for (;;) {
1167204076Spjd		int ch;
1168204076Spjd
1169204076Spjd		ch = getopt(argc, argv, "c:dFhP:");
1170204076Spjd		if (ch == -1)
1171204076Spjd			break;
1172204076Spjd		switch (ch) {
1173204076Spjd		case 'c':
1174204076Spjd			cfgpath = optarg;
1175204076Spjd			break;
1176204076Spjd		case 'd':
1177204076Spjd			debuglevel++;
1178204076Spjd			break;
1179204076Spjd		case 'F':
1180204076Spjd			foreground = true;
1181204076Spjd			break;
1182204076Spjd		case 'P':
1183204076Spjd			pidfile = optarg;
1184204076Spjd			break;
1185204076Spjd		case 'h':
1186204076Spjd		default:
1187204076Spjd			usage();
1188204076Spjd		}
1189204076Spjd	}
1190204076Spjd	argc -= optind;
1191204076Spjd	argv += optind;
1192204076Spjd
1193217965Spjd	pjdlog_init(PJDLOG_MODE_STD);
1194204076Spjd	pjdlog_debug_set(debuglevel);
1195204076Spjd
1196214273Spjd	g_gate_load();
1197214273Spjd
1198229509Strociny	/*
1199229509Strociny	 * When path to the configuration file is relative, obtain full path,
1200229509Strociny	 * so we can always find the file, even after daemonizing and changing
1201229509Strociny	 * working directory to /.
1202229509Strociny	 */
1203229509Strociny	if (cfgpath[0] != '/') {
1204229509Strociny		const char *newcfgpath;
1205229509Strociny
1206229509Strociny		newcfgpath = realpath(cfgpath, NULL);
1207229509Strociny		if (newcfgpath == NULL) {
1208229509Strociny			pjdlog_exit(EX_CONFIG,
1209229509Strociny			    "Unable to obtain full path of %s", cfgpath);
1210229509Strociny		}
1211229509Strociny		cfgpath = newcfgpath;
1212229509Strociny	}
1213229509Strociny
1214229509Strociny	cfg = yy_config_parse(cfgpath, true);
1215229509Strociny	PJDLOG_ASSERT(cfg != NULL);
1216229509Strociny
1217229509Strociny	if (pidfile != NULL) {
1218229509Strociny		if (strlcpy(cfg->hc_pidfile, pidfile,
1219229509Strociny		    sizeof(cfg->hc_pidfile)) >= sizeof(cfg->hc_pidfile)) {
1220229509Strociny			pjdlog_exitx(EX_CONFIG, "Pidfile path is too long.");
1221229509Strociny		}
1222229509Strociny	}
1223229509Strociny	pfh = pidfile_open(cfg->hc_pidfile, 0600, &otherpid);
1224204076Spjd	if (pfh == NULL) {
1225204076Spjd		if (errno == EEXIST) {
1226204076Spjd			pjdlog_exitx(EX_TEMPFAIL,
1227229509Strociny			    "Another hastd is already running, pidfile: %s, pid: %jd.",
1228229509Strociny			    cfg->hc_pidfile, (intmax_t)otherpid);
1229204076Spjd		}
1230229509Strociny		/* If we cannot create pidfile for other reasons, only warn. */
1231229509Strociny		pjdlog_errno(LOG_WARNING, "Unable to open or create pidfile %s",
1232229509Strociny		    cfg->hc_pidfile);
1233204076Spjd	}
1234204076Spjd
1235213428Spjd	/*
1236217307Spjd	 * Restore default actions for interesting signals in case parent
1237217307Spjd	 * process (like init(8)) decided to ignore some of them (like SIGHUP).
1238217307Spjd	 */
1239217307Spjd	PJDLOG_VERIFY(signal(SIGHUP, SIG_DFL) != SIG_ERR);
1240217307Spjd	PJDLOG_VERIFY(signal(SIGINT, SIG_DFL) != SIG_ERR);
1241217307Spjd	PJDLOG_VERIFY(signal(SIGTERM, SIG_DFL) != SIG_ERR);
1242217307Spjd	/*
1243213428Spjd	 * Because SIGCHLD is ignored by default, setup dummy handler for it,
1244213428Spjd	 * so we can mask it.
1245213428Spjd	 */
1246213428Spjd	PJDLOG_VERIFY(signal(SIGCHLD, dummy_sighandler) != SIG_ERR);
1247217307Spjd
1248213009Spjd	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
1249213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0);
1250213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
1251213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
1252213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGCHLD) == 0);
1253213009Spjd	PJDLOG_VERIFY(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
1254204076Spjd
1255204076Spjd	/* Listen on control address. */
1256204076Spjd	if (proto_server(cfg->hc_controladdr, &cfg->hc_controlconn) < 0) {
1257204076Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
1258204076Spjd		pjdlog_exit(EX_OSERR, "Unable to listen on control address %s",
1259204076Spjd		    cfg->hc_controladdr);
1260204076Spjd	}
1261204076Spjd	/* Listen for remote connections. */
1262222108Spjd	TAILQ_FOREACH(lst, &cfg->hc_listen, hl_next) {
1263222108Spjd		if (proto_server(lst->hl_addr, &lst->hl_conn) < 0) {
1264222108Spjd			KEEP_ERRNO((void)pidfile_remove(pfh));
1265222108Spjd			pjdlog_exit(EX_OSERR, "Unable to listen on address %s",
1266222108Spjd			    lst->hl_addr);
1267222108Spjd		}
1268204076Spjd	}
1269204076Spjd
1270204076Spjd	if (!foreground) {
1271204076Spjd		if (daemon(0, 0) < 0) {
1272204076Spjd			KEEP_ERRNO((void)pidfile_remove(pfh));
1273204076Spjd			pjdlog_exit(EX_OSERR, "Unable to daemonize");
1274204076Spjd		}
1275204076Spjd
1276204076Spjd		/* Start logging to syslog. */
1277204076Spjd		pjdlog_mode_set(PJDLOG_MODE_SYSLOG);
1278204076Spjd
1279204076Spjd		/* Write PID to a file. */
1280204076Spjd		if (pidfile_write(pfh) < 0) {
1281204076Spjd			pjdlog_errno(LOG_WARNING,
1282229509Strociny			    "Unable to write PID to a file %s",
1283229509Strociny			    cfg->hc_pidfile);
1284229509Strociny		} else {
1285229509Strociny			pjdlog_debug(1, "PID stored in %s.", cfg->hc_pidfile);
1286204076Spjd		}
1287204076Spjd	}
1288204076Spjd
1289222108Spjd	pjdlog_info("Started successfully, running protocol version %d.",
1290222108Spjd	    HAST_PROTO_VERSION);
1291222108Spjd
1292222108Spjd	pjdlog_debug(1, "Listening on control address %s.",
1293222108Spjd	    cfg->hc_controladdr);
1294222108Spjd	TAILQ_FOREACH(lst, &cfg->hc_listen, hl_next)
1295222108Spjd		pjdlog_info("Listening on address %s.", lst->hl_addr);
1296222108Spjd
1297211977Spjd	hook_init();
1298211977Spjd
1299204076Spjd	main_loop();
1300204076Spjd
1301204076Spjd	exit(0);
1302204076Spjd}
1303