1 // SPDX-License-Identifier: GPL-2.0 2 #include <internal/lib.h> 3 #include <subcmd/parse-options.h> 4 #include <api/fd/array.h> 5 #include <api/fs/fs.h> 6 #include <linux/zalloc.h> 7 #include <linux/string.h> 8 #include <linux/limits.h> 9 #include <linux/string.h> 10 #include <string.h> 11 #include <sys/file.h> 12 #include <signal.h> 13 #include <stdlib.h> 14 #include <time.h> 15 #include <stdio.h> 16 #include <unistd.h> 17 #include <errno.h> 18 #include <sys/inotify.h> 19 #include <libgen.h> 20 #include <sys/types.h> 21 #include <sys/socket.h> 22 #include <sys/un.h> 23 #include <sys/stat.h> 24 #include <sys/signalfd.h> 25 #include <sys/wait.h> 26 #include <poll.h> 27 #include <sys/stat.h> 28 #include <time.h> 29 #include "builtin.h" 30 #include "perf.h" 31 #include "debug.h" 32 #include "config.h" 33 #include "util.h" 34 35 #define SESSION_OUTPUT "output" 36 #define SESSION_CONTROL "control" 37 #define SESSION_ACK "ack" 38 39 /* 40 * Session states: 41 * 42 * OK - session is up and running 43 * RECONFIG - session is pending for reconfiguration, 44 * new values are already loaded in session object 45 * KILL - session is pending to be killed 46 * 47 * Session object life and its state is maintained by 48 * following functions: 49 * 50 * setup_server_config 51 * - reads config file and setup session objects 52 * with following states: 53 * 54 * OK - no change needed 55 * RECONFIG - session needs to be changed 56 * (run variable changed) 57 * KILL - session needs to be killed 58 * (session is no longer in config file) 59 * 60 * daemon__reconfig 61 * - scans session objects and does following actions 62 * for states: 63 * 64 * OK - skip 65 * RECONFIG - session is killed and re-run with new config 66 * KILL - session is killed 67 * 68 * - all sessions have OK state on the function exit 69 */ 70 enum daemon_session_state { 71 OK, 72 RECONFIG, 73 KILL, 74 }; 75 76 struct daemon_session { 77 char *base; 78 char *name; 79 char *run; 80 char *control; 81 int pid; 82 struct list_head list; 83 enum daemon_session_state state; 84 time_t start; 85 }; 86 87 struct daemon { 88 const char *config; 89 char *config_real; 90 char *config_base; 91 const char *csv_sep; 92 const char *base_user; 93 char *base; 94 struct list_head sessions; 95 FILE *out; 96 char perf[PATH_MAX]; 97 int signal_fd; 98 time_t start; 99 }; 100 101 static struct daemon __daemon = { 102 .sessions = LIST_HEAD_INIT(__daemon.sessions), 103 }; 104 105 static const char * const daemon_usage[] = { 106 "perf daemon start [<options>]", 107 "perf daemon [<options>]", 108 NULL 109 }; 110 111 static bool done; 112 113 static void sig_handler(int sig __maybe_unused) 114 { 115 done = true; 116 } 117 118 static struct daemon_session *daemon__add_session(struct daemon *config, char *name) 119 { 120 struct daemon_session *session = zalloc(sizeof(*session)); 121 122 if (!session) 123 return NULL; 124 125 session->name = strdup(name); 126 if (!session->name) { 127 free(session); 128 return NULL; 129 } 130 131 session->pid = -1; 132 list_add_tail(&session->list, &config->sessions); 133 return session; 134 } 135 136 static struct daemon_session *daemon__find_session(struct daemon *daemon, char *name) 137 { 138 struct daemon_session *session; 139 140 list_for_each_entry(session, &daemon->sessions, list) { 141 if (!strcmp(session->name, name)) 142 return session; 143 } 144 145 return NULL; 146 } 147 148 static int get_session_name(const char *var, char *session, int len) 149 { 150 const char *p = var + sizeof("session-") - 1; 151 152 while (*p != '.' && *p != 0x0 && len--) 153 *session++ = *p++; 154 155 *session = 0; 156 return *p == '.' ? 0 : -EINVAL; 157 } 158 159 static int session_config(struct daemon *daemon, const char *var, const char *value) 160 { 161 struct daemon_session *session; 162 char name[100]; 163 164 if (get_session_name(var, name, sizeof(name))) 165 return -EINVAL; 166 167 var = strchr(var, '.'); 168 if (!var) 169 return -EINVAL; 170 171 var++; 172 173 session = daemon__find_session(daemon, name); 174 175 if (!session) { 176 /* New session is defined. */ 177 session = daemon__add_session(daemon, name); 178 if (!session) 179 return -ENOMEM; 180 181 pr_debug("reconfig: found new session %s\n", name); 182 183 /* Trigger reconfig to start it. */ 184 session->state = RECONFIG; 185 } else if (session->state == KILL) { 186 /* Current session is defined, no action needed. */ 187 pr_debug("reconfig: found current session %s\n", name); 188 session->state = OK; 189 } 190 191 if (!strcmp(var, "run")) { 192 bool same = false; 193 194 if (session->run) 195 same = !strcmp(session->run, value); 196 197 if (!same) { 198 if (session->run) { 199 free(session->run); 200 pr_debug("reconfig: session %s is changed\n", name); 201 } 202 203 session->run = strdup(value); 204 if (!session->run) 205 return -ENOMEM; 206 207 /* 208 * Either new or changed run value is defined, 209 * trigger reconfig for the session. 210 */ 211 session->state = RECONFIG; 212 } 213 } 214 215 return 0; 216 } 217 218 static int server_config(const char *var, const char *value, void *cb) 219 { 220 struct daemon *daemon = cb; 221 222 if (strstarts(var, "session-")) { 223 return session_config(daemon, var, value); 224 } else if (!strcmp(var, "daemon.base") && !daemon->base_user) { 225 if (daemon->base && strcmp(daemon->base, value)) { 226 pr_err("failed: can't redefine base, bailing out\n"); 227 return -EINVAL; 228 } 229 daemon->base = strdup(value); 230 if (!daemon->base) 231 return -ENOMEM; 232 } 233 234 return 0; 235 } 236 237 static int client_config(const char *var, const char *value, void *cb) 238 { 239 struct daemon *daemon = cb; 240 241 if (!strcmp(var, "daemon.base") && !daemon->base_user) { 242 daemon->base = strdup(value); 243 if (!daemon->base) 244 return -ENOMEM; 245 } 246 247 return 0; 248 } 249 250 static int check_base(struct daemon *daemon) 251 { 252 struct stat st; 253 254 if (!daemon->base) { 255 pr_err("failed: base not defined\n"); 256 return -EINVAL; 257 } 258 259 if (stat(daemon->base, &st)) { 260 switch (errno) { 261 case EACCES: 262 pr_err("failed: permission denied for '%s' base\n", 263 daemon->base); 264 return -EACCES; 265 case ENOENT: 266 pr_err("failed: base '%s' does not exists\n", 267 daemon->base); 268 return -EACCES; 269 default: 270 pr_err("failed: can't access base '%s': %s\n", 271 daemon->base, strerror(errno)); 272 return -errno; 273 } 274 } 275 276 if ((st.st_mode & S_IFMT) != S_IFDIR) { 277 pr_err("failed: base '%s' is not directory\n", 278 daemon->base); 279 return -EINVAL; 280 } 281 282 return 0; 283 } 284 285 static int setup_client_config(struct daemon *daemon) 286 { 287 struct perf_config_set *set = perf_config_set__load_file(daemon->config_real); 288 int err = -ENOMEM; 289 290 if (set) { 291 err = perf_config_set(set, client_config, daemon); 292 perf_config_set__delete(set); 293 } 294 295 return err ?: check_base(daemon); 296 } 297 298 static int setup_server_config(struct daemon *daemon) 299 { 300 struct perf_config_set *set; 301 struct daemon_session *session; 302 int err = -ENOMEM; 303 304 pr_debug("reconfig: started\n"); 305 306 /* 307 * Mark all sessions for kill, the server config 308 * will set following states, see explanation at 309 * enum daemon_session_state declaration. 310 */ 311 list_for_each_entry(session, &daemon->sessions, list) 312 session->state = KILL; 313 314 set = perf_config_set__load_file(daemon->config_real); 315 if (set) { 316 err = perf_config_set(set, server_config, daemon); 317 perf_config_set__delete(set); 318 } 319 320 return err ?: check_base(daemon); 321 } 322 323 static int daemon_session__run(struct daemon_session *session, 324 struct daemon *daemon) 325 { 326 char buf[PATH_MAX]; 327 char **argv; 328 int argc, fd; 329 330 if (asprintf(&session->base, "%s/session-%s", 331 daemon->base, session->name) < 0) { 332 perror("failed: asprintf"); 333 return -1; 334 } 335 336 if (mkdir(session->base, 0755) && errno != EEXIST) { 337 perror("failed: mkdir"); 338 return -1; 339 } 340 341 session->start = time(NULL); 342 343 session->pid = fork(); 344 if (session->pid < 0) 345 return -1; 346 if (session->pid > 0) { 347 pr_info("reconfig: ruining session [%s:%d]: %s\n", 348 session->name, session->pid, session->run); 349 return 0; 350 } 351 352 if (chdir(session->base)) { 353 perror("failed: chdir"); 354 return -1; 355 } 356 357 fd = open("/dev/null", O_RDONLY); 358 if (fd < 0) { 359 perror("failed: open /dev/null"); 360 return -1; 361 } 362 363 dup2(fd, 0); 364 close(fd); 365 366 fd = open(SESSION_OUTPUT, O_RDWR|O_CREAT|O_TRUNC, 0644); 367 if (fd < 0) { 368 perror("failed: open session output"); 369 return -1; 370 } 371 372 dup2(fd, 1); 373 dup2(fd, 2); 374 close(fd); 375 376 if (mkfifo(SESSION_CONTROL, O_RDWR) && errno != EEXIST) { 377 perror("failed: create control fifo"); 378 return -1; 379 } 380 381 if (mkfifo(SESSION_ACK, O_RDWR) && errno != EEXIST) { 382 perror("failed: create ack fifo"); 383 return -1; 384 } 385 386 scnprintf(buf, sizeof(buf), "%s record --control=fifo:%s,%s %s", 387 daemon->perf, SESSION_CONTROL, SESSION_ACK, session->run); 388 389 argv = argv_split(buf, &argc); 390 if (!argv) 391 exit(-1); 392 393 exit(execve(daemon->perf, argv, NULL)); 394 return -1; 395 } 396 397 static pid_t handle_signalfd(struct daemon *daemon) 398 { 399 struct daemon_session *session; 400 struct signalfd_siginfo si; 401 ssize_t err; 402 int status; 403 pid_t pid; 404 405 err = read(daemon->signal_fd, &si, sizeof(struct signalfd_siginfo)); 406 if (err != sizeof(struct signalfd_siginfo)) 407 return -1; 408 409 list_for_each_entry(session, &daemon->sessions, list) { 410 411 if (session->pid != (int) si.ssi_pid) 412 continue; 413 414 pid = waitpid(session->pid, &status, 0); 415 if (pid == session->pid) { 416 if (WIFEXITED(status)) { 417 pr_info("session '%s' exited, status=%d\n", 418 session->name, WEXITSTATUS(status)); 419 } else if (WIFSIGNALED(status)) { 420 pr_info("session '%s' killed (signal %d)\n", 421 session->name, WTERMSIG(status)); 422 } else if (WIFSTOPPED(status)) { 423 pr_info("session '%s' stopped (signal %d)\n", 424 session->name, WSTOPSIG(status)); 425 } else { 426 pr_info("session '%s' Unexpected status (0x%x)\n", 427 session->name, status); 428 } 429 } 430 431 session->state = KILL; 432 session->pid = -1; 433 return pid; 434 } 435 436 return 0; 437 } 438 439 static int daemon_session__wait(struct daemon_session *session, struct daemon *daemon, 440 int secs) 441 { 442 struct pollfd pollfd = { 443 .fd = daemon->signal_fd, 444 .events = POLLIN, 445 }; 446 pid_t wpid = 0, pid = session->pid; 447 time_t start; 448 449 start = time(NULL); 450 451 do { 452 int err = poll(&pollfd, 1, 1000); 453 454 if (err > 0) { 455 wpid = handle_signalfd(daemon); 456 } else if (err < 0) { 457 perror("failed: poll\n"); 458 return -1; 459 } 460 461 if (start + secs < time(NULL)) 462 return -1; 463 } while (wpid != pid); 464 465 return 0; 466 } 467 468 static bool daemon__has_alive_session(struct daemon *daemon) 469 { 470 struct daemon_session *session; 471 472 list_for_each_entry(session, &daemon->sessions, list) { 473 if (session->pid != -1) 474 return true; 475 } 476 477 return false; 478 } 479 480 static int daemon__wait(struct daemon *daemon, int secs) 481 { 482 struct pollfd pollfd = { 483 .fd = daemon->signal_fd, 484 .events = POLLIN, 485 }; 486 time_t start; 487 488 start = time(NULL); 489 490 do { 491 int err = poll(&pollfd, 1, 1000); 492 493 if (err > 0) { 494 handle_signalfd(daemon); 495 } else if (err < 0) { 496 perror("failed: poll\n"); 497 return -1; 498 } 499 500 if (start + secs < time(NULL)) 501 return -1; 502 } while (daemon__has_alive_session(daemon)); 503 504 return 0; 505 } 506 507 static int daemon_session__control(struct daemon_session *session, 508 const char *msg, bool do_ack) 509 { 510 struct pollfd pollfd = { .events = POLLIN, }; 511 char control_path[PATH_MAX]; 512 char ack_path[PATH_MAX]; 513 int control, ack = -1, len; 514 char buf[20]; 515 int ret = -1; 516 ssize_t err; 517 518 /* open the control file */ 519 scnprintf(control_path, sizeof(control_path), "%s/%s", 520 session->base, SESSION_CONTROL); 521 522 control = open(control_path, O_WRONLY|O_NONBLOCK); 523 if (!control) 524 return -1; 525 526 if (do_ack) { 527 /* open the ack file */ 528 scnprintf(ack_path, sizeof(ack_path), "%s/%s", 529 session->base, SESSION_ACK); 530 531 ack = open(ack_path, O_RDONLY, O_NONBLOCK); 532 if (!ack) { 533 close(control); 534 return -1; 535 } 536 } 537 538 /* write the command */ 539 len = strlen(msg); 540 541 err = writen(control, msg, len); 542 if (err != len) { 543 pr_err("failed: write to control pipe: %d (%s)\n", 544 errno, control_path); 545 goto out; 546 } 547 548 if (!do_ack) 549 goto out; 550 551 /* wait for an ack */ 552 pollfd.fd = ack; 553 554 if (!poll(&pollfd, 1, 2000)) { 555 pr_err("failed: control ack timeout\n"); 556 goto out; 557 } 558 559 if (!(pollfd.revents & POLLIN)) { 560 pr_err("failed: did not received an ack\n"); 561 goto out; 562 } 563 564 err = read(ack, buf, sizeof(buf)); 565 if (err > 0) 566 ret = strcmp(buf, "ack\n"); 567 else 568 perror("failed: read ack %d\n"); 569 570 out: 571 if (ack != -1) 572 close(ack); 573 574 close(control); 575 return ret; 576 } 577 578 static int setup_server_socket(struct daemon *daemon) 579 { 580 struct sockaddr_un addr; 581 char path[PATH_MAX]; 582 int fd = socket(AF_UNIX, SOCK_STREAM, 0); 583 584 if (fd < 0) { 585 fprintf(stderr, "socket: %s\n", strerror(errno)); 586 return -1; 587 } 588 589 if (fcntl(fd, F_SETFD, FD_CLOEXEC)) { 590 perror("failed: fcntl FD_CLOEXEC"); 591 close(fd); 592 return -1; 593 } 594 595 scnprintf(path, sizeof(path), "%s/control", daemon->base); 596 597 if (strlen(path) + 1 >= sizeof(addr.sun_path)) { 598 pr_err("failed: control path too long '%s'\n", path); 599 close(fd); 600 return -1; 601 } 602 603 memset(&addr, 0, sizeof(addr)); 604 addr.sun_family = AF_UNIX; 605 606 strlcpy(addr.sun_path, path, sizeof(addr.sun_path) - 1); 607 unlink(path); 608 609 if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) == -1) { 610 perror("failed: bind"); 611 close(fd); 612 return -1; 613 } 614 615 if (listen(fd, 1) == -1) { 616 perror("failed: listen"); 617 close(fd); 618 return -1; 619 } 620 621 return fd; 622 } 623 624 enum { 625 CMD_LIST = 0, 626 CMD_SIGNAL = 1, 627 CMD_STOP = 2, 628 CMD_PING = 3, 629 CMD_MAX, 630 }; 631 632 #define SESSION_MAX 64 633 634 union cmd { 635 int cmd; 636 637 /* CMD_LIST */ 638 struct { 639 int cmd; 640 int verbose; 641 char csv_sep; 642 } list; 643 644 /* CMD_SIGNAL */ 645 struct { 646 int cmd; 647 int sig; 648 char name[SESSION_MAX]; 649 } signal; 650 651 /* CMD_PING */ 652 struct { 653 int cmd; 654 char name[SESSION_MAX]; 655 } ping; 656 }; 657 658 enum { 659 PING_OK = 0, 660 PING_FAIL = 1, 661 PING_MAX, 662 }; 663 664 static int daemon_session__ping(struct daemon_session *session) 665 { 666 return daemon_session__control(session, "ping", true) ? PING_FAIL : PING_OK; 667 } 668 669 static int cmd_session_list(struct daemon *daemon, union cmd *cmd, FILE *out) 670 { 671 char csv_sep = cmd->list.csv_sep; 672 struct daemon_session *session; 673 time_t curr = time(NULL); 674 675 if (csv_sep) { 676 fprintf(out, "%d%c%s%c%s%c%s/%s", 677 /* pid daemon */ 678 getpid(), csv_sep, "daemon", 679 /* base */ 680 csv_sep, daemon->base, 681 /* output */ 682 csv_sep, daemon->base, SESSION_OUTPUT); 683 684 fprintf(out, "%c%s/%s", 685 /* lock */ 686 csv_sep, daemon->base, "lock"); 687 688 fprintf(out, "%c%lu", 689 /* session up time */ 690 csv_sep, (curr - daemon->start) / 60); 691 692 fprintf(out, "\n"); 693 } else { 694 fprintf(out, "[%d:daemon] base: %s\n", getpid(), daemon->base); 695 if (cmd->list.verbose) { 696 fprintf(out, " output: %s/%s\n", 697 daemon->base, SESSION_OUTPUT); 698 fprintf(out, " lock: %s/lock\n", 699 daemon->base); 700 fprintf(out, " up: %lu minutes\n", 701 (curr - daemon->start) / 60); 702 } 703 } 704 705 list_for_each_entry(session, &daemon->sessions, list) { 706 if (csv_sep) { 707 fprintf(out, "%d%c%s%c%s", 708 /* pid */ 709 session->pid, 710 /* name */ 711 csv_sep, session->name, 712 /* base */ 713 csv_sep, session->run); 714 715 fprintf(out, "%c%s%c%s/%s", 716 /* session dir */ 717 csv_sep, session->base, 718 /* session output */ 719 csv_sep, session->base, SESSION_OUTPUT); 720 721 fprintf(out, "%c%s/%s%c%s/%s", 722 /* session control */ 723 csv_sep, session->base, SESSION_CONTROL, 724 /* session ack */ 725 csv_sep, session->base, SESSION_ACK); 726 727 fprintf(out, "%c%lu", 728 /* session up time */ 729 csv_sep, (curr - session->start) / 60); 730 731 fprintf(out, "\n"); 732 } else { 733 fprintf(out, "[%d:%s] perf record %s\n", 734 session->pid, session->name, session->run); 735 if (!cmd->list.verbose) 736 continue; 737 fprintf(out, " base: %s\n", 738 session->base); 739 fprintf(out, " output: %s/%s\n", 740 session->base, SESSION_OUTPUT); 741 fprintf(out, " control: %s/%s\n", 742 session->base, SESSION_CONTROL); 743 fprintf(out, " ack: %s/%s\n", 744 session->base, SESSION_ACK); 745 fprintf(out, " up: %lu minutes\n", 746 (curr - session->start) / 60); 747 } 748 } 749 750 return 0; 751 } 752 753 static int daemon_session__signal(struct daemon_session *session, int sig) 754 { 755 if (session->pid < 0) 756 return -1; 757 return kill(session->pid, sig); 758 } 759 760 static int cmd_session_kill(struct daemon *daemon, union cmd *cmd, FILE *out) 761 { 762 struct daemon_session *session; 763 bool all = false; 764 765 all = !strcmp(cmd->signal.name, "all"); 766 767 list_for_each_entry(session, &daemon->sessions, list) { 768 if (all || !strcmp(cmd->signal.name, session->name)) { 769 daemon_session__signal(session, cmd->signal.sig); 770 fprintf(out, "signal %d sent to session '%s [%d]'\n", 771 cmd->signal.sig, session->name, session->pid); 772 } 773 } 774 775 return 0; 776 } 777 778 static const char *ping_str[PING_MAX] = { 779 [PING_OK] = "OK", 780 [PING_FAIL] = "FAIL", 781 }; 782 783 static int cmd_session_ping(struct daemon *daemon, union cmd *cmd, FILE *out) 784 { 785 struct daemon_session *session; 786 bool all = false, found = false; 787 788 all = !strcmp(cmd->ping.name, "all"); 789 790 list_for_each_entry(session, &daemon->sessions, list) { 791 if (all || !strcmp(cmd->ping.name, session->name)) { 792 int state = daemon_session__ping(session); 793 794 fprintf(out, "%-4s %s\n", ping_str[state], session->name); 795 found = true; 796 } 797 } 798 799 if (!found && !all) { 800 fprintf(out, "%-4s %s (not found)\n", 801 ping_str[PING_FAIL], cmd->ping.name); 802 } 803 return 0; 804 } 805 806 static int handle_server_socket(struct daemon *daemon, int sock_fd) 807 { 808 int ret = -1, fd; 809 FILE *out = NULL; 810 union cmd cmd; 811 812 fd = accept(sock_fd, NULL, NULL); 813 if (fd < 0) { 814 perror("failed: accept"); 815 return -1; 816 } 817 818 if (sizeof(cmd) != readn(fd, &cmd, sizeof(cmd))) { 819 perror("failed: read"); 820 goto out; 821 } 822 823 out = fdopen(fd, "w"); 824 if (!out) { 825 perror("failed: fdopen"); 826 goto out; 827 } 828 829 switch (cmd.cmd) { 830 case CMD_LIST: 831 ret = cmd_session_list(daemon, &cmd, out); 832 break; 833 case CMD_SIGNAL: 834 ret = cmd_session_kill(daemon, &cmd, out); 835 break; 836 case CMD_STOP: 837 done = 1; 838 ret = 0; 839 pr_debug("perf daemon is exciting\n"); 840 break; 841 case CMD_PING: 842 ret = cmd_session_ping(daemon, &cmd, out); 843 break; 844 default: 845 break; 846 } 847 848 fclose(out); 849 out: 850 /* If out is defined, then fd is closed via fclose. */ 851 if (!out) 852 close(fd); 853 return ret; 854 } 855 856 static int setup_client_socket(struct daemon *daemon) 857 { 858 struct sockaddr_un addr; 859 char path[PATH_MAX]; 860 int fd = socket(AF_UNIX, SOCK_STREAM, 0); 861 862 if (fd == -1) { 863 perror("failed: socket"); 864 return -1; 865 } 866 867 scnprintf(path, sizeof(path), "%s/control", daemon->base); 868 869 if (strlen(path) + 1 >= sizeof(addr.sun_path)) { 870 pr_err("failed: control path too long '%s'\n", path); 871 close(fd); 872 return -1; 873 } 874 875 memset(&addr, 0, sizeof(addr)); 876 addr.sun_family = AF_UNIX; 877 strlcpy(addr.sun_path, path, sizeof(addr.sun_path) - 1); 878 879 if (connect(fd, (struct sockaddr *) &addr, sizeof(addr)) == -1) { 880 perror("failed: connect"); 881 close(fd); 882 return -1; 883 } 884 885 return fd; 886 } 887 888 static void daemon_session__kill(struct daemon_session *session, 889 struct daemon *daemon) 890 { 891 int how = 0; 892 893 do { 894 switch (how) { 895 case 0: 896 daemon_session__control(session, "stop", false); 897 break; 898 case 1: 899 daemon_session__signal(session, SIGTERM); 900 break; 901 case 2: 902 daemon_session__signal(session, SIGKILL); 903 break; 904 default: 905 break; 906 } 907 how++; 908 909 } while (daemon_session__wait(session, daemon, 10)); 910 } 911 912 static void daemon__signal(struct daemon *daemon, int sig) 913 { 914 struct daemon_session *session; 915 916 list_for_each_entry(session, &daemon->sessions, list) 917 daemon_session__signal(session, sig); 918 } 919 920 static void daemon_session__delete(struct daemon_session *session) 921 { 922 free(session->base); 923 free(session->name); 924 free(session->run); 925 free(session); 926 } 927 928 static void daemon_session__remove(struct daemon_session *session) 929 { 930 list_del(&session->list); 931 daemon_session__delete(session); 932 } 933 934 static void daemon__stop(struct daemon *daemon) 935 { 936 struct daemon_session *session; 937 938 list_for_each_entry(session, &daemon->sessions, list) 939 daemon_session__control(session, "stop", false); 940 } 941 942 static void daemon__kill(struct daemon *daemon) 943 { 944 int how = 0; 945 946 do { 947 switch (how) { 948 case 0: 949 daemon__stop(daemon); 950 break; 951 case 1: 952 daemon__signal(daemon, SIGTERM); 953 break; 954 case 2: 955 daemon__signal(daemon, SIGKILL); 956 break; 957 default: 958 break; 959 } 960 how++; 961 962 } while (daemon__wait(daemon, 10)); 963 } 964 965 static void daemon__exit(struct daemon *daemon) 966 { 967 struct daemon_session *session, *h; 968 969 list_for_each_entry_safe(session, h, &daemon->sessions, list) 970 daemon_session__remove(session); 971 972 free(daemon->config_real); 973 free(daemon->config_base); 974 free(daemon->base); 975 } 976 977 static int daemon__reconfig(struct daemon *daemon) 978 { 979 struct daemon_session *session, *n; 980 981 list_for_each_entry_safe(session, n, &daemon->sessions, list) { 982 /* No change. */ 983 if (session->state == OK) 984 continue; 985 986 /* Remove session. */ 987 if (session->state == KILL) { 988 if (session->pid > 0) { 989 daemon_session__kill(session, daemon); 990 pr_info("reconfig: session '%s' killed\n", session->name); 991 } 992 daemon_session__remove(session); 993 continue; 994 } 995 996 /* Reconfig session. */ 997 if (session->pid > 0) { 998 daemon_session__kill(session, daemon); 999 pr_info("reconfig: session '%s' killed\n", session->name); 1000 } 1001 if (daemon_session__run(session, daemon)) 1002 return -1; 1003 1004 session->state = OK; 1005 } 1006 1007 return 0; 1008 } 1009 1010 static int setup_config_changes(struct daemon *daemon) 1011 { 1012 char *basen = strdup(daemon->config_real); 1013 char *dirn = strdup(daemon->config_real); 1014 char *base, *dir; 1015 int fd, wd = -1; 1016 1017 if (!dirn || !basen) 1018 goto out; 1019 1020 fd = inotify_init1(IN_NONBLOCK|O_CLOEXEC); 1021 if (fd < 0) { 1022 perror("failed: inotify_init"); 1023 goto out; 1024 } 1025 1026 dir = dirname(dirn); 1027 base = basename(basen); 1028 pr_debug("config file: %s, dir: %s\n", base, dir); 1029 1030 wd = inotify_add_watch(fd, dir, IN_CLOSE_WRITE); 1031 if (wd >= 0) { 1032 daemon->config_base = strdup(base); 1033 if (!daemon->config_base) { 1034 close(fd); 1035 wd = -1; 1036 } 1037 } else { 1038 perror("failed: inotify_add_watch"); 1039 } 1040 1041 out: 1042 free(basen); 1043 free(dirn); 1044 return wd < 0 ? -1 : fd; 1045 } 1046 1047 static bool process_inotify_event(struct daemon *daemon, char *buf, ssize_t len) 1048 { 1049 char *p = buf; 1050 1051 while (p < (buf + len)) { 1052 struct inotify_event *event = (struct inotify_event *) p; 1053 1054 /* 1055 * We monitor config directory, check if our 1056 * config file was changes. 1057 */ 1058 if ((event->mask & IN_CLOSE_WRITE) && 1059 !(event->mask & IN_ISDIR)) { 1060 if (!strcmp(event->name, daemon->config_base)) 1061 return true; 1062 } 1063 p += sizeof(*event) + event->len; 1064 } 1065 return false; 1066 } 1067 1068 static int handle_config_changes(struct daemon *daemon, int conf_fd, 1069 bool *config_changed) 1070 { 1071 char buf[4096]; 1072 ssize_t len; 1073 1074 while (!(*config_changed)) { 1075 len = read(conf_fd, buf, sizeof(buf)); 1076 if (len == -1) { 1077 if (errno != EAGAIN) { 1078 perror("failed: read"); 1079 return -1; 1080 } 1081 return 0; 1082 } 1083 *config_changed = process_inotify_event(daemon, buf, len); 1084 } 1085 return 0; 1086 } 1087 1088 static int setup_config(struct daemon *daemon) 1089 { 1090 if (daemon->base_user) { 1091 daemon->base = strdup(daemon->base_user); 1092 if (!daemon->base) 1093 return -ENOMEM; 1094 } 1095 1096 if (daemon->config) { 1097 char *real = realpath(daemon->config, NULL); 1098 1099 if (!real) { 1100 perror("failed: realpath"); 1101 return -1; 1102 } 1103 daemon->config_real = real; 1104 return 0; 1105 } 1106 1107 if (perf_config_system() && !access(perf_etc_perfconfig(), R_OK)) 1108 daemon->config_real = strdup(perf_etc_perfconfig()); 1109 else if (perf_config_global() && perf_home_perfconfig()) 1110 daemon->config_real = strdup(perf_home_perfconfig()); 1111 1112 return daemon->config_real ? 0 : -1; 1113 } 1114 1115 #ifndef F_TLOCK 1116 #define F_TLOCK 2 1117 1118 #include <sys/file.h> 1119 1120 static int lockf(int fd, int cmd, off_t len) 1121 { 1122 if (cmd != F_TLOCK || len != 0) 1123 return -1; 1124 1125 return flock(fd, LOCK_EX | LOCK_NB); 1126 } 1127 #endif // F_TLOCK 1128 1129 /* 1130 * Each daemon tries to create and lock BASE/lock file, 1131 * if it's successful we are sure we're the only daemon 1132 * running over the BASE. 1133 * 1134 * Once daemon is finished, file descriptor to lock file 1135 * is closed and lock is released. 1136 */ 1137 static int check_lock(struct daemon *daemon) 1138 { 1139 char path[PATH_MAX]; 1140 char buf[20]; 1141 int fd, pid; 1142 ssize_t len; 1143 1144 scnprintf(path, sizeof(path), "%s/lock", daemon->base); 1145 1146 fd = open(path, O_RDWR|O_CREAT|O_CLOEXEC, 0640); 1147 if (fd < 0) 1148 return -1; 1149 1150 if (lockf(fd, F_TLOCK, 0) < 0) { 1151 filename__read_int(path, &pid); 1152 fprintf(stderr, "failed: another perf daemon (pid %d) owns %s\n", 1153 pid, daemon->base); 1154 close(fd); 1155 return -1; 1156 } 1157 1158 scnprintf(buf, sizeof(buf), "%d", getpid()); 1159 len = strlen(buf); 1160 1161 if (write(fd, buf, len) != len) { 1162 perror("failed: write"); 1163 close(fd); 1164 return -1; 1165 } 1166 1167 if (ftruncate(fd, len)) { 1168 perror("failed: ftruncate"); 1169 close(fd); 1170 return -1; 1171 } 1172 1173 return 0; 1174 } 1175 1176 static int go_background(struct daemon *daemon) 1177 { 1178 int pid, fd; 1179 1180 pid = fork(); 1181 if (pid < 0) 1182 return -1; 1183 1184 if (pid > 0) 1185 return 1; 1186 1187 if (setsid() < 0) 1188 return -1; 1189 1190 if (check_lock(daemon)) 1191 return -1; 1192 1193 umask(0); 1194 1195 if (chdir(daemon->base)) { 1196 perror("failed: chdir"); 1197 return -1; 1198 } 1199 1200 fd = open("output", O_RDWR|O_CREAT|O_TRUNC, 0644); 1201 if (fd < 0) { 1202 perror("failed: open"); 1203 return -1; 1204 } 1205 1206 if (fcntl(fd, F_SETFD, FD_CLOEXEC)) { 1207 perror("failed: fcntl FD_CLOEXEC"); 1208 close(fd); 1209 return -1; 1210 } 1211 1212 close(0); 1213 dup2(fd, 1); 1214 dup2(fd, 2); 1215 close(fd); 1216 1217 daemon->out = fdopen(1, "w"); 1218 if (!daemon->out) { 1219 close(1); 1220 close(2); 1221 return -1; 1222 } 1223 1224 setbuf(daemon->out, NULL); 1225 return 0; 1226 } 1227 1228 static int setup_signalfd(struct daemon *daemon) 1229 { 1230 sigset_t mask; 1231 1232 sigemptyset(&mask); 1233 sigaddset(&mask, SIGCHLD); 1234 1235 if (sigprocmask(SIG_BLOCK, &mask, NULL) == -1) 1236 return -1; 1237 1238 daemon->signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC); 1239 return daemon->signal_fd; 1240 } 1241 1242 static int __cmd_start(struct daemon *daemon, struct option parent_options[], 1243 int argc, const char **argv) 1244 { 1245 bool foreground = false; 1246 struct option start_options[] = { 1247 OPT_BOOLEAN('f', "foreground", &foreground, "stay on console"), 1248 OPT_PARENT(parent_options), 1249 OPT_END() 1250 }; 1251 int sock_fd = -1, conf_fd = -1, signal_fd = -1; 1252 int sock_pos, file_pos, signal_pos; 1253 struct fdarray fda; 1254 int err = 0; 1255 1256 argc = parse_options(argc, argv, start_options, daemon_usage, 0); 1257 if (argc) 1258 usage_with_options(daemon_usage, start_options); 1259 1260 daemon->start = time(NULL); 1261 1262 if (setup_config(daemon)) { 1263 pr_err("failed: config not found\n"); 1264 return -1; 1265 } 1266 1267 if (setup_server_config(daemon)) 1268 return -1; 1269 1270 if (foreground && check_lock(daemon)) 1271 return -1; 1272 1273 if (!foreground) { 1274 err = go_background(daemon); 1275 if (err) { 1276 /* original process, exit normally */ 1277 if (err == 1) 1278 err = 0; 1279 daemon__exit(daemon); 1280 return err; 1281 } 1282 } 1283 1284 debug_set_file(daemon->out); 1285 debug_set_display_time(true); 1286 1287 pr_info("daemon started (pid %d)\n", getpid()); 1288 1289 fdarray__init(&fda, 3); 1290 1291 sock_fd = setup_server_socket(daemon); 1292 if (sock_fd < 0) 1293 goto out; 1294 1295 conf_fd = setup_config_changes(daemon); 1296 if (conf_fd < 0) 1297 goto out; 1298 1299 signal_fd = setup_signalfd(daemon); 1300 if (signal_fd < 0) 1301 goto out; 1302 1303 sock_pos = fdarray__add(&fda, sock_fd, POLLIN|POLLERR|POLLHUP, 0); 1304 if (sock_pos < 0) 1305 goto out; 1306 1307 file_pos = fdarray__add(&fda, conf_fd, POLLIN|POLLERR|POLLHUP, 0); 1308 if (file_pos < 0) 1309 goto out; 1310 1311 signal_pos = fdarray__add(&fda, signal_fd, POLLIN|POLLERR|POLLHUP, 0); 1312 if (signal_pos < 0) 1313 goto out; 1314 1315 signal(SIGINT, sig_handler); 1316 signal(SIGTERM, sig_handler); 1317 signal(SIGPIPE, SIG_IGN); 1318 1319 while (!done && !err) { 1320 err = daemon__reconfig(daemon); 1321 1322 if (!err && fdarray__poll(&fda, -1)) { 1323 bool reconfig = false; 1324 1325 if (fda.entries[sock_pos].revents & POLLIN) 1326 err = handle_server_socket(daemon, sock_fd); 1327 if (fda.entries[file_pos].revents & POLLIN) 1328 err = handle_config_changes(daemon, conf_fd, &reconfig); 1329 if (fda.entries[signal_pos].revents & POLLIN) 1330 err = handle_signalfd(daemon) < 0; 1331 1332 if (reconfig) 1333 err = setup_server_config(daemon); 1334 } 1335 } 1336 1337 out: 1338 fdarray__exit(&fda); 1339 1340 daemon__kill(daemon); 1341 daemon__exit(daemon); 1342 1343 if (sock_fd != -1) 1344 close(sock_fd); 1345 if (conf_fd != -1) 1346 close(conf_fd); 1347 if (conf_fd != -1) 1348 close(signal_fd); 1349 1350 pr_info("daemon exited\n"); 1351 fclose(daemon->out); 1352 return err; 1353 } 1354 1355 static int send_cmd(struct daemon *daemon, union cmd *cmd) 1356 { 1357 int ret = -1, fd; 1358 char *line = NULL; 1359 size_t len = 0; 1360 ssize_t nread; 1361 FILE *in = NULL; 1362 1363 if (setup_client_config(daemon)) 1364 return -1; 1365 1366 fd = setup_client_socket(daemon); 1367 if (fd < 0) 1368 return -1; 1369 1370 if (sizeof(*cmd) != writen(fd, cmd, sizeof(*cmd))) { 1371 perror("failed: write"); 1372 goto out; 1373 } 1374 1375 in = fdopen(fd, "r"); 1376 if (!in) { 1377 perror("failed: fdopen"); 1378 goto out; 1379 } 1380 1381 while ((nread = getline(&line, &len, in)) != -1) { 1382 if (fwrite(line, nread, 1, stdout) != 1) 1383 goto out_fclose; 1384 fflush(stdout); 1385 } 1386 1387 ret = 0; 1388 out_fclose: 1389 fclose(in); 1390 free(line); 1391 out: 1392 /* If in is defined, then fd is closed via fclose. */ 1393 if (!in) 1394 close(fd); 1395 return ret; 1396 } 1397 1398 static int send_cmd_list(struct daemon *daemon) 1399 { 1400 union cmd cmd = { .cmd = CMD_LIST, }; 1401 1402 cmd.list.verbose = verbose; 1403 cmd.list.csv_sep = daemon->csv_sep ? *daemon->csv_sep : 0; 1404 1405 return send_cmd(daemon, &cmd); 1406 } 1407 1408 static int __cmd_signal(struct daemon *daemon, struct option parent_options[], 1409 int argc, const char **argv) 1410 { 1411 const char *name = "all"; 1412 struct option start_options[] = { 1413 OPT_STRING(0, "session", &name, "session", 1414 "Sent signal to specific session"), 1415 OPT_PARENT(parent_options), 1416 OPT_END() 1417 }; 1418 union cmd cmd; 1419 1420 argc = parse_options(argc, argv, start_options, daemon_usage, 0); 1421 if (argc) 1422 usage_with_options(daemon_usage, start_options); 1423 1424 if (setup_config(daemon)) { 1425 pr_err("failed: config not found\n"); 1426 return -1; 1427 } 1428 1429 cmd.signal.cmd = CMD_SIGNAL, 1430 cmd.signal.sig = SIGUSR2; 1431 strncpy(cmd.signal.name, name, sizeof(cmd.signal.name) - 1); 1432 1433 return send_cmd(daemon, &cmd); 1434 } 1435 1436 static int __cmd_stop(struct daemon *daemon, struct option parent_options[], 1437 int argc, const char **argv) 1438 { 1439 struct option start_options[] = { 1440 OPT_PARENT(parent_options), 1441 OPT_END() 1442 }; 1443 union cmd cmd = { .cmd = CMD_STOP, }; 1444 1445 argc = parse_options(argc, argv, start_options, daemon_usage, 0); 1446 if (argc) 1447 usage_with_options(daemon_usage, start_options); 1448 1449 if (setup_config(daemon)) { 1450 pr_err("failed: config not found\n"); 1451 return -1; 1452 } 1453 1454 return send_cmd(daemon, &cmd); 1455 } 1456 1457 static int __cmd_ping(struct daemon *daemon, struct option parent_options[], 1458 int argc, const char **argv) 1459 { 1460 const char *name = "all"; 1461 struct option ping_options[] = { 1462 OPT_STRING(0, "session", &name, "session", 1463 "Ping to specific session"), 1464 OPT_PARENT(parent_options), 1465 OPT_END() 1466 }; 1467 union cmd cmd = { .cmd = CMD_PING, }; 1468 1469 argc = parse_options(argc, argv, ping_options, daemon_usage, 0); 1470 if (argc) 1471 usage_with_options(daemon_usage, ping_options); 1472 1473 if (setup_config(daemon)) { 1474 pr_err("failed: config not found\n"); 1475 return -1; 1476 } 1477 1478 scnprintf(cmd.ping.name, sizeof(cmd.ping.name), "%s", name); 1479 return send_cmd(daemon, &cmd); 1480 } 1481 1482 int cmd_daemon(int argc, const char **argv) 1483 { 1484 struct option daemon_options[] = { 1485 OPT_INCR('v', "verbose", &verbose, "be more verbose"), 1486 OPT_STRING(0, "config", &__daemon.config, 1487 "config file", "config file path"), 1488 OPT_STRING(0, "base", &__daemon.base_user, 1489 "directory", "base directory"), 1490 OPT_STRING_OPTARG('x', "field-separator", &__daemon.csv_sep, 1491 "field separator", "print counts with custom separator", ","), 1492 OPT_END() 1493 }; 1494 1495 perf_exe(__daemon.perf, sizeof(__daemon.perf)); 1496 __daemon.out = stdout; 1497 1498 argc = parse_options(argc, argv, daemon_options, daemon_usage, 1499 PARSE_OPT_STOP_AT_NON_OPTION); 1500 1501 if (argc) { 1502 if (!strcmp(argv[0], "start")) 1503 return __cmd_start(&__daemon, daemon_options, argc, argv); 1504 if (!strcmp(argv[0], "signal")) 1505 return __cmd_signal(&__daemon, daemon_options, argc, argv); 1506 else if (!strcmp(argv[0], "stop")) 1507 return __cmd_stop(&__daemon, daemon_options, argc, argv); 1508 else if (!strcmp(argv[0], "ping")) 1509 return __cmd_ping(&__daemon, daemon_options, argc, argv); 1510 1511 pr_err("failed: unknown command '%s'\n", argv[0]); 1512 return -1; 1513 } 1514 1515 if (setup_config(&__daemon)) { 1516 pr_err("failed: config not found\n"); 1517 return -1; 1518 } 1519 1520 return send_cmd_list(&__daemon); 1521 } 1522