hastd.c revision 219900
159078Smdodd/*- 259078Smdodd * Copyright (c) 2009-2010 The FreeBSD Foundation 359078Smdodd * Copyright (c) 2010-2011 Pawel Jakub Dawidek <pawel@dawidek.net> 432801Sjulian * All rights reserved. 559078Smdodd * 659078Smdodd * This software was developed by Pawel Jakub Dawidek under sponsorship from 759078Smdodd * the FreeBSD Foundation. 832801Sjulian * 932801Sjulian * Redistribution and use in source and binary forms, with or without 1032801Sjulian * modification, are permitted provided that the following conditions 1132801Sjulian * are met: 1259078Smdodd * 1. Redistributions of source code must retain the above copyright 1332801Sjulian * notice, this list of conditions and the following disclaimer. 1432801Sjulian * 2. Redistributions in binary form must reproduce the above copyright 1532801Sjulian * notice, this list of conditions and the following disclaimer in the 1632801Sjulian * documentation and/or other materials provided with the distribution. 1732801Sjulian * 1832801Sjulian * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND 1932801Sjulian * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 2059078Smdodd * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 2159078Smdodd * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE 2232801Sjulian * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 2332801Sjulian * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 2432801Sjulian * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 2532801Sjulian * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 2632801Sjulian * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 2732801Sjulian * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 2832801Sjulian * SUCH DAMAGE. 2959078Smdodd */ 3032801Sjulian 3132801Sjulian#include <sys/cdefs.h> 3232801Sjulian__FBSDID("$FreeBSD: head/sbin/hastd/hastd.c 219900 2011-03-23 11:09:04Z pjd $"); 3332801Sjulian 3432801Sjulian#include <sys/param.h> 3559078Smdodd#include <sys/linker.h> 36117126Sscottl#include <sys/module.h> 37117126Sscottl#include <sys/stat.h> 3859078Smdodd#include <sys/wait.h> 3932801Sjulian 4039234Sgibbs#include <err.h> 4139234Sgibbs#include <errno.h> 4239234Sgibbs#include <libutil.h> 4359078Smdodd#include <signal.h> 4459078Smdodd#include <stdbool.h> 4539234Sgibbs#include <stdio.h> 46119277Simp#include <stdlib.h> 47119277Simp#include <string.h> 4859078Smdodd#include <sysexits.h> 4939234Sgibbs#include <time.h> 5039234Sgibbs#include <unistd.h> 5139234Sgibbs 5232801Sjulian#include <activemap.h> 5359078Smdodd#include <pjdlog.h> 5459078Smdodd 5532801Sjulian#include "control.h" 5659078Smdodd#include "event.h" 5759078Smdodd#include "hast.h" 5832801Sjulian#include "hast_proto.h" 5959078Smdodd#include "hastd.h" 6032801Sjulian#include "hooks.h" 6159078Smdodd#include "subr.h" 6259078Smdodd 6332801Sjulian/* Path to configuration file. */ 6459078Smdoddconst char *cfgpath = HAST_CONFIG; 6559078Smdodd/* Hastd configuration. */ 6659078Smdoddstatic struct hastd_config *cfg; 6759078Smdodd/* Was SIGINT or SIGTERM signal received? */ 6859078Smdoddbool sigexit_received = false; 6959078Smdodd/* PID file handle. */ 7059078Smdoddstruct pidfh *pfh; 7159078Smdodd 7259078Smdodd/* How often check for hooks running for too long. */ 7359078Smdodd#define REPORT_INTERVAL 5 7432801Sjulian 7559078Smdoddstatic void 7659078Smdoddusage(void) 7732801Sjulian{ 7859078Smdodd 7959078Smdodd errx(EX_USAGE, "[-dFh] [-c config] [-P pidfile]"); 8059078Smdodd} 8132801Sjulian 8259078Smdoddstatic void 8332801Sjuliang_gate_load(void) 84112780Smdodd{ 85112780Smdodd 8659078Smdodd if (modfind("g_gate") == -1) { 8732801Sjulian /* Not present in kernel, try loading it. */ 8859078Smdodd if (kldload("geom_gate") == -1 || modfind("g_gate") == -1) { 8959078Smdodd if (errno != EEXIST) { 90112780Smdodd pjdlog_exit(EX_OSERR, 91112780Smdodd "Unable to load geom_gate module"); 92112780Smdodd } 93112780Smdodd } 94112780Smdodd } 9559078Smdodd} 9632801Sjulian 97112780Smdoddvoid 98112780Smdodddescriptors_cleanup(struct hast_resource *res) 99112780Smdodd{ 100112780Smdodd struct hast_resource *tres; 101112780Smdodd 102112780Smdodd TAILQ_FOREACH(tres, &cfg->hc_resources, hr_next) { 10359078Smdodd if (tres == res) { 10432801Sjulian PJDLOG_VERIFY(res->hr_role == HAST_ROLE_SECONDARY || 105112780Smdodd (res->hr_remotein == NULL && 10659078Smdodd res->hr_remoteout == NULL)); 10759078Smdodd continue; 10859078Smdodd } 10959078Smdodd if (tres->hr_remotein != NULL) 110112780Smdodd proto_close(tres->hr_remotein); 11132801Sjulian if (tres->hr_remoteout != NULL) 112112780Smdodd proto_close(tres->hr_remoteout); 113112780Smdodd if (tres->hr_ctrl != NULL) 114112780Smdodd proto_close(tres->hr_ctrl); 115112780Smdodd if (tres->hr_event != NULL) 11659078Smdodd proto_close(tres->hr_event); 11759078Smdodd if (tres->hr_conn != NULL) 11859078Smdodd proto_close(tres->hr_conn); 11959078Smdodd } 12032801Sjulian if (cfg->hc_controlin != NULL) 12159078Smdodd proto_close(cfg->hc_controlin); 12259078Smdodd proto_close(cfg->hc_controlconn); 12359078Smdodd proto_close(cfg->hc_listenconn); 12432801Sjulian (void)pidfile_close(pfh); 125112780Smdodd hook_fini(); 12632801Sjulian pjdlog_fini(); 12759078Smdodd} 12859078Smdodd 12932801Sjulianstatic const char * 13059078Smdodddtype2str(mode_t mode) 13159078Smdodd{ 13239234Sgibbs 13332801Sjulian if (S_ISBLK(mode)) 134112780Smdodd return ("block device"); 13532801Sjulian else if (S_ISCHR(mode)) 13639234Sgibbs return ("character device"); 13739234Sgibbs else if (S_ISDIR(mode)) 13859078Smdodd return ("directory"); 13959078Smdodd else if (S_ISFIFO(mode)) 14059078Smdodd return ("pipe or FIFO"); 14159078Smdodd else if (S_ISLNK(mode)) 14259078Smdodd return ("symbolic link"); 14359078Smdodd else if (S_ISREG(mode)) 14459078Smdodd return ("regular file"); 14559078Smdodd else if (S_ISSOCK(mode)) 146104710Speter return ("socket"); 14759078Smdodd else if (S_ISWHT(mode)) 14859078Smdodd return ("whiteout"); 149117126Sscottl else 150117126Sscottl return ("unknown"); 15159078Smdodd} 15239234Sgibbs 15359078Smdoddvoid 15459078Smdodddescriptors_assert(const struct hast_resource *res, int pjdlogmode) 15539234Sgibbs{ 15632801Sjulian char msg[256]; 15759078Smdodd struct stat sb; 15832801Sjulian long maxfd; 15939234Sgibbs bool isopen; 16039234Sgibbs mode_t mode; 16159078Smdodd int fd; 16259078Smdodd 16339234Sgibbs /* 16432801Sjulian * At this point descriptor to syslog socket is closed, so if we want 16539234Sgibbs * to log assertion message, we have to first store it in 'msg' local 16639234Sgibbs * buffer and then open syslog socket and log it. 16759078Smdodd */ 16839234Sgibbs msg[0] = '\0'; 16959078Smdodd 170112780Smdodd maxfd = sysconf(_SC_OPEN_MAX); 171112780Smdodd if (maxfd < 0) { 17259078Smdodd pjdlog_init(pjdlogmode); 17359078Smdodd pjdlog_prefix_set("[%s] (%s) ", res->hr_name, 17459078Smdodd role2str(res->hr_role)); 17559078Smdodd pjdlog_errno(LOG_WARNING, "sysconf(_SC_OPEN_MAX) failed"); 17659078Smdodd pjdlog_fini(); 17759078Smdodd maxfd = 16384; 17859078Smdodd } 17959078Smdodd for (fd = 0; fd <= maxfd; fd++) { 180112780Smdodd if (fstat(fd, &sb) == 0) { 18159078Smdodd isopen = true; 182112780Smdodd mode = sb.st_mode; 183112780Smdodd } else if (errno == EBADF) { 184112780Smdodd isopen = false; 18559078Smdodd mode = 0; 18632801Sjulian } else { 18759078Smdodd (void)snprintf(msg, sizeof(msg), 18859078Smdodd "Unable to fstat descriptor %d: %s", fd, 18959078Smdodd strerror(errno)); 19059078Smdodd break; 19159078Smdodd } 192112780Smdodd if (fd == STDIN_FILENO || fd == STDOUT_FILENO || 19359078Smdodd fd == STDERR_FILENO) { 19459078Smdodd if (!isopen) { 19559078Smdodd (void)snprintf(msg, sizeof(msg), 19659078Smdodd "Descriptor %d (%s) is closed, but should be open.", 19759078Smdodd fd, (fd == STDIN_FILENO ? "stdin" : 19859078Smdodd (fd == STDOUT_FILENO ? "stdout" : "stderr"))); 19959078Smdodd break; 20059078Smdodd } 20159078Smdodd } else if (fd == proto_descriptor(res->hr_event)) { 20259078Smdodd if (!isopen) { 20359078Smdodd (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 295static void 296child_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 311static void 312child_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 358static bool 359resource_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 389static bool 390resource_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 418static void 419resource_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 460static void 461hastd_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; 606failed: 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 617static void 618terminate_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 636static void 637listen_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_error("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 goto fail; 740 } 741 /* Does token (if exists) match? */ 742 if (token != NULL && memcmp(token, res->hr_token, 743 sizeof(res->hr_token)) != 0) { 744 pjdlog_error("Token received from %s doesn't match.", raddr); 745 nv_add_stringf(nverr, "errmsg", "Token doesn't match."); 746 goto fail; 747 } 748 /* 749 * If there is no token, but we have half-open connection 750 * (only remotein) or full connection (worker process is running) 751 * we have to cancel those and accept the new connection. 752 */ 753 if (token == NULL) { 754 PJDLOG_ASSERT(res->hr_remoteout == NULL); 755 pjdlog_debug(1, "Initial connection from %s.", raddr); 756 if (res->hr_workerpid != 0) { 757 PJDLOG_ASSERT(res->hr_remotein == NULL); 758 pjdlog_debug(1, 759 "Worker process exists (pid=%u), stopping it.", 760 (unsigned int)res->hr_workerpid); 761 /* Stop child process. */ 762 if (kill(res->hr_workerpid, SIGINT) < 0) { 763 pjdlog_errno(LOG_ERR, 764 "Unable to stop worker process (pid=%u)", 765 (unsigned int)res->hr_workerpid); 766 /* 767 * Other than logging the problem we 768 * ignore it - nothing smart to do. 769 */ 770 } 771 /* Wait for it to exit. */ 772 else if ((pid = waitpid(res->hr_workerpid, 773 &status, 0)) != res->hr_workerpid) { 774 /* We can only log the problem. */ 775 pjdlog_errno(LOG_ERR, 776 "Waiting for worker process (pid=%u) failed", 777 (unsigned int)res->hr_workerpid); 778 } else { 779 child_exit_log(res->hr_workerpid, status); 780 } 781 child_cleanup(res); 782 } else if (res->hr_remotein != NULL) { 783 char oaddr[256]; 784 785 proto_remote_address(res->hr_remotein, oaddr, 786 sizeof(oaddr)); 787 pjdlog_debug(1, 788 "Canceling half-open connection from %s on connection from %s.", 789 oaddr, raddr); 790 proto_close(res->hr_remotein); 791 res->hr_remotein = NULL; 792 } 793 } 794 795 /* 796 * Checks and cleanups are done. 797 */ 798 799 if (token == NULL) { 800 arc4random_buf(res->hr_token, sizeof(res->hr_token)); 801 nvout = nv_alloc(); 802 nv_add_uint8_array(nvout, res->hr_token, 803 sizeof(res->hr_token), "token"); 804 if (nv_error(nvout) != 0) { 805 pjdlog_common(LOG_ERR, 0, nv_error(nvout), 806 "Unable to prepare return header for %s", raddr); 807 nv_add_stringf(nverr, "errmsg", 808 "Remote node was unable to prepare return header: %s.", 809 strerror(nv_error(nvout))); 810 goto fail; 811 } 812 if (hast_proto_send(NULL, conn, nvout, NULL, 0) < 0) { 813 int error = errno; 814 815 pjdlog_errno(LOG_ERR, "Unable to send response to %s", 816 raddr); 817 nv_add_stringf(nverr, "errmsg", 818 "Remote node was unable to send response: %s.", 819 strerror(error)); 820 goto fail; 821 } 822 res->hr_remotein = conn; 823 pjdlog_debug(1, "Incoming connection from %s configured.", 824 raddr); 825 } else { 826 res->hr_remoteout = conn; 827 pjdlog_debug(1, "Outgoing connection to %s configured.", raddr); 828 hastd_secondary(res, nvin); 829 } 830 nv_free(nvin); 831 nv_free(nvout); 832 nv_free(nverr); 833 pjdlog_prefix_set("%s", ""); 834 return; 835fail: 836 if (nv_error(nverr) != 0) { 837 pjdlog_common(LOG_ERR, 0, nv_error(nverr), 838 "Unable to prepare error header for %s", raddr); 839 goto close; 840 } 841 if (hast_proto_send(NULL, conn, nverr, NULL, 0) < 0) { 842 pjdlog_errno(LOG_ERR, "Unable to send error to %s", raddr); 843 goto close; 844 } 845close: 846 if (nvin != NULL) 847 nv_free(nvin); 848 if (nvout != NULL) 849 nv_free(nvout); 850 if (nverr != NULL) 851 nv_free(nverr); 852 proto_close(conn); 853 pjdlog_prefix_set("%s", ""); 854} 855 856static void 857connection_migrate(struct hast_resource *res) 858{ 859 struct proto_conn *conn; 860 int16_t val = 0; 861 862 pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role)); 863 864 PJDLOG_ASSERT(res->hr_role == HAST_ROLE_PRIMARY); 865 866 if (proto_recv(res->hr_conn, &val, sizeof(val)) < 0) { 867 pjdlog_errno(LOG_WARNING, 868 "Unable to receive connection command"); 869 return; 870 } 871 if (proto_client(res->hr_sourceaddr[0] != '\0' ? res->hr_sourceaddr : NULL, 872 res->hr_remoteaddr, &conn) < 0) { 873 val = errno; 874 pjdlog_errno(LOG_WARNING, 875 "Unable to create outgoing connection to %s", 876 res->hr_remoteaddr); 877 goto out; 878 } 879 if (proto_connect(conn, -1) < 0) { 880 val = errno; 881 pjdlog_errno(LOG_WARNING, "Unable to connect to %s", 882 res->hr_remoteaddr); 883 proto_close(conn); 884 goto out; 885 } 886 val = 0; 887out: 888 if (proto_send(res->hr_conn, &val, sizeof(val)) < 0) { 889 pjdlog_errno(LOG_WARNING, 890 "Unable to send reply to connection request"); 891 } 892 if (val == 0 && proto_connection_send(res->hr_conn, conn) < 0) 893 pjdlog_errno(LOG_WARNING, "Unable to send connection"); 894 895 pjdlog_prefix_set("%s", ""); 896} 897 898static void 899check_signals(void) 900{ 901 struct timespec sigtimeout; 902 sigset_t mask; 903 int signo; 904 905 sigtimeout.tv_sec = 0; 906 sigtimeout.tv_nsec = 0; 907 908 PJDLOG_VERIFY(sigemptyset(&mask) == 0); 909 PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0); 910 PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0); 911 PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0); 912 PJDLOG_VERIFY(sigaddset(&mask, SIGCHLD) == 0); 913 914 while ((signo = sigtimedwait(&mask, NULL, &sigtimeout)) != -1) { 915 switch (signo) { 916 case SIGINT: 917 case SIGTERM: 918 sigexit_received = true; 919 terminate_workers(); 920 proto_close(cfg->hc_controlconn); 921 exit(EX_OK); 922 break; 923 case SIGCHLD: 924 child_exit(); 925 break; 926 case SIGHUP: 927 hastd_reload(); 928 break; 929 default: 930 PJDLOG_ABORT("Unexpected signal (%d).", signo); 931 } 932 } 933} 934 935static void 936main_loop(void) 937{ 938 struct hast_resource *res; 939 struct timeval seltimeout; 940 int fd, maxfd, ret; 941 time_t lastcheck, now; 942 fd_set rfds; 943 944 lastcheck = time(NULL); 945 seltimeout.tv_sec = REPORT_INTERVAL; 946 seltimeout.tv_usec = 0; 947 948 pjdlog_info("Started successfully, running protocol version %d.", 949 HAST_PROTO_VERSION); 950 951 for (;;) { 952 check_signals(); 953 954 /* Setup descriptors for select(2). */ 955 FD_ZERO(&rfds); 956 maxfd = fd = proto_descriptor(cfg->hc_controlconn); 957 PJDLOG_ASSERT(fd >= 0); 958 FD_SET(fd, &rfds); 959 fd = proto_descriptor(cfg->hc_listenconn); 960 PJDLOG_ASSERT(fd >= 0); 961 FD_SET(fd, &rfds); 962 maxfd = fd > maxfd ? fd : maxfd; 963 TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) { 964 if (res->hr_event == NULL) 965 continue; 966 fd = proto_descriptor(res->hr_event); 967 PJDLOG_ASSERT(fd >= 0); 968 FD_SET(fd, &rfds); 969 maxfd = fd > maxfd ? fd : maxfd; 970 if (res->hr_role == HAST_ROLE_PRIMARY) { 971 /* Only primary workers asks for connections. */ 972 PJDLOG_ASSERT(res->hr_conn != NULL); 973 fd = proto_descriptor(res->hr_conn); 974 PJDLOG_ASSERT(fd >= 0); 975 FD_SET(fd, &rfds); 976 maxfd = fd > maxfd ? fd : maxfd; 977 } else { 978 PJDLOG_ASSERT(res->hr_conn == NULL); 979 } 980 } 981 982 PJDLOG_ASSERT(maxfd + 1 <= (int)FD_SETSIZE); 983 ret = select(maxfd + 1, &rfds, NULL, NULL, &seltimeout); 984 now = time(NULL); 985 if (lastcheck + REPORT_INTERVAL <= now) { 986 hook_check(); 987 lastcheck = now; 988 } 989 if (ret == 0) { 990 /* 991 * select(2) timed out, so there should be no 992 * descriptors to check. 993 */ 994 continue; 995 } else if (ret == -1) { 996 if (errno == EINTR) 997 continue; 998 KEEP_ERRNO((void)pidfile_remove(pfh)); 999 pjdlog_exit(EX_OSERR, "select() failed"); 1000 } 1001 1002 /* 1003 * Check for signals before we do anything to update our 1004 * info about terminated workers in the meantime. 1005 */ 1006 check_signals(); 1007 1008 if (FD_ISSET(proto_descriptor(cfg->hc_controlconn), &rfds)) 1009 control_handle(cfg); 1010 if (FD_ISSET(proto_descriptor(cfg->hc_listenconn), &rfds)) 1011 listen_accept(); 1012 TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) { 1013 if (res->hr_event == NULL) 1014 continue; 1015 if (FD_ISSET(proto_descriptor(res->hr_event), &rfds)) { 1016 if (event_recv(res) == 0) 1017 continue; 1018 /* The worker process exited? */ 1019 proto_close(res->hr_event); 1020 res->hr_event = NULL; 1021 if (res->hr_conn != NULL) { 1022 proto_close(res->hr_conn); 1023 res->hr_conn = NULL; 1024 } 1025 continue; 1026 } 1027 if (res->hr_role == HAST_ROLE_PRIMARY) { 1028 PJDLOG_ASSERT(res->hr_conn != NULL); 1029 if (FD_ISSET(proto_descriptor(res->hr_conn), 1030 &rfds)) { 1031 connection_migrate(res); 1032 } 1033 } else { 1034 PJDLOG_ASSERT(res->hr_conn == NULL); 1035 } 1036 } 1037 } 1038} 1039 1040static void 1041dummy_sighandler(int sig __unused) 1042{ 1043 /* Nothing to do. */ 1044} 1045 1046int 1047main(int argc, char *argv[]) 1048{ 1049 const char *pidfile; 1050 pid_t otherpid; 1051 bool foreground; 1052 int debuglevel; 1053 sigset_t mask; 1054 1055 foreground = false; 1056 debuglevel = 0; 1057 pidfile = HASTD_PIDFILE; 1058 1059 for (;;) { 1060 int ch; 1061 1062 ch = getopt(argc, argv, "c:dFhP:"); 1063 if (ch == -1) 1064 break; 1065 switch (ch) { 1066 case 'c': 1067 cfgpath = optarg; 1068 break; 1069 case 'd': 1070 debuglevel++; 1071 break; 1072 case 'F': 1073 foreground = true; 1074 break; 1075 case 'P': 1076 pidfile = optarg; 1077 break; 1078 case 'h': 1079 default: 1080 usage(); 1081 } 1082 } 1083 argc -= optind; 1084 argv += optind; 1085 1086 pjdlog_init(PJDLOG_MODE_STD); 1087 pjdlog_debug_set(debuglevel); 1088 1089 g_gate_load(); 1090 1091 pfh = pidfile_open(pidfile, 0600, &otherpid); 1092 if (pfh == NULL) { 1093 if (errno == EEXIST) { 1094 pjdlog_exitx(EX_TEMPFAIL, 1095 "Another hastd is already running, pid: %jd.", 1096 (intmax_t)otherpid); 1097 } 1098 /* If we cannot create pidfile from other reasons, only warn. */ 1099 pjdlog_errno(LOG_WARNING, "Unable to open or create pidfile"); 1100 } 1101 1102 cfg = yy_config_parse(cfgpath, true); 1103 PJDLOG_ASSERT(cfg != NULL); 1104 1105 /* 1106 * Restore default actions for interesting signals in case parent 1107 * process (like init(8)) decided to ignore some of them (like SIGHUP). 1108 */ 1109 PJDLOG_VERIFY(signal(SIGHUP, SIG_DFL) != SIG_ERR); 1110 PJDLOG_VERIFY(signal(SIGINT, SIG_DFL) != SIG_ERR); 1111 PJDLOG_VERIFY(signal(SIGTERM, SIG_DFL) != SIG_ERR); 1112 /* 1113 * Because SIGCHLD is ignored by default, setup dummy handler for it, 1114 * so we can mask it. 1115 */ 1116 PJDLOG_VERIFY(signal(SIGCHLD, dummy_sighandler) != SIG_ERR); 1117 1118 PJDLOG_VERIFY(sigemptyset(&mask) == 0); 1119 PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0); 1120 PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0); 1121 PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0); 1122 PJDLOG_VERIFY(sigaddset(&mask, SIGCHLD) == 0); 1123 PJDLOG_VERIFY(sigprocmask(SIG_SETMASK, &mask, NULL) == 0); 1124 1125 /* Listen on control address. */ 1126 if (proto_server(cfg->hc_controladdr, &cfg->hc_controlconn) < 0) { 1127 KEEP_ERRNO((void)pidfile_remove(pfh)); 1128 pjdlog_exit(EX_OSERR, "Unable to listen on control address %s", 1129 cfg->hc_controladdr); 1130 } 1131 /* Listen for remote connections. */ 1132 if (proto_server(cfg->hc_listenaddr, &cfg->hc_listenconn) < 0) { 1133 KEEP_ERRNO((void)pidfile_remove(pfh)); 1134 pjdlog_exit(EX_OSERR, "Unable to listen on address %s", 1135 cfg->hc_listenaddr); 1136 } 1137 1138 if (!foreground) { 1139 if (daemon(0, 0) < 0) { 1140 KEEP_ERRNO((void)pidfile_remove(pfh)); 1141 pjdlog_exit(EX_OSERR, "Unable to daemonize"); 1142 } 1143 1144 /* Start logging to syslog. */ 1145 pjdlog_mode_set(PJDLOG_MODE_SYSLOG); 1146 1147 /* Write PID to a file. */ 1148 if (pidfile_write(pfh) < 0) { 1149 pjdlog_errno(LOG_WARNING, 1150 "Unable to write PID to a file"); 1151 } 1152 } 1153 1154 hook_init(); 1155 1156 main_loop(); 1157 1158 exit(0); 1159} 1160