2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2009-2010 The FreeBSD Foundation
5 * Copyright (c) 2010-2011 Pawel Jakub Dawidek <pawel@dawidek.net>
8 * This software was developed by Pawel Jakub Dawidek under sponsorship from
9 * the FreeBSD Foundation.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
20 * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 #include <sys/cdefs.h>
34 __FBSDID("$FreeBSD$");
36 #include <sys/param.h>
37 #include <sys/linker.h>
38 #include <sys/module.h>
54 #include <activemap.h>
60 #include "hast_proto.h"
65 /* Path to configuration file. */
66 const char *cfgpath = HAST_CONFIG;
67 /* Hastd configuration. */
68 static struct hastd_config *cfg;
69 /* Was SIGINT or SIGTERM signal received? */
70 bool sigexit_received = false;
71 /* Path to pidfile. */
72 static const char *pidfile;
75 /* Do we run in foreground? */
76 static bool foreground;
78 /* How often check for hooks running for too long. */
79 #define REPORT_INTERVAL 5
85 errx(EX_USAGE, "[-dFh] [-c config] [-P pidfile]");
92 if (modfind("g_gate") == -1) {
93 /* Not present in kernel, try loading it. */
94 if (kldload("geom_gate") == -1 || modfind("g_gate") == -1) {
95 if (errno != EEXIST) {
97 "Unable to load geom_gate module");
104 descriptors_cleanup(struct hast_resource *res)
106 struct hast_resource *tres, *tmres;
107 struct hastd_listen *lst;
109 TAILQ_FOREACH_SAFE(tres, &cfg->hc_resources, hr_next, tmres) {
111 PJDLOG_VERIFY(res->hr_role == HAST_ROLE_SECONDARY ||
112 (res->hr_remotein == NULL &&
113 res->hr_remoteout == NULL));
116 if (tres->hr_remotein != NULL)
117 proto_close(tres->hr_remotein);
118 if (tres->hr_remoteout != NULL)
119 proto_close(tres->hr_remoteout);
120 if (tres->hr_ctrl != NULL)
121 proto_close(tres->hr_ctrl);
122 if (tres->hr_event != NULL)
123 proto_close(tres->hr_event);
124 if (tres->hr_conn != NULL)
125 proto_close(tres->hr_conn);
126 TAILQ_REMOVE(&cfg->hc_resources, tres, hr_next);
129 if (cfg->hc_controlin != NULL)
130 proto_close(cfg->hc_controlin);
131 proto_close(cfg->hc_controlconn);
132 while ((lst = TAILQ_FIRST(&cfg->hc_listen)) != NULL) {
133 TAILQ_REMOVE(&cfg->hc_listen, lst, hl_next);
134 if (lst->hl_conn != NULL)
135 proto_close(lst->hl_conn);
138 (void)pidfile_close(pfh);
144 dtype2str(mode_t mode)
148 return ("block device");
149 else if (S_ISCHR(mode))
150 return ("character device");
151 else if (S_ISDIR(mode))
152 return ("directory");
153 else if (S_ISFIFO(mode))
154 return ("pipe or FIFO");
155 else if (S_ISLNK(mode))
156 return ("symbolic link");
157 else if (S_ISREG(mode))
158 return ("regular file");
159 else if (S_ISSOCK(mode))
161 else if (S_ISWHT(mode))
168 descriptors_assert(const struct hast_resource *res, int pjdlogmode)
178 * At this point descriptor to syslog socket is closed, so if we want
179 * to log assertion message, we have to first store it in 'msg' local
180 * buffer and then open syslog socket and log it.
184 maxfd = sysconf(_SC_OPEN_MAX);
186 pjdlog_init(pjdlogmode);
187 pjdlog_prefix_set("[%s] (%s) ", res->hr_name,
188 role2str(res->hr_role));
189 pjdlog_errno(LOG_WARNING, "sysconf(_SC_OPEN_MAX) failed");
193 for (fd = 0; fd <= maxfd; fd++) {
194 if (fstat(fd, &sb) == 0) {
197 } else if (errno == EBADF) {
201 (void)snprintf(msg, sizeof(msg),
202 "Unable to fstat descriptor %d: %s", fd,
206 if (fd == STDIN_FILENO || fd == STDOUT_FILENO ||
207 fd == STDERR_FILENO) {
209 (void)snprintf(msg, sizeof(msg),
210 "Descriptor %d (%s) is closed, but should be open.",
211 fd, (fd == STDIN_FILENO ? "stdin" :
212 (fd == STDOUT_FILENO ? "stdout" : "stderr")));
215 } else if (fd == proto_descriptor(res->hr_event)) {
217 (void)snprintf(msg, sizeof(msg),
218 "Descriptor %d (event) is closed, but should be open.",
222 if (!S_ISSOCK(mode)) {
223 (void)snprintf(msg, sizeof(msg),
224 "Descriptor %d (event) is %s, but should be %s.",
225 fd, dtype2str(mode), dtype2str(S_IFSOCK));
228 } else if (fd == proto_descriptor(res->hr_ctrl)) {
230 (void)snprintf(msg, sizeof(msg),
231 "Descriptor %d (ctrl) is closed, but should be open.",
235 if (!S_ISSOCK(mode)) {
236 (void)snprintf(msg, sizeof(msg),
237 "Descriptor %d (ctrl) is %s, but should be %s.",
238 fd, dtype2str(mode), dtype2str(S_IFSOCK));
241 } else if (res->hr_role == HAST_ROLE_PRIMARY &&
242 fd == proto_descriptor(res->hr_conn)) {
244 (void)snprintf(msg, sizeof(msg),
245 "Descriptor %d (conn) is closed, but should be open.",
249 if (!S_ISSOCK(mode)) {
250 (void)snprintf(msg, sizeof(msg),
251 "Descriptor %d (conn) is %s, but should be %s.",
252 fd, dtype2str(mode), dtype2str(S_IFSOCK));
255 } else if (res->hr_role == HAST_ROLE_SECONDARY &&
256 res->hr_conn != NULL &&
257 fd == proto_descriptor(res->hr_conn)) {
259 (void)snprintf(msg, sizeof(msg),
260 "Descriptor %d (conn) is open, but should be closed.",
264 } else if (res->hr_role == HAST_ROLE_SECONDARY &&
265 fd == proto_descriptor(res->hr_remotein)) {
267 (void)snprintf(msg, sizeof(msg),
268 "Descriptor %d (remote in) is closed, but should be open.",
272 if (!S_ISSOCK(mode)) {
273 (void)snprintf(msg, sizeof(msg),
274 "Descriptor %d (remote in) is %s, but should be %s.",
275 fd, dtype2str(mode), dtype2str(S_IFSOCK));
278 } else if (res->hr_role == HAST_ROLE_SECONDARY &&
279 fd == proto_descriptor(res->hr_remoteout)) {
281 (void)snprintf(msg, sizeof(msg),
282 "Descriptor %d (remote out) is closed, but should be open.",
286 if (!S_ISSOCK(mode)) {
287 (void)snprintf(msg, sizeof(msg),
288 "Descriptor %d (remote out) is %s, but should be %s.",
289 fd, dtype2str(mode), dtype2str(S_IFSOCK));
294 (void)snprintf(msg, sizeof(msg),
295 "Descriptor %d is open (%s), but should be closed.",
296 fd, dtype2str(mode));
301 if (msg[0] != '\0') {
302 pjdlog_init(pjdlogmode);
303 pjdlog_prefix_set("[%s] (%s) ", res->hr_name,
304 role2str(res->hr_role));
305 PJDLOG_ABORT("%s", msg);
310 child_exit_log(unsigned int pid, int status)
313 if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
314 pjdlog_debug(1, "Worker process exited gracefully (pid=%u).",
316 } else if (WIFSIGNALED(status)) {
317 pjdlog_error("Worker process killed (pid=%u, signal=%d).",
318 pid, WTERMSIG(status));
320 pjdlog_error("Worker process exited ungracefully (pid=%u, exitcode=%d).",
321 pid, WIFEXITED(status) ? WEXITSTATUS(status) : -1);
328 struct hast_resource *res;
332 while ((pid = wait3(&status, WNOHANG, NULL)) > 0) {
333 /* Find resource related to the process that just exited. */
334 TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
335 if (pid == res->hr_workerpid)
340 * This can happen when new connection arrives and we
341 * cancel child responsible for the old one or if this
342 * was hook which we executed.
344 hook_check_one(pid, status);
347 pjdlog_prefix_set("[%s] (%s) ", res->hr_name,
348 role2str(res->hr_role));
349 child_exit_log(pid, status);
351 if (res->hr_role == HAST_ROLE_PRIMARY) {
353 * Restart child process if it was killed by signal
354 * or exited because of temporary problem.
356 if (WIFSIGNALED(status) ||
357 (WIFEXITED(status) &&
358 WEXITSTATUS(status) == EX_TEMPFAIL)) {
360 pjdlog_info("Restarting worker process.");
363 res->hr_role = HAST_ROLE_INIT;
364 pjdlog_info("Changing resource role back to %s.",
365 role2str(res->hr_role));
368 pjdlog_prefix_set("%s", "");
373 resource_needs_restart(const struct hast_resource *res0,
374 const struct hast_resource *res1)
377 PJDLOG_ASSERT(strcmp(res0->hr_name, res1->hr_name) == 0);
379 if (strcmp(res0->hr_provname, res1->hr_provname) != 0)
381 if (strcmp(res0->hr_localpath, res1->hr_localpath) != 0)
383 if (res0->hr_role == HAST_ROLE_INIT ||
384 res0->hr_role == HAST_ROLE_SECONDARY) {
385 if (strcmp(res0->hr_remoteaddr, res1->hr_remoteaddr) != 0)
387 if (strcmp(res0->hr_sourceaddr, res1->hr_sourceaddr) != 0)
389 if (res0->hr_replication != res1->hr_replication)
391 if (res0->hr_checksum != res1->hr_checksum)
393 if (res0->hr_compression != res1->hr_compression)
395 if (res0->hr_timeout != res1->hr_timeout)
397 if (strcmp(res0->hr_exec, res1->hr_exec) != 0)
400 * When metaflush has changed we don't really need restart,
401 * but it is just easier this way.
403 if (res0->hr_metaflush != res1->hr_metaflush)
410 resource_needs_reload(const struct hast_resource *res0,
411 const struct hast_resource *res1)
414 PJDLOG_ASSERT(strcmp(res0->hr_name, res1->hr_name) == 0);
415 PJDLOG_ASSERT(strcmp(res0->hr_provname, res1->hr_provname) == 0);
416 PJDLOG_ASSERT(strcmp(res0->hr_localpath, res1->hr_localpath) == 0);
418 if (res0->hr_role != HAST_ROLE_PRIMARY)
421 if (strcmp(res0->hr_remoteaddr, res1->hr_remoteaddr) != 0)
423 if (strcmp(res0->hr_sourceaddr, res1->hr_sourceaddr) != 0)
425 if (res0->hr_replication != res1->hr_replication)
427 if (res0->hr_checksum != res1->hr_checksum)
429 if (res0->hr_compression != res1->hr_compression)
431 if (res0->hr_timeout != res1->hr_timeout)
433 if (strcmp(res0->hr_exec, res1->hr_exec) != 0)
435 if (res0->hr_metaflush != res1->hr_metaflush)
441 resource_reload(const struct hast_resource *res)
443 struct nv *nvin, *nvout;
446 PJDLOG_ASSERT(res->hr_role == HAST_ROLE_PRIMARY);
449 nv_add_uint8(nvout, CONTROL_RELOAD, "cmd");
450 nv_add_string(nvout, res->hr_remoteaddr, "remoteaddr");
451 nv_add_string(nvout, res->hr_sourceaddr, "sourceaddr");
452 nv_add_int32(nvout, (int32_t)res->hr_replication, "replication");
453 nv_add_int32(nvout, (int32_t)res->hr_checksum, "checksum");
454 nv_add_int32(nvout, (int32_t)res->hr_compression, "compression");
455 nv_add_int32(nvout, (int32_t)res->hr_timeout, "timeout");
456 nv_add_string(nvout, res->hr_exec, "exec");
457 nv_add_int32(nvout, (int32_t)res->hr_metaflush, "metaflush");
458 if (nv_error(nvout) != 0) {
460 pjdlog_error("Unable to allocate header for reload message.");
463 if (hast_proto_send(res, res->hr_ctrl, nvout, NULL, 0) == -1) {
464 pjdlog_errno(LOG_ERR, "Unable to send reload message");
470 /* Receive response. */
471 if (hast_proto_recv_hdr(res->hr_ctrl, &nvin) == -1) {
472 pjdlog_errno(LOG_ERR, "Unable to receive reload reply");
475 error = nv_get_int16(nvin, "error");
478 pjdlog_common(LOG_ERR, 0, error, "Reload failed");
486 struct hastd_config *newcfg;
487 struct hast_resource *nres, *cres, *tres;
488 struct hastd_listen *nlst, *clst;
489 struct pidfh *newpfh;
490 unsigned int nlisten;
494 pjdlog_info("Reloading configuration...");
498 newcfg = yy_config_parse(cfgpath, false);
503 * Check if control address has changed.
505 if (strcmp(cfg->hc_controladdr, newcfg->hc_controladdr) != 0) {
506 if (proto_server(newcfg->hc_controladdr,
507 &newcfg->hc_controlconn) == -1) {
508 pjdlog_errno(LOG_ERR,
509 "Unable to listen on control address %s",
510 newcfg->hc_controladdr);
515 * Check if any listen address has changed.
518 TAILQ_FOREACH(nlst, &newcfg->hc_listen, hl_next) {
519 TAILQ_FOREACH(clst, &cfg->hc_listen, hl_next) {
520 if (strcmp(nlst->hl_addr, clst->hl_addr) == 0)
523 if (clst != NULL && clst->hl_conn != NULL) {
524 pjdlog_info("Keep listening on address %s.",
526 nlst->hl_conn = clst->hl_conn;
528 } else if (proto_server(nlst->hl_addr, &nlst->hl_conn) == 0) {
529 pjdlog_info("Listening on new address %s.",
533 pjdlog_errno(LOG_WARNING,
534 "Unable to listen on address %s", nlst->hl_addr);
538 pjdlog_error("No addresses to listen on.");
542 * Check if pidfile's path has changed.
544 if (!foreground && pidfile == NULL &&
545 strcmp(cfg->hc_pidfile, newcfg->hc_pidfile) != 0) {
546 newpfh = pidfile_open(newcfg->hc_pidfile, 0600, &otherpid);
547 if (newpfh == NULL) {
548 if (errno == EEXIST) {
549 pjdlog_errno(LOG_WARNING,
550 "Another hastd is already running, pidfile: %s, pid: %jd.",
551 newcfg->hc_pidfile, (intmax_t)otherpid);
553 pjdlog_errno(LOG_WARNING,
554 "Unable to open or create pidfile %s",
557 } else if (pidfile_write(newpfh) == -1) {
558 /* Write PID to a file. */
559 pjdlog_errno(LOG_WARNING,
560 "Unable to write PID to file %s",
563 pjdlog_debug(1, "PID stored in %s.",
568 /* No failures from now on. */
571 * Switch to new control socket.
573 if (newcfg->hc_controlconn != NULL) {
574 pjdlog_info("Control socket changed from %s to %s.",
575 cfg->hc_controladdr, newcfg->hc_controladdr);
576 proto_close(cfg->hc_controlconn);
577 cfg->hc_controlconn = newcfg->hc_controlconn;
578 newcfg->hc_controlconn = NULL;
579 strlcpy(cfg->hc_controladdr, newcfg->hc_controladdr,
580 sizeof(cfg->hc_controladdr));
583 * Switch to new pidfile.
585 if (newpfh != NULL) {
586 pjdlog_info("Pidfile changed from %s to %s.", cfg->hc_pidfile,
588 (void)pidfile_remove(pfh);
590 (void)strlcpy(cfg->hc_pidfile, newcfg->hc_pidfile,
591 sizeof(cfg->hc_pidfile));
594 * Switch to new listen addresses. Close all that were removed.
596 while ((clst = TAILQ_FIRST(&cfg->hc_listen)) != NULL) {
597 TAILQ_FOREACH(nlst, &newcfg->hc_listen, hl_next) {
598 if (strcmp(nlst->hl_addr, clst->hl_addr) == 0)
601 if (nlst == NULL && clst->hl_conn != NULL) {
602 proto_close(clst->hl_conn);
603 pjdlog_info("No longer listening on address %s.",
606 TAILQ_REMOVE(&cfg->hc_listen, clst, hl_next);
609 TAILQ_CONCAT(&cfg->hc_listen, &newcfg->hc_listen, hl_next);
612 * Stop and remove resources that were removed from the configuration.
614 TAILQ_FOREACH_SAFE(cres, &cfg->hc_resources, hr_next, tres) {
615 TAILQ_FOREACH(nres, &newcfg->hc_resources, hr_next) {
616 if (strcmp(cres->hr_name, nres->hr_name) == 0)
620 control_set_role(cres, HAST_ROLE_INIT);
621 TAILQ_REMOVE(&cfg->hc_resources, cres, hr_next);
622 pjdlog_info("Resource %s removed.", cres->hr_name);
627 * Move new resources to the current configuration.
629 TAILQ_FOREACH_SAFE(nres, &newcfg->hc_resources, hr_next, tres) {
630 TAILQ_FOREACH(cres, &cfg->hc_resources, hr_next) {
631 if (strcmp(cres->hr_name, nres->hr_name) == 0)
635 TAILQ_REMOVE(&newcfg->hc_resources, nres, hr_next);
636 TAILQ_INSERT_TAIL(&cfg->hc_resources, nres, hr_next);
637 pjdlog_info("Resource %s added.", nres->hr_name);
641 * Deal with modified resources.
642 * Depending on what has changed exactly we might want to perform
645 * We do full resource restart in the following situations:
646 * Resource role is INIT or SECONDARY.
647 * Resource role is PRIMARY and path to local component or provider
649 * In case of PRIMARY, the worker process will be killed and restarted,
650 * which also means removing /dev/hast/<name> provider and
653 * We do just reload (send SIGHUP to worker process) if we act as
654 * PRIMARY, but only if remote address, source address, replication
655 * mode, timeout, execution path or metaflush has changed.
656 * For those, there is no need to restart worker process.
657 * If PRIMARY receives SIGHUP, it will reconnect if remote address or
658 * source address has changed or it will set new timeout if only timeout
659 * has changed or it will update metaflush if only metaflush has
662 TAILQ_FOREACH_SAFE(nres, &newcfg->hc_resources, hr_next, tres) {
663 TAILQ_FOREACH(cres, &cfg->hc_resources, hr_next) {
664 if (strcmp(cres->hr_name, nres->hr_name) == 0)
667 PJDLOG_ASSERT(cres != NULL);
668 if (resource_needs_restart(cres, nres)) {
669 pjdlog_info("Resource %s configuration was modified, restarting it.",
671 role = cres->hr_role;
672 control_set_role(cres, HAST_ROLE_INIT);
673 TAILQ_REMOVE(&cfg->hc_resources, cres, hr_next);
675 TAILQ_REMOVE(&newcfg->hc_resources, nres, hr_next);
676 TAILQ_INSERT_TAIL(&cfg->hc_resources, nres, hr_next);
677 control_set_role(nres, role);
678 } else if (resource_needs_reload(cres, nres)) {
679 pjdlog_info("Resource %s configuration was modified, reloading it.",
681 strlcpy(cres->hr_remoteaddr, nres->hr_remoteaddr,
682 sizeof(cres->hr_remoteaddr));
683 strlcpy(cres->hr_sourceaddr, nres->hr_sourceaddr,
684 sizeof(cres->hr_sourceaddr));
685 cres->hr_replication = nres->hr_replication;
686 cres->hr_checksum = nres->hr_checksum;
687 cres->hr_compression = nres->hr_compression;
688 cres->hr_timeout = nres->hr_timeout;
689 strlcpy(cres->hr_exec, nres->hr_exec,
690 sizeof(cres->hr_exec));
691 cres->hr_metaflush = nres->hr_metaflush;
692 if (cres->hr_workerpid != 0)
693 resource_reload(cres);
697 yy_config_free(newcfg);
698 pjdlog_info("Configuration reloaded successfully.");
701 if (newcfg != NULL) {
702 if (newcfg->hc_controlconn != NULL)
703 proto_close(newcfg->hc_controlconn);
704 while ((nlst = TAILQ_FIRST(&newcfg->hc_listen)) != NULL) {
705 if (nlst->hl_conn != NULL) {
706 TAILQ_FOREACH(clst, &cfg->hc_listen, hl_next) {
707 if (strcmp(nlst->hl_addr,
708 clst->hl_addr) == 0) {
712 if (clst == NULL || clst->hl_conn == NULL)
713 proto_close(nlst->hl_conn);
715 TAILQ_REMOVE(&newcfg->hc_listen, nlst, hl_next);
718 yy_config_free(newcfg);
721 (void)pidfile_remove(newpfh);
722 pjdlog_warning("Configuration not reloaded.");
726 terminate_workers(void)
728 struct hast_resource *res;
730 pjdlog_info("Termination signal received, exiting.");
731 TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
732 if (res->hr_workerpid == 0)
734 pjdlog_info("Terminating worker process (resource=%s, role=%s, pid=%u).",
735 res->hr_name, role2str(res->hr_role), res->hr_workerpid);
736 if (kill(res->hr_workerpid, SIGTERM) == 0)
738 pjdlog_errno(LOG_WARNING,
739 "Unable to send signal to worker process (resource=%s, role=%s, pid=%u).",
740 res->hr_name, role2str(res->hr_role), res->hr_workerpid);
745 listen_accept(struct hastd_listen *lst)
747 struct hast_resource *res;
748 struct proto_conn *conn;
749 struct nv *nvin, *nvout, *nverr;
751 const unsigned char *token;
752 char laddr[256], raddr[256];
758 proto_local_address(lst->hl_conn, laddr, sizeof(laddr));
759 pjdlog_debug(1, "Accepting connection to %s.", laddr);
761 if (proto_accept(lst->hl_conn, &conn) == -1) {
762 pjdlog_errno(LOG_ERR, "Unable to accept connection %s", laddr);
766 proto_local_address(conn, laddr, sizeof(laddr));
767 proto_remote_address(conn, raddr, sizeof(raddr));
768 pjdlog_info("Connection from %s to %s.", raddr, laddr);
770 /* Error in setting timeout is not critical, but why should it fail? */
771 if (proto_timeout(conn, HAST_TIMEOUT) == -1)
772 pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
774 nvin = nvout = nverr = NULL;
777 * Before receiving any data see if remote host have access to any
780 TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
781 if (proto_address_match(conn, res->hr_remoteaddr))
785 pjdlog_error("Client %s isn't known.", raddr);
788 /* Ok, remote host can access at least one resource. */
790 if (hast_proto_recv_hdr(conn, &nvin) == -1) {
791 pjdlog_errno(LOG_ERR, "Unable to receive header from %s",
796 resname = nv_get_string(nvin, "resource");
797 if (resname == NULL) {
798 pjdlog_error("No 'resource' field in the header received from %s.",
802 pjdlog_debug(2, "%s: resource=%s", raddr, resname);
803 version = nv_get_uint8(nvin, "version");
804 pjdlog_debug(2, "%s: version=%hhu", raddr, version);
807 * If no version is sent, it means this is protocol version 1.
811 token = nv_get_uint8_array(nvin, &size, "token");
813 * NULL token means that this is first connection.
815 if (token != NULL && size != sizeof(res->hr_token)) {
816 pjdlog_error("Received token of invalid size from %s (expected %zu, got %zu).",
817 raddr, sizeof(res->hr_token), size);
822 * From now on we want to send errors to the remote node.
826 /* Find resource related to this connection. */
827 TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
828 if (strcmp(resname, res->hr_name) == 0)
831 /* Have we found the resource? */
833 pjdlog_error("No resource '%s' as requested by %s.",
835 nv_add_stringf(nverr, "errmsg", "Resource not configured.");
839 /* Now that we know resource name setup log prefix. */
840 pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
842 /* Does the remote host have access to this resource? */
843 if (!proto_address_match(conn, res->hr_remoteaddr)) {
844 pjdlog_error("Client %s has no access to the resource.", raddr);
845 nv_add_stringf(nverr, "errmsg", "No access to the resource.");
848 /* Is the resource marked as secondary? */
849 if (res->hr_role != HAST_ROLE_SECONDARY) {
850 pjdlog_warning("We act as %s for the resource and not as %s as requested by %s.",
851 role2str(res->hr_role), role2str(HAST_ROLE_SECONDARY),
853 nv_add_stringf(nverr, "errmsg",
854 "Remote node acts as %s for the resource and not as %s.",
855 role2str(res->hr_role), role2str(HAST_ROLE_SECONDARY));
856 if (res->hr_role == HAST_ROLE_PRIMARY) {
858 * If we act as primary request the other side to wait
859 * for us a bit, as we might be finishing cleanups.
861 nv_add_uint8(nverr, 1, "wait");
865 /* Does token (if exists) match? */
866 if (token != NULL && memcmp(token, res->hr_token,
867 sizeof(res->hr_token)) != 0) {
868 pjdlog_error("Token received from %s doesn't match.", raddr);
869 nv_add_stringf(nverr, "errmsg", "Token doesn't match.");
873 * If there is no token, but we have half-open connection
874 * (only remotein) or full connection (worker process is running)
875 * we have to cancel those and accept the new connection.
878 PJDLOG_ASSERT(res->hr_remoteout == NULL);
879 pjdlog_debug(1, "Initial connection from %s.", raddr);
880 if (res->hr_workerpid != 0) {
881 PJDLOG_ASSERT(res->hr_remotein == NULL);
883 "Worker process exists (pid=%u), stopping it.",
884 (unsigned int)res->hr_workerpid);
885 /* Stop child process. */
886 if (kill(res->hr_workerpid, SIGINT) == -1) {
887 pjdlog_errno(LOG_ERR,
888 "Unable to stop worker process (pid=%u)",
889 (unsigned int)res->hr_workerpid);
891 * Other than logging the problem we
892 * ignore it - nothing smart to do.
895 /* Wait for it to exit. */
896 else if ((pid = waitpid(res->hr_workerpid,
897 &status, 0)) != res->hr_workerpid) {
898 /* We can only log the problem. */
899 pjdlog_errno(LOG_ERR,
900 "Waiting for worker process (pid=%u) failed",
901 (unsigned int)res->hr_workerpid);
903 child_exit_log(res->hr_workerpid, status);
906 } else if (res->hr_remotein != NULL) {
909 proto_remote_address(res->hr_remotein, oaddr,
912 "Canceling half-open connection from %s on connection from %s.",
914 proto_close(res->hr_remotein);
915 res->hr_remotein = NULL;
920 * Checks and cleanups are done.
924 if (version > HAST_PROTO_VERSION) {
925 pjdlog_info("Remote protocol version %hhu is not supported, falling back to version %hhu.",
926 version, (unsigned char)HAST_PROTO_VERSION);
927 version = HAST_PROTO_VERSION;
929 pjdlog_debug(1, "Negotiated protocol version %hhu.", version);
930 res->hr_version = version;
931 arc4random_buf(res->hr_token, sizeof(res->hr_token));
933 nv_add_uint8(nvout, version, "version");
934 nv_add_uint8_array(nvout, res->hr_token,
935 sizeof(res->hr_token), "token");
936 if (nv_error(nvout) != 0) {
937 pjdlog_common(LOG_ERR, 0, nv_error(nvout),
938 "Unable to prepare return header for %s", raddr);
939 nv_add_stringf(nverr, "errmsg",
940 "Remote node was unable to prepare return header: %s.",
941 strerror(nv_error(nvout)));
944 if (hast_proto_send(res, conn, nvout, NULL, 0) == -1) {
947 pjdlog_errno(LOG_ERR, "Unable to send response to %s",
949 nv_add_stringf(nverr, "errmsg",
950 "Remote node was unable to send response: %s.",
954 res->hr_remotein = conn;
955 pjdlog_debug(1, "Incoming connection from %s configured.",
958 res->hr_remoteout = conn;
959 pjdlog_debug(1, "Outgoing connection to %s configured.", raddr);
960 hastd_secondary(res, nvin);
965 pjdlog_prefix_set("%s", "");
968 if (nv_error(nverr) != 0) {
969 pjdlog_common(LOG_ERR, 0, nv_error(nverr),
970 "Unable to prepare error header for %s", raddr);
973 if (hast_proto_send(NULL, conn, nverr, NULL, 0) == -1) {
974 pjdlog_errno(LOG_ERR, "Unable to send error to %s", raddr);
985 pjdlog_prefix_set("%s", "");
989 connection_migrate(struct hast_resource *res)
991 struct proto_conn *conn;
994 pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
996 PJDLOG_ASSERT(res->hr_role == HAST_ROLE_PRIMARY);
998 if (proto_recv(res->hr_conn, &val, sizeof(val)) == -1) {
999 pjdlog_errno(LOG_WARNING,
1000 "Unable to receive connection command");
1003 if (proto_client(res->hr_sourceaddr[0] != '\0' ? res->hr_sourceaddr : NULL,
1004 res->hr_remoteaddr, &conn) == -1) {
1006 pjdlog_errno(LOG_WARNING,
1007 "Unable to create outgoing connection to %s",
1008 res->hr_remoteaddr);
1011 if (proto_connect(conn, -1) == -1) {
1013 pjdlog_errno(LOG_WARNING, "Unable to connect to %s",
1014 res->hr_remoteaddr);
1020 if (proto_send(res->hr_conn, &val, sizeof(val)) == -1) {
1021 pjdlog_errno(LOG_WARNING,
1022 "Unable to send reply to connection request");
1024 if (val == 0 && proto_connection_send(res->hr_conn, conn) == -1)
1025 pjdlog_errno(LOG_WARNING, "Unable to send connection");
1027 pjdlog_prefix_set("%s", "");
1033 struct timespec sigtimeout;
1037 sigtimeout.tv_sec = 0;
1038 sigtimeout.tv_nsec = 0;
1040 PJDLOG_VERIFY(sigemptyset(&mask) == 0);
1041 PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0);
1042 PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
1043 PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
1044 PJDLOG_VERIFY(sigaddset(&mask, SIGCHLD) == 0);
1046 while ((signo = sigtimedwait(&mask, NULL, &sigtimeout)) != -1) {
1050 sigexit_received = true;
1051 terminate_workers();
1052 proto_close(cfg->hc_controlconn);
1062 PJDLOG_ABORT("Unexpected signal (%d).", signo);
1070 struct hast_resource *res;
1071 struct hastd_listen *lst;
1072 struct timeval seltimeout;
1074 time_t lastcheck, now;
1077 lastcheck = time(NULL);
1078 seltimeout.tv_sec = REPORT_INTERVAL;
1079 seltimeout.tv_usec = 0;
1084 /* Setup descriptors for select(2). */
1086 maxfd = fd = proto_descriptor(cfg->hc_controlconn);
1087 PJDLOG_ASSERT(fd >= 0);
1089 TAILQ_FOREACH(lst, &cfg->hc_listen, hl_next) {
1090 if (lst->hl_conn == NULL)
1092 fd = proto_descriptor(lst->hl_conn);
1093 PJDLOG_ASSERT(fd >= 0);
1095 maxfd = MAX(fd, maxfd);
1097 TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
1098 if (res->hr_event == NULL)
1100 fd = proto_descriptor(res->hr_event);
1101 PJDLOG_ASSERT(fd >= 0);
1103 maxfd = MAX(fd, maxfd);
1104 if (res->hr_role == HAST_ROLE_PRIMARY) {
1105 /* Only primary workers asks for connections. */
1106 PJDLOG_ASSERT(res->hr_conn != NULL);
1107 fd = proto_descriptor(res->hr_conn);
1108 PJDLOG_ASSERT(fd >= 0);
1110 maxfd = MAX(fd, maxfd);
1112 PJDLOG_ASSERT(res->hr_conn == NULL);
1116 PJDLOG_ASSERT(maxfd + 1 <= (int)FD_SETSIZE);
1117 ret = select(maxfd + 1, &rfds, NULL, NULL, &seltimeout);
1119 if (lastcheck + REPORT_INTERVAL <= now) {
1125 * select(2) timed out, so there should be no
1126 * descriptors to check.
1129 } else if (ret == -1) {
1132 KEEP_ERRNO((void)pidfile_remove(pfh));
1133 pjdlog_exit(EX_OSERR, "select() failed");
1137 * Check for signals before we do anything to update our
1138 * info about terminated workers in the meantime.
1142 if (FD_ISSET(proto_descriptor(cfg->hc_controlconn), &rfds))
1143 control_handle(cfg);
1144 TAILQ_FOREACH(lst, &cfg->hc_listen, hl_next) {
1145 if (lst->hl_conn == NULL)
1147 if (FD_ISSET(proto_descriptor(lst->hl_conn), &rfds))
1150 TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
1151 if (res->hr_event == NULL)
1153 if (FD_ISSET(proto_descriptor(res->hr_event), &rfds)) {
1154 if (event_recv(res) == 0)
1156 /* The worker process exited? */
1157 proto_close(res->hr_event);
1158 res->hr_event = NULL;
1159 if (res->hr_conn != NULL) {
1160 proto_close(res->hr_conn);
1161 res->hr_conn = NULL;
1165 if (res->hr_role == HAST_ROLE_PRIMARY) {
1166 PJDLOG_ASSERT(res->hr_conn != NULL);
1167 if (FD_ISSET(proto_descriptor(res->hr_conn),
1169 connection_migrate(res);
1172 PJDLOG_ASSERT(res->hr_conn == NULL);
1179 dummy_sighandler(int sig __unused)
1181 /* Nothing to do. */
1185 main(int argc, char *argv[])
1187 struct hastd_listen *lst;
1198 ch = getopt(argc, argv, "c:dFhP:");
1222 pjdlog_init(PJDLOG_MODE_STD);
1223 pjdlog_debug_set(debuglevel);
1228 * When path to the configuration file is relative, obtain full path,
1229 * so we can always find the file, even after daemonizing and changing
1230 * working directory to /.
1232 if (cfgpath[0] != '/') {
1233 const char *newcfgpath;
1235 newcfgpath = realpath(cfgpath, NULL);
1236 if (newcfgpath == NULL) {
1237 pjdlog_exit(EX_CONFIG,
1238 "Unable to obtain full path of %s", cfgpath);
1240 cfgpath = newcfgpath;
1243 cfg = yy_config_parse(cfgpath, true);
1244 PJDLOG_ASSERT(cfg != NULL);
1246 if (pidfile != NULL) {
1247 if (strlcpy(cfg->hc_pidfile, pidfile,
1248 sizeof(cfg->hc_pidfile)) >= sizeof(cfg->hc_pidfile)) {
1249 pjdlog_exitx(EX_CONFIG, "Pidfile path is too long.");
1253 if (pidfile != NULL || !foreground) {
1254 pfh = pidfile_open(cfg->hc_pidfile, 0600, &otherpid);
1256 if (errno == EEXIST) {
1257 pjdlog_exitx(EX_TEMPFAIL,
1258 "Another hastd is already running, pidfile: %s, pid: %jd.",
1259 cfg->hc_pidfile, (intmax_t)otherpid);
1262 * If we cannot create pidfile for other reasons,
1265 pjdlog_errno(LOG_WARNING,
1266 "Unable to open or create pidfile %s",
1272 * Restore default actions for interesting signals in case parent
1273 * process (like init(8)) decided to ignore some of them (like SIGHUP).
1275 PJDLOG_VERIFY(signal(SIGHUP, SIG_DFL) != SIG_ERR);
1276 PJDLOG_VERIFY(signal(SIGINT, SIG_DFL) != SIG_ERR);
1277 PJDLOG_VERIFY(signal(SIGTERM, SIG_DFL) != SIG_ERR);
1279 * Because SIGCHLD is ignored by default, setup dummy handler for it,
1280 * so we can mask it.
1282 PJDLOG_VERIFY(signal(SIGCHLD, dummy_sighandler) != SIG_ERR);
1284 PJDLOG_VERIFY(sigemptyset(&mask) == 0);
1285 PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0);
1286 PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
1287 PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
1288 PJDLOG_VERIFY(sigaddset(&mask, SIGCHLD) == 0);
1289 PJDLOG_VERIFY(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
1291 /* Listen on control address. */
1292 if (proto_server(cfg->hc_controladdr, &cfg->hc_controlconn) == -1) {
1293 KEEP_ERRNO((void)pidfile_remove(pfh));
1294 pjdlog_exit(EX_OSERR, "Unable to listen on control address %s",
1295 cfg->hc_controladdr);
1297 /* Listen for remote connections. */
1298 TAILQ_FOREACH(lst, &cfg->hc_listen, hl_next) {
1299 if (proto_server(lst->hl_addr, &lst->hl_conn) == -1) {
1300 KEEP_ERRNO((void)pidfile_remove(pfh));
1301 pjdlog_exit(EX_OSERR, "Unable to listen on address %s",
1307 if (daemon(0, 0) == -1) {
1308 KEEP_ERRNO((void)pidfile_remove(pfh));
1309 pjdlog_exit(EX_OSERR, "Unable to daemonize");
1312 /* Start logging to syslog. */
1313 pjdlog_mode_set(PJDLOG_MODE_SYSLOG);
1315 if (pidfile != NULL || !foreground) {
1316 /* Write PID to a file. */
1317 if (pidfile_write(pfh) == -1) {
1318 pjdlog_errno(LOG_WARNING,
1319 "Unable to write PID to a file %s",
1322 pjdlog_debug(1, "PID stored in %s.", cfg->hc_pidfile);
1326 pjdlog_info("Started successfully, running protocol version %d.",
1327 HAST_PROTO_VERSION);
1329 pjdlog_debug(1, "Listening on control address %s.",
1330 cfg->hc_controladdr);
1331 TAILQ_FOREACH(lst, &cfg->hc_listen, hl_next)
1332 pjdlog_info("Listening on address %s.", lst->hl_addr);