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. */
71 /* Do we run in foreground? */
72 static bool foreground;
74 /* How often check for hooks running for too long. */
75 #define REPORT_INTERVAL 5
81 errx(EX_USAGE, "[-dFh] [-c config] [-P pidfile]");
88 if (modfind("g_gate") == -1) {
89 /* Not present in kernel, try loading it. */
90 if (kldload("geom_gate") == -1 || modfind("g_gate") == -1) {
91 if (errno != EEXIST) {
93 "Unable to load geom_gate module");
100 descriptors_cleanup(struct hast_resource *res)
102 struct hast_resource *tres, *tmres;
103 struct hastd_listen *lst;
105 TAILQ_FOREACH_SAFE(tres, &cfg->hc_resources, hr_next, tmres) {
107 PJDLOG_VERIFY(res->hr_role == HAST_ROLE_SECONDARY ||
108 (res->hr_remotein == NULL &&
109 res->hr_remoteout == NULL));
112 if (tres->hr_remotein != NULL)
113 proto_close(tres->hr_remotein);
114 if (tres->hr_remoteout != NULL)
115 proto_close(tres->hr_remoteout);
116 if (tres->hr_ctrl != NULL)
117 proto_close(tres->hr_ctrl);
118 if (tres->hr_event != NULL)
119 proto_close(tres->hr_event);
120 if (tres->hr_conn != NULL)
121 proto_close(tres->hr_conn);
122 TAILQ_REMOVE(&cfg->hc_resources, tres, hr_next);
125 if (cfg->hc_controlin != NULL)
126 proto_close(cfg->hc_controlin);
127 proto_close(cfg->hc_controlconn);
128 while ((lst = TAILQ_FIRST(&cfg->hc_listen)) != NULL) {
129 TAILQ_REMOVE(&cfg->hc_listen, lst, hl_next);
130 if (lst->hl_conn != NULL)
131 proto_close(lst->hl_conn);
134 (void)pidfile_close(pfh);
140 dtype2str(mode_t mode)
144 return ("block device");
145 else if (S_ISCHR(mode))
146 return ("character device");
147 else if (S_ISDIR(mode))
148 return ("directory");
149 else if (S_ISFIFO(mode))
150 return ("pipe or FIFO");
151 else if (S_ISLNK(mode))
152 return ("symbolic link");
153 else if (S_ISREG(mode))
154 return ("regular file");
155 else if (S_ISSOCK(mode))
157 else if (S_ISWHT(mode))
164 descriptors_assert(const struct hast_resource *res, int pjdlogmode)
174 * At this point descriptor to syslog socket is closed, so if we want
175 * to log assertion message, we have to first store it in 'msg' local
176 * buffer and then open syslog socket and log it.
180 maxfd = sysconf(_SC_OPEN_MAX);
182 pjdlog_init(pjdlogmode);
183 pjdlog_prefix_set("[%s] (%s) ", res->hr_name,
184 role2str(res->hr_role));
185 pjdlog_errno(LOG_WARNING, "sysconf(_SC_OPEN_MAX) failed");
189 for (fd = 0; fd <= maxfd; fd++) {
190 if (fstat(fd, &sb) == 0) {
193 } else if (errno == EBADF) {
197 (void)snprintf(msg, sizeof(msg),
198 "Unable to fstat descriptor %d: %s", fd,
202 if (fd == STDIN_FILENO || fd == STDOUT_FILENO ||
203 fd == STDERR_FILENO) {
205 (void)snprintf(msg, sizeof(msg),
206 "Descriptor %d (%s) is closed, but should be open.",
207 fd, (fd == STDIN_FILENO ? "stdin" :
208 (fd == STDOUT_FILENO ? "stdout" : "stderr")));
211 } else if (fd == proto_descriptor(res->hr_event)) {
213 (void)snprintf(msg, sizeof(msg),
214 "Descriptor %d (event) is closed, but should be open.",
218 if (!S_ISSOCK(mode)) {
219 (void)snprintf(msg, sizeof(msg),
220 "Descriptor %d (event) is %s, but should be %s.",
221 fd, dtype2str(mode), dtype2str(S_IFSOCK));
224 } else if (fd == proto_descriptor(res->hr_ctrl)) {
226 (void)snprintf(msg, sizeof(msg),
227 "Descriptor %d (ctrl) is closed, but should be open.",
231 if (!S_ISSOCK(mode)) {
232 (void)snprintf(msg, sizeof(msg),
233 "Descriptor %d (ctrl) is %s, but should be %s.",
234 fd, dtype2str(mode), dtype2str(S_IFSOCK));
237 } else if (res->hr_role == HAST_ROLE_PRIMARY &&
238 fd == proto_descriptor(res->hr_conn)) {
240 (void)snprintf(msg, sizeof(msg),
241 "Descriptor %d (conn) is closed, but should be open.",
245 if (!S_ISSOCK(mode)) {
246 (void)snprintf(msg, sizeof(msg),
247 "Descriptor %d (conn) is %s, but should be %s.",
248 fd, dtype2str(mode), dtype2str(S_IFSOCK));
251 } else if (res->hr_role == HAST_ROLE_SECONDARY &&
252 res->hr_conn != NULL &&
253 fd == proto_descriptor(res->hr_conn)) {
255 (void)snprintf(msg, sizeof(msg),
256 "Descriptor %d (conn) is open, but should be closed.",
260 } else if (res->hr_role == HAST_ROLE_SECONDARY &&
261 fd == proto_descriptor(res->hr_remotein)) {
263 (void)snprintf(msg, sizeof(msg),
264 "Descriptor %d (remote in) is closed, but should be open.",
268 if (!S_ISSOCK(mode)) {
269 (void)snprintf(msg, sizeof(msg),
270 "Descriptor %d (remote in) is %s, but should be %s.",
271 fd, dtype2str(mode), dtype2str(S_IFSOCK));
274 } else if (res->hr_role == HAST_ROLE_SECONDARY &&
275 fd == proto_descriptor(res->hr_remoteout)) {
277 (void)snprintf(msg, sizeof(msg),
278 "Descriptor %d (remote out) is closed, but should be open.",
282 if (!S_ISSOCK(mode)) {
283 (void)snprintf(msg, sizeof(msg),
284 "Descriptor %d (remote out) is %s, but should be %s.",
285 fd, dtype2str(mode), dtype2str(S_IFSOCK));
290 (void)snprintf(msg, sizeof(msg),
291 "Descriptor %d is open (%s), but should be closed.",
292 fd, dtype2str(mode));
297 if (msg[0] != '\0') {
298 pjdlog_init(pjdlogmode);
299 pjdlog_prefix_set("[%s] (%s) ", res->hr_name,
300 role2str(res->hr_role));
301 PJDLOG_ABORT("%s", msg);
306 child_exit_log(unsigned int pid, int status)
309 if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
310 pjdlog_debug(1, "Worker process exited gracefully (pid=%u).",
312 } else if (WIFSIGNALED(status)) {
313 pjdlog_error("Worker process killed (pid=%u, signal=%d).",
314 pid, WTERMSIG(status));
316 pjdlog_error("Worker process exited ungracefully (pid=%u, exitcode=%d).",
317 pid, WIFEXITED(status) ? WEXITSTATUS(status) : -1);
324 struct hast_resource *res;
328 while ((pid = wait3(&status, WNOHANG, NULL)) > 0) {
329 /* Find resource related to the process that just exited. */
330 TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
331 if (pid == res->hr_workerpid)
336 * This can happen when new connection arrives and we
337 * cancel child responsible for the old one or if this
338 * was hook which we executed.
340 hook_check_one(pid, status);
343 pjdlog_prefix_set("[%s] (%s) ", res->hr_name,
344 role2str(res->hr_role));
345 child_exit_log(pid, status);
347 if (res->hr_role == HAST_ROLE_PRIMARY) {
349 * Restart child process if it was killed by signal
350 * or exited because of temporary problem.
352 if (WIFSIGNALED(status) ||
353 (WIFEXITED(status) &&
354 WEXITSTATUS(status) == EX_TEMPFAIL)) {
356 pjdlog_info("Restarting worker process.");
359 res->hr_role = HAST_ROLE_INIT;
360 pjdlog_info("Changing resource role back to %s.",
361 role2str(res->hr_role));
364 pjdlog_prefix_set("%s", "");
369 resource_needs_restart(const struct hast_resource *res0,
370 const struct hast_resource *res1)
373 PJDLOG_ASSERT(strcmp(res0->hr_name, res1->hr_name) == 0);
375 if (strcmp(res0->hr_provname, res1->hr_provname) != 0)
377 if (strcmp(res0->hr_localpath, res1->hr_localpath) != 0)
379 if (res0->hr_role == HAST_ROLE_INIT ||
380 res0->hr_role == HAST_ROLE_SECONDARY) {
381 if (strcmp(res0->hr_remoteaddr, res1->hr_remoteaddr) != 0)
383 if (strcmp(res0->hr_sourceaddr, res1->hr_sourceaddr) != 0)
385 if (res0->hr_replication != res1->hr_replication)
387 if (res0->hr_checksum != res1->hr_checksum)
389 if (res0->hr_compression != res1->hr_compression)
391 if (res0->hr_timeout != res1->hr_timeout)
393 if (strcmp(res0->hr_exec, res1->hr_exec) != 0)
396 * When metaflush has changed we don't really need restart,
397 * but it is just easier this way.
399 if (res0->hr_metaflush != res1->hr_metaflush)
406 resource_needs_reload(const struct hast_resource *res0,
407 const struct hast_resource *res1)
410 PJDLOG_ASSERT(strcmp(res0->hr_name, res1->hr_name) == 0);
411 PJDLOG_ASSERT(strcmp(res0->hr_provname, res1->hr_provname) == 0);
412 PJDLOG_ASSERT(strcmp(res0->hr_localpath, res1->hr_localpath) == 0);
414 if (res0->hr_role != HAST_ROLE_PRIMARY)
417 if (strcmp(res0->hr_remoteaddr, res1->hr_remoteaddr) != 0)
419 if (strcmp(res0->hr_sourceaddr, res1->hr_sourceaddr) != 0)
421 if (res0->hr_replication != res1->hr_replication)
423 if (res0->hr_checksum != res1->hr_checksum)
425 if (res0->hr_compression != res1->hr_compression)
427 if (res0->hr_timeout != res1->hr_timeout)
429 if (strcmp(res0->hr_exec, res1->hr_exec) != 0)
431 if (res0->hr_metaflush != res1->hr_metaflush)
437 resource_reload(const struct hast_resource *res)
439 struct nv *nvin, *nvout;
442 PJDLOG_ASSERT(res->hr_role == HAST_ROLE_PRIMARY);
445 nv_add_uint8(nvout, CONTROL_RELOAD, "cmd");
446 nv_add_string(nvout, res->hr_remoteaddr, "remoteaddr");
447 nv_add_string(nvout, res->hr_sourceaddr, "sourceaddr");
448 nv_add_int32(nvout, (int32_t)res->hr_replication, "replication");
449 nv_add_int32(nvout, (int32_t)res->hr_checksum, "checksum");
450 nv_add_int32(nvout, (int32_t)res->hr_compression, "compression");
451 nv_add_int32(nvout, (int32_t)res->hr_timeout, "timeout");
452 nv_add_string(nvout, res->hr_exec, "exec");
453 nv_add_int32(nvout, (int32_t)res->hr_metaflush, "metaflush");
454 if (nv_error(nvout) != 0) {
456 pjdlog_error("Unable to allocate header for reload message.");
459 if (hast_proto_send(res, res->hr_ctrl, nvout, NULL, 0) == -1) {
460 pjdlog_errno(LOG_ERR, "Unable to send reload message");
466 /* Receive response. */
467 if (hast_proto_recv_hdr(res->hr_ctrl, &nvin) == -1) {
468 pjdlog_errno(LOG_ERR, "Unable to receive reload reply");
471 error = nv_get_int16(nvin, "error");
474 pjdlog_common(LOG_ERR, 0, error, "Reload failed");
482 struct hastd_config *newcfg;
483 struct hast_resource *nres, *cres, *tres;
484 struct hastd_listen *nlst, *clst;
485 struct pidfh *newpfh;
486 unsigned int nlisten;
490 pjdlog_info("Reloading configuration...");
494 newcfg = yy_config_parse(cfgpath, false);
499 * Check if control address has changed.
501 if (strcmp(cfg->hc_controladdr, newcfg->hc_controladdr) != 0) {
502 if (proto_server(newcfg->hc_controladdr,
503 &newcfg->hc_controlconn) == -1) {
504 pjdlog_errno(LOG_ERR,
505 "Unable to listen on control address %s",
506 newcfg->hc_controladdr);
511 * Check if any listen address has changed.
514 TAILQ_FOREACH(nlst, &newcfg->hc_listen, hl_next) {
515 TAILQ_FOREACH(clst, &cfg->hc_listen, hl_next) {
516 if (strcmp(nlst->hl_addr, clst->hl_addr) == 0)
519 if (clst != NULL && clst->hl_conn != NULL) {
520 pjdlog_info("Keep listening on address %s.",
522 nlst->hl_conn = clst->hl_conn;
524 } else if (proto_server(nlst->hl_addr, &nlst->hl_conn) == 0) {
525 pjdlog_info("Listening on new address %s.",
529 pjdlog_errno(LOG_WARNING,
530 "Unable to listen on address %s", nlst->hl_addr);
534 pjdlog_error("No addresses to listen on.");
538 * Check if pidfile's path has changed.
540 if (!foreground && strcmp(cfg->hc_pidfile, newcfg->hc_pidfile) != 0) {
541 newpfh = pidfile_open(newcfg->hc_pidfile, 0600, &otherpid);
542 if (newpfh == NULL) {
543 if (errno == EEXIST) {
544 pjdlog_errno(LOG_WARNING,
545 "Another hastd is already running, pidfile: %s, pid: %jd.",
546 newcfg->hc_pidfile, (intmax_t)otherpid);
548 pjdlog_errno(LOG_WARNING,
549 "Unable to open or create pidfile %s",
552 } else if (pidfile_write(newpfh) == -1) {
553 /* Write PID to a file. */
554 pjdlog_errno(LOG_WARNING,
555 "Unable to write PID to file %s",
558 pjdlog_debug(1, "PID stored in %s.",
563 /* No failures from now on. */
566 * Switch to new control socket.
568 if (newcfg->hc_controlconn != NULL) {
569 pjdlog_info("Control socket changed from %s to %s.",
570 cfg->hc_controladdr, newcfg->hc_controladdr);
571 proto_close(cfg->hc_controlconn);
572 cfg->hc_controlconn = newcfg->hc_controlconn;
573 newcfg->hc_controlconn = NULL;
574 strlcpy(cfg->hc_controladdr, newcfg->hc_controladdr,
575 sizeof(cfg->hc_controladdr));
578 * Switch to new pidfile.
580 if (newpfh != NULL) {
581 pjdlog_info("Pidfile changed from %s to %s.", cfg->hc_pidfile,
583 (void)pidfile_remove(pfh);
585 (void)strlcpy(cfg->hc_pidfile, newcfg->hc_pidfile,
586 sizeof(cfg->hc_pidfile));
589 * Switch to new listen addresses. Close all that were removed.
591 while ((clst = TAILQ_FIRST(&cfg->hc_listen)) != NULL) {
592 TAILQ_FOREACH(nlst, &newcfg->hc_listen, hl_next) {
593 if (strcmp(nlst->hl_addr, clst->hl_addr) == 0)
596 if (nlst == NULL && clst->hl_conn != NULL) {
597 proto_close(clst->hl_conn);
598 pjdlog_info("No longer listening on address %s.",
601 TAILQ_REMOVE(&cfg->hc_listen, clst, hl_next);
604 TAILQ_CONCAT(&cfg->hc_listen, &newcfg->hc_listen, hl_next);
607 * Stop and remove resources that were removed from the configuration.
609 TAILQ_FOREACH_SAFE(cres, &cfg->hc_resources, hr_next, tres) {
610 TAILQ_FOREACH(nres, &newcfg->hc_resources, hr_next) {
611 if (strcmp(cres->hr_name, nres->hr_name) == 0)
615 control_set_role(cres, HAST_ROLE_INIT);
616 TAILQ_REMOVE(&cfg->hc_resources, cres, hr_next);
617 pjdlog_info("Resource %s removed.", cres->hr_name);
622 * Move new resources to the current configuration.
624 TAILQ_FOREACH_SAFE(nres, &newcfg->hc_resources, hr_next, tres) {
625 TAILQ_FOREACH(cres, &cfg->hc_resources, hr_next) {
626 if (strcmp(cres->hr_name, nres->hr_name) == 0)
630 TAILQ_REMOVE(&newcfg->hc_resources, nres, hr_next);
631 TAILQ_INSERT_TAIL(&cfg->hc_resources, nres, hr_next);
632 pjdlog_info("Resource %s added.", nres->hr_name);
636 * Deal with modified resources.
637 * Depending on what has changed exactly we might want to perform
640 * We do full resource restart in the following situations:
641 * Resource role is INIT or SECONDARY.
642 * Resource role is PRIMARY and path to local component or provider
644 * In case of PRIMARY, the worker process will be killed and restarted,
645 * which also means removing /dev/hast/<name> provider and
648 * We do just reload (send SIGHUP to worker process) if we act as
649 * PRIMARY, but only if remote address, source address, replication
650 * mode, timeout, execution path or metaflush has changed.
651 * For those, there is no need to restart worker process.
652 * If PRIMARY receives SIGHUP, it will reconnect if remote address or
653 * source address has changed or it will set new timeout if only timeout
654 * has changed or it will update metaflush if only metaflush has
657 TAILQ_FOREACH_SAFE(nres, &newcfg->hc_resources, hr_next, tres) {
658 TAILQ_FOREACH(cres, &cfg->hc_resources, hr_next) {
659 if (strcmp(cres->hr_name, nres->hr_name) == 0)
662 PJDLOG_ASSERT(cres != NULL);
663 if (resource_needs_restart(cres, nres)) {
664 pjdlog_info("Resource %s configuration was modified, restarting it.",
666 role = cres->hr_role;
667 control_set_role(cres, HAST_ROLE_INIT);
668 TAILQ_REMOVE(&cfg->hc_resources, cres, hr_next);
670 TAILQ_REMOVE(&newcfg->hc_resources, nres, hr_next);
671 TAILQ_INSERT_TAIL(&cfg->hc_resources, nres, hr_next);
672 control_set_role(nres, role);
673 } else if (resource_needs_reload(cres, nres)) {
674 pjdlog_info("Resource %s configuration was modified, reloading it.",
676 strlcpy(cres->hr_remoteaddr, nres->hr_remoteaddr,
677 sizeof(cres->hr_remoteaddr));
678 strlcpy(cres->hr_sourceaddr, nres->hr_sourceaddr,
679 sizeof(cres->hr_sourceaddr));
680 cres->hr_replication = nres->hr_replication;
681 cres->hr_checksum = nres->hr_checksum;
682 cres->hr_compression = nres->hr_compression;
683 cres->hr_timeout = nres->hr_timeout;
684 strlcpy(cres->hr_exec, nres->hr_exec,
685 sizeof(cres->hr_exec));
686 cres->hr_metaflush = nres->hr_metaflush;
687 if (cres->hr_workerpid != 0)
688 resource_reload(cres);
692 yy_config_free(newcfg);
693 pjdlog_info("Configuration reloaded successfully.");
696 if (newcfg != NULL) {
697 if (newcfg->hc_controlconn != NULL)
698 proto_close(newcfg->hc_controlconn);
699 while ((nlst = TAILQ_FIRST(&newcfg->hc_listen)) != NULL) {
700 if (nlst->hl_conn != NULL) {
701 TAILQ_FOREACH(clst, &cfg->hc_listen, hl_next) {
702 if (strcmp(nlst->hl_addr,
703 clst->hl_addr) == 0) {
707 if (clst == NULL || clst->hl_conn == NULL)
708 proto_close(nlst->hl_conn);
710 TAILQ_REMOVE(&newcfg->hc_listen, nlst, hl_next);
713 yy_config_free(newcfg);
716 (void)pidfile_remove(newpfh);
717 pjdlog_warning("Configuration not reloaded.");
721 terminate_workers(void)
723 struct hast_resource *res;
725 pjdlog_info("Termination signal received, exiting.");
726 TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
727 if (res->hr_workerpid == 0)
729 pjdlog_info("Terminating worker process (resource=%s, role=%s, pid=%u).",
730 res->hr_name, role2str(res->hr_role), res->hr_workerpid);
731 if (kill(res->hr_workerpid, SIGTERM) == 0)
733 pjdlog_errno(LOG_WARNING,
734 "Unable to send signal to worker process (resource=%s, role=%s, pid=%u).",
735 res->hr_name, role2str(res->hr_role), res->hr_workerpid);
740 listen_accept(struct hastd_listen *lst)
742 struct hast_resource *res;
743 struct proto_conn *conn;
744 struct nv *nvin, *nvout, *nverr;
746 const unsigned char *token;
747 char laddr[256], raddr[256];
752 proto_local_address(lst->hl_conn, laddr, sizeof(laddr));
753 pjdlog_debug(1, "Accepting connection to %s.", laddr);
755 if (proto_accept(lst->hl_conn, &conn) == -1) {
756 pjdlog_errno(LOG_ERR, "Unable to accept connection %s", laddr);
760 proto_local_address(conn, laddr, sizeof(laddr));
761 proto_remote_address(conn, raddr, sizeof(raddr));
762 pjdlog_info("Connection from %s to %s.", raddr, laddr);
764 /* Error in setting timeout is not critical, but why should it fail? */
765 if (proto_timeout(conn, HAST_TIMEOUT) == -1)
766 pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
768 nvin = nvout = nverr = NULL;
771 * Before receiving any data see if remote host have access to any
774 TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
775 if (proto_address_match(conn, res->hr_remoteaddr))
779 pjdlog_error("Client %s isn't known.", raddr);
782 /* Ok, remote host can access at least one resource. */
784 if (hast_proto_recv_hdr(conn, &nvin) == -1) {
785 pjdlog_errno(LOG_ERR, "Unable to receive header from %s",
790 resname = nv_get_string(nvin, "resource");
791 if (resname == NULL) {
792 pjdlog_error("No 'resource' field in the header received from %s.",
796 pjdlog_debug(2, "%s: resource=%s", raddr, resname);
797 token = nv_get_uint8_array(nvin, &size, "token");
799 * NULL token means that this is first connection.
801 if (token != NULL && size != sizeof(res->hr_token)) {
802 pjdlog_error("Received token of invalid size from %s (expected %zu, got %zu).",
803 raddr, sizeof(res->hr_token), size);
808 * From now on we want to send errors to the remote node.
812 /* Find resource related to this connection. */
813 TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
814 if (strcmp(resname, res->hr_name) == 0)
817 /* Have we found the resource? */
819 pjdlog_error("No resource '%s' as requested by %s.",
821 nv_add_stringf(nverr, "errmsg", "Resource not configured.");
825 /* Now that we know resource name setup log prefix. */
826 pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
828 /* Does the remote host have access to this resource? */
829 if (!proto_address_match(conn, res->hr_remoteaddr)) {
830 pjdlog_error("Client %s has no access to the resource.", raddr);
831 nv_add_stringf(nverr, "errmsg", "No access to the resource.");
834 /* Is the resource marked as secondary? */
835 if (res->hr_role != HAST_ROLE_SECONDARY) {
836 pjdlog_warning("We act as %s for the resource and not as %s as requested by %s.",
837 role2str(res->hr_role), role2str(HAST_ROLE_SECONDARY),
839 nv_add_stringf(nverr, "errmsg",
840 "Remote node acts as %s for the resource and not as %s.",
841 role2str(res->hr_role), role2str(HAST_ROLE_SECONDARY));
842 if (res->hr_role == HAST_ROLE_PRIMARY) {
844 * If we act as primary request the other side to wait
845 * for us a bit, as we might be finishing cleanups.
847 nv_add_uint8(nverr, 1, "wait");
851 /* Does token (if exists) match? */
852 if (token != NULL && memcmp(token, res->hr_token,
853 sizeof(res->hr_token)) != 0) {
854 pjdlog_error("Token received from %s doesn't match.", raddr);
855 nv_add_stringf(nverr, "errmsg", "Token doesn't match.");
859 * If there is no token, but we have half-open connection
860 * (only remotein) or full connection (worker process is running)
861 * we have to cancel those and accept the new connection.
864 PJDLOG_ASSERT(res->hr_remoteout == NULL);
865 pjdlog_debug(1, "Initial connection from %s.", raddr);
866 if (res->hr_workerpid != 0) {
867 PJDLOG_ASSERT(res->hr_remotein == NULL);
869 "Worker process exists (pid=%u), stopping it.",
870 (unsigned int)res->hr_workerpid);
871 /* Stop child process. */
872 if (kill(res->hr_workerpid, SIGINT) == -1) {
873 pjdlog_errno(LOG_ERR,
874 "Unable to stop worker process (pid=%u)",
875 (unsigned int)res->hr_workerpid);
877 * Other than logging the problem we
878 * ignore it - nothing smart to do.
881 /* Wait for it to exit. */
882 else if ((pid = waitpid(res->hr_workerpid,
883 &status, 0)) != res->hr_workerpid) {
884 /* We can only log the problem. */
885 pjdlog_errno(LOG_ERR,
886 "Waiting for worker process (pid=%u) failed",
887 (unsigned int)res->hr_workerpid);
889 child_exit_log(res->hr_workerpid, status);
892 } else if (res->hr_remotein != NULL) {
895 proto_remote_address(res->hr_remotein, oaddr,
898 "Canceling half-open connection from %s on connection from %s.",
900 proto_close(res->hr_remotein);
901 res->hr_remotein = NULL;
906 * Checks and cleanups are done.
910 arc4random_buf(res->hr_token, sizeof(res->hr_token));
912 nv_add_uint8_array(nvout, res->hr_token,
913 sizeof(res->hr_token), "token");
914 if (nv_error(nvout) != 0) {
915 pjdlog_common(LOG_ERR, 0, nv_error(nvout),
916 "Unable to prepare return header for %s", raddr);
917 nv_add_stringf(nverr, "errmsg",
918 "Remote node was unable to prepare return header: %s.",
919 strerror(nv_error(nvout)));
922 if (hast_proto_send(NULL, conn, nvout, NULL, 0) == -1) {
925 pjdlog_errno(LOG_ERR, "Unable to send response to %s",
927 nv_add_stringf(nverr, "errmsg",
928 "Remote node was unable to send response: %s.",
932 res->hr_remotein = conn;
933 pjdlog_debug(1, "Incoming connection from %s configured.",
936 res->hr_remoteout = conn;
937 pjdlog_debug(1, "Outgoing connection to %s configured.", raddr);
938 hastd_secondary(res, nvin);
943 pjdlog_prefix_set("%s", "");
946 if (nv_error(nverr) != 0) {
947 pjdlog_common(LOG_ERR, 0, nv_error(nverr),
948 "Unable to prepare error header for %s", raddr);
951 if (hast_proto_send(NULL, conn, nverr, NULL, 0) == -1) {
952 pjdlog_errno(LOG_ERR, "Unable to send error to %s", raddr);
963 pjdlog_prefix_set("%s", "");
967 connection_migrate(struct hast_resource *res)
969 struct proto_conn *conn;
972 pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
974 PJDLOG_ASSERT(res->hr_role == HAST_ROLE_PRIMARY);
976 if (proto_recv(res->hr_conn, &val, sizeof(val)) == -1) {
977 pjdlog_errno(LOG_WARNING,
978 "Unable to receive connection command");
981 if (proto_client(res->hr_sourceaddr[0] != '\0' ? res->hr_sourceaddr : NULL,
982 res->hr_remoteaddr, &conn) == -1) {
984 pjdlog_errno(LOG_WARNING,
985 "Unable to create outgoing connection to %s",
989 if (proto_connect(conn, -1) == -1) {
991 pjdlog_errno(LOG_WARNING, "Unable to connect to %s",
998 if (proto_send(res->hr_conn, &val, sizeof(val)) == -1) {
999 pjdlog_errno(LOG_WARNING,
1000 "Unable to send reply to connection request");
1002 if (val == 0 && proto_connection_send(res->hr_conn, conn) == -1)
1003 pjdlog_errno(LOG_WARNING, "Unable to send connection");
1005 pjdlog_prefix_set("%s", "");
1011 struct timespec sigtimeout;
1015 sigtimeout.tv_sec = 0;
1016 sigtimeout.tv_nsec = 0;
1018 PJDLOG_VERIFY(sigemptyset(&mask) == 0);
1019 PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0);
1020 PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
1021 PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
1022 PJDLOG_VERIFY(sigaddset(&mask, SIGCHLD) == 0);
1024 while ((signo = sigtimedwait(&mask, NULL, &sigtimeout)) != -1) {
1028 sigexit_received = true;
1029 terminate_workers();
1030 proto_close(cfg->hc_controlconn);
1040 PJDLOG_ABORT("Unexpected signal (%d).", signo);
1048 struct hast_resource *res;
1049 struct hastd_listen *lst;
1050 struct timeval seltimeout;
1052 time_t lastcheck, now;
1055 lastcheck = time(NULL);
1056 seltimeout.tv_sec = REPORT_INTERVAL;
1057 seltimeout.tv_usec = 0;
1062 /* Setup descriptors for select(2). */
1064 maxfd = fd = proto_descriptor(cfg->hc_controlconn);
1065 PJDLOG_ASSERT(fd >= 0);
1067 TAILQ_FOREACH(lst, &cfg->hc_listen, hl_next) {
1068 if (lst->hl_conn == NULL)
1070 fd = proto_descriptor(lst->hl_conn);
1071 PJDLOG_ASSERT(fd >= 0);
1073 maxfd = fd > maxfd ? fd : maxfd;
1075 TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
1076 if (res->hr_event == NULL)
1078 fd = proto_descriptor(res->hr_event);
1079 PJDLOG_ASSERT(fd >= 0);
1081 maxfd = fd > maxfd ? fd : maxfd;
1082 if (res->hr_role == HAST_ROLE_PRIMARY) {
1083 /* Only primary workers asks for connections. */
1084 PJDLOG_ASSERT(res->hr_conn != NULL);
1085 fd = proto_descriptor(res->hr_conn);
1086 PJDLOG_ASSERT(fd >= 0);
1088 maxfd = fd > maxfd ? fd : maxfd;
1090 PJDLOG_ASSERT(res->hr_conn == NULL);
1094 PJDLOG_ASSERT(maxfd + 1 <= (int)FD_SETSIZE);
1095 ret = select(maxfd + 1, &rfds, NULL, NULL, &seltimeout);
1097 if (lastcheck + REPORT_INTERVAL <= now) {
1103 * select(2) timed out, so there should be no
1104 * descriptors to check.
1107 } else if (ret == -1) {
1110 KEEP_ERRNO((void)pidfile_remove(pfh));
1111 pjdlog_exit(EX_OSERR, "select() failed");
1115 * Check for signals before we do anything to update our
1116 * info about terminated workers in the meantime.
1120 if (FD_ISSET(proto_descriptor(cfg->hc_controlconn), &rfds))
1121 control_handle(cfg);
1122 TAILQ_FOREACH(lst, &cfg->hc_listen, hl_next) {
1123 if (lst->hl_conn == NULL)
1125 if (FD_ISSET(proto_descriptor(lst->hl_conn), &rfds))
1128 TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
1129 if (res->hr_event == NULL)
1131 if (FD_ISSET(proto_descriptor(res->hr_event), &rfds)) {
1132 if (event_recv(res) == 0)
1134 /* The worker process exited? */
1135 proto_close(res->hr_event);
1136 res->hr_event = NULL;
1137 if (res->hr_conn != NULL) {
1138 proto_close(res->hr_conn);
1139 res->hr_conn = NULL;
1143 if (res->hr_role == HAST_ROLE_PRIMARY) {
1144 PJDLOG_ASSERT(res->hr_conn != NULL);
1145 if (FD_ISSET(proto_descriptor(res->hr_conn),
1147 connection_migrate(res);
1150 PJDLOG_ASSERT(res->hr_conn == NULL);
1157 dummy_sighandler(int sig __unused)
1159 /* Nothing to do. */
1163 main(int argc, char *argv[])
1165 struct hastd_listen *lst;
1166 const char *pidfile;
1178 ch = getopt(argc, argv, "c:dFhP:");
1202 pjdlog_init(PJDLOG_MODE_STD);
1203 pjdlog_debug_set(debuglevel);
1208 * When path to the configuration file is relative, obtain full path,
1209 * so we can always find the file, even after daemonizing and changing
1210 * working directory to /.
1212 if (cfgpath[0] != '/') {
1213 const char *newcfgpath;
1215 newcfgpath = realpath(cfgpath, NULL);
1216 if (newcfgpath == NULL) {
1217 pjdlog_exit(EX_CONFIG,
1218 "Unable to obtain full path of %s", cfgpath);
1220 cfgpath = newcfgpath;
1223 cfg = yy_config_parse(cfgpath, true);
1224 PJDLOG_ASSERT(cfg != NULL);
1226 if (pidfile != NULL) {
1227 if (strlcpy(cfg->hc_pidfile, pidfile,
1228 sizeof(cfg->hc_pidfile)) >= sizeof(cfg->hc_pidfile)) {
1229 pjdlog_exitx(EX_CONFIG, "Pidfile path is too long.");
1234 pfh = pidfile_open(cfg->hc_pidfile, 0600, &otherpid);
1236 if (errno == EEXIST) {
1237 pjdlog_exitx(EX_TEMPFAIL,
1238 "Another hastd is already running, pidfile: %s, pid: %jd.",
1239 cfg->hc_pidfile, (intmax_t)otherpid);
1242 * If we cannot create pidfile for other reasons,
1245 pjdlog_errno(LOG_WARNING,
1246 "Unable to open or create pidfile %s",
1252 * Restore default actions for interesting signals in case parent
1253 * process (like init(8)) decided to ignore some of them (like SIGHUP).
1255 PJDLOG_VERIFY(signal(SIGHUP, SIG_DFL) != SIG_ERR);
1256 PJDLOG_VERIFY(signal(SIGINT, SIG_DFL) != SIG_ERR);
1257 PJDLOG_VERIFY(signal(SIGTERM, SIG_DFL) != SIG_ERR);
1259 * Because SIGCHLD is ignored by default, setup dummy handler for it,
1260 * so we can mask it.
1262 PJDLOG_VERIFY(signal(SIGCHLD, dummy_sighandler) != SIG_ERR);
1264 PJDLOG_VERIFY(sigemptyset(&mask) == 0);
1265 PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0);
1266 PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
1267 PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
1268 PJDLOG_VERIFY(sigaddset(&mask, SIGCHLD) == 0);
1269 PJDLOG_VERIFY(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
1271 /* Listen on control address. */
1272 if (proto_server(cfg->hc_controladdr, &cfg->hc_controlconn) == -1) {
1273 KEEP_ERRNO((void)pidfile_remove(pfh));
1274 pjdlog_exit(EX_OSERR, "Unable to listen on control address %s",
1275 cfg->hc_controladdr);
1277 /* Listen for remote connections. */
1278 TAILQ_FOREACH(lst, &cfg->hc_listen, hl_next) {
1279 if (proto_server(lst->hl_addr, &lst->hl_conn) == -1) {
1280 KEEP_ERRNO((void)pidfile_remove(pfh));
1281 pjdlog_exit(EX_OSERR, "Unable to listen on address %s",
1287 if (daemon(0, 0) == -1) {
1288 KEEP_ERRNO((void)pidfile_remove(pfh));
1289 pjdlog_exit(EX_OSERR, "Unable to daemonize");
1292 /* Start logging to syslog. */
1293 pjdlog_mode_set(PJDLOG_MODE_SYSLOG);
1295 /* Write PID to a file. */
1296 if (pidfile_write(pfh) == -1) {
1297 pjdlog_errno(LOG_WARNING,
1298 "Unable to write PID to a file %s",
1301 pjdlog_debug(1, "PID stored in %s.", cfg->hc_pidfile);
1305 pjdlog_info("Started successfully, running protocol version %d.",
1306 HAST_PROTO_VERSION);
1308 pjdlog_debug(1, "Listening on control address %s.",
1309 cfg->hc_controladdr);
1310 TAILQ_FOREACH(lst, &cfg->hc_listen, hl_next)
1311 pjdlog_info("Listening on address %s.", lst->hl_addr);