2 * Copyright (c) 2009-2010 The FreeBSD Foundation
3 * Copyright (c) 2010-2011 Pawel Jakub Dawidek <pawel@dawidek.net>
6 * This software was developed by Pawel Jakub Dawidek under sponsorship from
7 * the FreeBSD Foundation.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
19 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
22 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
34 #include <sys/param.h>
35 #include <sys/linker.h>
36 #include <sys/module.h>
52 #include <activemap.h>
58 #include "hast_proto.h"
63 /* Path to configuration file. */
64 const char *cfgpath = HAST_CONFIG;
65 /* Hastd configuration. */
66 static struct hastd_config *cfg;
67 /* Was SIGINT or SIGTERM signal received? */
68 bool sigexit_received = false;
69 /* PID file handle. */
72 /* How often check for hooks running for too long. */
73 #define REPORT_INTERVAL 5
79 errx(EX_USAGE, "[-dFh] [-c config] [-P pidfile]");
86 if (modfind("g_gate") == -1) {
87 /* Not present in kernel, try loading it. */
88 if (kldload("geom_gate") == -1 || modfind("g_gate") == -1) {
89 if (errno != EEXIST) {
91 "Unable to load geom_gate module");
98 descriptors_cleanup(struct hast_resource *res)
100 struct hast_resource *tres;
102 TAILQ_FOREACH(tres, &cfg->hc_resources, hr_next) {
104 PJDLOG_VERIFY(res->hr_role == HAST_ROLE_SECONDARY ||
105 (res->hr_remotein == NULL &&
106 res->hr_remoteout == NULL));
109 if (tres->hr_remotein != NULL)
110 proto_close(tres->hr_remotein);
111 if (tres->hr_remoteout != NULL)
112 proto_close(tres->hr_remoteout);
113 if (tres->hr_ctrl != NULL)
114 proto_close(tres->hr_ctrl);
115 if (tres->hr_event != NULL)
116 proto_close(tres->hr_event);
117 if (tres->hr_conn != NULL)
118 proto_close(tres->hr_conn);
120 if (cfg->hc_controlin != NULL)
121 proto_close(cfg->hc_controlin);
122 proto_close(cfg->hc_controlconn);
123 proto_close(cfg->hc_listenconn);
124 (void)pidfile_close(pfh);
130 dtype2str(mode_t mode)
134 return ("block device");
135 else if (S_ISCHR(mode))
136 return ("character device");
137 else if (S_ISDIR(mode))
138 return ("directory");
139 else if (S_ISFIFO(mode))
140 return ("pipe or FIFO");
141 else if (S_ISLNK(mode))
142 return ("symbolic link");
143 else if (S_ISREG(mode))
144 return ("regular file");
145 else if (S_ISSOCK(mode))
147 else if (S_ISWHT(mode))
154 descriptors_assert(const struct hast_resource *res, int pjdlogmode)
164 * At this point descriptor to syslog socket is closed, so if we want
165 * to log assertion message, we have to first store it in 'msg' local
166 * buffer and then open syslog socket and log it.
170 maxfd = sysconf(_SC_OPEN_MAX);
172 pjdlog_init(pjdlogmode);
173 pjdlog_prefix_set("[%s] (%s) ", res->hr_name,
174 role2str(res->hr_role));
175 pjdlog_errno(LOG_WARNING, "sysconf(_SC_OPEN_MAX) failed");
179 for (fd = 0; fd <= maxfd; fd++) {
180 if (fstat(fd, &sb) == 0) {
183 } else if (errno == EBADF) {
187 (void)snprintf(msg, sizeof(msg),
188 "Unable to fstat descriptor %d: %s", fd,
192 if (fd == STDIN_FILENO || fd == STDOUT_FILENO ||
193 fd == STDERR_FILENO) {
195 (void)snprintf(msg, sizeof(msg),
196 "Descriptor %d (%s) is closed, but should be open.",
197 fd, (fd == STDIN_FILENO ? "stdin" :
198 (fd == STDOUT_FILENO ? "stdout" : "stderr")));
201 } else if (fd == proto_descriptor(res->hr_event)) {
203 (void)snprintf(msg, sizeof(msg),
204 "Descriptor %d (event) is closed, but should be open.",
208 if (!S_ISSOCK(mode)) {
209 (void)snprintf(msg, sizeof(msg),
210 "Descriptor %d (event) is %s, but should be %s.",
211 fd, dtype2str(mode), dtype2str(S_IFSOCK));
214 } else if (fd == proto_descriptor(res->hr_ctrl)) {
216 (void)snprintf(msg, sizeof(msg),
217 "Descriptor %d (ctrl) is closed, but should be open.",
221 if (!S_ISSOCK(mode)) {
222 (void)snprintf(msg, sizeof(msg),
223 "Descriptor %d (ctrl) is %s, but should be %s.",
224 fd, dtype2str(mode), dtype2str(S_IFSOCK));
227 } else if (res->hr_role == HAST_ROLE_PRIMARY &&
228 fd == proto_descriptor(res->hr_conn)) {
230 (void)snprintf(msg, sizeof(msg),
231 "Descriptor %d (conn) is closed, but should be open.",
235 if (!S_ISSOCK(mode)) {
236 (void)snprintf(msg, sizeof(msg),
237 "Descriptor %d (conn) is %s, but should be %s.",
238 fd, dtype2str(mode), dtype2str(S_IFSOCK));
241 } else if (res->hr_role == HAST_ROLE_SECONDARY &&
242 res->hr_conn != NULL &&
243 fd == proto_descriptor(res->hr_conn)) {
245 (void)snprintf(msg, sizeof(msg),
246 "Descriptor %d (conn) is open, but should be closed.",
250 } else if (res->hr_role == HAST_ROLE_SECONDARY &&
251 fd == proto_descriptor(res->hr_remotein)) {
253 (void)snprintf(msg, sizeof(msg),
254 "Descriptor %d (remote in) is closed, but should be open.",
258 if (!S_ISSOCK(mode)) {
259 (void)snprintf(msg, sizeof(msg),
260 "Descriptor %d (remote in) is %s, but should be %s.",
261 fd, dtype2str(mode), dtype2str(S_IFSOCK));
264 } else if (res->hr_role == HAST_ROLE_SECONDARY &&
265 fd == proto_descriptor(res->hr_remoteout)) {
267 (void)snprintf(msg, sizeof(msg),
268 "Descriptor %d (remote out) is closed, but should be open.",
272 if (!S_ISSOCK(mode)) {
273 (void)snprintf(msg, sizeof(msg),
274 "Descriptor %d (remote out) is %s, but should be %s.",
275 fd, dtype2str(mode), dtype2str(S_IFSOCK));
280 (void)snprintf(msg, sizeof(msg),
281 "Descriptor %d is open (%s), but should be closed.",
282 fd, dtype2str(mode));
287 if (msg[0] != '\0') {
288 pjdlog_init(pjdlogmode);
289 pjdlog_prefix_set("[%s] (%s) ", res->hr_name,
290 role2str(res->hr_role));
291 PJDLOG_ABORT("%s", msg);
296 child_exit_log(unsigned int pid, int status)
299 if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
300 pjdlog_debug(1, "Worker process exited gracefully (pid=%u).",
302 } else if (WIFSIGNALED(status)) {
303 pjdlog_error("Worker process killed (pid=%u, signal=%d).",
304 pid, WTERMSIG(status));
306 pjdlog_error("Worker process exited ungracefully (pid=%u, exitcode=%d).",
307 pid, WIFEXITED(status) ? WEXITSTATUS(status) : -1);
314 struct hast_resource *res;
318 while ((pid = wait3(&status, WNOHANG, NULL)) > 0) {
319 /* Find resource related to the process that just exited. */
320 TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
321 if (pid == res->hr_workerpid)
326 * This can happen when new connection arrives and we
327 * cancel child responsible for the old one or if this
328 * was hook which we executed.
330 hook_check_one(pid, status);
333 pjdlog_prefix_set("[%s] (%s) ", res->hr_name,
334 role2str(res->hr_role));
335 child_exit_log(pid, status);
337 if (res->hr_role == HAST_ROLE_PRIMARY) {
339 * Restart child process if it was killed by signal
340 * or exited because of temporary problem.
342 if (WIFSIGNALED(status) ||
343 (WIFEXITED(status) &&
344 WEXITSTATUS(status) == EX_TEMPFAIL)) {
346 pjdlog_info("Restarting worker process.");
349 res->hr_role = HAST_ROLE_INIT;
350 pjdlog_info("Changing resource role back to %s.",
351 role2str(res->hr_role));
354 pjdlog_prefix_set("%s", "");
359 resource_needs_restart(const struct hast_resource *res0,
360 const struct hast_resource *res1)
363 PJDLOG_ASSERT(strcmp(res0->hr_name, res1->hr_name) == 0);
365 if (strcmp(res0->hr_provname, res1->hr_provname) != 0)
367 if (strcmp(res0->hr_localpath, res1->hr_localpath) != 0)
369 if (res0->hr_role == HAST_ROLE_INIT ||
370 res0->hr_role == HAST_ROLE_SECONDARY) {
371 if (strcmp(res0->hr_remoteaddr, res1->hr_remoteaddr) != 0)
373 if (strcmp(res0->hr_sourceaddr, res1->hr_sourceaddr) != 0)
375 if (res0->hr_replication != res1->hr_replication)
377 if (res0->hr_checksum != res1->hr_checksum)
379 if (res0->hr_compression != res1->hr_compression)
381 if (res0->hr_timeout != res1->hr_timeout)
383 if (strcmp(res0->hr_exec, res1->hr_exec) != 0)
390 resource_needs_reload(const struct hast_resource *res0,
391 const struct hast_resource *res1)
394 PJDLOG_ASSERT(strcmp(res0->hr_name, res1->hr_name) == 0);
395 PJDLOG_ASSERT(strcmp(res0->hr_provname, res1->hr_provname) == 0);
396 PJDLOG_ASSERT(strcmp(res0->hr_localpath, res1->hr_localpath) == 0);
398 if (res0->hr_role != HAST_ROLE_PRIMARY)
401 if (strcmp(res0->hr_remoteaddr, res1->hr_remoteaddr) != 0)
403 if (strcmp(res0->hr_sourceaddr, res1->hr_sourceaddr) != 0)
405 if (res0->hr_replication != res1->hr_replication)
407 if (res0->hr_checksum != res1->hr_checksum)
409 if (res0->hr_compression != res1->hr_compression)
411 if (res0->hr_timeout != res1->hr_timeout)
413 if (strcmp(res0->hr_exec, res1->hr_exec) != 0)
419 resource_reload(const struct hast_resource *res)
421 struct nv *nvin, *nvout;
424 PJDLOG_ASSERT(res->hr_role == HAST_ROLE_PRIMARY);
427 nv_add_uint8(nvout, HASTCTL_RELOAD, "cmd");
428 nv_add_string(nvout, res->hr_remoteaddr, "remoteaddr");
429 nv_add_string(nvout, res->hr_sourceaddr, "sourceaddr");
430 nv_add_int32(nvout, (int32_t)res->hr_replication, "replication");
431 nv_add_int32(nvout, (int32_t)res->hr_checksum, "checksum");
432 nv_add_int32(nvout, (int32_t)res->hr_compression, "compression");
433 nv_add_int32(nvout, (int32_t)res->hr_timeout, "timeout");
434 nv_add_string(nvout, res->hr_exec, "exec");
435 if (nv_error(nvout) != 0) {
437 pjdlog_error("Unable to allocate header for reload message.");
440 if (hast_proto_send(res, res->hr_ctrl, nvout, NULL, 0) < 0) {
441 pjdlog_errno(LOG_ERR, "Unable to send reload message");
447 /* Receive response. */
448 if (hast_proto_recv_hdr(res->hr_ctrl, &nvin) < 0) {
449 pjdlog_errno(LOG_ERR, "Unable to receive reload reply");
452 error = nv_get_int16(nvin, "error");
455 pjdlog_common(LOG_ERR, 0, error, "Reload failed");
463 struct hastd_config *newcfg;
464 struct hast_resource *nres, *cres, *tres;
467 pjdlog_info("Reloading configuration...");
469 newcfg = yy_config_parse(cfgpath, false);
474 * Check if control address has changed.
476 if (strcmp(cfg->hc_controladdr, newcfg->hc_controladdr) != 0) {
477 if (proto_server(newcfg->hc_controladdr,
478 &newcfg->hc_controlconn) < 0) {
479 pjdlog_errno(LOG_ERR,
480 "Unable to listen on control address %s",
481 newcfg->hc_controladdr);
486 * Check if listen address has changed.
488 if (strcmp(cfg->hc_listenaddr, newcfg->hc_listenaddr) != 0) {
489 if (proto_server(newcfg->hc_listenaddr,
490 &newcfg->hc_listenconn) < 0) {
491 pjdlog_errno(LOG_ERR, "Unable to listen on address %s",
492 newcfg->hc_listenaddr);
497 * Only when both control and listen sockets are successfully
498 * initialized switch them to new configuration.
500 if (newcfg->hc_controlconn != NULL) {
501 pjdlog_info("Control socket changed from %s to %s.",
502 cfg->hc_controladdr, newcfg->hc_controladdr);
503 proto_close(cfg->hc_controlconn);
504 cfg->hc_controlconn = newcfg->hc_controlconn;
505 newcfg->hc_controlconn = NULL;
506 strlcpy(cfg->hc_controladdr, newcfg->hc_controladdr,
507 sizeof(cfg->hc_controladdr));
509 if (newcfg->hc_listenconn != NULL) {
510 pjdlog_info("Listen socket changed from %s to %s.",
511 cfg->hc_listenaddr, newcfg->hc_listenaddr);
512 proto_close(cfg->hc_listenconn);
513 cfg->hc_listenconn = newcfg->hc_listenconn;
514 newcfg->hc_listenconn = NULL;
515 strlcpy(cfg->hc_listenaddr, newcfg->hc_listenaddr,
516 sizeof(cfg->hc_listenaddr));
520 * Stop and remove resources that were removed from the configuration.
522 TAILQ_FOREACH_SAFE(cres, &cfg->hc_resources, hr_next, tres) {
523 TAILQ_FOREACH(nres, &newcfg->hc_resources, hr_next) {
524 if (strcmp(cres->hr_name, nres->hr_name) == 0)
528 control_set_role(cres, HAST_ROLE_INIT);
529 TAILQ_REMOVE(&cfg->hc_resources, cres, hr_next);
530 pjdlog_info("Resource %s removed.", cres->hr_name);
535 * Move new resources to the current configuration.
537 TAILQ_FOREACH_SAFE(nres, &newcfg->hc_resources, hr_next, tres) {
538 TAILQ_FOREACH(cres, &cfg->hc_resources, hr_next) {
539 if (strcmp(cres->hr_name, nres->hr_name) == 0)
543 TAILQ_REMOVE(&newcfg->hc_resources, nres, hr_next);
544 TAILQ_INSERT_TAIL(&cfg->hc_resources, nres, hr_next);
545 pjdlog_info("Resource %s added.", nres->hr_name);
549 * Deal with modified resources.
550 * Depending on what has changed exactly we might want to perform
553 * We do full resource restart in the following situations:
554 * Resource role is INIT or SECONDARY.
555 * Resource role is PRIMARY and path to local component or provider
557 * In case of PRIMARY, the worker process will be killed and restarted,
558 * which also means removing /dev/hast/<name> provider and
561 * We do just reload (send SIGHUP to worker process) if we act as
562 * PRIMARY, but only if remote address, replication mode, timeout or
563 * execution path has changed. For those, there is no need to restart
565 * If PRIMARY receives SIGHUP, it will reconnect if remote address or
566 * replication mode has changed or simply set new timeout if only
567 * timeout has changed.
569 TAILQ_FOREACH_SAFE(nres, &newcfg->hc_resources, hr_next, tres) {
570 TAILQ_FOREACH(cres, &cfg->hc_resources, hr_next) {
571 if (strcmp(cres->hr_name, nres->hr_name) == 0)
574 PJDLOG_ASSERT(cres != NULL);
575 if (resource_needs_restart(cres, nres)) {
576 pjdlog_info("Resource %s configuration was modified, restarting it.",
578 role = cres->hr_role;
579 control_set_role(cres, HAST_ROLE_INIT);
580 TAILQ_REMOVE(&cfg->hc_resources, cres, hr_next);
582 TAILQ_REMOVE(&newcfg->hc_resources, nres, hr_next);
583 TAILQ_INSERT_TAIL(&cfg->hc_resources, nres, hr_next);
584 control_set_role(nres, role);
585 } else if (resource_needs_reload(cres, nres)) {
586 pjdlog_info("Resource %s configuration was modified, reloading it.",
588 strlcpy(cres->hr_remoteaddr, nres->hr_remoteaddr,
589 sizeof(cres->hr_remoteaddr));
590 strlcpy(cres->hr_sourceaddr, nres->hr_sourceaddr,
591 sizeof(cres->hr_sourceaddr));
592 cres->hr_replication = nres->hr_replication;
593 cres->hr_checksum = nres->hr_checksum;
594 cres->hr_compression = nres->hr_compression;
595 cres->hr_timeout = nres->hr_timeout;
596 strlcpy(cres->hr_exec, nres->hr_exec,
597 sizeof(cres->hr_exec));
598 if (cres->hr_workerpid != 0)
599 resource_reload(cres);
603 yy_config_free(newcfg);
604 pjdlog_info("Configuration reloaded successfully.");
607 if (newcfg != NULL) {
608 if (newcfg->hc_controlconn != NULL)
609 proto_close(newcfg->hc_controlconn);
610 if (newcfg->hc_listenconn != NULL)
611 proto_close(newcfg->hc_listenconn);
612 yy_config_free(newcfg);
614 pjdlog_warning("Configuration not reloaded.");
618 terminate_workers(void)
620 struct hast_resource *res;
622 pjdlog_info("Termination signal received, exiting.");
623 TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
624 if (res->hr_workerpid == 0)
626 pjdlog_info("Terminating worker process (resource=%s, role=%s, pid=%u).",
627 res->hr_name, role2str(res->hr_role), res->hr_workerpid);
628 if (kill(res->hr_workerpid, SIGTERM) == 0)
630 pjdlog_errno(LOG_WARNING,
631 "Unable to send signal to worker process (resource=%s, role=%s, pid=%u).",
632 res->hr_name, role2str(res->hr_role), res->hr_workerpid);
639 struct hast_resource *res;
640 struct proto_conn *conn;
641 struct nv *nvin, *nvout, *nverr;
643 const unsigned char *token;
644 char laddr[256], raddr[256];
649 proto_local_address(cfg->hc_listenconn, laddr, sizeof(laddr));
650 pjdlog_debug(1, "Accepting connection to %s.", laddr);
652 if (proto_accept(cfg->hc_listenconn, &conn) < 0) {
653 pjdlog_errno(LOG_ERR, "Unable to accept connection %s", laddr);
657 proto_local_address(conn, laddr, sizeof(laddr));
658 proto_remote_address(conn, raddr, sizeof(raddr));
659 pjdlog_info("Connection from %s to %s.", raddr, laddr);
661 /* Error in setting timeout is not critical, but why should it fail? */
662 if (proto_timeout(conn, HAST_TIMEOUT) < 0)
663 pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
665 nvin = nvout = nverr = NULL;
668 * Before receiving any data see if remote host have access to any
671 TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
672 if (proto_address_match(conn, res->hr_remoteaddr))
676 pjdlog_error("Client %s isn't known.", raddr);
679 /* Ok, remote host can access at least one resource. */
681 if (hast_proto_recv_hdr(conn, &nvin) < 0) {
682 pjdlog_errno(LOG_ERR, "Unable to receive header from %s",
687 resname = nv_get_string(nvin, "resource");
688 if (resname == NULL) {
689 pjdlog_error("No 'resource' field in the header received from %s.",
693 pjdlog_debug(2, "%s: resource=%s", raddr, resname);
694 token = nv_get_uint8_array(nvin, &size, "token");
696 * NULL token means that this is first conection.
698 if (token != NULL && size != sizeof(res->hr_token)) {
699 pjdlog_error("Received token of invalid size from %s (expected %zu, got %zu).",
700 raddr, sizeof(res->hr_token), size);
705 * From now on we want to send errors to the remote node.
709 /* Find resource related to this connection. */
710 TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
711 if (strcmp(resname, res->hr_name) == 0)
714 /* Have we found the resource? */
716 pjdlog_error("No resource '%s' as requested by %s.",
718 nv_add_stringf(nverr, "errmsg", "Resource not configured.");
722 /* Now that we know resource name setup log prefix. */
723 pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
725 /* Does the remote host have access to this resource? */
726 if (!proto_address_match(conn, res->hr_remoteaddr)) {
727 pjdlog_error("Client %s has no access to the resource.", raddr);
728 nv_add_stringf(nverr, "errmsg", "No access to the resource.");
731 /* Is the resource marked as secondary? */
732 if (res->hr_role != HAST_ROLE_SECONDARY) {
733 pjdlog_warning("We act as %s for the resource and not as %s as requested by %s.",
734 role2str(res->hr_role), role2str(HAST_ROLE_SECONDARY),
736 nv_add_stringf(nverr, "errmsg",
737 "Remote node acts as %s for the resource and not as %s.",
738 role2str(res->hr_role), role2str(HAST_ROLE_SECONDARY));
739 if (res->hr_role == HAST_ROLE_PRIMARY) {
741 * If we act as primary request the other side to wait
742 * for us a bit, as we might be finishing cleanups.
744 nv_add_uint8(nverr, 1, "wait");
748 /* Does token (if exists) match? */
749 if (token != NULL && memcmp(token, res->hr_token,
750 sizeof(res->hr_token)) != 0) {
751 pjdlog_error("Token received from %s doesn't match.", raddr);
752 nv_add_stringf(nverr, "errmsg", "Token doesn't match.");
756 * If there is no token, but we have half-open connection
757 * (only remotein) or full connection (worker process is running)
758 * we have to cancel those and accept the new connection.
761 PJDLOG_ASSERT(res->hr_remoteout == NULL);
762 pjdlog_debug(1, "Initial connection from %s.", raddr);
763 if (res->hr_workerpid != 0) {
764 PJDLOG_ASSERT(res->hr_remotein == NULL);
766 "Worker process exists (pid=%u), stopping it.",
767 (unsigned int)res->hr_workerpid);
768 /* Stop child process. */
769 if (kill(res->hr_workerpid, SIGINT) < 0) {
770 pjdlog_errno(LOG_ERR,
771 "Unable to stop worker process (pid=%u)",
772 (unsigned int)res->hr_workerpid);
774 * Other than logging the problem we
775 * ignore it - nothing smart to do.
778 /* Wait for it to exit. */
779 else if ((pid = waitpid(res->hr_workerpid,
780 &status, 0)) != res->hr_workerpid) {
781 /* We can only log the problem. */
782 pjdlog_errno(LOG_ERR,
783 "Waiting for worker process (pid=%u) failed",
784 (unsigned int)res->hr_workerpid);
786 child_exit_log(res->hr_workerpid, status);
789 } else if (res->hr_remotein != NULL) {
792 proto_remote_address(res->hr_remotein, oaddr,
795 "Canceling half-open connection from %s on connection from %s.",
797 proto_close(res->hr_remotein);
798 res->hr_remotein = NULL;
803 * Checks and cleanups are done.
807 arc4random_buf(res->hr_token, sizeof(res->hr_token));
809 nv_add_uint8_array(nvout, res->hr_token,
810 sizeof(res->hr_token), "token");
811 if (nv_error(nvout) != 0) {
812 pjdlog_common(LOG_ERR, 0, nv_error(nvout),
813 "Unable to prepare return header for %s", raddr);
814 nv_add_stringf(nverr, "errmsg",
815 "Remote node was unable to prepare return header: %s.",
816 strerror(nv_error(nvout)));
819 if (hast_proto_send(NULL, conn, nvout, NULL, 0) < 0) {
822 pjdlog_errno(LOG_ERR, "Unable to send response to %s",
824 nv_add_stringf(nverr, "errmsg",
825 "Remote node was unable to send response: %s.",
829 res->hr_remotein = conn;
830 pjdlog_debug(1, "Incoming connection from %s configured.",
833 res->hr_remoteout = conn;
834 pjdlog_debug(1, "Outgoing connection to %s configured.", raddr);
835 hastd_secondary(res, nvin);
840 pjdlog_prefix_set("%s", "");
843 if (nv_error(nverr) != 0) {
844 pjdlog_common(LOG_ERR, 0, nv_error(nverr),
845 "Unable to prepare error header for %s", raddr);
848 if (hast_proto_send(NULL, conn, nverr, NULL, 0) < 0) {
849 pjdlog_errno(LOG_ERR, "Unable to send error to %s", raddr);
860 pjdlog_prefix_set("%s", "");
864 connection_migrate(struct hast_resource *res)
866 struct proto_conn *conn;
869 pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
871 PJDLOG_ASSERT(res->hr_role == HAST_ROLE_PRIMARY);
873 if (proto_recv(res->hr_conn, &val, sizeof(val)) < 0) {
874 pjdlog_errno(LOG_WARNING,
875 "Unable to receive connection command");
878 if (proto_client(res->hr_sourceaddr[0] != '\0' ? res->hr_sourceaddr : NULL,
879 res->hr_remoteaddr, &conn) < 0) {
881 pjdlog_errno(LOG_WARNING,
882 "Unable to create outgoing connection to %s",
886 if (proto_connect(conn, -1) < 0) {
888 pjdlog_errno(LOG_WARNING, "Unable to connect to %s",
895 if (proto_send(res->hr_conn, &val, sizeof(val)) < 0) {
896 pjdlog_errno(LOG_WARNING,
897 "Unable to send reply to connection request");
899 if (val == 0 && proto_connection_send(res->hr_conn, conn) < 0)
900 pjdlog_errno(LOG_WARNING, "Unable to send connection");
902 pjdlog_prefix_set("%s", "");
908 struct timespec sigtimeout;
912 sigtimeout.tv_sec = 0;
913 sigtimeout.tv_nsec = 0;
915 PJDLOG_VERIFY(sigemptyset(&mask) == 0);
916 PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0);
917 PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
918 PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
919 PJDLOG_VERIFY(sigaddset(&mask, SIGCHLD) == 0);
921 while ((signo = sigtimedwait(&mask, NULL, &sigtimeout)) != -1) {
925 sigexit_received = true;
927 proto_close(cfg->hc_controlconn);
937 PJDLOG_ABORT("Unexpected signal (%d).", signo);
945 struct hast_resource *res;
946 struct timeval seltimeout;
948 time_t lastcheck, now;
951 lastcheck = time(NULL);
952 seltimeout.tv_sec = REPORT_INTERVAL;
953 seltimeout.tv_usec = 0;
955 pjdlog_info("Started successfully, running protocol version %d.",
961 /* Setup descriptors for select(2). */
963 maxfd = fd = proto_descriptor(cfg->hc_controlconn);
964 PJDLOG_ASSERT(fd >= 0);
966 fd = proto_descriptor(cfg->hc_listenconn);
967 PJDLOG_ASSERT(fd >= 0);
969 maxfd = fd > maxfd ? fd : maxfd;
970 TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
971 if (res->hr_event == NULL)
973 fd = proto_descriptor(res->hr_event);
974 PJDLOG_ASSERT(fd >= 0);
976 maxfd = fd > maxfd ? fd : maxfd;
977 if (res->hr_role == HAST_ROLE_PRIMARY) {
978 /* Only primary workers asks for connections. */
979 PJDLOG_ASSERT(res->hr_conn != NULL);
980 fd = proto_descriptor(res->hr_conn);
981 PJDLOG_ASSERT(fd >= 0);
983 maxfd = fd > maxfd ? fd : maxfd;
985 PJDLOG_ASSERT(res->hr_conn == NULL);
989 PJDLOG_ASSERT(maxfd + 1 <= (int)FD_SETSIZE);
990 ret = select(maxfd + 1, &rfds, NULL, NULL, &seltimeout);
992 if (lastcheck + REPORT_INTERVAL <= now) {
998 * select(2) timed out, so there should be no
999 * descriptors to check.
1002 } else if (ret == -1) {
1005 KEEP_ERRNO((void)pidfile_remove(pfh));
1006 pjdlog_exit(EX_OSERR, "select() failed");
1010 * Check for signals before we do anything to update our
1011 * info about terminated workers in the meantime.
1015 if (FD_ISSET(proto_descriptor(cfg->hc_controlconn), &rfds))
1016 control_handle(cfg);
1017 if (FD_ISSET(proto_descriptor(cfg->hc_listenconn), &rfds))
1019 TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
1020 if (res->hr_event == NULL)
1022 if (FD_ISSET(proto_descriptor(res->hr_event), &rfds)) {
1023 if (event_recv(res) == 0)
1025 /* The worker process exited? */
1026 proto_close(res->hr_event);
1027 res->hr_event = NULL;
1028 if (res->hr_conn != NULL) {
1029 proto_close(res->hr_conn);
1030 res->hr_conn = NULL;
1034 if (res->hr_role == HAST_ROLE_PRIMARY) {
1035 PJDLOG_ASSERT(res->hr_conn != NULL);
1036 if (FD_ISSET(proto_descriptor(res->hr_conn),
1038 connection_migrate(res);
1041 PJDLOG_ASSERT(res->hr_conn == NULL);
1048 dummy_sighandler(int sig __unused)
1050 /* Nothing to do. */
1054 main(int argc, char *argv[])
1056 const char *pidfile;
1064 pidfile = HASTD_PIDFILE;
1069 ch = getopt(argc, argv, "c:dFhP:");
1093 pjdlog_init(PJDLOG_MODE_STD);
1094 pjdlog_debug_set(debuglevel);
1098 pfh = pidfile_open(pidfile, 0600, &otherpid);
1100 if (errno == EEXIST) {
1101 pjdlog_exitx(EX_TEMPFAIL,
1102 "Another hastd is already running, pid: %jd.",
1103 (intmax_t)otherpid);
1105 /* If we cannot create pidfile from other reasons, only warn. */
1106 pjdlog_errno(LOG_WARNING, "Unable to open or create pidfile");
1109 cfg = yy_config_parse(cfgpath, true);
1110 PJDLOG_ASSERT(cfg != NULL);
1113 * Restore default actions for interesting signals in case parent
1114 * process (like init(8)) decided to ignore some of them (like SIGHUP).
1116 PJDLOG_VERIFY(signal(SIGHUP, SIG_DFL) != SIG_ERR);
1117 PJDLOG_VERIFY(signal(SIGINT, SIG_DFL) != SIG_ERR);
1118 PJDLOG_VERIFY(signal(SIGTERM, SIG_DFL) != SIG_ERR);
1120 * Because SIGCHLD is ignored by default, setup dummy handler for it,
1121 * so we can mask it.
1123 PJDLOG_VERIFY(signal(SIGCHLD, dummy_sighandler) != SIG_ERR);
1125 PJDLOG_VERIFY(sigemptyset(&mask) == 0);
1126 PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0);
1127 PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
1128 PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
1129 PJDLOG_VERIFY(sigaddset(&mask, SIGCHLD) == 0);
1130 PJDLOG_VERIFY(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
1132 /* Listen on control address. */
1133 if (proto_server(cfg->hc_controladdr, &cfg->hc_controlconn) < 0) {
1134 KEEP_ERRNO((void)pidfile_remove(pfh));
1135 pjdlog_exit(EX_OSERR, "Unable to listen on control address %s",
1136 cfg->hc_controladdr);
1138 /* Listen for remote connections. */
1139 if (proto_server(cfg->hc_listenaddr, &cfg->hc_listenconn) < 0) {
1140 KEEP_ERRNO((void)pidfile_remove(pfh));
1141 pjdlog_exit(EX_OSERR, "Unable to listen on address %s",
1142 cfg->hc_listenaddr);
1146 if (daemon(0, 0) < 0) {
1147 KEEP_ERRNO((void)pidfile_remove(pfh));
1148 pjdlog_exit(EX_OSERR, "Unable to daemonize");
1151 /* Start logging to syslog. */
1152 pjdlog_mode_set(PJDLOG_MODE_SYSLOG);
1154 /* Write PID to a file. */
1155 if (pidfile_write(pfh) < 0) {
1156 pjdlog_errno(LOG_WARNING,
1157 "Unable to write PID to a file");