]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - sbin/hastd/hastd.c
MFC r220520, r220521, r220522, r220523, r220573, r220744, r220865,
[FreeBSD/stable/8.git] / sbin / hastd / hastd.c
1 /*-
2  * Copyright (c) 2009-2010 The FreeBSD Foundation
3  * Copyright (c) 2010-2011 Pawel Jakub Dawidek <pawel@dawidek.net>
4  * All rights reserved.
5  *
6  * This software was developed by Pawel Jakub Dawidek under sponsorship from
7  * the FreeBSD Foundation.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
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.
17  *
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
28  * SUCH DAMAGE.
29  */
30
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
33
34 #include <sys/param.h>
35 #include <sys/linker.h>
36 #include <sys/module.h>
37 #include <sys/stat.h>
38 #include <sys/wait.h>
39
40 #include <err.h>
41 #include <errno.h>
42 #include <libutil.h>
43 #include <signal.h>
44 #include <stdbool.h>
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <string.h>
48 #include <sysexits.h>
49 #include <time.h>
50 #include <unistd.h>
51
52 #include <activemap.h>
53 #include <pjdlog.h>
54
55 #include "control.h"
56 #include "event.h"
57 #include "hast.h"
58 #include "hast_proto.h"
59 #include "hastd.h"
60 #include "hooks.h"
61 #include "subr.h"
62
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. */
70 struct pidfh *pfh;
71
72 /* How often check for hooks running for too long. */
73 #define REPORT_INTERVAL 5
74
75 static void
76 usage(void)
77 {
78
79         errx(EX_USAGE, "[-dFh] [-c config] [-P pidfile]");
80 }
81
82 static void
83 g_gate_load(void)
84 {
85
86         if (modfind("g_gate") == -1) {
87                 /* Not present in kernel, try loading it. */
88                 if (kldload("geom_gate") == -1 || modfind("g_gate") == -1) {
89                         if (errno != EEXIST) {
90                                 pjdlog_exit(EX_OSERR,
91                                     "Unable to load geom_gate module");
92                         }
93                 }
94         }
95 }
96
97 void
98 descriptors_cleanup(struct hast_resource *res)
99 {
100         struct hast_resource *tres;
101
102         TAILQ_FOREACH(tres, &cfg->hc_resources, hr_next) {
103                 if (tres == res) {
104                         PJDLOG_VERIFY(res->hr_role == HAST_ROLE_SECONDARY ||
105                             (res->hr_remotein == NULL &&
106                              res->hr_remoteout == NULL));
107                         continue;
108                 }
109                 if (tres->hr_remotein != NULL)
110                         proto_close(tres->hr_remotein);
111                 if (tres->hr_remoteout != NULL)
112                         proto_close(tres->hr_remoteout);
113                 if (tres->hr_ctrl != NULL)
114                         proto_close(tres->hr_ctrl);
115                 if (tres->hr_event != NULL)
116                         proto_close(tres->hr_event);
117                 if (tres->hr_conn != NULL)
118                         proto_close(tres->hr_conn);
119         }
120         if (cfg->hc_controlin != NULL)
121                 proto_close(cfg->hc_controlin);
122         proto_close(cfg->hc_controlconn);
123         proto_close(cfg->hc_listenconn);
124         (void)pidfile_close(pfh);
125         hook_fini();
126         pjdlog_fini();
127 }
128
129 static const char *
130 dtype2str(mode_t mode)
131 {
132
133         if (S_ISBLK(mode))
134                 return ("block device");
135         else if (S_ISCHR(mode))
136                 return ("character device");
137         else if (S_ISDIR(mode))
138                 return ("directory");
139         else if (S_ISFIFO(mode))
140                 return ("pipe or FIFO");
141         else if (S_ISLNK(mode))
142                 return ("symbolic link");
143         else if (S_ISREG(mode))
144                 return ("regular file");
145         else if (S_ISSOCK(mode))
146                 return ("socket");
147         else if (S_ISWHT(mode))
148                 return ("whiteout");
149         else
150                 return ("unknown");
151 }
152
153 void
154 descriptors_assert(const struct hast_resource *res, int pjdlogmode)
155 {
156         char msg[256];
157         struct stat sb;
158         long maxfd;
159         bool isopen;
160         mode_t mode;
161         int fd;
162
163         /*
164          * At this point descriptor to syslog socket is closed, so if we want
165          * to log assertion message, we have to first store it in 'msg' local
166          * buffer and then open syslog socket and log it.
167          */
168         msg[0] = '\0';
169
170         maxfd = sysconf(_SC_OPEN_MAX);
171         if (maxfd < 0) {
172                 pjdlog_init(pjdlogmode);
173                 pjdlog_prefix_set("[%s] (%s) ", res->hr_name,
174                     role2str(res->hr_role));
175                 pjdlog_errno(LOG_WARNING, "sysconf(_SC_OPEN_MAX) failed");
176                 pjdlog_fini();
177                 maxfd = 16384;
178         }
179         for (fd = 0; fd <= maxfd; fd++) {
180                 if (fstat(fd, &sb) == 0) {
181                         isopen = true;
182                         mode = sb.st_mode;
183                 } else if (errno == EBADF) {
184                         isopen = false;
185                         mode = 0;
186                 } else {
187                         (void)snprintf(msg, sizeof(msg),
188                             "Unable to fstat descriptor %d: %s", fd,
189                             strerror(errno));
190                         break;
191                 }
192                 if (fd == STDIN_FILENO || fd == STDOUT_FILENO ||
193                     fd == STDERR_FILENO) {
194                         if (!isopen) {
195                                 (void)snprintf(msg, sizeof(msg),
196                                     "Descriptor %d (%s) is closed, but should be open.",
197                                     fd, (fd == STDIN_FILENO ? "stdin" :
198                                     (fd == STDOUT_FILENO ? "stdout" : "stderr")));
199                                 break;
200                         }
201                 } else if (fd == proto_descriptor(res->hr_event)) {
202                         if (!isopen) {
203                                 (void)snprintf(msg, sizeof(msg),
204                                     "Descriptor %d (event) is closed, but should be open.",
205                                     fd);
206                                 break;
207                         }
208                         if (!S_ISSOCK(mode)) {
209                                 (void)snprintf(msg, sizeof(msg),
210                                     "Descriptor %d (event) is %s, but should be %s.",
211                                     fd, dtype2str(mode), dtype2str(S_IFSOCK));
212                                 break;
213                         }
214                 } else if (fd == proto_descriptor(res->hr_ctrl)) {
215                         if (!isopen) {
216                                 (void)snprintf(msg, sizeof(msg),
217                                     "Descriptor %d (ctrl) is closed, but should be open.",
218                                     fd);
219                                 break;
220                         }
221                         if (!S_ISSOCK(mode)) {
222                                 (void)snprintf(msg, sizeof(msg),
223                                     "Descriptor %d (ctrl) is %s, but should be %s.",
224                                     fd, dtype2str(mode), dtype2str(S_IFSOCK));
225                                 break;
226                         }
227                 } else if (res->hr_role == HAST_ROLE_PRIMARY &&
228                     fd == proto_descriptor(res->hr_conn)) {
229                         if (!isopen) {
230                                 (void)snprintf(msg, sizeof(msg),
231                                     "Descriptor %d (conn) is closed, but should be open.",
232                                     fd);
233                                 break;
234                         }
235                         if (!S_ISSOCK(mode)) {
236                                 (void)snprintf(msg, sizeof(msg),
237                                     "Descriptor %d (conn) is %s, but should be %s.",
238                                     fd, dtype2str(mode), dtype2str(S_IFSOCK));
239                                 break;
240                         }
241                 } else if (res->hr_role == HAST_ROLE_SECONDARY &&
242                     res->hr_conn != NULL &&
243                     fd == proto_descriptor(res->hr_conn)) {
244                         if (isopen) {
245                                 (void)snprintf(msg, sizeof(msg),
246                                     "Descriptor %d (conn) is open, but should be closed.",
247                                     fd);
248                                 break;
249                         }
250                 } else if (res->hr_role == HAST_ROLE_SECONDARY &&
251                     fd == proto_descriptor(res->hr_remotein)) {
252                         if (!isopen) {
253                                 (void)snprintf(msg, sizeof(msg),
254                                     "Descriptor %d (remote in) is closed, but should be open.",
255                                     fd);
256                                 break;
257                         }
258                         if (!S_ISSOCK(mode)) {
259                                 (void)snprintf(msg, sizeof(msg),
260                                     "Descriptor %d (remote in) is %s, but should be %s.",
261                                     fd, dtype2str(mode), dtype2str(S_IFSOCK));
262                                 break;
263                         }
264                 } else if (res->hr_role == HAST_ROLE_SECONDARY &&
265                     fd == proto_descriptor(res->hr_remoteout)) {
266                         if (!isopen) {
267                                 (void)snprintf(msg, sizeof(msg),
268                                     "Descriptor %d (remote out) is closed, but should be open.",
269                                     fd);
270                                 break;
271                         }
272                         if (!S_ISSOCK(mode)) {
273                                 (void)snprintf(msg, sizeof(msg),
274                                     "Descriptor %d (remote out) is %s, but should be %s.",
275                                     fd, dtype2str(mode), dtype2str(S_IFSOCK));
276                                 break;
277                         }
278                 } else {
279                         if (isopen) {
280                                 (void)snprintf(msg, sizeof(msg),
281                                     "Descriptor %d is open (%s), but should be closed.",
282                                     fd, dtype2str(mode));
283                                 break;
284                         }
285                 }
286         }
287         if (msg[0] != '\0') {
288                 pjdlog_init(pjdlogmode);
289                 pjdlog_prefix_set("[%s] (%s) ", res->hr_name,
290                     role2str(res->hr_role));
291                 PJDLOG_ABORT("%s", msg);
292         }
293 }
294
295 static void
296 child_exit_log(unsigned int pid, int status)
297 {
298
299         if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
300                 pjdlog_debug(1, "Worker process exited gracefully (pid=%u).",
301                     pid);
302         } else if (WIFSIGNALED(status)) {
303                 pjdlog_error("Worker process killed (pid=%u, signal=%d).",
304                     pid, WTERMSIG(status));
305         } else {
306                 pjdlog_error("Worker process exited ungracefully (pid=%u, exitcode=%d).",
307                     pid, WIFEXITED(status) ? WEXITSTATUS(status) : -1);
308         }
309 }
310
311 static void
312 child_exit(void)
313 {
314         struct hast_resource *res;
315         int status;
316         pid_t pid;
317
318         while ((pid = wait3(&status, WNOHANG, NULL)) > 0) {
319                 /* Find resource related to the process that just exited. */
320                 TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
321                         if (pid == res->hr_workerpid)
322                                 break;
323                 }
324                 if (res == NULL) {
325                         /*
326                          * This can happen when new connection arrives and we
327                          * cancel child responsible for the old one or if this
328                          * was hook which we executed.
329                          */
330                         hook_check_one(pid, status);
331                         continue;
332                 }
333                 pjdlog_prefix_set("[%s] (%s) ", res->hr_name,
334                     role2str(res->hr_role));
335                 child_exit_log(pid, status);
336                 child_cleanup(res);
337                 if (res->hr_role == HAST_ROLE_PRIMARY) {
338                         /*
339                          * Restart child process if it was killed by signal
340                          * or exited because of temporary problem.
341                          */
342                         if (WIFSIGNALED(status) ||
343                             (WIFEXITED(status) &&
344                              WEXITSTATUS(status) == EX_TEMPFAIL)) {
345                                 sleep(1);
346                                 pjdlog_info("Restarting worker process.");
347                                 hastd_primary(res);
348                         } else {
349                                 res->hr_role = HAST_ROLE_INIT;
350                                 pjdlog_info("Changing resource role back to %s.",
351                                     role2str(res->hr_role));
352                         }
353                 }
354                 pjdlog_prefix_set("%s", "");
355         }
356 }
357
358 static bool
359 resource_needs_restart(const struct hast_resource *res0,
360     const struct hast_resource *res1)
361 {
362
363         PJDLOG_ASSERT(strcmp(res0->hr_name, res1->hr_name) == 0);
364
365         if (strcmp(res0->hr_provname, res1->hr_provname) != 0)
366                 return (true);
367         if (strcmp(res0->hr_localpath, res1->hr_localpath) != 0)
368                 return (true);
369         if (res0->hr_role == HAST_ROLE_INIT ||
370             res0->hr_role == HAST_ROLE_SECONDARY) {
371                 if (strcmp(res0->hr_remoteaddr, res1->hr_remoteaddr) != 0)
372                         return (true);
373                 if (strcmp(res0->hr_sourceaddr, res1->hr_sourceaddr) != 0)
374                         return (true);
375                 if (res0->hr_replication != res1->hr_replication)
376                         return (true);
377                 if (res0->hr_checksum != res1->hr_checksum)
378                         return (true);
379                 if (res0->hr_compression != res1->hr_compression)
380                         return (true);
381                 if (res0->hr_timeout != res1->hr_timeout)
382                         return (true);
383                 if (strcmp(res0->hr_exec, res1->hr_exec) != 0)
384                         return (true);
385         }
386         return (false);
387 }
388
389 static bool
390 resource_needs_reload(const struct hast_resource *res0,
391     const struct hast_resource *res1)
392 {
393
394         PJDLOG_ASSERT(strcmp(res0->hr_name, res1->hr_name) == 0);
395         PJDLOG_ASSERT(strcmp(res0->hr_provname, res1->hr_provname) == 0);
396         PJDLOG_ASSERT(strcmp(res0->hr_localpath, res1->hr_localpath) == 0);
397
398         if (res0->hr_role != HAST_ROLE_PRIMARY)
399                 return (false);
400
401         if (strcmp(res0->hr_remoteaddr, res1->hr_remoteaddr) != 0)
402                 return (true);
403         if (strcmp(res0->hr_sourceaddr, res1->hr_sourceaddr) != 0)
404                 return (true);
405         if (res0->hr_replication != res1->hr_replication)
406                 return (true);
407         if (res0->hr_checksum != res1->hr_checksum)
408                 return (true);
409         if (res0->hr_compression != res1->hr_compression)
410                 return (true);
411         if (res0->hr_timeout != res1->hr_timeout)
412                 return (true);
413         if (strcmp(res0->hr_exec, res1->hr_exec) != 0)
414                 return (true);
415         return (false);
416 }
417
418 static void
419 resource_reload(const struct hast_resource *res)
420 {
421         struct nv *nvin, *nvout;
422         int error;
423
424         PJDLOG_ASSERT(res->hr_role == HAST_ROLE_PRIMARY);
425
426         nvout = nv_alloc();
427         nv_add_uint8(nvout, HASTCTL_RELOAD, "cmd");
428         nv_add_string(nvout, res->hr_remoteaddr, "remoteaddr");
429         nv_add_string(nvout, res->hr_sourceaddr, "sourceaddr");
430         nv_add_int32(nvout, (int32_t)res->hr_replication, "replication");
431         nv_add_int32(nvout, (int32_t)res->hr_checksum, "checksum");
432         nv_add_int32(nvout, (int32_t)res->hr_compression, "compression");
433         nv_add_int32(nvout, (int32_t)res->hr_timeout, "timeout");
434         nv_add_string(nvout, res->hr_exec, "exec");
435         if (nv_error(nvout) != 0) {
436                 nv_free(nvout);
437                 pjdlog_error("Unable to allocate header for reload message.");
438                 return;
439         }
440         if (hast_proto_send(res, res->hr_ctrl, nvout, NULL, 0) < 0) {
441                 pjdlog_errno(LOG_ERR, "Unable to send reload message");
442                 nv_free(nvout);
443                 return;
444         }
445         nv_free(nvout);
446
447         /* Receive response. */
448         if (hast_proto_recv_hdr(res->hr_ctrl, &nvin) < 0) {
449                 pjdlog_errno(LOG_ERR, "Unable to receive reload reply");
450                 return;
451         }
452         error = nv_get_int16(nvin, "error");
453         nv_free(nvin);
454         if (error != 0) {
455                 pjdlog_common(LOG_ERR, 0, error, "Reload failed");
456                 return;
457         }
458 }
459
460 static void
461 hastd_reload(void)
462 {
463         struct hastd_config *newcfg;
464         struct hast_resource *nres, *cres, *tres;
465         uint8_t role;
466
467         pjdlog_info("Reloading configuration...");
468
469         newcfg = yy_config_parse(cfgpath, false);
470         if (newcfg == NULL)
471                 goto failed;
472
473         /*
474          * Check if control address has changed.
475          */
476         if (strcmp(cfg->hc_controladdr, newcfg->hc_controladdr) != 0) {
477                 if (proto_server(newcfg->hc_controladdr,
478                     &newcfg->hc_controlconn) < 0) {
479                         pjdlog_errno(LOG_ERR,
480                             "Unable to listen on control address %s",
481                             newcfg->hc_controladdr);
482                         goto failed;
483                 }
484         }
485         /*
486          * Check if listen address has changed.
487          */
488         if (strcmp(cfg->hc_listenaddr, newcfg->hc_listenaddr) != 0) {
489                 if (proto_server(newcfg->hc_listenaddr,
490                     &newcfg->hc_listenconn) < 0) {
491                         pjdlog_errno(LOG_ERR, "Unable to listen on address %s",
492                             newcfg->hc_listenaddr);
493                         goto failed;
494                 }
495         }
496         /*
497          * Only when both control and listen sockets are successfully
498          * initialized switch them to new configuration.
499          */
500         if (newcfg->hc_controlconn != NULL) {
501                 pjdlog_info("Control socket changed from %s to %s.",
502                     cfg->hc_controladdr, newcfg->hc_controladdr);
503                 proto_close(cfg->hc_controlconn);
504                 cfg->hc_controlconn = newcfg->hc_controlconn;
505                 newcfg->hc_controlconn = NULL;
506                 strlcpy(cfg->hc_controladdr, newcfg->hc_controladdr,
507                     sizeof(cfg->hc_controladdr));
508         }
509         if (newcfg->hc_listenconn != NULL) {
510                 pjdlog_info("Listen socket changed from %s to %s.",
511                     cfg->hc_listenaddr, newcfg->hc_listenaddr);
512                 proto_close(cfg->hc_listenconn);
513                 cfg->hc_listenconn = newcfg->hc_listenconn;
514                 newcfg->hc_listenconn = NULL;
515                 strlcpy(cfg->hc_listenaddr, newcfg->hc_listenaddr,
516                     sizeof(cfg->hc_listenaddr));
517         }
518
519         /*
520          * Stop and remove resources that were removed from the configuration.
521          */
522         TAILQ_FOREACH_SAFE(cres, &cfg->hc_resources, hr_next, tres) {
523                 TAILQ_FOREACH(nres, &newcfg->hc_resources, hr_next) {
524                         if (strcmp(cres->hr_name, nres->hr_name) == 0)
525                                 break;
526                 }
527                 if (nres == NULL) {
528                         control_set_role(cres, HAST_ROLE_INIT);
529                         TAILQ_REMOVE(&cfg->hc_resources, cres, hr_next);
530                         pjdlog_info("Resource %s removed.", cres->hr_name);
531                         free(cres);
532                 }
533         }
534         /*
535          * Move new resources to the current configuration.
536          */
537         TAILQ_FOREACH_SAFE(nres, &newcfg->hc_resources, hr_next, tres) {
538                 TAILQ_FOREACH(cres, &cfg->hc_resources, hr_next) {
539                         if (strcmp(cres->hr_name, nres->hr_name) == 0)
540                                 break;
541                 }
542                 if (cres == NULL) {
543                         TAILQ_REMOVE(&newcfg->hc_resources, nres, hr_next);
544                         TAILQ_INSERT_TAIL(&cfg->hc_resources, nres, hr_next);
545                         pjdlog_info("Resource %s added.", nres->hr_name);
546                 }
547         }
548         /*
549          * Deal with modified resources.
550          * Depending on what has changed exactly we might want to perform
551          * different actions.
552          *
553          * We do full resource restart in the following situations:
554          * Resource role is INIT or SECONDARY.
555          * Resource role is PRIMARY and path to local component or provider
556          * name has changed.
557          * In case of PRIMARY, the worker process will be killed and restarted,
558          * which also means removing /dev/hast/<name> provider and
559          * recreating it.
560          *
561          * We do just reload (send SIGHUP to worker process) if we act as
562          * PRIMARY, but only if remote address, replication mode, timeout or
563          * execution path has changed. For those, there is no need to restart
564          * worker process.
565          * If PRIMARY receives SIGHUP, it will reconnect if remote address or
566          * replication mode has changed or simply set new timeout if only
567          * timeout has changed.
568          */
569         TAILQ_FOREACH_SAFE(nres, &newcfg->hc_resources, hr_next, tres) {
570                 TAILQ_FOREACH(cres, &cfg->hc_resources, hr_next) {
571                         if (strcmp(cres->hr_name, nres->hr_name) == 0)
572                                 break;
573                 }
574                 PJDLOG_ASSERT(cres != NULL);
575                 if (resource_needs_restart(cres, nres)) {
576                         pjdlog_info("Resource %s configuration was modified, restarting it.",
577                             cres->hr_name);
578                         role = cres->hr_role;
579                         control_set_role(cres, HAST_ROLE_INIT);
580                         TAILQ_REMOVE(&cfg->hc_resources, cres, hr_next);
581                         free(cres);
582                         TAILQ_REMOVE(&newcfg->hc_resources, nres, hr_next);
583                         TAILQ_INSERT_TAIL(&cfg->hc_resources, nres, hr_next);
584                         control_set_role(nres, role);
585                 } else if (resource_needs_reload(cres, nres)) {
586                         pjdlog_info("Resource %s configuration was modified, reloading it.",
587                             cres->hr_name);
588                         strlcpy(cres->hr_remoteaddr, nres->hr_remoteaddr,
589                             sizeof(cres->hr_remoteaddr));
590                         strlcpy(cres->hr_sourceaddr, nres->hr_sourceaddr,
591                             sizeof(cres->hr_sourceaddr));
592                         cres->hr_replication = nres->hr_replication;
593                         cres->hr_checksum = nres->hr_checksum;
594                         cres->hr_compression = nres->hr_compression;
595                         cres->hr_timeout = nres->hr_timeout;
596                         strlcpy(cres->hr_exec, nres->hr_exec,
597                             sizeof(cres->hr_exec));
598                         if (cres->hr_workerpid != 0)
599                                 resource_reload(cres);
600                 }
601         }
602
603         yy_config_free(newcfg);
604         pjdlog_info("Configuration reloaded successfully.");
605         return;
606 failed:
607         if (newcfg != NULL) {
608                 if (newcfg->hc_controlconn != NULL)
609                         proto_close(newcfg->hc_controlconn);
610                 if (newcfg->hc_listenconn != NULL)
611                         proto_close(newcfg->hc_listenconn);
612                 yy_config_free(newcfg);
613         }
614         pjdlog_warning("Configuration not reloaded.");
615 }
616
617 static void
618 terminate_workers(void)
619 {
620         struct hast_resource *res;
621
622         pjdlog_info("Termination signal received, exiting.");
623         TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
624                 if (res->hr_workerpid == 0)
625                         continue;
626                 pjdlog_info("Terminating worker process (resource=%s, role=%s, pid=%u).",
627                     res->hr_name, role2str(res->hr_role), res->hr_workerpid);
628                 if (kill(res->hr_workerpid, SIGTERM) == 0)
629                         continue;
630                 pjdlog_errno(LOG_WARNING,
631                     "Unable to send signal to worker process (resource=%s, role=%s, pid=%u).",
632                     res->hr_name, role2str(res->hr_role), res->hr_workerpid);
633         }
634 }
635
636 static void
637 listen_accept(void)
638 {
639         struct hast_resource *res;
640         struct proto_conn *conn;
641         struct nv *nvin, *nvout, *nverr;
642         const char *resname;
643         const unsigned char *token;
644         char laddr[256], raddr[256];
645         size_t size;
646         pid_t pid;
647         int status;
648
649         proto_local_address(cfg->hc_listenconn, laddr, sizeof(laddr));
650         pjdlog_debug(1, "Accepting connection to %s.", laddr);
651
652         if (proto_accept(cfg->hc_listenconn, &conn) < 0) {
653                 pjdlog_errno(LOG_ERR, "Unable to accept connection %s", laddr);
654                 return;
655         }
656
657         proto_local_address(conn, laddr, sizeof(laddr));
658         proto_remote_address(conn, raddr, sizeof(raddr));
659         pjdlog_info("Connection from %s to %s.", raddr, laddr);
660
661         /* Error in setting timeout is not critical, but why should it fail? */
662         if (proto_timeout(conn, HAST_TIMEOUT) < 0)
663                 pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
664
665         nvin = nvout = nverr = NULL;
666
667         /*
668          * Before receiving any data see if remote host have access to any
669          * resource.
670          */
671         TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
672                 if (proto_address_match(conn, res->hr_remoteaddr))
673                         break;
674         }
675         if (res == NULL) {
676                 pjdlog_error("Client %s isn't known.", raddr);
677                 goto close;
678         }
679         /* Ok, remote host can access at least one resource. */
680
681         if (hast_proto_recv_hdr(conn, &nvin) < 0) {
682                 pjdlog_errno(LOG_ERR, "Unable to receive header from %s",
683                     raddr);
684                 goto close;
685         }
686
687         resname = nv_get_string(nvin, "resource");
688         if (resname == NULL) {
689                 pjdlog_error("No 'resource' field in the header received from %s.",
690                     raddr);
691                 goto close;
692         }
693         pjdlog_debug(2, "%s: resource=%s", raddr, resname);
694         token = nv_get_uint8_array(nvin, &size, "token");
695         /*
696          * NULL token means that this is first conection.
697          */
698         if (token != NULL && size != sizeof(res->hr_token)) {
699                 pjdlog_error("Received token of invalid size from %s (expected %zu, got %zu).",
700                     raddr, sizeof(res->hr_token), size);
701                 goto close;
702         }
703
704         /*
705          * From now on we want to send errors to the remote node.
706          */
707         nverr = nv_alloc();
708
709         /* Find resource related to this connection. */
710         TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
711                 if (strcmp(resname, res->hr_name) == 0)
712                         break;
713         }
714         /* Have we found the resource? */
715         if (res == NULL) {
716                 pjdlog_error("No resource '%s' as requested by %s.",
717                     resname, raddr);
718                 nv_add_stringf(nverr, "errmsg", "Resource not configured.");
719                 goto fail;
720         }
721
722         /* Now that we know resource name setup log prefix. */
723         pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
724
725         /* Does the remote host have access to this resource? */
726         if (!proto_address_match(conn, res->hr_remoteaddr)) {
727                 pjdlog_error("Client %s has no access to the resource.", raddr);
728                 nv_add_stringf(nverr, "errmsg", "No access to the resource.");
729                 goto fail;
730         }
731         /* Is the resource marked as secondary? */
732         if (res->hr_role != HAST_ROLE_SECONDARY) {
733                 pjdlog_warning("We act as %s for the resource and not as %s as requested by %s.",
734                     role2str(res->hr_role), role2str(HAST_ROLE_SECONDARY),
735                     raddr);
736                 nv_add_stringf(nverr, "errmsg",
737                     "Remote node acts as %s for the resource and not as %s.",
738                     role2str(res->hr_role), role2str(HAST_ROLE_SECONDARY));
739                 if (res->hr_role == HAST_ROLE_PRIMARY) {
740                         /*
741                          * If we act as primary request the other side to wait
742                          * for us a bit, as we might be finishing cleanups.
743                          */
744                         nv_add_uint8(nverr, 1, "wait");
745                 }
746                 goto fail;
747         }
748         /* Does token (if exists) match? */
749         if (token != NULL && memcmp(token, res->hr_token,
750             sizeof(res->hr_token)) != 0) {
751                 pjdlog_error("Token received from %s doesn't match.", raddr);
752                 nv_add_stringf(nverr, "errmsg", "Token doesn't match.");
753                 goto fail;
754         }
755         /*
756          * If there is no token, but we have half-open connection
757          * (only remotein) or full connection (worker process is running)
758          * we have to cancel those and accept the new connection.
759          */
760         if (token == NULL) {
761                 PJDLOG_ASSERT(res->hr_remoteout == NULL);
762                 pjdlog_debug(1, "Initial connection from %s.", raddr);
763                 if (res->hr_workerpid != 0) {
764                         PJDLOG_ASSERT(res->hr_remotein == NULL);
765                         pjdlog_debug(1,
766                             "Worker process exists (pid=%u), stopping it.",
767                             (unsigned int)res->hr_workerpid);
768                         /* Stop child process. */
769                         if (kill(res->hr_workerpid, SIGINT) < 0) {
770                                 pjdlog_errno(LOG_ERR,
771                                     "Unable to stop worker process (pid=%u)",
772                                     (unsigned int)res->hr_workerpid);
773                                 /*
774                                  * Other than logging the problem we
775                                  * ignore it - nothing smart to do.
776                                  */
777                         }
778                         /* Wait for it to exit. */
779                         else if ((pid = waitpid(res->hr_workerpid,
780                             &status, 0)) != res->hr_workerpid) {
781                                 /* We can only log the problem. */
782                                 pjdlog_errno(LOG_ERR,
783                                     "Waiting for worker process (pid=%u) failed",
784                                     (unsigned int)res->hr_workerpid);
785                         } else {
786                                 child_exit_log(res->hr_workerpid, status);
787                         }
788                         child_cleanup(res);
789                 } else if (res->hr_remotein != NULL) {
790                         char oaddr[256];
791
792                         proto_remote_address(res->hr_remotein, oaddr,
793                             sizeof(oaddr));
794                         pjdlog_debug(1,
795                             "Canceling half-open connection from %s on connection from %s.",
796                             oaddr, raddr);
797                         proto_close(res->hr_remotein);
798                         res->hr_remotein = NULL;
799                 }
800         }
801
802         /*
803          * Checks and cleanups are done.
804          */
805
806         if (token == NULL) {
807                 arc4random_buf(res->hr_token, sizeof(res->hr_token));
808                 nvout = nv_alloc();
809                 nv_add_uint8_array(nvout, res->hr_token,
810                     sizeof(res->hr_token), "token");
811                 if (nv_error(nvout) != 0) {
812                         pjdlog_common(LOG_ERR, 0, nv_error(nvout),
813                             "Unable to prepare return header for %s", raddr);
814                         nv_add_stringf(nverr, "errmsg",
815                             "Remote node was unable to prepare return header: %s.",
816                             strerror(nv_error(nvout)));
817                         goto fail;
818                 }
819                 if (hast_proto_send(NULL, conn, nvout, NULL, 0) < 0) {
820                         int error = errno;
821
822                         pjdlog_errno(LOG_ERR, "Unable to send response to %s",
823                             raddr);
824                         nv_add_stringf(nverr, "errmsg",
825                             "Remote node was unable to send response: %s.",
826                             strerror(error));
827                         goto fail;
828                 }
829                 res->hr_remotein = conn;
830                 pjdlog_debug(1, "Incoming connection from %s configured.",
831                     raddr);
832         } else {
833                 res->hr_remoteout = conn;
834                 pjdlog_debug(1, "Outgoing connection to %s configured.", raddr);
835                 hastd_secondary(res, nvin);
836         }
837         nv_free(nvin);
838         nv_free(nvout);
839         nv_free(nverr);
840         pjdlog_prefix_set("%s", "");
841         return;
842 fail:
843         if (nv_error(nverr) != 0) {
844                 pjdlog_common(LOG_ERR, 0, nv_error(nverr),
845                     "Unable to prepare error header for %s", raddr);
846                 goto close;
847         }
848         if (hast_proto_send(NULL, conn, nverr, NULL, 0) < 0) {
849                 pjdlog_errno(LOG_ERR, "Unable to send error to %s", raddr);
850                 goto close;
851         }
852 close:
853         if (nvin != NULL)
854                 nv_free(nvin);
855         if (nvout != NULL)
856                 nv_free(nvout);
857         if (nverr != NULL)
858                 nv_free(nverr);
859         proto_close(conn);
860         pjdlog_prefix_set("%s", "");
861 }
862
863 static void
864 connection_migrate(struct hast_resource *res)
865 {
866         struct proto_conn *conn;
867         int16_t val = 0;
868
869         pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
870
871         PJDLOG_ASSERT(res->hr_role == HAST_ROLE_PRIMARY);
872
873         if (proto_recv(res->hr_conn, &val, sizeof(val)) < 0) {
874                 pjdlog_errno(LOG_WARNING,
875                     "Unable to receive connection command");
876                 return;
877         }
878         if (proto_client(res->hr_sourceaddr[0] != '\0' ? res->hr_sourceaddr : NULL,
879             res->hr_remoteaddr, &conn) < 0) {
880                 val = errno;
881                 pjdlog_errno(LOG_WARNING,
882                     "Unable to create outgoing connection to %s",
883                     res->hr_remoteaddr);
884                 goto out;
885         }
886         if (proto_connect(conn, -1) < 0) {
887                 val = errno;
888                 pjdlog_errno(LOG_WARNING, "Unable to connect to %s",
889                     res->hr_remoteaddr);
890                 proto_close(conn);
891                 goto out;
892         }
893         val = 0;
894 out:
895         if (proto_send(res->hr_conn, &val, sizeof(val)) < 0) {
896                 pjdlog_errno(LOG_WARNING,
897                     "Unable to send reply to connection request");
898         }
899         if (val == 0 && proto_connection_send(res->hr_conn, conn) < 0)
900                 pjdlog_errno(LOG_WARNING, "Unable to send connection");
901
902         pjdlog_prefix_set("%s", "");
903 }
904
905 static void
906 check_signals(void)
907 {
908         struct timespec sigtimeout;
909         sigset_t mask;
910         int signo;
911
912         sigtimeout.tv_sec = 0;
913         sigtimeout.tv_nsec = 0;
914
915         PJDLOG_VERIFY(sigemptyset(&mask) == 0);
916         PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0);
917         PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
918         PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
919         PJDLOG_VERIFY(sigaddset(&mask, SIGCHLD) == 0);
920
921         while ((signo = sigtimedwait(&mask, NULL, &sigtimeout)) != -1) {
922                 switch (signo) {
923                 case SIGINT:
924                 case SIGTERM:
925                         sigexit_received = true;
926                         terminate_workers();
927                         proto_close(cfg->hc_controlconn);
928                         exit(EX_OK);
929                         break;
930                 case SIGCHLD:
931                         child_exit();
932                         break;
933                 case SIGHUP:
934                         hastd_reload();
935                         break;
936                 default:
937                         PJDLOG_ABORT("Unexpected signal (%d).", signo);
938                 }
939         }
940 }
941
942 static void
943 main_loop(void)
944 {
945         struct hast_resource *res;
946         struct timeval seltimeout;
947         int fd, maxfd, ret;
948         time_t lastcheck, now;
949         fd_set rfds;
950
951         lastcheck = time(NULL);
952         seltimeout.tv_sec = REPORT_INTERVAL;
953         seltimeout.tv_usec = 0;
954
955         pjdlog_info("Started successfully, running protocol version %d.",
956             HAST_PROTO_VERSION);
957
958         for (;;) {
959                 check_signals();
960
961                 /* Setup descriptors for select(2). */
962                 FD_ZERO(&rfds);
963                 maxfd = fd = proto_descriptor(cfg->hc_controlconn);
964                 PJDLOG_ASSERT(fd >= 0);
965                 FD_SET(fd, &rfds);
966                 fd = proto_descriptor(cfg->hc_listenconn);
967                 PJDLOG_ASSERT(fd >= 0);
968                 FD_SET(fd, &rfds);
969                 maxfd = fd > maxfd ? fd : maxfd;
970                 TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
971                         if (res->hr_event == NULL)
972                                 continue;
973                         fd = proto_descriptor(res->hr_event);
974                         PJDLOG_ASSERT(fd >= 0);
975                         FD_SET(fd, &rfds);
976                         maxfd = fd > maxfd ? fd : maxfd;
977                         if (res->hr_role == HAST_ROLE_PRIMARY) {
978                                 /* Only primary workers asks for connections. */
979                                 PJDLOG_ASSERT(res->hr_conn != NULL);
980                                 fd = proto_descriptor(res->hr_conn);
981                                 PJDLOG_ASSERT(fd >= 0);
982                                 FD_SET(fd, &rfds);
983                                 maxfd = fd > maxfd ? fd : maxfd;
984                         } else {
985                                 PJDLOG_ASSERT(res->hr_conn == NULL);
986                         }
987                 }
988
989                 PJDLOG_ASSERT(maxfd + 1 <= (int)FD_SETSIZE);
990                 ret = select(maxfd + 1, &rfds, NULL, NULL, &seltimeout);
991                 now = time(NULL);
992                 if (lastcheck + REPORT_INTERVAL <= now) {
993                         hook_check();
994                         lastcheck = now;
995                 }
996                 if (ret == 0) {
997                         /*
998                          * select(2) timed out, so there should be no
999                          * descriptors to check.
1000                          */
1001                         continue;
1002                 } else if (ret == -1) {
1003                         if (errno == EINTR)
1004                                 continue;
1005                         KEEP_ERRNO((void)pidfile_remove(pfh));
1006                         pjdlog_exit(EX_OSERR, "select() failed");
1007                 }
1008
1009                 /*
1010                  * Check for signals before we do anything to update our
1011                  * info about terminated workers in the meantime.
1012                  */
1013                 check_signals();
1014
1015                 if (FD_ISSET(proto_descriptor(cfg->hc_controlconn), &rfds))
1016                         control_handle(cfg);
1017                 if (FD_ISSET(proto_descriptor(cfg->hc_listenconn), &rfds))
1018                         listen_accept();
1019                 TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
1020                         if (res->hr_event == NULL)
1021                                 continue;
1022                         if (FD_ISSET(proto_descriptor(res->hr_event), &rfds)) {
1023                                 if (event_recv(res) == 0)
1024                                         continue;
1025                                 /* The worker process exited? */
1026                                 proto_close(res->hr_event);
1027                                 res->hr_event = NULL;
1028                                 if (res->hr_conn != NULL) {
1029                                         proto_close(res->hr_conn);
1030                                         res->hr_conn = NULL;
1031                                 }
1032                                 continue;
1033                         }
1034                         if (res->hr_role == HAST_ROLE_PRIMARY) {
1035                                 PJDLOG_ASSERT(res->hr_conn != NULL);
1036                                 if (FD_ISSET(proto_descriptor(res->hr_conn),
1037                                     &rfds)) {
1038                                         connection_migrate(res);
1039                                 }
1040                         } else {
1041                                 PJDLOG_ASSERT(res->hr_conn == NULL);
1042                         }
1043                 }
1044         }
1045 }
1046
1047 static void
1048 dummy_sighandler(int sig __unused)
1049 {
1050         /* Nothing to do. */
1051 }
1052
1053 int
1054 main(int argc, char *argv[])
1055 {
1056         const char *pidfile;
1057         pid_t otherpid;
1058         bool foreground;
1059         int debuglevel;
1060         sigset_t mask;
1061
1062         foreground = false;
1063         debuglevel = 0;
1064         pidfile = HASTD_PIDFILE;
1065
1066         for (;;) {
1067                 int ch;
1068
1069                 ch = getopt(argc, argv, "c:dFhP:");
1070                 if (ch == -1)
1071                         break;
1072                 switch (ch) {
1073                 case 'c':
1074                         cfgpath = optarg;
1075                         break;
1076                 case 'd':
1077                         debuglevel++;
1078                         break;
1079                 case 'F':
1080                         foreground = true;
1081                         break;
1082                 case 'P':
1083                         pidfile = optarg;
1084                         break;
1085                 case 'h':
1086                 default:
1087                         usage();
1088                 }
1089         }
1090         argc -= optind;
1091         argv += optind;
1092
1093         pjdlog_init(PJDLOG_MODE_STD);
1094         pjdlog_debug_set(debuglevel);
1095
1096         g_gate_load();
1097
1098         pfh = pidfile_open(pidfile, 0600, &otherpid);
1099         if (pfh == NULL) {
1100                 if (errno == EEXIST) {
1101                         pjdlog_exitx(EX_TEMPFAIL,
1102                             "Another hastd is already running, pid: %jd.",
1103                             (intmax_t)otherpid);
1104                 }
1105                 /* If we cannot create pidfile from other reasons, only warn. */
1106                 pjdlog_errno(LOG_WARNING, "Unable to open or create pidfile");
1107         }
1108
1109         cfg = yy_config_parse(cfgpath, true);
1110         PJDLOG_ASSERT(cfg != NULL);
1111
1112         /*
1113          * Restore default actions for interesting signals in case parent
1114          * process (like init(8)) decided to ignore some of them (like SIGHUP).
1115          */
1116         PJDLOG_VERIFY(signal(SIGHUP, SIG_DFL) != SIG_ERR);
1117         PJDLOG_VERIFY(signal(SIGINT, SIG_DFL) != SIG_ERR);
1118         PJDLOG_VERIFY(signal(SIGTERM, SIG_DFL) != SIG_ERR);
1119         /*
1120          * Because SIGCHLD is ignored by default, setup dummy handler for it,
1121          * so we can mask it.
1122          */
1123         PJDLOG_VERIFY(signal(SIGCHLD, dummy_sighandler) != SIG_ERR);
1124
1125         PJDLOG_VERIFY(sigemptyset(&mask) == 0);
1126         PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0);
1127         PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
1128         PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
1129         PJDLOG_VERIFY(sigaddset(&mask, SIGCHLD) == 0);
1130         PJDLOG_VERIFY(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
1131
1132         /* Listen on control address. */
1133         if (proto_server(cfg->hc_controladdr, &cfg->hc_controlconn) < 0) {
1134                 KEEP_ERRNO((void)pidfile_remove(pfh));
1135                 pjdlog_exit(EX_OSERR, "Unable to listen on control address %s",
1136                     cfg->hc_controladdr);
1137         }
1138         /* Listen for remote connections. */
1139         if (proto_server(cfg->hc_listenaddr, &cfg->hc_listenconn) < 0) {
1140                 KEEP_ERRNO((void)pidfile_remove(pfh));
1141                 pjdlog_exit(EX_OSERR, "Unable to listen on address %s",
1142                     cfg->hc_listenaddr);
1143         }
1144
1145         if (!foreground) {
1146                 if (daemon(0, 0) < 0) {
1147                         KEEP_ERRNO((void)pidfile_remove(pfh));
1148                         pjdlog_exit(EX_OSERR, "Unable to daemonize");
1149                 }
1150
1151                 /* Start logging to syslog. */
1152                 pjdlog_mode_set(PJDLOG_MODE_SYSLOG);
1153
1154                 /* Write PID to a file. */
1155                 if (pidfile_write(pfh) < 0) {
1156                         pjdlog_errno(LOG_WARNING,
1157                             "Unable to write PID to a file");
1158                 }
1159         }
1160
1161         hook_init();
1162
1163         main_loop();
1164
1165         exit(0);
1166 }