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 /* Path to pidfile. */
70 static const char *pidfile;
73 /* Do we run in foreground? */
74 static bool foreground;
76 /* How often check for hooks running for too long. */
77 #define REPORT_INTERVAL 5
83 errx(EX_USAGE, "[-dFh] [-c config] [-P pidfile]");
90 if (modfind("g_gate") == -1) {
91 /* Not present in kernel, try loading it. */
92 if (kldload("geom_gate") == -1 || modfind("g_gate") == -1) {
93 if (errno != EEXIST) {
95 "Unable to load geom_gate module");
102 descriptors_cleanup(struct hast_resource *res)
104 struct hast_resource *tres, *tmres;
105 struct hastd_listen *lst;
107 TAILQ_FOREACH_SAFE(tres, &cfg->hc_resources, hr_next, tmres) {
109 PJDLOG_VERIFY(res->hr_role == HAST_ROLE_SECONDARY ||
110 (res->hr_remotein == NULL &&
111 res->hr_remoteout == NULL));
114 if (tres->hr_remotein != NULL)
115 proto_close(tres->hr_remotein);
116 if (tres->hr_remoteout != NULL)
117 proto_close(tres->hr_remoteout);
118 if (tres->hr_ctrl != NULL)
119 proto_close(tres->hr_ctrl);
120 if (tres->hr_event != NULL)
121 proto_close(tres->hr_event);
122 if (tres->hr_conn != NULL)
123 proto_close(tres->hr_conn);
124 TAILQ_REMOVE(&cfg->hc_resources, tres, hr_next);
127 if (cfg->hc_controlin != NULL)
128 proto_close(cfg->hc_controlin);
129 proto_close(cfg->hc_controlconn);
130 while ((lst = TAILQ_FIRST(&cfg->hc_listen)) != NULL) {
131 TAILQ_REMOVE(&cfg->hc_listen, lst, hl_next);
132 if (lst->hl_conn != NULL)
133 proto_close(lst->hl_conn);
136 (void)pidfile_close(pfh);
142 dtype2str(mode_t mode)
146 return ("block device");
147 else if (S_ISCHR(mode))
148 return ("character device");
149 else if (S_ISDIR(mode))
150 return ("directory");
151 else if (S_ISFIFO(mode))
152 return ("pipe or FIFO");
153 else if (S_ISLNK(mode))
154 return ("symbolic link");
155 else if (S_ISREG(mode))
156 return ("regular file");
157 else if (S_ISSOCK(mode))
159 else if (S_ISWHT(mode))
166 descriptors_assert(const struct hast_resource *res, int pjdlogmode)
176 * At this point descriptor to syslog socket is closed, so if we want
177 * to log assertion message, we have to first store it in 'msg' local
178 * buffer and then open syslog socket and log it.
182 maxfd = sysconf(_SC_OPEN_MAX);
184 pjdlog_init(pjdlogmode);
185 pjdlog_prefix_set("[%s] (%s) ", res->hr_name,
186 role2str(res->hr_role));
187 pjdlog_errno(LOG_WARNING, "sysconf(_SC_OPEN_MAX) failed");
191 for (fd = 0; fd <= maxfd; fd++) {
192 if (fstat(fd, &sb) == 0) {
195 } else if (errno == EBADF) {
199 (void)snprintf(msg, sizeof(msg),
200 "Unable to fstat descriptor %d: %s", fd,
204 if (fd == STDIN_FILENO || fd == STDOUT_FILENO ||
205 fd == STDERR_FILENO) {
207 (void)snprintf(msg, sizeof(msg),
208 "Descriptor %d (%s) is closed, but should be open.",
209 fd, (fd == STDIN_FILENO ? "stdin" :
210 (fd == STDOUT_FILENO ? "stdout" : "stderr")));
213 } else if (fd == proto_descriptor(res->hr_event)) {
215 (void)snprintf(msg, sizeof(msg),
216 "Descriptor %d (event) is closed, but should be open.",
220 if (!S_ISSOCK(mode)) {
221 (void)snprintf(msg, sizeof(msg),
222 "Descriptor %d (event) is %s, but should be %s.",
223 fd, dtype2str(mode), dtype2str(S_IFSOCK));
226 } else if (fd == proto_descriptor(res->hr_ctrl)) {
228 (void)snprintf(msg, sizeof(msg),
229 "Descriptor %d (ctrl) is closed, but should be open.",
233 if (!S_ISSOCK(mode)) {
234 (void)snprintf(msg, sizeof(msg),
235 "Descriptor %d (ctrl) is %s, but should be %s.",
236 fd, dtype2str(mode), dtype2str(S_IFSOCK));
239 } else if (res->hr_role == HAST_ROLE_PRIMARY &&
240 fd == proto_descriptor(res->hr_conn)) {
242 (void)snprintf(msg, sizeof(msg),
243 "Descriptor %d (conn) is closed, but should be open.",
247 if (!S_ISSOCK(mode)) {
248 (void)snprintf(msg, sizeof(msg),
249 "Descriptor %d (conn) is %s, but should be %s.",
250 fd, dtype2str(mode), dtype2str(S_IFSOCK));
253 } else if (res->hr_role == HAST_ROLE_SECONDARY &&
254 res->hr_conn != NULL &&
255 fd == proto_descriptor(res->hr_conn)) {
257 (void)snprintf(msg, sizeof(msg),
258 "Descriptor %d (conn) is open, but should be closed.",
262 } else if (res->hr_role == HAST_ROLE_SECONDARY &&
263 fd == proto_descriptor(res->hr_remotein)) {
265 (void)snprintf(msg, sizeof(msg),
266 "Descriptor %d (remote in) is closed, but should be open.",
270 if (!S_ISSOCK(mode)) {
271 (void)snprintf(msg, sizeof(msg),
272 "Descriptor %d (remote in) is %s, but should be %s.",
273 fd, dtype2str(mode), dtype2str(S_IFSOCK));
276 } else if (res->hr_role == HAST_ROLE_SECONDARY &&
277 fd == proto_descriptor(res->hr_remoteout)) {
279 (void)snprintf(msg, sizeof(msg),
280 "Descriptor %d (remote out) is closed, but should be open.",
284 if (!S_ISSOCK(mode)) {
285 (void)snprintf(msg, sizeof(msg),
286 "Descriptor %d (remote out) is %s, but should be %s.",
287 fd, dtype2str(mode), dtype2str(S_IFSOCK));
292 (void)snprintf(msg, sizeof(msg),
293 "Descriptor %d is open (%s), but should be closed.",
294 fd, dtype2str(mode));
299 if (msg[0] != '\0') {
300 pjdlog_init(pjdlogmode);
301 pjdlog_prefix_set("[%s] (%s) ", res->hr_name,
302 role2str(res->hr_role));
303 PJDLOG_ABORT("%s", msg);
308 child_exit_log(unsigned int pid, int status)
311 if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
312 pjdlog_debug(1, "Worker process exited gracefully (pid=%u).",
314 } else if (WIFSIGNALED(status)) {
315 pjdlog_error("Worker process killed (pid=%u, signal=%d).",
316 pid, WTERMSIG(status));
318 pjdlog_error("Worker process exited ungracefully (pid=%u, exitcode=%d).",
319 pid, WIFEXITED(status) ? WEXITSTATUS(status) : -1);
326 struct hast_resource *res;
330 while ((pid = wait3(&status, WNOHANG, NULL)) > 0) {
331 /* Find resource related to the process that just exited. */
332 TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
333 if (pid == res->hr_workerpid)
338 * This can happen when new connection arrives and we
339 * cancel child responsible for the old one or if this
340 * was hook which we executed.
342 hook_check_one(pid, status);
345 pjdlog_prefix_set("[%s] (%s) ", res->hr_name,
346 role2str(res->hr_role));
347 child_exit_log(pid, status);
349 if (res->hr_role == HAST_ROLE_PRIMARY) {
351 * Restart child process if it was killed by signal
352 * or exited because of temporary problem.
354 if (WIFSIGNALED(status) ||
355 (WIFEXITED(status) &&
356 WEXITSTATUS(status) == EX_TEMPFAIL)) {
358 pjdlog_info("Restarting worker process.");
361 res->hr_role = HAST_ROLE_INIT;
362 pjdlog_info("Changing resource role back to %s.",
363 role2str(res->hr_role));
366 pjdlog_prefix_set("%s", "");
371 resource_needs_restart(const struct hast_resource *res0,
372 const struct hast_resource *res1)
375 PJDLOG_ASSERT(strcmp(res0->hr_name, res1->hr_name) == 0);
377 if (strcmp(res0->hr_provname, res1->hr_provname) != 0)
379 if (strcmp(res0->hr_localpath, res1->hr_localpath) != 0)
381 if (res0->hr_role == HAST_ROLE_INIT ||
382 res0->hr_role == HAST_ROLE_SECONDARY) {
383 if (strcmp(res0->hr_remoteaddr, res1->hr_remoteaddr) != 0)
385 if (strcmp(res0->hr_sourceaddr, res1->hr_sourceaddr) != 0)
387 if (res0->hr_replication != res1->hr_replication)
389 if (res0->hr_checksum != res1->hr_checksum)
391 if (res0->hr_compression != res1->hr_compression)
393 if (res0->hr_timeout != res1->hr_timeout)
395 if (strcmp(res0->hr_exec, res1->hr_exec) != 0)
398 * When metaflush has changed we don't really need restart,
399 * but it is just easier this way.
401 if (res0->hr_metaflush != res1->hr_metaflush)
408 resource_needs_reload(const struct hast_resource *res0,
409 const struct hast_resource *res1)
412 PJDLOG_ASSERT(strcmp(res0->hr_name, res1->hr_name) == 0);
413 PJDLOG_ASSERT(strcmp(res0->hr_provname, res1->hr_provname) == 0);
414 PJDLOG_ASSERT(strcmp(res0->hr_localpath, res1->hr_localpath) == 0);
416 if (res0->hr_role != HAST_ROLE_PRIMARY)
419 if (strcmp(res0->hr_remoteaddr, res1->hr_remoteaddr) != 0)
421 if (strcmp(res0->hr_sourceaddr, res1->hr_sourceaddr) != 0)
423 if (res0->hr_replication != res1->hr_replication)
425 if (res0->hr_checksum != res1->hr_checksum)
427 if (res0->hr_compression != res1->hr_compression)
429 if (res0->hr_timeout != res1->hr_timeout)
431 if (strcmp(res0->hr_exec, res1->hr_exec) != 0)
433 if (res0->hr_metaflush != res1->hr_metaflush)
439 resource_reload(const struct hast_resource *res)
441 struct nv *nvin, *nvout;
444 PJDLOG_ASSERT(res->hr_role == HAST_ROLE_PRIMARY);
447 nv_add_uint8(nvout, CONTROL_RELOAD, "cmd");
448 nv_add_string(nvout, res->hr_remoteaddr, "remoteaddr");
449 nv_add_string(nvout, res->hr_sourceaddr, "sourceaddr");
450 nv_add_int32(nvout, (int32_t)res->hr_replication, "replication");
451 nv_add_int32(nvout, (int32_t)res->hr_checksum, "checksum");
452 nv_add_int32(nvout, (int32_t)res->hr_compression, "compression");
453 nv_add_int32(nvout, (int32_t)res->hr_timeout, "timeout");
454 nv_add_string(nvout, res->hr_exec, "exec");
455 nv_add_int32(nvout, (int32_t)res->hr_metaflush, "metaflush");
456 if (nv_error(nvout) != 0) {
458 pjdlog_error("Unable to allocate header for reload message.");
461 if (hast_proto_send(res, res->hr_ctrl, nvout, NULL, 0) == -1) {
462 pjdlog_errno(LOG_ERR, "Unable to send reload message");
468 /* Receive response. */
469 if (hast_proto_recv_hdr(res->hr_ctrl, &nvin) == -1) {
470 pjdlog_errno(LOG_ERR, "Unable to receive reload reply");
473 error = nv_get_int16(nvin, "error");
476 pjdlog_common(LOG_ERR, 0, error, "Reload failed");
484 struct hastd_config *newcfg;
485 struct hast_resource *nres, *cres, *tres;
486 struct hastd_listen *nlst, *clst;
487 struct pidfh *newpfh;
488 unsigned int nlisten;
492 pjdlog_info("Reloading configuration...");
496 newcfg = yy_config_parse(cfgpath, false);
501 * Check if control address has changed.
503 if (strcmp(cfg->hc_controladdr, newcfg->hc_controladdr) != 0) {
504 if (proto_server(newcfg->hc_controladdr,
505 &newcfg->hc_controlconn) == -1) {
506 pjdlog_errno(LOG_ERR,
507 "Unable to listen on control address %s",
508 newcfg->hc_controladdr);
513 * Check if any listen address has changed.
516 TAILQ_FOREACH(nlst, &newcfg->hc_listen, hl_next) {
517 TAILQ_FOREACH(clst, &cfg->hc_listen, hl_next) {
518 if (strcmp(nlst->hl_addr, clst->hl_addr) == 0)
521 if (clst != NULL && clst->hl_conn != NULL) {
522 pjdlog_info("Keep listening on address %s.",
524 nlst->hl_conn = clst->hl_conn;
526 } else if (proto_server(nlst->hl_addr, &nlst->hl_conn) == 0) {
527 pjdlog_info("Listening on new address %s.",
531 pjdlog_errno(LOG_WARNING,
532 "Unable to listen on address %s", nlst->hl_addr);
536 pjdlog_error("No addresses to listen on.");
540 * Check if pidfile's path has changed.
542 if (!foreground && pidfile == NULL &&
543 strcmp(cfg->hc_pidfile, newcfg->hc_pidfile) != 0) {
544 newpfh = pidfile_open(newcfg->hc_pidfile, 0600, &otherpid);
545 if (newpfh == NULL) {
546 if (errno == EEXIST) {
547 pjdlog_errno(LOG_WARNING,
548 "Another hastd is already running, pidfile: %s, pid: %jd.",
549 newcfg->hc_pidfile, (intmax_t)otherpid);
551 pjdlog_errno(LOG_WARNING,
552 "Unable to open or create pidfile %s",
555 } else if (pidfile_write(newpfh) == -1) {
556 /* Write PID to a file. */
557 pjdlog_errno(LOG_WARNING,
558 "Unable to write PID to file %s",
561 pjdlog_debug(1, "PID stored in %s.",
566 /* No failures from now on. */
569 * Switch to new control socket.
571 if (newcfg->hc_controlconn != NULL) {
572 pjdlog_info("Control socket changed from %s to %s.",
573 cfg->hc_controladdr, newcfg->hc_controladdr);
574 proto_close(cfg->hc_controlconn);
575 cfg->hc_controlconn = newcfg->hc_controlconn;
576 newcfg->hc_controlconn = NULL;
577 strlcpy(cfg->hc_controladdr, newcfg->hc_controladdr,
578 sizeof(cfg->hc_controladdr));
581 * Switch to new pidfile.
583 if (newpfh != NULL) {
584 pjdlog_info("Pidfile changed from %s to %s.", cfg->hc_pidfile,
586 (void)pidfile_remove(pfh);
588 (void)strlcpy(cfg->hc_pidfile, newcfg->hc_pidfile,
589 sizeof(cfg->hc_pidfile));
592 * Switch to new listen addresses. Close all that were removed.
594 while ((clst = TAILQ_FIRST(&cfg->hc_listen)) != NULL) {
595 TAILQ_FOREACH(nlst, &newcfg->hc_listen, hl_next) {
596 if (strcmp(nlst->hl_addr, clst->hl_addr) == 0)
599 if (nlst == NULL && clst->hl_conn != NULL) {
600 proto_close(clst->hl_conn);
601 pjdlog_info("No longer listening on address %s.",
604 TAILQ_REMOVE(&cfg->hc_listen, clst, hl_next);
607 TAILQ_CONCAT(&cfg->hc_listen, &newcfg->hc_listen, hl_next);
610 * Stop and remove resources that were removed from the configuration.
612 TAILQ_FOREACH_SAFE(cres, &cfg->hc_resources, hr_next, tres) {
613 TAILQ_FOREACH(nres, &newcfg->hc_resources, hr_next) {
614 if (strcmp(cres->hr_name, nres->hr_name) == 0)
618 control_set_role(cres, HAST_ROLE_INIT);
619 TAILQ_REMOVE(&cfg->hc_resources, cres, hr_next);
620 pjdlog_info("Resource %s removed.", cres->hr_name);
625 * Move new resources to the current configuration.
627 TAILQ_FOREACH_SAFE(nres, &newcfg->hc_resources, hr_next, tres) {
628 TAILQ_FOREACH(cres, &cfg->hc_resources, hr_next) {
629 if (strcmp(cres->hr_name, nres->hr_name) == 0)
633 TAILQ_REMOVE(&newcfg->hc_resources, nres, hr_next);
634 TAILQ_INSERT_TAIL(&cfg->hc_resources, nres, hr_next);
635 pjdlog_info("Resource %s added.", nres->hr_name);
639 * Deal with modified resources.
640 * Depending on what has changed exactly we might want to perform
643 * We do full resource restart in the following situations:
644 * Resource role is INIT or SECONDARY.
645 * Resource role is PRIMARY and path to local component or provider
647 * In case of PRIMARY, the worker process will be killed and restarted,
648 * which also means removing /dev/hast/<name> provider and
651 * We do just reload (send SIGHUP to worker process) if we act as
652 * PRIMARY, but only if remote address, source address, replication
653 * mode, timeout, execution path or metaflush has changed.
654 * For those, there is no need to restart worker process.
655 * If PRIMARY receives SIGHUP, it will reconnect if remote address or
656 * source address has changed or it will set new timeout if only timeout
657 * has changed or it will update metaflush if only metaflush has
660 TAILQ_FOREACH_SAFE(nres, &newcfg->hc_resources, hr_next, tres) {
661 TAILQ_FOREACH(cres, &cfg->hc_resources, hr_next) {
662 if (strcmp(cres->hr_name, nres->hr_name) == 0)
665 PJDLOG_ASSERT(cres != NULL);
666 if (resource_needs_restart(cres, nres)) {
667 pjdlog_info("Resource %s configuration was modified, restarting it.",
669 role = cres->hr_role;
670 control_set_role(cres, HAST_ROLE_INIT);
671 TAILQ_REMOVE(&cfg->hc_resources, cres, hr_next);
673 TAILQ_REMOVE(&newcfg->hc_resources, nres, hr_next);
674 TAILQ_INSERT_TAIL(&cfg->hc_resources, nres, hr_next);
675 control_set_role(nres, role);
676 } else if (resource_needs_reload(cres, nres)) {
677 pjdlog_info("Resource %s configuration was modified, reloading it.",
679 strlcpy(cres->hr_remoteaddr, nres->hr_remoteaddr,
680 sizeof(cres->hr_remoteaddr));
681 strlcpy(cres->hr_sourceaddr, nres->hr_sourceaddr,
682 sizeof(cres->hr_sourceaddr));
683 cres->hr_replication = nres->hr_replication;
684 cres->hr_checksum = nres->hr_checksum;
685 cres->hr_compression = nres->hr_compression;
686 cres->hr_timeout = nres->hr_timeout;
687 strlcpy(cres->hr_exec, nres->hr_exec,
688 sizeof(cres->hr_exec));
689 cres->hr_metaflush = nres->hr_metaflush;
690 if (cres->hr_workerpid != 0)
691 resource_reload(cres);
695 yy_config_free(newcfg);
696 pjdlog_info("Configuration reloaded successfully.");
699 if (newcfg != NULL) {
700 if (newcfg->hc_controlconn != NULL)
701 proto_close(newcfg->hc_controlconn);
702 while ((nlst = TAILQ_FIRST(&newcfg->hc_listen)) != NULL) {
703 if (nlst->hl_conn != NULL) {
704 TAILQ_FOREACH(clst, &cfg->hc_listen, hl_next) {
705 if (strcmp(nlst->hl_addr,
706 clst->hl_addr) == 0) {
710 if (clst == NULL || clst->hl_conn == NULL)
711 proto_close(nlst->hl_conn);
713 TAILQ_REMOVE(&newcfg->hc_listen, nlst, hl_next);
716 yy_config_free(newcfg);
719 (void)pidfile_remove(newpfh);
720 pjdlog_warning("Configuration not reloaded.");
724 terminate_workers(void)
726 struct hast_resource *res;
728 pjdlog_info("Termination signal received, exiting.");
729 TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
730 if (res->hr_workerpid == 0)
732 pjdlog_info("Terminating worker process (resource=%s, role=%s, pid=%u).",
733 res->hr_name, role2str(res->hr_role), res->hr_workerpid);
734 if (kill(res->hr_workerpid, SIGTERM) == 0)
736 pjdlog_errno(LOG_WARNING,
737 "Unable to send signal to worker process (resource=%s, role=%s, pid=%u).",
738 res->hr_name, role2str(res->hr_role), res->hr_workerpid);
743 listen_accept(struct hastd_listen *lst)
745 struct hast_resource *res;
746 struct proto_conn *conn;
747 struct nv *nvin, *nvout, *nverr;
749 const unsigned char *token;
750 char laddr[256], raddr[256];
756 proto_local_address(lst->hl_conn, laddr, sizeof(laddr));
757 pjdlog_debug(1, "Accepting connection to %s.", laddr);
759 if (proto_accept(lst->hl_conn, &conn) == -1) {
760 pjdlog_errno(LOG_ERR, "Unable to accept connection %s", laddr);
764 proto_local_address(conn, laddr, sizeof(laddr));
765 proto_remote_address(conn, raddr, sizeof(raddr));
766 pjdlog_info("Connection from %s to %s.", raddr, laddr);
768 /* Error in setting timeout is not critical, but why should it fail? */
769 if (proto_timeout(conn, HAST_TIMEOUT) == -1)
770 pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
772 nvin = nvout = nverr = NULL;
775 * Before receiving any data see if remote host have access to any
778 TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
779 if (proto_address_match(conn, res->hr_remoteaddr))
783 pjdlog_error("Client %s isn't known.", raddr);
786 /* Ok, remote host can access at least one resource. */
788 if (hast_proto_recv_hdr(conn, &nvin) == -1) {
789 pjdlog_errno(LOG_ERR, "Unable to receive header from %s",
794 resname = nv_get_string(nvin, "resource");
795 if (resname == NULL) {
796 pjdlog_error("No 'resource' field in the header received from %s.",
800 pjdlog_debug(2, "%s: resource=%s", raddr, resname);
801 version = nv_get_uint8(nvin, "version");
802 pjdlog_debug(2, "%s: version=%hhu", raddr, version);
805 * If no version is sent, it means this is protocol version 1.
809 token = nv_get_uint8_array(nvin, &size, "token");
811 * NULL token means that this is first connection.
813 if (token != NULL && size != sizeof(res->hr_token)) {
814 pjdlog_error("Received token of invalid size from %s (expected %zu, got %zu).",
815 raddr, sizeof(res->hr_token), size);
820 * From now on we want to send errors to the remote node.
824 /* Find resource related to this connection. */
825 TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
826 if (strcmp(resname, res->hr_name) == 0)
829 /* Have we found the resource? */
831 pjdlog_error("No resource '%s' as requested by %s.",
833 nv_add_stringf(nverr, "errmsg", "Resource not configured.");
837 /* Now that we know resource name setup log prefix. */
838 pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
840 /* Does the remote host have access to this resource? */
841 if (!proto_address_match(conn, res->hr_remoteaddr)) {
842 pjdlog_error("Client %s has no access to the resource.", raddr);
843 nv_add_stringf(nverr, "errmsg", "No access to the resource.");
846 /* Is the resource marked as secondary? */
847 if (res->hr_role != HAST_ROLE_SECONDARY) {
848 pjdlog_warning("We act as %s for the resource and not as %s as requested by %s.",
849 role2str(res->hr_role), role2str(HAST_ROLE_SECONDARY),
851 nv_add_stringf(nverr, "errmsg",
852 "Remote node acts as %s for the resource and not as %s.",
853 role2str(res->hr_role), role2str(HAST_ROLE_SECONDARY));
854 if (res->hr_role == HAST_ROLE_PRIMARY) {
856 * If we act as primary request the other side to wait
857 * for us a bit, as we might be finishing cleanups.
859 nv_add_uint8(nverr, 1, "wait");
863 /* Does token (if exists) match? */
864 if (token != NULL && memcmp(token, res->hr_token,
865 sizeof(res->hr_token)) != 0) {
866 pjdlog_error("Token received from %s doesn't match.", raddr);
867 nv_add_stringf(nverr, "errmsg", "Token doesn't match.");
871 * If there is no token, but we have half-open connection
872 * (only remotein) or full connection (worker process is running)
873 * we have to cancel those and accept the new connection.
876 PJDLOG_ASSERT(res->hr_remoteout == NULL);
877 pjdlog_debug(1, "Initial connection from %s.", raddr);
878 if (res->hr_workerpid != 0) {
879 PJDLOG_ASSERT(res->hr_remotein == NULL);
881 "Worker process exists (pid=%u), stopping it.",
882 (unsigned int)res->hr_workerpid);
883 /* Stop child process. */
884 if (kill(res->hr_workerpid, SIGINT) == -1) {
885 pjdlog_errno(LOG_ERR,
886 "Unable to stop worker process (pid=%u)",
887 (unsigned int)res->hr_workerpid);
889 * Other than logging the problem we
890 * ignore it - nothing smart to do.
893 /* Wait for it to exit. */
894 else if ((pid = waitpid(res->hr_workerpid,
895 &status, 0)) != res->hr_workerpid) {
896 /* We can only log the problem. */
897 pjdlog_errno(LOG_ERR,
898 "Waiting for worker process (pid=%u) failed",
899 (unsigned int)res->hr_workerpid);
901 child_exit_log(res->hr_workerpid, status);
904 } else if (res->hr_remotein != NULL) {
907 proto_remote_address(res->hr_remotein, oaddr,
910 "Canceling half-open connection from %s on connection from %s.",
912 proto_close(res->hr_remotein);
913 res->hr_remotein = NULL;
918 * Checks and cleanups are done.
922 if (version > HAST_PROTO_VERSION) {
923 pjdlog_info("Remote protocol version %hhu is not supported, falling back to version %hhu.",
924 version, (unsigned char)HAST_PROTO_VERSION);
925 version = HAST_PROTO_VERSION;
927 pjdlog_debug(1, "Negotiated protocol version %hhu.", version);
928 res->hr_version = version;
929 arc4random_buf(res->hr_token, sizeof(res->hr_token));
931 nv_add_uint8(nvout, version, "version");
932 nv_add_uint8_array(nvout, res->hr_token,
933 sizeof(res->hr_token), "token");
934 if (nv_error(nvout) != 0) {
935 pjdlog_common(LOG_ERR, 0, nv_error(nvout),
936 "Unable to prepare return header for %s", raddr);
937 nv_add_stringf(nverr, "errmsg",
938 "Remote node was unable to prepare return header: %s.",
939 strerror(nv_error(nvout)));
942 if (hast_proto_send(res, conn, nvout, NULL, 0) == -1) {
945 pjdlog_errno(LOG_ERR, "Unable to send response to %s",
947 nv_add_stringf(nverr, "errmsg",
948 "Remote node was unable to send response: %s.",
952 res->hr_remotein = conn;
953 pjdlog_debug(1, "Incoming connection from %s configured.",
956 res->hr_remoteout = conn;
957 pjdlog_debug(1, "Outgoing connection to %s configured.", raddr);
958 hastd_secondary(res, nvin);
963 pjdlog_prefix_set("%s", "");
966 if (nv_error(nverr) != 0) {
967 pjdlog_common(LOG_ERR, 0, nv_error(nverr),
968 "Unable to prepare error header for %s", raddr);
971 if (hast_proto_send(NULL, conn, nverr, NULL, 0) == -1) {
972 pjdlog_errno(LOG_ERR, "Unable to send error to %s", raddr);
983 pjdlog_prefix_set("%s", "");
987 connection_migrate(struct hast_resource *res)
989 struct proto_conn *conn;
992 pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
994 PJDLOG_ASSERT(res->hr_role == HAST_ROLE_PRIMARY);
996 if (proto_recv(res->hr_conn, &val, sizeof(val)) == -1) {
997 pjdlog_errno(LOG_WARNING,
998 "Unable to receive connection command");
1001 if (proto_client(res->hr_sourceaddr[0] != '\0' ? res->hr_sourceaddr : NULL,
1002 res->hr_remoteaddr, &conn) == -1) {
1004 pjdlog_errno(LOG_WARNING,
1005 "Unable to create outgoing connection to %s",
1006 res->hr_remoteaddr);
1009 if (proto_connect(conn, -1) == -1) {
1011 pjdlog_errno(LOG_WARNING, "Unable to connect to %s",
1012 res->hr_remoteaddr);
1018 if (proto_send(res->hr_conn, &val, sizeof(val)) == -1) {
1019 pjdlog_errno(LOG_WARNING,
1020 "Unable to send reply to connection request");
1022 if (val == 0 && proto_connection_send(res->hr_conn, conn) == -1)
1023 pjdlog_errno(LOG_WARNING, "Unable to send connection");
1025 pjdlog_prefix_set("%s", "");
1031 struct timespec sigtimeout;
1035 sigtimeout.tv_sec = 0;
1036 sigtimeout.tv_nsec = 0;
1038 PJDLOG_VERIFY(sigemptyset(&mask) == 0);
1039 PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0);
1040 PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
1041 PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
1042 PJDLOG_VERIFY(sigaddset(&mask, SIGCHLD) == 0);
1044 while ((signo = sigtimedwait(&mask, NULL, &sigtimeout)) != -1) {
1048 sigexit_received = true;
1049 terminate_workers();
1050 proto_close(cfg->hc_controlconn);
1060 PJDLOG_ABORT("Unexpected signal (%d).", signo);
1068 struct hast_resource *res;
1069 struct hastd_listen *lst;
1070 struct timeval seltimeout;
1072 time_t lastcheck, now;
1075 lastcheck = time(NULL);
1076 seltimeout.tv_sec = REPORT_INTERVAL;
1077 seltimeout.tv_usec = 0;
1082 /* Setup descriptors for select(2). */
1084 maxfd = fd = proto_descriptor(cfg->hc_controlconn);
1085 PJDLOG_ASSERT(fd >= 0);
1087 TAILQ_FOREACH(lst, &cfg->hc_listen, hl_next) {
1088 if (lst->hl_conn == NULL)
1090 fd = proto_descriptor(lst->hl_conn);
1091 PJDLOG_ASSERT(fd >= 0);
1093 maxfd = fd > maxfd ? fd : maxfd;
1095 TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
1096 if (res->hr_event == NULL)
1098 fd = proto_descriptor(res->hr_event);
1099 PJDLOG_ASSERT(fd >= 0);
1101 maxfd = fd > maxfd ? fd : maxfd;
1102 if (res->hr_role == HAST_ROLE_PRIMARY) {
1103 /* Only primary workers asks for connections. */
1104 PJDLOG_ASSERT(res->hr_conn != NULL);
1105 fd = proto_descriptor(res->hr_conn);
1106 PJDLOG_ASSERT(fd >= 0);
1108 maxfd = fd > maxfd ? fd : maxfd;
1110 PJDLOG_ASSERT(res->hr_conn == NULL);
1114 PJDLOG_ASSERT(maxfd + 1 <= (int)FD_SETSIZE);
1115 ret = select(maxfd + 1, &rfds, NULL, NULL, &seltimeout);
1117 if (lastcheck + REPORT_INTERVAL <= now) {
1123 * select(2) timed out, so there should be no
1124 * descriptors to check.
1127 } else if (ret == -1) {
1130 KEEP_ERRNO((void)pidfile_remove(pfh));
1131 pjdlog_exit(EX_OSERR, "select() failed");
1135 * Check for signals before we do anything to update our
1136 * info about terminated workers in the meantime.
1140 if (FD_ISSET(proto_descriptor(cfg->hc_controlconn), &rfds))
1141 control_handle(cfg);
1142 TAILQ_FOREACH(lst, &cfg->hc_listen, hl_next) {
1143 if (lst->hl_conn == NULL)
1145 if (FD_ISSET(proto_descriptor(lst->hl_conn), &rfds))
1148 TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
1149 if (res->hr_event == NULL)
1151 if (FD_ISSET(proto_descriptor(res->hr_event), &rfds)) {
1152 if (event_recv(res) == 0)
1154 /* The worker process exited? */
1155 proto_close(res->hr_event);
1156 res->hr_event = NULL;
1157 if (res->hr_conn != NULL) {
1158 proto_close(res->hr_conn);
1159 res->hr_conn = NULL;
1163 if (res->hr_role == HAST_ROLE_PRIMARY) {
1164 PJDLOG_ASSERT(res->hr_conn != NULL);
1165 if (FD_ISSET(proto_descriptor(res->hr_conn),
1167 connection_migrate(res);
1170 PJDLOG_ASSERT(res->hr_conn == NULL);
1177 dummy_sighandler(int sig __unused)
1179 /* Nothing to do. */
1183 main(int argc, char *argv[])
1185 struct hastd_listen *lst;
1196 ch = getopt(argc, argv, "c:dFhP:");
1220 pjdlog_init(PJDLOG_MODE_STD);
1221 pjdlog_debug_set(debuglevel);
1226 * When path to the configuration file is relative, obtain full path,
1227 * so we can always find the file, even after daemonizing and changing
1228 * working directory to /.
1230 if (cfgpath[0] != '/') {
1231 const char *newcfgpath;
1233 newcfgpath = realpath(cfgpath, NULL);
1234 if (newcfgpath == NULL) {
1235 pjdlog_exit(EX_CONFIG,
1236 "Unable to obtain full path of %s", cfgpath);
1238 cfgpath = newcfgpath;
1241 cfg = yy_config_parse(cfgpath, true);
1242 PJDLOG_ASSERT(cfg != NULL);
1244 if (pidfile != NULL) {
1245 if (strlcpy(cfg->hc_pidfile, pidfile,
1246 sizeof(cfg->hc_pidfile)) >= sizeof(cfg->hc_pidfile)) {
1247 pjdlog_exitx(EX_CONFIG, "Pidfile path is too long.");
1251 if (pidfile != NULL || !foreground) {
1252 pfh = pidfile_open(cfg->hc_pidfile, 0600, &otherpid);
1254 if (errno == EEXIST) {
1255 pjdlog_exitx(EX_TEMPFAIL,
1256 "Another hastd is already running, pidfile: %s, pid: %jd.",
1257 cfg->hc_pidfile, (intmax_t)otherpid);
1260 * If we cannot create pidfile for other reasons,
1263 pjdlog_errno(LOG_WARNING,
1264 "Unable to open or create pidfile %s",
1270 * Restore default actions for interesting signals in case parent
1271 * process (like init(8)) decided to ignore some of them (like SIGHUP).
1273 PJDLOG_VERIFY(signal(SIGHUP, SIG_DFL) != SIG_ERR);
1274 PJDLOG_VERIFY(signal(SIGINT, SIG_DFL) != SIG_ERR);
1275 PJDLOG_VERIFY(signal(SIGTERM, SIG_DFL) != SIG_ERR);
1277 * Because SIGCHLD is ignored by default, setup dummy handler for it,
1278 * so we can mask it.
1280 PJDLOG_VERIFY(signal(SIGCHLD, dummy_sighandler) != SIG_ERR);
1282 PJDLOG_VERIFY(sigemptyset(&mask) == 0);
1283 PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0);
1284 PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
1285 PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
1286 PJDLOG_VERIFY(sigaddset(&mask, SIGCHLD) == 0);
1287 PJDLOG_VERIFY(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
1289 /* Listen on control address. */
1290 if (proto_server(cfg->hc_controladdr, &cfg->hc_controlconn) == -1) {
1291 KEEP_ERRNO((void)pidfile_remove(pfh));
1292 pjdlog_exit(EX_OSERR, "Unable to listen on control address %s",
1293 cfg->hc_controladdr);
1295 /* Listen for remote connections. */
1296 TAILQ_FOREACH(lst, &cfg->hc_listen, hl_next) {
1297 if (proto_server(lst->hl_addr, &lst->hl_conn) == -1) {
1298 KEEP_ERRNO((void)pidfile_remove(pfh));
1299 pjdlog_exit(EX_OSERR, "Unable to listen on address %s",
1305 if (daemon(0, 0) == -1) {
1306 KEEP_ERRNO((void)pidfile_remove(pfh));
1307 pjdlog_exit(EX_OSERR, "Unable to daemonize");
1310 /* Start logging to syslog. */
1311 pjdlog_mode_set(PJDLOG_MODE_SYSLOG);
1313 if (pidfile != NULL || !foreground) {
1314 /* Write PID to a file. */
1315 if (pidfile_write(pfh) == -1) {
1316 pjdlog_errno(LOG_WARNING,
1317 "Unable to write PID to a file %s",
1320 pjdlog_debug(1, "PID stored in %s.", cfg->hc_pidfile);
1324 pjdlog_info("Started successfully, running protocol version %d.",
1325 HAST_PROTO_VERSION);
1327 pjdlog_debug(1, "Listening on control address %s.",
1328 cfg->hc_controladdr);
1329 TAILQ_FOREACH(lst, &cfg->hc_listen, hl_next)
1330 pjdlog_info("Listening on address %s.", lst->hl_addr);