hastd.c revision 219814
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: head/sbin/hastd/hastd.c 219814 2011-03-21 08:33:58Z pjd $");
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;
101218041Spjd
102218041Spjd	TAILQ_FOREACH(tres, &cfg->hc_resources, hr_next) {
103218041Spjd		if (tres == res) {
104218041Spjd			PJDLOG_VERIFY(res->hr_role == HAST_ROLE_SECONDARY ||
105218041Spjd			    (res->hr_remotein == NULL &&
106218041Spjd			     res->hr_remoteout == NULL));
107218041Spjd			continue;
108218041Spjd		}
109218041Spjd		if (tres->hr_remotein != NULL)
110218041Spjd			proto_close(tres->hr_remotein);
111218041Spjd		if (tres->hr_remoteout != NULL)
112218041Spjd			proto_close(tres->hr_remoteout);
113218370Spjd		if (tres->hr_ctrl != NULL)
114218370Spjd			proto_close(tres->hr_ctrl);
115218370Spjd		if (tres->hr_event != NULL)
116218370Spjd			proto_close(tres->hr_event);
117218370Spjd		if (tres->hr_conn != NULL)
118218370Spjd			proto_close(tres->hr_conn);
119218041Spjd	}
120218041Spjd	if (cfg->hc_controlin != NULL)
121218041Spjd		proto_close(cfg->hc_controlin);
122218041Spjd	proto_close(cfg->hc_controlconn);
123218041Spjd	proto_close(cfg->hc_listenconn);
124218041Spjd	(void)pidfile_close(pfh);
125218041Spjd	hook_fini();
126218041Spjd	pjdlog_fini();
127218041Spjd}
128218041Spjd
129218044Spjdstatic const char *
130218044Spjddtype2str(mode_t mode)
131218044Spjd{
132218044Spjd
133218044Spjd	if (S_ISBLK(mode))
134218044Spjd		return ("block device");
135218044Spjd	else if (S_ISCHR(mode))
136218044Spjd		return ("character device");
137218044Spjd	else if (S_ISDIR(mode))
138218044Spjd		return ("directory");
139218044Spjd	else if (S_ISFIFO(mode))
140218044Spjd		return ("pipe or FIFO");
141218044Spjd	else if (S_ISLNK(mode))
142218044Spjd		return ("symbolic link");
143218044Spjd	else if (S_ISREG(mode))
144218044Spjd		return ("regular file");
145218044Spjd	else if (S_ISSOCK(mode))
146218044Spjd		return ("socket");
147218044Spjd	else if (S_ISWHT(mode))
148218044Spjd		return ("whiteout");
149218044Spjd	else
150218044Spjd		return ("unknown");
151218044Spjd}
152218044Spjd
153218044Spjdvoid
154218044Spjddescriptors_assert(const struct hast_resource *res, int pjdlogmode)
155218044Spjd{
156218044Spjd	char msg[256];
157218044Spjd	struct stat sb;
158218044Spjd	long maxfd;
159218044Spjd	bool isopen;
160218044Spjd	mode_t mode;
161218044Spjd	int fd;
162218044Spjd
163218044Spjd	/*
164218044Spjd	 * At this point descriptor to syslog socket is closed, so if we want
165218044Spjd	 * to log assertion message, we have to first store it in 'msg' local
166218044Spjd	 * buffer and then open syslog socket and log it.
167218044Spjd	 */
168218044Spjd	msg[0] = '\0';
169218044Spjd
170218044Spjd	maxfd = sysconf(_SC_OPEN_MAX);
171218044Spjd	if (maxfd < 0) {
172218373Spjd		pjdlog_init(pjdlogmode);
173218373Spjd		pjdlog_prefix_set("[%s] (%s) ", res->hr_name,
174218373Spjd		    role2str(res->hr_role));
175218044Spjd		pjdlog_errno(LOG_WARNING, "sysconf(_SC_OPEN_MAX) failed");
176218373Spjd		pjdlog_fini();
177218044Spjd		maxfd = 16384;
178218044Spjd	}
179218044Spjd	for (fd = 0; fd <= maxfd; fd++) {
180218044Spjd		if (fstat(fd, &sb) == 0) {
181218044Spjd			isopen = true;
182218044Spjd			mode = sb.st_mode;
183218044Spjd		} else if (errno == EBADF) {
184218044Spjd			isopen = false;
185218044Spjd			mode = 0;
186218044Spjd		} else {
187218375Spjd			(void)snprintf(msg, sizeof(msg),
188218044Spjd			    "Unable to fstat descriptor %d: %s", fd,
189218044Spjd			    strerror(errno));
190218374Spjd			break;
191218044Spjd		}
192218044Spjd		if (fd == STDIN_FILENO || fd == STDOUT_FILENO ||
193218044Spjd		    fd == STDERR_FILENO) {
194218044Spjd			if (!isopen) {
195218375Spjd				(void)snprintf(msg, sizeof(msg),
196218044Spjd				    "Descriptor %d (%s) is closed, but should be open.",
197218044Spjd				    fd, (fd == STDIN_FILENO ? "stdin" :
198218044Spjd				    (fd == STDOUT_FILENO ? "stdout" : "stderr")));
199218044Spjd				break;
200218044Spjd			}
201218044Spjd		} else if (fd == proto_descriptor(res->hr_event)) {
202218044Spjd			if (!isopen) {
203218375Spjd				(void)snprintf(msg, sizeof(msg),
204218044Spjd				    "Descriptor %d (event) is closed, but should be open.",
205218044Spjd				    fd);
206218044Spjd				break;
207218044Spjd			}
208218044Spjd			if (!S_ISSOCK(mode)) {
209218375Spjd				(void)snprintf(msg, sizeof(msg),
210218044Spjd				    "Descriptor %d (event) is %s, but should be %s.",
211218044Spjd				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
212218044Spjd				break;
213218044Spjd			}
214218044Spjd		} else if (fd == proto_descriptor(res->hr_ctrl)) {
215218044Spjd			if (!isopen) {
216218375Spjd				(void)snprintf(msg, sizeof(msg),
217218044Spjd				    "Descriptor %d (ctrl) is closed, but should be open.",
218218044Spjd				    fd);
219218044Spjd				break;
220218044Spjd			}
221218044Spjd			if (!S_ISSOCK(mode)) {
222218375Spjd				(void)snprintf(msg, sizeof(msg),
223218044Spjd				    "Descriptor %d (ctrl) is %s, but should be %s.",
224218044Spjd				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
225218044Spjd				break;
226218044Spjd			}
227218218Spjd		} else if (fd == proto_descriptor(res->hr_conn)) {
228218218Spjd			if (!isopen) {
229218375Spjd				(void)snprintf(msg, sizeof(msg),
230218218Spjd				    "Descriptor %d (conn) is closed, but should be open.",
231218218Spjd				    fd);
232218218Spjd				break;
233218218Spjd			}
234218218Spjd			if (!S_ISSOCK(mode)) {
235218375Spjd				(void)snprintf(msg, sizeof(msg),
236218218Spjd				    "Descriptor %d (conn) is %s, but should be %s.",
237218218Spjd				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
238218218Spjd				break;
239218218Spjd			}
240218044Spjd		} else if (res->hr_role == HAST_ROLE_SECONDARY &&
241218044Spjd		    fd == proto_descriptor(res->hr_remotein)) {
242218044Spjd			if (!isopen) {
243218375Spjd				(void)snprintf(msg, sizeof(msg),
244218044Spjd				    "Descriptor %d (remote in) is closed, but should be open.",
245218044Spjd				    fd);
246218044Spjd				break;
247218044Spjd			}
248218044Spjd			if (!S_ISSOCK(mode)) {
249218375Spjd				(void)snprintf(msg, sizeof(msg),
250218044Spjd				    "Descriptor %d (remote in) is %s, but should be %s.",
251218044Spjd				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
252218044Spjd				break;
253218044Spjd			}
254218044Spjd		} else if (res->hr_role == HAST_ROLE_SECONDARY &&
255218044Spjd		    fd == proto_descriptor(res->hr_remoteout)) {
256218044Spjd			if (!isopen) {
257218375Spjd				(void)snprintf(msg, sizeof(msg),
258218044Spjd				    "Descriptor %d (remote out) 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 out) is %s, but should be %s.",
265218044Spjd				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
266218044Spjd				break;
267218044Spjd			}
268218044Spjd		} else {
269218044Spjd			if (isopen) {
270218375Spjd				(void)snprintf(msg, sizeof(msg),
271218044Spjd				    "Descriptor %d is open (%s), but should be closed.",
272218044Spjd				    fd, dtype2str(mode));
273218044Spjd				break;
274218044Spjd			}
275218044Spjd		}
276218044Spjd	}
277218044Spjd	if (msg[0] != '\0') {
278218044Spjd		pjdlog_init(pjdlogmode);
279218044Spjd		pjdlog_prefix_set("[%s] (%s) ", res->hr_name,
280218044Spjd		    role2str(res->hr_role));
281218044Spjd		PJDLOG_ABORT("%s", msg);
282218044Spjd	}
283218044Spjd}
284218044Spjd
285204076Spjdstatic void
286207372Spjdchild_exit_log(unsigned int pid, int status)
287207372Spjd{
288207372Spjd
289207372Spjd	if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
290207372Spjd		pjdlog_debug(1, "Worker process exited gracefully (pid=%u).",
291207372Spjd		    pid);
292207372Spjd	} else if (WIFSIGNALED(status)) {
293207372Spjd		pjdlog_error("Worker process killed (pid=%u, signal=%d).",
294207372Spjd		    pid, WTERMSIG(status));
295207372Spjd	} else {
296207372Spjd		pjdlog_error("Worker process exited ungracefully (pid=%u, exitcode=%d).",
297207372Spjd		    pid, WIFEXITED(status) ? WEXITSTATUS(status) : -1);
298207372Spjd	}
299207372Spjd}
300207372Spjd
301207372Spjdstatic void
302204076Spjdchild_exit(void)
303204076Spjd{
304204076Spjd	struct hast_resource *res;
305204076Spjd	int status;
306204076Spjd	pid_t pid;
307204076Spjd
308204076Spjd	while ((pid = wait3(&status, WNOHANG, NULL)) > 0) {
309204076Spjd		/* Find resource related to the process that just exited. */
310204076Spjd		TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
311204076Spjd			if (pid == res->hr_workerpid)
312204076Spjd				break;
313204076Spjd		}
314204076Spjd		if (res == NULL) {
315204076Spjd			/*
316204076Spjd			 * This can happen when new connection arrives and we
317211977Spjd			 * cancel child responsible for the old one or if this
318211977Spjd			 * was hook which we executed.
319204076Spjd			 */
320211977Spjd			hook_check_one(pid, status);
321204076Spjd			continue;
322204076Spjd		}
323204076Spjd		pjdlog_prefix_set("[%s] (%s) ", res->hr_name,
324204076Spjd		    role2str(res->hr_role));
325207372Spjd		child_exit_log(pid, status);
326213006Spjd		child_cleanup(res);
327204076Spjd		if (res->hr_role == HAST_ROLE_PRIMARY) {
328207372Spjd			/*
329207372Spjd			 * Restart child process if it was killed by signal
330207372Spjd			 * or exited because of temporary problem.
331207372Spjd			 */
332207372Spjd			if (WIFSIGNALED(status) ||
333207372Spjd			    (WIFEXITED(status) &&
334207372Spjd			     WEXITSTATUS(status) == EX_TEMPFAIL)) {
335207348Spjd				sleep(1);
336207348Spjd				pjdlog_info("Restarting worker process.");
337207348Spjd				hastd_primary(res);
338207348Spjd			} else {
339207348Spjd				res->hr_role = HAST_ROLE_INIT;
340207348Spjd				pjdlog_info("Changing resource role back to %s.",
341207348Spjd				    role2str(res->hr_role));
342207348Spjd			}
343204076Spjd		}
344204076Spjd		pjdlog_prefix_set("%s", "");
345204076Spjd	}
346204076Spjd}
347204076Spjd
348210886Spjdstatic bool
349210886Spjdresource_needs_restart(const struct hast_resource *res0,
350210886Spjd    const struct hast_resource *res1)
351210886Spjd{
352210886Spjd
353218138Spjd	PJDLOG_ASSERT(strcmp(res0->hr_name, res1->hr_name) == 0);
354210886Spjd
355210886Spjd	if (strcmp(res0->hr_provname, res1->hr_provname) != 0)
356210886Spjd		return (true);
357210886Spjd	if (strcmp(res0->hr_localpath, res1->hr_localpath) != 0)
358210886Spjd		return (true);
359210886Spjd	if (res0->hr_role == HAST_ROLE_INIT ||
360210886Spjd	    res0->hr_role == HAST_ROLE_SECONDARY) {
361210886Spjd		if (strcmp(res0->hr_remoteaddr, res1->hr_remoteaddr) != 0)
362210886Spjd			return (true);
363210886Spjd		if (res0->hr_replication != res1->hr_replication)
364210886Spjd			return (true);
365219351Spjd		if (res0->hr_checksum != res1->hr_checksum)
366219351Spjd			return (true);
367219354Spjd		if (res0->hr_compression != res1->hr_compression)
368219354Spjd			return (true);
369210886Spjd		if (res0->hr_timeout != res1->hr_timeout)
370210886Spjd			return (true);
371211886Spjd		if (strcmp(res0->hr_exec, res1->hr_exec) != 0)
372211886Spjd			return (true);
373210886Spjd	}
374210886Spjd	return (false);
375210886Spjd}
376210886Spjd
377210886Spjdstatic bool
378210886Spjdresource_needs_reload(const struct hast_resource *res0,
379210886Spjd    const struct hast_resource *res1)
380210886Spjd{
381210886Spjd
382218138Spjd	PJDLOG_ASSERT(strcmp(res0->hr_name, res1->hr_name) == 0);
383218138Spjd	PJDLOG_ASSERT(strcmp(res0->hr_provname, res1->hr_provname) == 0);
384218138Spjd	PJDLOG_ASSERT(strcmp(res0->hr_localpath, res1->hr_localpath) == 0);
385210886Spjd
386210886Spjd	if (res0->hr_role != HAST_ROLE_PRIMARY)
387210886Spjd		return (false);
388210886Spjd
389210886Spjd	if (strcmp(res0->hr_remoteaddr, res1->hr_remoteaddr) != 0)
390210886Spjd		return (true);
391210886Spjd	if (res0->hr_replication != res1->hr_replication)
392210886Spjd		return (true);
393219351Spjd	if (res0->hr_checksum != res1->hr_checksum)
394219351Spjd		return (true);
395219354Spjd	if (res0->hr_compression != res1->hr_compression)
396219354Spjd		return (true);
397210886Spjd	if (res0->hr_timeout != res1->hr_timeout)
398210886Spjd		return (true);
399211886Spjd	if (strcmp(res0->hr_exec, res1->hr_exec) != 0)
400211886Spjd		return (true);
401210886Spjd	return (false);
402210886Spjd}
403210886Spjd
404204076Spjdstatic void
405217784Spjdresource_reload(const struct hast_resource *res)
406217784Spjd{
407217784Spjd	struct nv *nvin, *nvout;
408217784Spjd	int error;
409217784Spjd
410218138Spjd	PJDLOG_ASSERT(res->hr_role == HAST_ROLE_PRIMARY);
411217784Spjd
412217784Spjd	nvout = nv_alloc();
413217784Spjd	nv_add_uint8(nvout, HASTCTL_RELOAD, "cmd");
414217784Spjd	nv_add_string(nvout, res->hr_remoteaddr, "remoteaddr");
415217784Spjd	nv_add_int32(nvout, (int32_t)res->hr_replication, "replication");
416219351Spjd	nv_add_int32(nvout, (int32_t)res->hr_checksum, "checksum");
417219354Spjd	nv_add_int32(nvout, (int32_t)res->hr_compression, "compression");
418217784Spjd	nv_add_int32(nvout, (int32_t)res->hr_timeout, "timeout");
419217784Spjd	nv_add_string(nvout, res->hr_exec, "exec");
420217784Spjd	if (nv_error(nvout) != 0) {
421217784Spjd		nv_free(nvout);
422217784Spjd		pjdlog_error("Unable to allocate header for reload message.");
423217784Spjd		return;
424217784Spjd	}
425217784Spjd	if (hast_proto_send(res, res->hr_ctrl, nvout, NULL, 0) < 0) {
426217784Spjd		pjdlog_errno(LOG_ERR, "Unable to send reload message");
427217784Spjd		nv_free(nvout);
428217784Spjd		return;
429217784Spjd	}
430217784Spjd	nv_free(nvout);
431217784Spjd
432217784Spjd	/* Receive response. */
433217784Spjd	if (hast_proto_recv_hdr(res->hr_ctrl, &nvin) < 0) {
434217784Spjd		pjdlog_errno(LOG_ERR, "Unable to receive reload reply");
435217784Spjd		return;
436217784Spjd	}
437217784Spjd	error = nv_get_int16(nvin, "error");
438217784Spjd	nv_free(nvin);
439217784Spjd	if (error != 0) {
440217784Spjd		pjdlog_common(LOG_ERR, 0, error, "Reload failed");
441217784Spjd		return;
442217784Spjd	}
443217784Spjd}
444217784Spjd
445217784Spjdstatic void
446204076Spjdhastd_reload(void)
447204076Spjd{
448210886Spjd	struct hastd_config *newcfg;
449210886Spjd	struct hast_resource *nres, *cres, *tres;
450210886Spjd	uint8_t role;
451204076Spjd
452210886Spjd	pjdlog_info("Reloading configuration...");
453210886Spjd
454210886Spjd	newcfg = yy_config_parse(cfgpath, false);
455210886Spjd	if (newcfg == NULL)
456210886Spjd		goto failed;
457210886Spjd
458210886Spjd	/*
459210886Spjd	 * Check if control address has changed.
460210886Spjd	 */
461210886Spjd	if (strcmp(cfg->hc_controladdr, newcfg->hc_controladdr) != 0) {
462210886Spjd		if (proto_server(newcfg->hc_controladdr,
463210886Spjd		    &newcfg->hc_controlconn) < 0) {
464210886Spjd			pjdlog_errno(LOG_ERR,
465210886Spjd			    "Unable to listen on control address %s",
466210886Spjd			    newcfg->hc_controladdr);
467210886Spjd			goto failed;
468210886Spjd		}
469210886Spjd	}
470210886Spjd	/*
471210886Spjd	 * Check if listen address has changed.
472210886Spjd	 */
473210886Spjd	if (strcmp(cfg->hc_listenaddr, newcfg->hc_listenaddr) != 0) {
474210886Spjd		if (proto_server(newcfg->hc_listenaddr,
475210886Spjd		    &newcfg->hc_listenconn) < 0) {
476210886Spjd			pjdlog_errno(LOG_ERR, "Unable to listen on address %s",
477210886Spjd			    newcfg->hc_listenaddr);
478210886Spjd			goto failed;
479210886Spjd		}
480210886Spjd	}
481210886Spjd	/*
482210886Spjd	 * Only when both control and listen sockets are successfully
483210886Spjd	 * initialized switch them to new configuration.
484210886Spjd	 */
485210886Spjd	if (newcfg->hc_controlconn != NULL) {
486210886Spjd		pjdlog_info("Control socket changed from %s to %s.",
487210886Spjd		    cfg->hc_controladdr, newcfg->hc_controladdr);
488210886Spjd		proto_close(cfg->hc_controlconn);
489210886Spjd		cfg->hc_controlconn = newcfg->hc_controlconn;
490210886Spjd		newcfg->hc_controlconn = NULL;
491210886Spjd		strlcpy(cfg->hc_controladdr, newcfg->hc_controladdr,
492210886Spjd		    sizeof(cfg->hc_controladdr));
493210886Spjd	}
494210886Spjd	if (newcfg->hc_listenconn != NULL) {
495210886Spjd		pjdlog_info("Listen socket changed from %s to %s.",
496210886Spjd		    cfg->hc_listenaddr, newcfg->hc_listenaddr);
497210886Spjd		proto_close(cfg->hc_listenconn);
498210886Spjd		cfg->hc_listenconn = newcfg->hc_listenconn;
499210886Spjd		newcfg->hc_listenconn = NULL;
500210886Spjd		strlcpy(cfg->hc_listenaddr, newcfg->hc_listenaddr,
501210886Spjd		    sizeof(cfg->hc_listenaddr));
502210886Spjd	}
503210886Spjd
504210886Spjd	/*
505210886Spjd	 * Stop and remove resources that were removed from the configuration.
506210886Spjd	 */
507210886Spjd	TAILQ_FOREACH_SAFE(cres, &cfg->hc_resources, hr_next, tres) {
508210886Spjd		TAILQ_FOREACH(nres, &newcfg->hc_resources, hr_next) {
509210886Spjd			if (strcmp(cres->hr_name, nres->hr_name) == 0)
510210886Spjd				break;
511210886Spjd		}
512210886Spjd		if (nres == NULL) {
513210886Spjd			control_set_role(cres, HAST_ROLE_INIT);
514210886Spjd			TAILQ_REMOVE(&cfg->hc_resources, cres, hr_next);
515210886Spjd			pjdlog_info("Resource %s removed.", cres->hr_name);
516210886Spjd			free(cres);
517210886Spjd		}
518210886Spjd	}
519210886Spjd	/*
520210886Spjd	 * Move new resources to the current configuration.
521210886Spjd	 */
522210886Spjd	TAILQ_FOREACH_SAFE(nres, &newcfg->hc_resources, hr_next, tres) {
523210886Spjd		TAILQ_FOREACH(cres, &cfg->hc_resources, hr_next) {
524210886Spjd			if (strcmp(cres->hr_name, nres->hr_name) == 0)
525210886Spjd				break;
526210886Spjd		}
527210886Spjd		if (cres == NULL) {
528210886Spjd			TAILQ_REMOVE(&newcfg->hc_resources, nres, hr_next);
529210886Spjd			TAILQ_INSERT_TAIL(&cfg->hc_resources, nres, hr_next);
530210886Spjd			pjdlog_info("Resource %s added.", nres->hr_name);
531210886Spjd		}
532210886Spjd	}
533210886Spjd	/*
534210886Spjd	 * Deal with modified resources.
535210886Spjd	 * Depending on what has changed exactly we might want to perform
536210886Spjd	 * different actions.
537210886Spjd	 *
538210886Spjd	 * We do full resource restart in the following situations:
539210886Spjd	 * Resource role is INIT or SECONDARY.
540210886Spjd	 * Resource role is PRIMARY and path to local component or provider
541210886Spjd	 * name has changed.
542210886Spjd	 * In case of PRIMARY, the worker process will be killed and restarted,
543210886Spjd	 * which also means removing /dev/hast/<name> provider and
544210886Spjd	 * recreating it.
545210886Spjd	 *
546210886Spjd	 * We do just reload (send SIGHUP to worker process) if we act as
547217729Spjd	 * PRIMARY, but only if remote address, replication mode, timeout or
548217729Spjd	 * execution path has changed. For those, there is no need to restart
549217729Spjd	 * worker process.
550210886Spjd	 * If PRIMARY receives SIGHUP, it will reconnect if remote address or
551210886Spjd	 * replication mode has changed or simply set new timeout if only
552210886Spjd	 * timeout has changed.
553210886Spjd	 */
554210886Spjd	TAILQ_FOREACH_SAFE(nres, &newcfg->hc_resources, hr_next, tres) {
555210886Spjd		TAILQ_FOREACH(cres, &cfg->hc_resources, hr_next) {
556210886Spjd			if (strcmp(cres->hr_name, nres->hr_name) == 0)
557210886Spjd				break;
558210886Spjd		}
559218138Spjd		PJDLOG_ASSERT(cres != NULL);
560210886Spjd		if (resource_needs_restart(cres, nres)) {
561210886Spjd			pjdlog_info("Resource %s configuration was modified, restarting it.",
562210886Spjd			    cres->hr_name);
563210886Spjd			role = cres->hr_role;
564210886Spjd			control_set_role(cres, HAST_ROLE_INIT);
565210886Spjd			TAILQ_REMOVE(&cfg->hc_resources, cres, hr_next);
566210886Spjd			free(cres);
567210886Spjd			TAILQ_REMOVE(&newcfg->hc_resources, nres, hr_next);
568210886Spjd			TAILQ_INSERT_TAIL(&cfg->hc_resources, nres, hr_next);
569210886Spjd			control_set_role(nres, role);
570210886Spjd		} else if (resource_needs_reload(cres, nres)) {
571210886Spjd			pjdlog_info("Resource %s configuration was modified, reloading it.",
572210886Spjd			    cres->hr_name);
573210886Spjd			strlcpy(cres->hr_remoteaddr, nres->hr_remoteaddr,
574210886Spjd			    sizeof(cres->hr_remoteaddr));
575210886Spjd			cres->hr_replication = nres->hr_replication;
576219351Spjd			cres->hr_checksum = nres->hr_checksum;
577219354Spjd			cres->hr_compression = nres->hr_compression;
578210886Spjd			cres->hr_timeout = nres->hr_timeout;
579217729Spjd			strlcpy(cres->hr_exec, nres->hr_exec,
580217729Spjd			    sizeof(cres->hr_exec));
581217784Spjd			if (cres->hr_workerpid != 0)
582217784Spjd				resource_reload(cres);
583210886Spjd		}
584210886Spjd	}
585210886Spjd
586210886Spjd	yy_config_free(newcfg);
587210886Spjd	pjdlog_info("Configuration reloaded successfully.");
588210886Spjd	return;
589210886Spjdfailed:
590210886Spjd	if (newcfg != NULL) {
591210886Spjd		if (newcfg->hc_controlconn != NULL)
592210886Spjd			proto_close(newcfg->hc_controlconn);
593210886Spjd		if (newcfg->hc_listenconn != NULL)
594210886Spjd			proto_close(newcfg->hc_listenconn);
595210886Spjd		yy_config_free(newcfg);
596210886Spjd	}
597210886Spjd	pjdlog_warning("Configuration not reloaded.");
598204076Spjd}
599204076Spjd
600204076Spjdstatic void
601211899Spjdterminate_workers(void)
602211899Spjd{
603211899Spjd	struct hast_resource *res;
604211899Spjd
605211899Spjd	pjdlog_info("Termination signal received, exiting.");
606211899Spjd	TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
607211899Spjd		if (res->hr_workerpid == 0)
608211899Spjd			continue;
609211899Spjd		pjdlog_info("Terminating worker process (resource=%s, role=%s, pid=%u).",
610211899Spjd		    res->hr_name, role2str(res->hr_role), res->hr_workerpid);
611211899Spjd		if (kill(res->hr_workerpid, SIGTERM) == 0)
612211899Spjd			continue;
613211899Spjd		pjdlog_errno(LOG_WARNING,
614211899Spjd		    "Unable to send signal to worker process (resource=%s, role=%s, pid=%u).",
615211899Spjd		    res->hr_name, role2str(res->hr_role), res->hr_workerpid);
616211899Spjd	}
617211899Spjd}
618211899Spjd
619211899Spjdstatic void
620204076Spjdlisten_accept(void)
621204076Spjd{
622204076Spjd	struct hast_resource *res;
623204076Spjd	struct proto_conn *conn;
624204076Spjd	struct nv *nvin, *nvout, *nverr;
625204076Spjd	const char *resname;
626204076Spjd	const unsigned char *token;
627204076Spjd	char laddr[256], raddr[256];
628204076Spjd	size_t size;
629204076Spjd	pid_t pid;
630204076Spjd	int status;
631204076Spjd
632204076Spjd	proto_local_address(cfg->hc_listenconn, laddr, sizeof(laddr));
633204076Spjd	pjdlog_debug(1, "Accepting connection to %s.", laddr);
634204076Spjd
635204076Spjd	if (proto_accept(cfg->hc_listenconn, &conn) < 0) {
636204076Spjd		pjdlog_errno(LOG_ERR, "Unable to accept connection %s", laddr);
637204076Spjd		return;
638204076Spjd	}
639204076Spjd
640204076Spjd	proto_local_address(conn, laddr, sizeof(laddr));
641204076Spjd	proto_remote_address(conn, raddr, sizeof(raddr));
642209185Spjd	pjdlog_info("Connection from %s to %s.", raddr, laddr);
643204076Spjd
644207371Spjd	/* Error in setting timeout is not critical, but why should it fail? */
645207371Spjd	if (proto_timeout(conn, HAST_TIMEOUT) < 0)
646207371Spjd		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
647207371Spjd
648204076Spjd	nvin = nvout = nverr = NULL;
649204076Spjd
650204076Spjd	/*
651204076Spjd	 * Before receiving any data see if remote host have access to any
652204076Spjd	 * resource.
653204076Spjd	 */
654204076Spjd	TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
655204076Spjd		if (proto_address_match(conn, res->hr_remoteaddr))
656204076Spjd			break;
657204076Spjd	}
658204076Spjd	if (res == NULL) {
659204076Spjd		pjdlog_error("Client %s isn't known.", raddr);
660204076Spjd		goto close;
661204076Spjd	}
662204076Spjd	/* Ok, remote host can access at least one resource. */
663204076Spjd
664204076Spjd	if (hast_proto_recv_hdr(conn, &nvin) < 0) {
665204076Spjd		pjdlog_errno(LOG_ERR, "Unable to receive header from %s",
666204076Spjd		    raddr);
667204076Spjd		goto close;
668204076Spjd	}
669204076Spjd
670204076Spjd	resname = nv_get_string(nvin, "resource");
671204076Spjd	if (resname == NULL) {
672204076Spjd		pjdlog_error("No 'resource' field in the header received from %s.",
673204076Spjd		    raddr);
674204076Spjd		goto close;
675204076Spjd	}
676204076Spjd	pjdlog_debug(2, "%s: resource=%s", raddr, resname);
677204076Spjd	token = nv_get_uint8_array(nvin, &size, "token");
678204076Spjd	/*
679204076Spjd	 * NULL token means that this is first conection.
680204076Spjd	 */
681204076Spjd	if (token != NULL && size != sizeof(res->hr_token)) {
682204076Spjd		pjdlog_error("Received token of invalid size from %s (expected %zu, got %zu).",
683204076Spjd		    raddr, sizeof(res->hr_token), size);
684204076Spjd		goto close;
685204076Spjd	}
686204076Spjd
687204076Spjd	/*
688204076Spjd	 * From now on we want to send errors to the remote node.
689204076Spjd	 */
690204076Spjd	nverr = nv_alloc();
691204076Spjd
692204076Spjd	/* Find resource related to this connection. */
693204076Spjd	TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
694204076Spjd		if (strcmp(resname, res->hr_name) == 0)
695204076Spjd			break;
696204076Spjd	}
697204076Spjd	/* Have we found the resource? */
698204076Spjd	if (res == NULL) {
699204076Spjd		pjdlog_error("No resource '%s' as requested by %s.",
700204076Spjd		    resname, raddr);
701204076Spjd		nv_add_stringf(nverr, "errmsg", "Resource not configured.");
702204076Spjd		goto fail;
703204076Spjd	}
704204076Spjd
705204076Spjd	/* Now that we know resource name setup log prefix. */
706204076Spjd	pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
707204076Spjd
708204076Spjd	/* Does the remote host have access to this resource? */
709204076Spjd	if (!proto_address_match(conn, res->hr_remoteaddr)) {
710204076Spjd		pjdlog_error("Client %s has no access to the resource.", raddr);
711204076Spjd		nv_add_stringf(nverr, "errmsg", "No access to the resource.");
712204076Spjd		goto fail;
713204076Spjd	}
714204076Spjd	/* Is the resource marked as secondary? */
715204076Spjd	if (res->hr_role != HAST_ROLE_SECONDARY) {
716204076Spjd		pjdlog_error("We act as %s for the resource and not as %s as requested by %s.",
717204076Spjd		    role2str(res->hr_role), role2str(HAST_ROLE_SECONDARY),
718204076Spjd		    raddr);
719204076Spjd		nv_add_stringf(nverr, "errmsg",
720204076Spjd		    "Remote node acts as %s for the resource and not as %s.",
721204076Spjd		    role2str(res->hr_role), role2str(HAST_ROLE_SECONDARY));
722204076Spjd		goto fail;
723204076Spjd	}
724204076Spjd	/* Does token (if exists) match? */
725204076Spjd	if (token != NULL && memcmp(token, res->hr_token,
726204076Spjd	    sizeof(res->hr_token)) != 0) {
727204076Spjd		pjdlog_error("Token received from %s doesn't match.", raddr);
728209185Spjd		nv_add_stringf(nverr, "errmsg", "Token doesn't match.");
729204076Spjd		goto fail;
730204076Spjd	}
731204076Spjd	/*
732204076Spjd	 * If there is no token, but we have half-open connection
733204076Spjd	 * (only remotein) or full connection (worker process is running)
734204076Spjd	 * we have to cancel those and accept the new connection.
735204076Spjd	 */
736204076Spjd	if (token == NULL) {
737218138Spjd		PJDLOG_ASSERT(res->hr_remoteout == NULL);
738204076Spjd		pjdlog_debug(1, "Initial connection from %s.", raddr);
739204076Spjd		if (res->hr_workerpid != 0) {
740218138Spjd			PJDLOG_ASSERT(res->hr_remotein == NULL);
741204076Spjd			pjdlog_debug(1,
742204076Spjd			    "Worker process exists (pid=%u), stopping it.",
743204076Spjd			    (unsigned int)res->hr_workerpid);
744204076Spjd			/* Stop child process. */
745204076Spjd			if (kill(res->hr_workerpid, SIGINT) < 0) {
746204076Spjd				pjdlog_errno(LOG_ERR,
747204076Spjd				    "Unable to stop worker process (pid=%u)",
748204076Spjd				    (unsigned int)res->hr_workerpid);
749204076Spjd				/*
750204076Spjd				 * Other than logging the problem we
751204076Spjd				 * ignore it - nothing smart to do.
752204076Spjd				 */
753204076Spjd			}
754204076Spjd			/* Wait for it to exit. */
755204076Spjd			else if ((pid = waitpid(res->hr_workerpid,
756204076Spjd			    &status, 0)) != res->hr_workerpid) {
757207372Spjd				/* We can only log the problem. */
758204076Spjd				pjdlog_errno(LOG_ERR,
759204076Spjd				    "Waiting for worker process (pid=%u) failed",
760204076Spjd				    (unsigned int)res->hr_workerpid);
761204076Spjd			} else {
762207372Spjd				child_exit_log(res->hr_workerpid, status);
763204076Spjd			}
764213006Spjd			child_cleanup(res);
765204076Spjd		} else if (res->hr_remotein != NULL) {
766204076Spjd			char oaddr[256];
767204076Spjd
768213981Spjd			proto_remote_address(res->hr_remotein, oaddr,
769213981Spjd			    sizeof(oaddr));
770204076Spjd			pjdlog_debug(1,
771204076Spjd			    "Canceling half-open connection from %s on connection from %s.",
772204076Spjd			    oaddr, raddr);
773204076Spjd			proto_close(res->hr_remotein);
774204076Spjd			res->hr_remotein = NULL;
775204076Spjd		}
776204076Spjd	}
777204076Spjd
778204076Spjd	/*
779204076Spjd	 * Checks and cleanups are done.
780204076Spjd	 */
781204076Spjd
782204076Spjd	if (token == NULL) {
783204076Spjd		arc4random_buf(res->hr_token, sizeof(res->hr_token));
784204076Spjd		nvout = nv_alloc();
785204076Spjd		nv_add_uint8_array(nvout, res->hr_token,
786204076Spjd		    sizeof(res->hr_token), "token");
787204076Spjd		if (nv_error(nvout) != 0) {
788204076Spjd			pjdlog_common(LOG_ERR, 0, nv_error(nvout),
789204076Spjd			    "Unable to prepare return header for %s", raddr);
790204076Spjd			nv_add_stringf(nverr, "errmsg",
791204076Spjd			    "Remote node was unable to prepare return header: %s.",
792204076Spjd			    strerror(nv_error(nvout)));
793204076Spjd			goto fail;
794204076Spjd		}
795204076Spjd		if (hast_proto_send(NULL, conn, nvout, NULL, 0) < 0) {
796204076Spjd			int error = errno;
797204076Spjd
798204076Spjd			pjdlog_errno(LOG_ERR, "Unable to send response to %s",
799204076Spjd			    raddr);
800204076Spjd			nv_add_stringf(nverr, "errmsg",
801204076Spjd			    "Remote node was unable to send response: %s.",
802204076Spjd			    strerror(error));
803204076Spjd			goto fail;
804204076Spjd		}
805204076Spjd		res->hr_remotein = conn;
806204076Spjd		pjdlog_debug(1, "Incoming connection from %s configured.",
807204076Spjd		    raddr);
808204076Spjd	} else {
809204076Spjd		res->hr_remoteout = conn;
810204076Spjd		pjdlog_debug(1, "Outgoing connection to %s configured.", raddr);
811204076Spjd		hastd_secondary(res, nvin);
812204076Spjd	}
813204076Spjd	nv_free(nvin);
814204076Spjd	nv_free(nvout);
815204076Spjd	nv_free(nverr);
816204076Spjd	pjdlog_prefix_set("%s", "");
817204076Spjd	return;
818204076Spjdfail:
819204076Spjd	if (nv_error(nverr) != 0) {
820204076Spjd		pjdlog_common(LOG_ERR, 0, nv_error(nverr),
821204076Spjd		    "Unable to prepare error header for %s", raddr);
822204076Spjd		goto close;
823204076Spjd	}
824204076Spjd	if (hast_proto_send(NULL, conn, nverr, NULL, 0) < 0) {
825204076Spjd		pjdlog_errno(LOG_ERR, "Unable to send error to %s", raddr);
826204076Spjd		goto close;
827204076Spjd	}
828204076Spjdclose:
829204076Spjd	if (nvin != NULL)
830204076Spjd		nv_free(nvin);
831204076Spjd	if (nvout != NULL)
832204076Spjd		nv_free(nvout);
833204076Spjd	if (nverr != NULL)
834204076Spjd		nv_free(nverr);
835204076Spjd	proto_close(conn);
836204076Spjd	pjdlog_prefix_set("%s", "");
837204076Spjd}
838204076Spjd
839204076Spjdstatic void
840218218Spjdconnection_migrate(struct hast_resource *res)
841218218Spjd{
842218218Spjd	struct proto_conn *conn;
843218218Spjd	int16_t val = 0;
844218218Spjd
845219814Spjd	pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
846219814Spjd
847218218Spjd	if (proto_recv(res->hr_conn, &val, sizeof(val)) < 0) {
848218218Spjd		pjdlog_errno(LOG_WARNING,
849218218Spjd		    "Unable to receive connection command");
850218218Spjd		return;
851218218Spjd	}
852218218Spjd	if (proto_client(res->hr_remoteaddr, &conn) < 0) {
853218218Spjd		val = errno;
854218218Spjd		pjdlog_errno(LOG_WARNING,
855218218Spjd		    "Unable to create outgoing connection to %s",
856218218Spjd		    res->hr_remoteaddr);
857218218Spjd		goto out;
858218218Spjd	}
859218218Spjd	if (proto_connect(conn, -1) < 0) {
860218218Spjd		val = errno;
861218218Spjd		pjdlog_errno(LOG_WARNING, "Unable to connect to %s",
862218218Spjd		    res->hr_remoteaddr);
863218218Spjd		proto_close(conn);
864218218Spjd		goto out;
865218218Spjd	}
866218218Spjd	val = 0;
867218218Spjdout:
868218218Spjd	if (proto_send(res->hr_conn, &val, sizeof(val)) < 0) {
869218218Spjd		pjdlog_errno(LOG_WARNING,
870218218Spjd		    "Unable to send reply to connection request");
871218218Spjd	}
872218218Spjd	if (val == 0 && proto_connection_send(res->hr_conn, conn) < 0)
873218218Spjd		pjdlog_errno(LOG_WARNING, "Unable to send connection");
874219814Spjd
875219814Spjd	pjdlog_prefix_set("%s", "");
876218218Spjd}
877218218Spjd
878218218Spjdstatic void
879204076Spjdmain_loop(void)
880204076Spjd{
881212038Spjd	struct hast_resource *res;
882213009Spjd	struct timeval seltimeout;
883213009Spjd	struct timespec sigtimeout;
884213009Spjd	int fd, maxfd, ret, signo;
885219813Spjd	time_t lastcheck, now;
886213009Spjd	sigset_t mask;
887212037Spjd	fd_set rfds;
888204076Spjd
889219813Spjd	lastcheck = time(NULL);
890213009Spjd	seltimeout.tv_sec = REPORT_INTERVAL;
891213009Spjd	seltimeout.tv_usec = 0;
892213009Spjd	sigtimeout.tv_sec = 0;
893213009Spjd	sigtimeout.tv_nsec = 0;
894211977Spjd
895213009Spjd	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
896213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0);
897213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
898213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
899213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGCHLD) == 0);
900213009Spjd
901216477Spjd	pjdlog_info("Started successfully, running protocol version %d.",
902216477Spjd	    HAST_PROTO_VERSION);
903216477Spjd
904204076Spjd	for (;;) {
905213009Spjd		while ((signo = sigtimedwait(&mask, NULL, &sigtimeout)) != -1) {
906213009Spjd			switch (signo) {
907213009Spjd			case SIGINT:
908213009Spjd			case SIGTERM:
909213009Spjd				sigexit_received = true;
910213009Spjd				terminate_workers();
911217967Spjd				proto_close(cfg->hc_controlconn);
912213009Spjd				exit(EX_OK);
913213009Spjd				break;
914213009Spjd			case SIGCHLD:
915213009Spjd				child_exit();
916213009Spjd				break;
917213009Spjd			case SIGHUP:
918213009Spjd				hastd_reload();
919213009Spjd				break;
920213009Spjd			default:
921218138Spjd				PJDLOG_ABORT("Unexpected signal (%d).", signo);
922213009Spjd			}
923211899Spjd		}
924204076Spjd
925209177Spjd		/* Setup descriptors for select(2). */
926204076Spjd		FD_ZERO(&rfds);
927212038Spjd		maxfd = fd = proto_descriptor(cfg->hc_controlconn);
928218138Spjd		PJDLOG_ASSERT(fd >= 0);
929212038Spjd		FD_SET(fd, &rfds);
930212038Spjd		fd = proto_descriptor(cfg->hc_listenconn);
931218138Spjd		PJDLOG_ASSERT(fd >= 0);
932212038Spjd		FD_SET(fd, &rfds);
933212038Spjd		maxfd = fd > maxfd ? fd : maxfd;
934212038Spjd		TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
935212038Spjd			if (res->hr_event == NULL)
936212038Spjd				continue;
937218218Spjd			PJDLOG_ASSERT(res->hr_conn != NULL);
938212038Spjd			fd = proto_descriptor(res->hr_event);
939218138Spjd			PJDLOG_ASSERT(fd >= 0);
940212038Spjd			FD_SET(fd, &rfds);
941212038Spjd			maxfd = fd > maxfd ? fd : maxfd;
942218218Spjd			if (res->hr_role == HAST_ROLE_PRIMARY) {
943218218Spjd				/* Only primary workers asks for connections. */
944218218Spjd				fd = proto_descriptor(res->hr_conn);
945218218Spjd				PJDLOG_ASSERT(fd >= 0);
946218218Spjd				FD_SET(fd, &rfds);
947218218Spjd				maxfd = fd > maxfd ? fd : maxfd;
948218218Spjd			}
949212038Spjd		}
950204076Spjd
951218138Spjd		PJDLOG_ASSERT(maxfd + 1 <= (int)FD_SETSIZE);
952213009Spjd		ret = select(maxfd + 1, &rfds, NULL, NULL, &seltimeout);
953219813Spjd		now = time(NULL);
954219813Spjd		if (lastcheck + REPORT_INTERVAL <= now) {
955213429Spjd			hook_check();
956219813Spjd			lastcheck = now;
957219813Spjd		}
958219813Spjd		if (ret == 0) {
959219813Spjd			/*
960219813Spjd			 * select(2) timed out, so there should be no
961219813Spjd			 * descriptors to check.
962219813Spjd			 */
963219813Spjd			continue;
964219813Spjd		} else if (ret == -1) {
965204076Spjd			if (errno == EINTR)
966204076Spjd				continue;
967204076Spjd			KEEP_ERRNO((void)pidfile_remove(pfh));
968204076Spjd			pjdlog_exit(EX_OSERR, "select() failed");
969204076Spjd		}
970204076Spjd
971212038Spjd		if (FD_ISSET(proto_descriptor(cfg->hc_controlconn), &rfds))
972204076Spjd			control_handle(cfg);
973212038Spjd		if (FD_ISSET(proto_descriptor(cfg->hc_listenconn), &rfds))
974204076Spjd			listen_accept();
975212038Spjd		TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
976212038Spjd			if (res->hr_event == NULL)
977212038Spjd				continue;
978218218Spjd			PJDLOG_ASSERT(res->hr_conn != NULL);
979212038Spjd			if (FD_ISSET(proto_descriptor(res->hr_event), &rfds)) {
980212038Spjd				if (event_recv(res) == 0)
981212038Spjd					continue;
982212038Spjd				/* The worker process exited? */
983212038Spjd				proto_close(res->hr_event);
984212038Spjd				res->hr_event = NULL;
985218218Spjd				proto_close(res->hr_conn);
986218218Spjd				res->hr_conn = NULL;
987218218Spjd				continue;
988212038Spjd			}
989218218Spjd			if (res->hr_role == HAST_ROLE_PRIMARY &&
990218218Spjd			    FD_ISSET(proto_descriptor(res->hr_conn), &rfds)) {
991218218Spjd				connection_migrate(res);
992218218Spjd			}
993212038Spjd		}
994204076Spjd	}
995204076Spjd}
996204076Spjd
997213428Spjdstatic void
998213428Spjddummy_sighandler(int sig __unused)
999213428Spjd{
1000213428Spjd	/* Nothing to do. */
1001213428Spjd}
1002213428Spjd
1003204076Spjdint
1004204076Spjdmain(int argc, char *argv[])
1005204076Spjd{
1006204076Spjd	const char *pidfile;
1007204076Spjd	pid_t otherpid;
1008204076Spjd	bool foreground;
1009204076Spjd	int debuglevel;
1010213009Spjd	sigset_t mask;
1011204076Spjd
1012204076Spjd	foreground = false;
1013204076Spjd	debuglevel = 0;
1014204076Spjd	pidfile = HASTD_PIDFILE;
1015204076Spjd
1016204076Spjd	for (;;) {
1017204076Spjd		int ch;
1018204076Spjd
1019204076Spjd		ch = getopt(argc, argv, "c:dFhP:");
1020204076Spjd		if (ch == -1)
1021204076Spjd			break;
1022204076Spjd		switch (ch) {
1023204076Spjd		case 'c':
1024204076Spjd			cfgpath = optarg;
1025204076Spjd			break;
1026204076Spjd		case 'd':
1027204076Spjd			debuglevel++;
1028204076Spjd			break;
1029204076Spjd		case 'F':
1030204076Spjd			foreground = true;
1031204076Spjd			break;
1032204076Spjd		case 'P':
1033204076Spjd			pidfile = optarg;
1034204076Spjd			break;
1035204076Spjd		case 'h':
1036204076Spjd		default:
1037204076Spjd			usage();
1038204076Spjd		}
1039204076Spjd	}
1040204076Spjd	argc -= optind;
1041204076Spjd	argv += optind;
1042204076Spjd
1043217965Spjd	pjdlog_init(PJDLOG_MODE_STD);
1044204076Spjd	pjdlog_debug_set(debuglevel);
1045204076Spjd
1046214273Spjd	g_gate_load();
1047214273Spjd
1048204076Spjd	pfh = pidfile_open(pidfile, 0600, &otherpid);
1049204076Spjd	if (pfh == NULL) {
1050204076Spjd		if (errno == EEXIST) {
1051204076Spjd			pjdlog_exitx(EX_TEMPFAIL,
1052204076Spjd			    "Another hastd is already running, pid: %jd.",
1053204076Spjd			    (intmax_t)otherpid);
1054204076Spjd		}
1055204076Spjd		/* If we cannot create pidfile from other reasons, only warn. */
1056210879Spjd		pjdlog_errno(LOG_WARNING, "Unable to open or create pidfile");
1057204076Spjd	}
1058204076Spjd
1059210883Spjd	cfg = yy_config_parse(cfgpath, true);
1060218138Spjd	PJDLOG_ASSERT(cfg != NULL);
1061204076Spjd
1062213428Spjd	/*
1063217307Spjd	 * Restore default actions for interesting signals in case parent
1064217307Spjd	 * process (like init(8)) decided to ignore some of them (like SIGHUP).
1065217307Spjd	 */
1066217307Spjd	PJDLOG_VERIFY(signal(SIGHUP, SIG_DFL) != SIG_ERR);
1067217307Spjd	PJDLOG_VERIFY(signal(SIGINT, SIG_DFL) != SIG_ERR);
1068217307Spjd	PJDLOG_VERIFY(signal(SIGTERM, SIG_DFL) != SIG_ERR);
1069217307Spjd	/*
1070213428Spjd	 * Because SIGCHLD is ignored by default, setup dummy handler for it,
1071213428Spjd	 * so we can mask it.
1072213428Spjd	 */
1073213428Spjd	PJDLOG_VERIFY(signal(SIGCHLD, dummy_sighandler) != SIG_ERR);
1074217307Spjd
1075213009Spjd	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
1076213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0);
1077213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
1078213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
1079213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGCHLD) == 0);
1080213009Spjd	PJDLOG_VERIFY(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
1081204076Spjd
1082204076Spjd	/* Listen on control address. */
1083204076Spjd	if (proto_server(cfg->hc_controladdr, &cfg->hc_controlconn) < 0) {
1084204076Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
1085204076Spjd		pjdlog_exit(EX_OSERR, "Unable to listen on control address %s",
1086204076Spjd		    cfg->hc_controladdr);
1087204076Spjd	}
1088204076Spjd	/* Listen for remote connections. */
1089204076Spjd	if (proto_server(cfg->hc_listenaddr, &cfg->hc_listenconn) < 0) {
1090204076Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
1091204076Spjd		pjdlog_exit(EX_OSERR, "Unable to listen on address %s",
1092204076Spjd		    cfg->hc_listenaddr);
1093204076Spjd	}
1094204076Spjd
1095204076Spjd	if (!foreground) {
1096204076Spjd		if (daemon(0, 0) < 0) {
1097204076Spjd			KEEP_ERRNO((void)pidfile_remove(pfh));
1098204076Spjd			pjdlog_exit(EX_OSERR, "Unable to daemonize");
1099204076Spjd		}
1100204076Spjd
1101204076Spjd		/* Start logging to syslog. */
1102204076Spjd		pjdlog_mode_set(PJDLOG_MODE_SYSLOG);
1103204076Spjd
1104204076Spjd		/* Write PID to a file. */
1105204076Spjd		if (pidfile_write(pfh) < 0) {
1106204076Spjd			pjdlog_errno(LOG_WARNING,
1107204076Spjd			    "Unable to write PID to a file");
1108204076Spjd		}
1109204076Spjd	}
1110204076Spjd
1111211977Spjd	hook_init();
1112211977Spjd
1113204076Spjd	main_loop();
1114204076Spjd
1115204076Spjd	exit(0);
1116204076Spjd}
1117