hastd.c revision 219814
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: head/sbin/hastd/hastd.c 219814 2011-03-21 08:33:58Z pjd $"); 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. */ 64const char *cfgpath = HAST_CONFIG; 65/* Hastd configuration. */ 66static struct hastd_config *cfg; 67/* Was SIGINT or SIGTERM signal received? */ 68bool sigexit_received = false; 69/* PID file handle. */ 70struct pidfh *pfh; 71 72/* How often check for hooks running for too long. */ 73#define REPORT_INTERVAL 5 74 75static void 76usage(void) 77{ 78 79 errx(EX_USAGE, "[-dFh] [-c config] [-P pidfile]"); 80} 81 82static void 83g_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 97void 98descriptors_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 129static const char * 130dtype2str(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 153void 154descriptors_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 (fd == proto_descriptor(res->hr_conn)) { 228 if (!isopen) { 229 (void)snprintf(msg, sizeof(msg), 230 "Descriptor %d (conn) is closed, but should be open.", 231 fd); 232 break; 233 } 234 if (!S_ISSOCK(mode)) { 235 (void)snprintf(msg, sizeof(msg), 236 "Descriptor %d (conn) is %s, but should be %s.", 237 fd, dtype2str(mode), dtype2str(S_IFSOCK)); 238 break; 239 } 240 } else if (res->hr_role == HAST_ROLE_SECONDARY && 241 fd == proto_descriptor(res->hr_remotein)) { 242 if (!isopen) { 243 (void)snprintf(msg, sizeof(msg), 244 "Descriptor %d (remote in) is closed, but should be open.", 245 fd); 246 break; 247 } 248 if (!S_ISSOCK(mode)) { 249 (void)snprintf(msg, sizeof(msg), 250 "Descriptor %d (remote in) is %s, but should be %s.", 251 fd, dtype2str(mode), dtype2str(S_IFSOCK)); 252 break; 253 } 254 } else if (res->hr_role == HAST_ROLE_SECONDARY && 255 fd == proto_descriptor(res->hr_remoteout)) { 256 if (!isopen) { 257 (void)snprintf(msg, sizeof(msg), 258 "Descriptor %d (remote out) is closed, but should be open.", 259 fd); 260 break; 261 } 262 if (!S_ISSOCK(mode)) { 263 (void)snprintf(msg, sizeof(msg), 264 "Descriptor %d (remote out) is %s, but should be %s.", 265 fd, dtype2str(mode), dtype2str(S_IFSOCK)); 266 break; 267 } 268 } else { 269 if (isopen) { 270 (void)snprintf(msg, sizeof(msg), 271 "Descriptor %d is open (%s), but should be closed.", 272 fd, dtype2str(mode)); 273 break; 274 } 275 } 276 } 277 if (msg[0] != '\0') { 278 pjdlog_init(pjdlogmode); 279 pjdlog_prefix_set("[%s] (%s) ", res->hr_name, 280 role2str(res->hr_role)); 281 PJDLOG_ABORT("%s", msg); 282 } 283} 284 285static void 286child_exit_log(unsigned int pid, int status) 287{ 288 289 if (WIFEXITED(status) && WEXITSTATUS(status) == 0) { 290 pjdlog_debug(1, "Worker process exited gracefully (pid=%u).", 291 pid); 292 } else if (WIFSIGNALED(status)) { 293 pjdlog_error("Worker process killed (pid=%u, signal=%d).", 294 pid, WTERMSIG(status)); 295 } else { 296 pjdlog_error("Worker process exited ungracefully (pid=%u, exitcode=%d).", 297 pid, WIFEXITED(status) ? WEXITSTATUS(status) : -1); 298 } 299} 300 301static void 302child_exit(void) 303{ 304 struct hast_resource *res; 305 int status; 306 pid_t pid; 307 308 while ((pid = wait3(&status, WNOHANG, NULL)) > 0) { 309 /* Find resource related to the process that just exited. */ 310 TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) { 311 if (pid == res->hr_workerpid) 312 break; 313 } 314 if (res == NULL) { 315 /* 316 * This can happen when new connection arrives and we 317 * cancel child responsible for the old one or if this 318 * was hook which we executed. 319 */ 320 hook_check_one(pid, status); 321 continue; 322 } 323 pjdlog_prefix_set("[%s] (%s) ", res->hr_name, 324 role2str(res->hr_role)); 325 child_exit_log(pid, status); 326 child_cleanup(res); 327 if (res->hr_role == HAST_ROLE_PRIMARY) { 328 /* 329 * Restart child process if it was killed by signal 330 * or exited because of temporary problem. 331 */ 332 if (WIFSIGNALED(status) || 333 (WIFEXITED(status) && 334 WEXITSTATUS(status) == EX_TEMPFAIL)) { 335 sleep(1); 336 pjdlog_info("Restarting worker process."); 337 hastd_primary(res); 338 } else { 339 res->hr_role = HAST_ROLE_INIT; 340 pjdlog_info("Changing resource role back to %s.", 341 role2str(res->hr_role)); 342 } 343 } 344 pjdlog_prefix_set("%s", ""); 345 } 346} 347 348static bool 349resource_needs_restart(const struct hast_resource *res0, 350 const struct hast_resource *res1) 351{ 352 353 PJDLOG_ASSERT(strcmp(res0->hr_name, res1->hr_name) == 0); 354 355 if (strcmp(res0->hr_provname, res1->hr_provname) != 0) 356 return (true); 357 if (strcmp(res0->hr_localpath, res1->hr_localpath) != 0) 358 return (true); 359 if (res0->hr_role == HAST_ROLE_INIT || 360 res0->hr_role == HAST_ROLE_SECONDARY) { 361 if (strcmp(res0->hr_remoteaddr, res1->hr_remoteaddr) != 0) 362 return (true); 363 if (res0->hr_replication != res1->hr_replication) 364 return (true); 365 if (res0->hr_checksum != res1->hr_checksum) 366 return (true); 367 if (res0->hr_compression != res1->hr_compression) 368 return (true); 369 if (res0->hr_timeout != res1->hr_timeout) 370 return (true); 371 if (strcmp(res0->hr_exec, res1->hr_exec) != 0) 372 return (true); 373 } 374 return (false); 375} 376 377static bool 378resource_needs_reload(const struct hast_resource *res0, 379 const struct hast_resource *res1) 380{ 381 382 PJDLOG_ASSERT(strcmp(res0->hr_name, res1->hr_name) == 0); 383 PJDLOG_ASSERT(strcmp(res0->hr_provname, res1->hr_provname) == 0); 384 PJDLOG_ASSERT(strcmp(res0->hr_localpath, res1->hr_localpath) == 0); 385 386 if (res0->hr_role != HAST_ROLE_PRIMARY) 387 return (false); 388 389 if (strcmp(res0->hr_remoteaddr, res1->hr_remoteaddr) != 0) 390 return (true); 391 if (res0->hr_replication != res1->hr_replication) 392 return (true); 393 if (res0->hr_checksum != res1->hr_checksum) 394 return (true); 395 if (res0->hr_compression != res1->hr_compression) 396 return (true); 397 if (res0->hr_timeout != res1->hr_timeout) 398 return (true); 399 if (strcmp(res0->hr_exec, res1->hr_exec) != 0) 400 return (true); 401 return (false); 402} 403 404static void 405resource_reload(const struct hast_resource *res) 406{ 407 struct nv *nvin, *nvout; 408 int error; 409 410 PJDLOG_ASSERT(res->hr_role == HAST_ROLE_PRIMARY); 411 412 nvout = nv_alloc(); 413 nv_add_uint8(nvout, HASTCTL_RELOAD, "cmd"); 414 nv_add_string(nvout, res->hr_remoteaddr, "remoteaddr"); 415 nv_add_int32(nvout, (int32_t)res->hr_replication, "replication"); 416 nv_add_int32(nvout, (int32_t)res->hr_checksum, "checksum"); 417 nv_add_int32(nvout, (int32_t)res->hr_compression, "compression"); 418 nv_add_int32(nvout, (int32_t)res->hr_timeout, "timeout"); 419 nv_add_string(nvout, res->hr_exec, "exec"); 420 if (nv_error(nvout) != 0) { 421 nv_free(nvout); 422 pjdlog_error("Unable to allocate header for reload message."); 423 return; 424 } 425 if (hast_proto_send(res, res->hr_ctrl, nvout, NULL, 0) < 0) { 426 pjdlog_errno(LOG_ERR, "Unable to send reload message"); 427 nv_free(nvout); 428 return; 429 } 430 nv_free(nvout); 431 432 /* Receive response. */ 433 if (hast_proto_recv_hdr(res->hr_ctrl, &nvin) < 0) { 434 pjdlog_errno(LOG_ERR, "Unable to receive reload reply"); 435 return; 436 } 437 error = nv_get_int16(nvin, "error"); 438 nv_free(nvin); 439 if (error != 0) { 440 pjdlog_common(LOG_ERR, 0, error, "Reload failed"); 441 return; 442 } 443} 444 445static void 446hastd_reload(void) 447{ 448 struct hastd_config *newcfg; 449 struct hast_resource *nres, *cres, *tres; 450 uint8_t role; 451 452 pjdlog_info("Reloading configuration..."); 453 454 newcfg = yy_config_parse(cfgpath, false); 455 if (newcfg == NULL) 456 goto failed; 457 458 /* 459 * Check if control address has changed. 460 */ 461 if (strcmp(cfg->hc_controladdr, newcfg->hc_controladdr) != 0) { 462 if (proto_server(newcfg->hc_controladdr, 463 &newcfg->hc_controlconn) < 0) { 464 pjdlog_errno(LOG_ERR, 465 "Unable to listen on control address %s", 466 newcfg->hc_controladdr); 467 goto failed; 468 } 469 } 470 /* 471 * Check if listen address has changed. 472 */ 473 if (strcmp(cfg->hc_listenaddr, newcfg->hc_listenaddr) != 0) { 474 if (proto_server(newcfg->hc_listenaddr, 475 &newcfg->hc_listenconn) < 0) { 476 pjdlog_errno(LOG_ERR, "Unable to listen on address %s", 477 newcfg->hc_listenaddr); 478 goto failed; 479 } 480 } 481 /* 482 * Only when both control and listen sockets are successfully 483 * initialized switch them to new configuration. 484 */ 485 if (newcfg->hc_controlconn != NULL) { 486 pjdlog_info("Control socket changed from %s to %s.", 487 cfg->hc_controladdr, newcfg->hc_controladdr); 488 proto_close(cfg->hc_controlconn); 489 cfg->hc_controlconn = newcfg->hc_controlconn; 490 newcfg->hc_controlconn = NULL; 491 strlcpy(cfg->hc_controladdr, newcfg->hc_controladdr, 492 sizeof(cfg->hc_controladdr)); 493 } 494 if (newcfg->hc_listenconn != NULL) { 495 pjdlog_info("Listen socket changed from %s to %s.", 496 cfg->hc_listenaddr, newcfg->hc_listenaddr); 497 proto_close(cfg->hc_listenconn); 498 cfg->hc_listenconn = newcfg->hc_listenconn; 499 newcfg->hc_listenconn = NULL; 500 strlcpy(cfg->hc_listenaddr, newcfg->hc_listenaddr, 501 sizeof(cfg->hc_listenaddr)); 502 } 503 504 /* 505 * Stop and remove resources that were removed from the configuration. 506 */ 507 TAILQ_FOREACH_SAFE(cres, &cfg->hc_resources, hr_next, tres) { 508 TAILQ_FOREACH(nres, &newcfg->hc_resources, hr_next) { 509 if (strcmp(cres->hr_name, nres->hr_name) == 0) 510 break; 511 } 512 if (nres == NULL) { 513 control_set_role(cres, HAST_ROLE_INIT); 514 TAILQ_REMOVE(&cfg->hc_resources, cres, hr_next); 515 pjdlog_info("Resource %s removed.", cres->hr_name); 516 free(cres); 517 } 518 } 519 /* 520 * Move new resources to the current configuration. 521 */ 522 TAILQ_FOREACH_SAFE(nres, &newcfg->hc_resources, hr_next, tres) { 523 TAILQ_FOREACH(cres, &cfg->hc_resources, hr_next) { 524 if (strcmp(cres->hr_name, nres->hr_name) == 0) 525 break; 526 } 527 if (cres == NULL) { 528 TAILQ_REMOVE(&newcfg->hc_resources, nres, hr_next); 529 TAILQ_INSERT_TAIL(&cfg->hc_resources, nres, hr_next); 530 pjdlog_info("Resource %s added.", nres->hr_name); 531 } 532 } 533 /* 534 * Deal with modified resources. 535 * Depending on what has changed exactly we might want to perform 536 * different actions. 537 * 538 * We do full resource restart in the following situations: 539 * Resource role is INIT or SECONDARY. 540 * Resource role is PRIMARY and path to local component or provider 541 * name has changed. 542 * In case of PRIMARY, the worker process will be killed and restarted, 543 * which also means removing /dev/hast/<name> provider and 544 * recreating it. 545 * 546 * We do just reload (send SIGHUP to worker process) if we act as 547 * PRIMARY, but only if remote address, replication mode, timeout or 548 * execution path has changed. For those, there is no need to restart 549 * worker process. 550 * If PRIMARY receives SIGHUP, it will reconnect if remote address or 551 * replication mode has changed or simply set new timeout if only 552 * timeout has changed. 553 */ 554 TAILQ_FOREACH_SAFE(nres, &newcfg->hc_resources, hr_next, tres) { 555 TAILQ_FOREACH(cres, &cfg->hc_resources, hr_next) { 556 if (strcmp(cres->hr_name, nres->hr_name) == 0) 557 break; 558 } 559 PJDLOG_ASSERT(cres != NULL); 560 if (resource_needs_restart(cres, nres)) { 561 pjdlog_info("Resource %s configuration was modified, restarting it.", 562 cres->hr_name); 563 role = cres->hr_role; 564 control_set_role(cres, HAST_ROLE_INIT); 565 TAILQ_REMOVE(&cfg->hc_resources, cres, hr_next); 566 free(cres); 567 TAILQ_REMOVE(&newcfg->hc_resources, nres, hr_next); 568 TAILQ_INSERT_TAIL(&cfg->hc_resources, nres, hr_next); 569 control_set_role(nres, role); 570 } else if (resource_needs_reload(cres, nres)) { 571 pjdlog_info("Resource %s configuration was modified, reloading it.", 572 cres->hr_name); 573 strlcpy(cres->hr_remoteaddr, nres->hr_remoteaddr, 574 sizeof(cres->hr_remoteaddr)); 575 cres->hr_replication = nres->hr_replication; 576 cres->hr_checksum = nres->hr_checksum; 577 cres->hr_compression = nres->hr_compression; 578 cres->hr_timeout = nres->hr_timeout; 579 strlcpy(cres->hr_exec, nres->hr_exec, 580 sizeof(cres->hr_exec)); 581 if (cres->hr_workerpid != 0) 582 resource_reload(cres); 583 } 584 } 585 586 yy_config_free(newcfg); 587 pjdlog_info("Configuration reloaded successfully."); 588 return; 589failed: 590 if (newcfg != NULL) { 591 if (newcfg->hc_controlconn != NULL) 592 proto_close(newcfg->hc_controlconn); 593 if (newcfg->hc_listenconn != NULL) 594 proto_close(newcfg->hc_listenconn); 595 yy_config_free(newcfg); 596 } 597 pjdlog_warning("Configuration not reloaded."); 598} 599 600static void 601terminate_workers(void) 602{ 603 struct hast_resource *res; 604 605 pjdlog_info("Termination signal received, exiting."); 606 TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) { 607 if (res->hr_workerpid == 0) 608 continue; 609 pjdlog_info("Terminating worker process (resource=%s, role=%s, pid=%u).", 610 res->hr_name, role2str(res->hr_role), res->hr_workerpid); 611 if (kill(res->hr_workerpid, SIGTERM) == 0) 612 continue; 613 pjdlog_errno(LOG_WARNING, 614 "Unable to send signal to worker process (resource=%s, role=%s, pid=%u).", 615 res->hr_name, role2str(res->hr_role), res->hr_workerpid); 616 } 617} 618 619static void 620listen_accept(void) 621{ 622 struct hast_resource *res; 623 struct proto_conn *conn; 624 struct nv *nvin, *nvout, *nverr; 625 const char *resname; 626 const unsigned char *token; 627 char laddr[256], raddr[256]; 628 size_t size; 629 pid_t pid; 630 int status; 631 632 proto_local_address(cfg->hc_listenconn, laddr, sizeof(laddr)); 633 pjdlog_debug(1, "Accepting connection to %s.", laddr); 634 635 if (proto_accept(cfg->hc_listenconn, &conn) < 0) { 636 pjdlog_errno(LOG_ERR, "Unable to accept connection %s", laddr); 637 return; 638 } 639 640 proto_local_address(conn, laddr, sizeof(laddr)); 641 proto_remote_address(conn, raddr, sizeof(raddr)); 642 pjdlog_info("Connection from %s to %s.", raddr, laddr); 643 644 /* Error in setting timeout is not critical, but why should it fail? */ 645 if (proto_timeout(conn, HAST_TIMEOUT) < 0) 646 pjdlog_errno(LOG_WARNING, "Unable to set connection timeout"); 647 648 nvin = nvout = nverr = NULL; 649 650 /* 651 * Before receiving any data see if remote host have access to any 652 * resource. 653 */ 654 TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) { 655 if (proto_address_match(conn, res->hr_remoteaddr)) 656 break; 657 } 658 if (res == NULL) { 659 pjdlog_error("Client %s isn't known.", raddr); 660 goto close; 661 } 662 /* Ok, remote host can access at least one resource. */ 663 664 if (hast_proto_recv_hdr(conn, &nvin) < 0) { 665 pjdlog_errno(LOG_ERR, "Unable to receive header from %s", 666 raddr); 667 goto close; 668 } 669 670 resname = nv_get_string(nvin, "resource"); 671 if (resname == NULL) { 672 pjdlog_error("No 'resource' field in the header received from %s.", 673 raddr); 674 goto close; 675 } 676 pjdlog_debug(2, "%s: resource=%s", raddr, resname); 677 token = nv_get_uint8_array(nvin, &size, "token"); 678 /* 679 * NULL token means that this is first conection. 680 */ 681 if (token != NULL && size != sizeof(res->hr_token)) { 682 pjdlog_error("Received token of invalid size from %s (expected %zu, got %zu).", 683 raddr, sizeof(res->hr_token), size); 684 goto close; 685 } 686 687 /* 688 * From now on we want to send errors to the remote node. 689 */ 690 nverr = nv_alloc(); 691 692 /* Find resource related to this connection. */ 693 TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) { 694 if (strcmp(resname, res->hr_name) == 0) 695 break; 696 } 697 /* Have we found the resource? */ 698 if (res == NULL) { 699 pjdlog_error("No resource '%s' as requested by %s.", 700 resname, raddr); 701 nv_add_stringf(nverr, "errmsg", "Resource not configured."); 702 goto fail; 703 } 704 705 /* Now that we know resource name setup log prefix. */ 706 pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role)); 707 708 /* Does the remote host have access to this resource? */ 709 if (!proto_address_match(conn, res->hr_remoteaddr)) { 710 pjdlog_error("Client %s has no access to the resource.", raddr); 711 nv_add_stringf(nverr, "errmsg", "No access to the resource."); 712 goto fail; 713 } 714 /* Is the resource marked as secondary? */ 715 if (res->hr_role != HAST_ROLE_SECONDARY) { 716 pjdlog_error("We act as %s for the resource and not as %s as requested by %s.", 717 role2str(res->hr_role), role2str(HAST_ROLE_SECONDARY), 718 raddr); 719 nv_add_stringf(nverr, "errmsg", 720 "Remote node acts as %s for the resource and not as %s.", 721 role2str(res->hr_role), role2str(HAST_ROLE_SECONDARY)); 722 goto fail; 723 } 724 /* Does token (if exists) match? */ 725 if (token != NULL && memcmp(token, res->hr_token, 726 sizeof(res->hr_token)) != 0) { 727 pjdlog_error("Token received from %s doesn't match.", raddr); 728 nv_add_stringf(nverr, "errmsg", "Token doesn't match."); 729 goto fail; 730 } 731 /* 732 * If there is no token, but we have half-open connection 733 * (only remotein) or full connection (worker process is running) 734 * we have to cancel those and accept the new connection. 735 */ 736 if (token == NULL) { 737 PJDLOG_ASSERT(res->hr_remoteout == NULL); 738 pjdlog_debug(1, "Initial connection from %s.", raddr); 739 if (res->hr_workerpid != 0) { 740 PJDLOG_ASSERT(res->hr_remotein == NULL); 741 pjdlog_debug(1, 742 "Worker process exists (pid=%u), stopping it.", 743 (unsigned int)res->hr_workerpid); 744 /* Stop child process. */ 745 if (kill(res->hr_workerpid, SIGINT) < 0) { 746 pjdlog_errno(LOG_ERR, 747 "Unable to stop worker process (pid=%u)", 748 (unsigned int)res->hr_workerpid); 749 /* 750 * Other than logging the problem we 751 * ignore it - nothing smart to do. 752 */ 753 } 754 /* Wait for it to exit. */ 755 else if ((pid = waitpid(res->hr_workerpid, 756 &status, 0)) != res->hr_workerpid) { 757 /* We can only log the problem. */ 758 pjdlog_errno(LOG_ERR, 759 "Waiting for worker process (pid=%u) failed", 760 (unsigned int)res->hr_workerpid); 761 } else { 762 child_exit_log(res->hr_workerpid, status); 763 } 764 child_cleanup(res); 765 } else if (res->hr_remotein != NULL) { 766 char oaddr[256]; 767 768 proto_remote_address(res->hr_remotein, oaddr, 769 sizeof(oaddr)); 770 pjdlog_debug(1, 771 "Canceling half-open connection from %s on connection from %s.", 772 oaddr, raddr); 773 proto_close(res->hr_remotein); 774 res->hr_remotein = NULL; 775 } 776 } 777 778 /* 779 * Checks and cleanups are done. 780 */ 781 782 if (token == NULL) { 783 arc4random_buf(res->hr_token, sizeof(res->hr_token)); 784 nvout = nv_alloc(); 785 nv_add_uint8_array(nvout, res->hr_token, 786 sizeof(res->hr_token), "token"); 787 if (nv_error(nvout) != 0) { 788 pjdlog_common(LOG_ERR, 0, nv_error(nvout), 789 "Unable to prepare return header for %s", raddr); 790 nv_add_stringf(nverr, "errmsg", 791 "Remote node was unable to prepare return header: %s.", 792 strerror(nv_error(nvout))); 793 goto fail; 794 } 795 if (hast_proto_send(NULL, conn, nvout, NULL, 0) < 0) { 796 int error = errno; 797 798 pjdlog_errno(LOG_ERR, "Unable to send response to %s", 799 raddr); 800 nv_add_stringf(nverr, "errmsg", 801 "Remote node was unable to send response: %s.", 802 strerror(error)); 803 goto fail; 804 } 805 res->hr_remotein = conn; 806 pjdlog_debug(1, "Incoming connection from %s configured.", 807 raddr); 808 } else { 809 res->hr_remoteout = conn; 810 pjdlog_debug(1, "Outgoing connection to %s configured.", raddr); 811 hastd_secondary(res, nvin); 812 } 813 nv_free(nvin); 814 nv_free(nvout); 815 nv_free(nverr); 816 pjdlog_prefix_set("%s", ""); 817 return; 818fail: 819 if (nv_error(nverr) != 0) { 820 pjdlog_common(LOG_ERR, 0, nv_error(nverr), 821 "Unable to prepare error header for %s", raddr); 822 goto close; 823 } 824 if (hast_proto_send(NULL, conn, nverr, NULL, 0) < 0) { 825 pjdlog_errno(LOG_ERR, "Unable to send error to %s", raddr); 826 goto close; 827 } 828close: 829 if (nvin != NULL) 830 nv_free(nvin); 831 if (nvout != NULL) 832 nv_free(nvout); 833 if (nverr != NULL) 834 nv_free(nverr); 835 proto_close(conn); 836 pjdlog_prefix_set("%s", ""); 837} 838 839static void 840connection_migrate(struct hast_resource *res) 841{ 842 struct proto_conn *conn; 843 int16_t val = 0; 844 845 pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role)); 846 847 if (proto_recv(res->hr_conn, &val, sizeof(val)) < 0) { 848 pjdlog_errno(LOG_WARNING, 849 "Unable to receive connection command"); 850 return; 851 } 852 if (proto_client(res->hr_remoteaddr, &conn) < 0) { 853 val = errno; 854 pjdlog_errno(LOG_WARNING, 855 "Unable to create outgoing connection to %s", 856 res->hr_remoteaddr); 857 goto out; 858 } 859 if (proto_connect(conn, -1) < 0) { 860 val = errno; 861 pjdlog_errno(LOG_WARNING, "Unable to connect to %s", 862 res->hr_remoteaddr); 863 proto_close(conn); 864 goto out; 865 } 866 val = 0; 867out: 868 if (proto_send(res->hr_conn, &val, sizeof(val)) < 0) { 869 pjdlog_errno(LOG_WARNING, 870 "Unable to send reply to connection request"); 871 } 872 if (val == 0 && proto_connection_send(res->hr_conn, conn) < 0) 873 pjdlog_errno(LOG_WARNING, "Unable to send connection"); 874 875 pjdlog_prefix_set("%s", ""); 876} 877 878static void 879main_loop(void) 880{ 881 struct hast_resource *res; 882 struct timeval seltimeout; 883 struct timespec sigtimeout; 884 int fd, maxfd, ret, signo; 885 time_t lastcheck, now; 886 sigset_t mask; 887 fd_set rfds; 888 889 lastcheck = time(NULL); 890 seltimeout.tv_sec = REPORT_INTERVAL; 891 seltimeout.tv_usec = 0; 892 sigtimeout.tv_sec = 0; 893 sigtimeout.tv_nsec = 0; 894 895 PJDLOG_VERIFY(sigemptyset(&mask) == 0); 896 PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0); 897 PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0); 898 PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0); 899 PJDLOG_VERIFY(sigaddset(&mask, SIGCHLD) == 0); 900 901 pjdlog_info("Started successfully, running protocol version %d.", 902 HAST_PROTO_VERSION); 903 904 for (;;) { 905 while ((signo = sigtimedwait(&mask, NULL, &sigtimeout)) != -1) { 906 switch (signo) { 907 case SIGINT: 908 case SIGTERM: 909 sigexit_received = true; 910 terminate_workers(); 911 proto_close(cfg->hc_controlconn); 912 exit(EX_OK); 913 break; 914 case SIGCHLD: 915 child_exit(); 916 break; 917 case SIGHUP: 918 hastd_reload(); 919 break; 920 default: 921 PJDLOG_ABORT("Unexpected signal (%d).", signo); 922 } 923 } 924 925 /* Setup descriptors for select(2). */ 926 FD_ZERO(&rfds); 927 maxfd = fd = proto_descriptor(cfg->hc_controlconn); 928 PJDLOG_ASSERT(fd >= 0); 929 FD_SET(fd, &rfds); 930 fd = proto_descriptor(cfg->hc_listenconn); 931 PJDLOG_ASSERT(fd >= 0); 932 FD_SET(fd, &rfds); 933 maxfd = fd > maxfd ? fd : maxfd; 934 TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) { 935 if (res->hr_event == NULL) 936 continue; 937 PJDLOG_ASSERT(res->hr_conn != NULL); 938 fd = proto_descriptor(res->hr_event); 939 PJDLOG_ASSERT(fd >= 0); 940 FD_SET(fd, &rfds); 941 maxfd = fd > maxfd ? fd : maxfd; 942 if (res->hr_role == HAST_ROLE_PRIMARY) { 943 /* Only primary workers asks for connections. */ 944 fd = proto_descriptor(res->hr_conn); 945 PJDLOG_ASSERT(fd >= 0); 946 FD_SET(fd, &rfds); 947 maxfd = fd > maxfd ? fd : maxfd; 948 } 949 } 950 951 PJDLOG_ASSERT(maxfd + 1 <= (int)FD_SETSIZE); 952 ret = select(maxfd + 1, &rfds, NULL, NULL, &seltimeout); 953 now = time(NULL); 954 if (lastcheck + REPORT_INTERVAL <= now) { 955 hook_check(); 956 lastcheck = now; 957 } 958 if (ret == 0) { 959 /* 960 * select(2) timed out, so there should be no 961 * descriptors to check. 962 */ 963 continue; 964 } else if (ret == -1) { 965 if (errno == EINTR) 966 continue; 967 KEEP_ERRNO((void)pidfile_remove(pfh)); 968 pjdlog_exit(EX_OSERR, "select() failed"); 969 } 970 971 if (FD_ISSET(proto_descriptor(cfg->hc_controlconn), &rfds)) 972 control_handle(cfg); 973 if (FD_ISSET(proto_descriptor(cfg->hc_listenconn), &rfds)) 974 listen_accept(); 975 TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) { 976 if (res->hr_event == NULL) 977 continue; 978 PJDLOG_ASSERT(res->hr_conn != NULL); 979 if (FD_ISSET(proto_descriptor(res->hr_event), &rfds)) { 980 if (event_recv(res) == 0) 981 continue; 982 /* The worker process exited? */ 983 proto_close(res->hr_event); 984 res->hr_event = NULL; 985 proto_close(res->hr_conn); 986 res->hr_conn = NULL; 987 continue; 988 } 989 if (res->hr_role == HAST_ROLE_PRIMARY && 990 FD_ISSET(proto_descriptor(res->hr_conn), &rfds)) { 991 connection_migrate(res); 992 } 993 } 994 } 995} 996 997static void 998dummy_sighandler(int sig __unused) 999{ 1000 /* Nothing to do. */ 1001} 1002 1003int 1004main(int argc, char *argv[]) 1005{ 1006 const char *pidfile; 1007 pid_t otherpid; 1008 bool foreground; 1009 int debuglevel; 1010 sigset_t mask; 1011 1012 foreground = false; 1013 debuglevel = 0; 1014 pidfile = HASTD_PIDFILE; 1015 1016 for (;;) { 1017 int ch; 1018 1019 ch = getopt(argc, argv, "c:dFhP:"); 1020 if (ch == -1) 1021 break; 1022 switch (ch) { 1023 case 'c': 1024 cfgpath = optarg; 1025 break; 1026 case 'd': 1027 debuglevel++; 1028 break; 1029 case 'F': 1030 foreground = true; 1031 break; 1032 case 'P': 1033 pidfile = optarg; 1034 break; 1035 case 'h': 1036 default: 1037 usage(); 1038 } 1039 } 1040 argc -= optind; 1041 argv += optind; 1042 1043 pjdlog_init(PJDLOG_MODE_STD); 1044 pjdlog_debug_set(debuglevel); 1045 1046 g_gate_load(); 1047 1048 pfh = pidfile_open(pidfile, 0600, &otherpid); 1049 if (pfh == NULL) { 1050 if (errno == EEXIST) { 1051 pjdlog_exitx(EX_TEMPFAIL, 1052 "Another hastd is already running, pid: %jd.", 1053 (intmax_t)otherpid); 1054 } 1055 /* If we cannot create pidfile from other reasons, only warn. */ 1056 pjdlog_errno(LOG_WARNING, "Unable to open or create pidfile"); 1057 } 1058 1059 cfg = yy_config_parse(cfgpath, true); 1060 PJDLOG_ASSERT(cfg != NULL); 1061 1062 /* 1063 * Restore default actions for interesting signals in case parent 1064 * process (like init(8)) decided to ignore some of them (like SIGHUP). 1065 */ 1066 PJDLOG_VERIFY(signal(SIGHUP, SIG_DFL) != SIG_ERR); 1067 PJDLOG_VERIFY(signal(SIGINT, SIG_DFL) != SIG_ERR); 1068 PJDLOG_VERIFY(signal(SIGTERM, SIG_DFL) != SIG_ERR); 1069 /* 1070 * Because SIGCHLD is ignored by default, setup dummy handler for it, 1071 * so we can mask it. 1072 */ 1073 PJDLOG_VERIFY(signal(SIGCHLD, dummy_sighandler) != SIG_ERR); 1074 1075 PJDLOG_VERIFY(sigemptyset(&mask) == 0); 1076 PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0); 1077 PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0); 1078 PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0); 1079 PJDLOG_VERIFY(sigaddset(&mask, SIGCHLD) == 0); 1080 PJDLOG_VERIFY(sigprocmask(SIG_SETMASK, &mask, NULL) == 0); 1081 1082 /* Listen on control address. */ 1083 if (proto_server(cfg->hc_controladdr, &cfg->hc_controlconn) < 0) { 1084 KEEP_ERRNO((void)pidfile_remove(pfh)); 1085 pjdlog_exit(EX_OSERR, "Unable to listen on control address %s", 1086 cfg->hc_controladdr); 1087 } 1088 /* Listen for remote connections. */ 1089 if (proto_server(cfg->hc_listenaddr, &cfg->hc_listenconn) < 0) { 1090 KEEP_ERRNO((void)pidfile_remove(pfh)); 1091 pjdlog_exit(EX_OSERR, "Unable to listen on address %s", 1092 cfg->hc_listenaddr); 1093 } 1094 1095 if (!foreground) { 1096 if (daemon(0, 0) < 0) { 1097 KEEP_ERRNO((void)pidfile_remove(pfh)); 1098 pjdlog_exit(EX_OSERR, "Unable to daemonize"); 1099 } 1100 1101 /* Start logging to syslog. */ 1102 pjdlog_mode_set(PJDLOG_MODE_SYSLOG); 1103 1104 /* Write PID to a file. */ 1105 if (pidfile_write(pfh) < 0) { 1106 pjdlog_errno(LOG_WARNING, 1107 "Unable to write PID to a file"); 1108 } 1109 } 1110 1111 hook_init(); 1112 1113 main_loop(); 1114 1115 exit(0); 1116} 1117