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) - 1)) 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, 0600) && errno != EEXIST) { 377 perror("failed: create control fifo"); 378 return -1; 379 } 380 381 if (mkfifo(SESSION_ACK, 0600) && 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 /* 406 * Take signal fd data as pure signal notification and check all 407 * the sessions state. The reason is that multiple signals can get 408 * coalesced in kernel and we can receive only single signal even 409 * if multiple SIGCHLD were generated. 410 */ 411 err = read(daemon->signal_fd, &si, sizeof(struct signalfd_siginfo)); 412 if (err != sizeof(struct signalfd_siginfo)) { 413 pr_err("failed to read signal fd\n"); 414 return -1; 415 } 416 417 list_for_each_entry(session, &daemon->sessions, list) { 418 if (session->pid == -1) 419 continue; 420 421 pid = waitpid(session->pid, &status, WNOHANG); 422 if (pid <= 0) 423 continue; 424 425 if (WIFEXITED(status)) { 426 pr_info("session '%s' exited, status=%d\n", 427 session->name, WEXITSTATUS(status)); 428 } else if (WIFSIGNALED(status)) { 429 pr_info("session '%s' killed (signal %d)\n", 430 session->name, WTERMSIG(status)); 431 } else if (WIFSTOPPED(status)) { 432 pr_info("session '%s' stopped (signal %d)\n", 433 session->name, WSTOPSIG(status)); 434 } else { 435 pr_info("session '%s' Unexpected status (0x%x)\n", 436 session->name, status); 437 } 438 439 session->state = KILL; 440 session->pid = -1; 441 } 442 443 return 0; 444 } 445 446 static int daemon_session__wait(struct daemon_session *session, struct daemon *daemon, 447 int secs) 448 { 449 struct pollfd pollfd = { 450 .fd = daemon->signal_fd, 451 .events = POLLIN, 452 }; 453 time_t start; 454 455 start = time(NULL); 456 457 do { 458 int err = poll(&pollfd, 1, 1000); 459 460 if (err > 0) { 461 handle_signalfd(daemon); 462 } else if (err < 0) { 463 perror("failed: poll\n"); 464 return -1; 465 } 466 467 if (start + secs < time(NULL)) 468 return -1; 469 } while (session->pid != -1); 470 471 return 0; 472 } 473 474 static bool daemon__has_alive_session(struct daemon *daemon) 475 { 476 struct daemon_session *session; 477 478 list_for_each_entry(session, &daemon->sessions, list) { 479 if (session->pid != -1) 480 return true; 481 } 482 483 return false; 484 } 485 486 static int daemon__wait(struct daemon *daemon, int secs) 487 { 488 struct pollfd pollfd = { 489 .fd = daemon->signal_fd, 490 .events = POLLIN, 491 }; 492 time_t start; 493 494 start = time(NULL); 495 496 do { 497 int err = poll(&pollfd, 1, 1000); 498 499 if (err > 0) { 500 handle_signalfd(daemon); 501 } else if (err < 0) { 502 perror("failed: poll\n"); 503 return -1; 504 } 505 506 if (start + secs < time(NULL)) 507 return -1; 508 } while (daemon__has_alive_session(daemon)); 509 510 return 0; 511 } 512 513 static int daemon_session__control(struct daemon_session *session, 514 const char *msg, bool do_ack) 515 { 516 struct pollfd pollfd = { .events = POLLIN, }; 517 char control_path[PATH_MAX]; 518 char ack_path[PATH_MAX]; 519 int control, ack = -1, len; 520 char buf[20]; 521 int ret = -1; 522 ssize_t err; 523 524 /* open the control file */ 525 scnprintf(control_path, sizeof(control_path), "%s/%s", 526 session->base, SESSION_CONTROL); 527 528 control = open(control_path, O_WRONLY|O_NONBLOCK); 529 if (!control) 530 return -1; 531 532 if (do_ack) { 533 /* open the ack file */ 534 scnprintf(ack_path, sizeof(ack_path), "%s/%s", 535 session->base, SESSION_ACK); 536 537 ack = open(ack_path, O_RDONLY, O_NONBLOCK); 538 if (!ack) { 539 close(control); 540 return -1; 541 } 542 } 543 544 /* write the command */ 545 len = strlen(msg); 546 547 err = writen(control, msg, len); 548 if (err != len) { 549 pr_err("failed: write to control pipe: %d (%s)\n", 550 errno, control_path); 551 goto out; 552 } 553 554 if (!do_ack) 555 goto out; 556 557 /* wait for an ack */ 558 pollfd.fd = ack; 559 560 if (!poll(&pollfd, 1, 2000)) { 561 pr_err("failed: control ack timeout\n"); 562 goto out; 563 } 564 565 if (!(pollfd.revents & POLLIN)) { 566 pr_err("failed: did not received an ack\n"); 567 goto out; 568 } 569 570 err = read(ack, buf, sizeof(buf)); 571 if (err > 0) 572 ret = strcmp(buf, "ack\n"); 573 else 574 perror("failed: read ack %d\n"); 575 576 out: 577 if (ack != -1) 578 close(ack); 579 580 close(control); 581 return ret; 582 } 583 584 static int setup_server_socket(struct daemon *daemon) 585 { 586 struct sockaddr_un addr; 587 char path[PATH_MAX]; 588 int fd = socket(AF_UNIX, SOCK_STREAM, 0); 589 590 if (fd < 0) { 591 fprintf(stderr, "socket: %s\n", strerror(errno)); 592 return -1; 593 } 594 595 if (fcntl(fd, F_SETFD, FD_CLOEXEC)) { 596 perror("failed: fcntl FD_CLOEXEC"); 597 close(fd); 598 return -1; 599 } 600 601 scnprintf(path, sizeof(path), "%s/control", daemon->base); 602 603 if (strlen(path) + 1 >= sizeof(addr.sun_path)) { 604 pr_err("failed: control path too long '%s'\n", path); 605 close(fd); 606 return -1; 607 } 608 609 memset(&addr, 0, sizeof(addr)); 610 addr.sun_family = AF_UNIX; 611 612 strlcpy(addr.sun_path, path, sizeof(addr.sun_path) - 1); 613 unlink(path); 614 615 if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) == -1) { 616 perror("failed: bind"); 617 close(fd); 618 return -1; 619 } 620 621 if (listen(fd, 1) == -1) { 622 perror("failed: listen"); 623 close(fd); 624 return -1; 625 } 626 627 return fd; 628 } 629 630 enum { 631 CMD_LIST = 0, 632 CMD_SIGNAL = 1, 633 CMD_STOP = 2, 634 CMD_PING = 3, 635 CMD_MAX, 636 }; 637 638 #define SESSION_MAX 64 639 640 union cmd { 641 int cmd; 642 643 /* CMD_LIST */ 644 struct { 645 int cmd; 646 int verbose; 647 char csv_sep; 648 } list; 649 650 /* CMD_SIGNAL */ 651 struct { 652 int cmd; 653 int sig; 654 char name[SESSION_MAX]; 655 } signal; 656 657 /* CMD_PING */ 658 struct { 659 int cmd; 660 char name[SESSION_MAX]; 661 } ping; 662 }; 663 664 enum { 665 PING_OK = 0, 666 PING_FAIL = 1, 667 PING_MAX, 668 }; 669 670 static int daemon_session__ping(struct daemon_session *session) 671 { 672 return daemon_session__control(session, "ping", true) ? PING_FAIL : PING_OK; 673 } 674 675 static int cmd_session_list(struct daemon *daemon, union cmd *cmd, FILE *out) 676 { 677 char csv_sep = cmd->list.csv_sep; 678 struct daemon_session *session; 679 time_t curr = time(NULL); 680 681 if (csv_sep) { 682 fprintf(out, "%d%c%s%c%s%c%s/%s", 683 /* pid daemon */ 684 getpid(), csv_sep, "daemon", 685 /* base */ 686 csv_sep, daemon->base, 687 /* output */ 688 csv_sep, daemon->base, SESSION_OUTPUT); 689 690 fprintf(out, "%c%s/%s", 691 /* lock */ 692 csv_sep, daemon->base, "lock"); 693 694 fprintf(out, "%c%lu", 695 /* session up time */ 696 csv_sep, (curr - daemon->start) / 60); 697 698 fprintf(out, "\n"); 699 } else { 700 fprintf(out, "[%d:daemon] base: %s\n", getpid(), daemon->base); 701 if (cmd->list.verbose) { 702 fprintf(out, " output: %s/%s\n", 703 daemon->base, SESSION_OUTPUT); 704 fprintf(out, " lock: %s/lock\n", 705 daemon->base); 706 fprintf(out, " up: %lu minutes\n", 707 (curr - daemon->start) / 60); 708 } 709 } 710 711 list_for_each_entry(session, &daemon->sessions, list) { 712 if (csv_sep) { 713 fprintf(out, "%d%c%s%c%s", 714 /* pid */ 715 session->pid, 716 /* name */ 717 csv_sep, session->name, 718 /* base */ 719 csv_sep, session->run); 720 721 fprintf(out, "%c%s%c%s/%s", 722 /* session dir */ 723 csv_sep, session->base, 724 /* session output */ 725 csv_sep, session->base, SESSION_OUTPUT); 726 727 fprintf(out, "%c%s/%s%c%s/%s", 728 /* session control */ 729 csv_sep, session->base, SESSION_CONTROL, 730 /* session ack */ 731 csv_sep, session->base, SESSION_ACK); 732 733 fprintf(out, "%c%lu", 734 /* session up time */ 735 csv_sep, (curr - session->start) / 60); 736 737 fprintf(out, "\n"); 738 } else { 739 fprintf(out, "[%d:%s] perf record %s\n", 740 session->pid, session->name, session->run); 741 if (!cmd->list.verbose) 742 continue; 743 fprintf(out, " base: %s\n", 744 session->base); 745 fprintf(out, " output: %s/%s\n", 746 session->base, SESSION_OUTPUT); 747 fprintf(out, " control: %s/%s\n", 748 session->base, SESSION_CONTROL); 749 fprintf(out, " ack: %s/%s\n", 750 session->base, SESSION_ACK); 751 fprintf(out, " up: %lu minutes\n", 752 (curr - session->start) / 60); 753 } 754 } 755 756 return 0; 757 } 758 759 static int daemon_session__signal(struct daemon_session *session, int sig) 760 { 761 if (session->pid < 0) 762 return -1; 763 return kill(session->pid, sig); 764 } 765 766 static int cmd_session_kill(struct daemon *daemon, union cmd *cmd, FILE *out) 767 { 768 struct daemon_session *session; 769 bool all = false; 770 771 all = !strcmp(cmd->signal.name, "all"); 772 773 list_for_each_entry(session, &daemon->sessions, list) { 774 if (all || !strcmp(cmd->signal.name, session->name)) { 775 daemon_session__signal(session, cmd->signal.sig); 776 fprintf(out, "signal %d sent to session '%s [%d]'\n", 777 cmd->signal.sig, session->name, session->pid); 778 } 779 } 780 781 return 0; 782 } 783 784 static const char *ping_str[PING_MAX] = { 785 [PING_OK] = "OK", 786 [PING_FAIL] = "FAIL", 787 }; 788 789 static int cmd_session_ping(struct daemon *daemon, union cmd *cmd, FILE *out) 790 { 791 struct daemon_session *session; 792 bool all = false, found = false; 793 794 all = !strcmp(cmd->ping.name, "all"); 795 796 list_for_each_entry(session, &daemon->sessions, list) { 797 if (all || !strcmp(cmd->ping.name, session->name)) { 798 int state = daemon_session__ping(session); 799 800 fprintf(out, "%-4s %s\n", ping_str[state], session->name); 801 found = true; 802 } 803 } 804 805 if (!found && !all) { 806 fprintf(out, "%-4s %s (not found)\n", 807 ping_str[PING_FAIL], cmd->ping.name); 808 } 809 return 0; 810 } 811 812 static int handle_server_socket(struct daemon *daemon, int sock_fd) 813 { 814 int ret = -1, fd; 815 FILE *out = NULL; 816 union cmd cmd; 817 818 fd = accept(sock_fd, NULL, NULL); 819 if (fd < 0) { 820 perror("failed: accept"); 821 return -1; 822 } 823 824 if (sizeof(cmd) != readn(fd, &cmd, sizeof(cmd))) { 825 perror("failed: read"); 826 goto out; 827 } 828 829 out = fdopen(fd, "w"); 830 if (!out) { 831 perror("failed: fdopen"); 832 goto out; 833 } 834 835 switch (cmd.cmd) { 836 case CMD_LIST: 837 ret = cmd_session_list(daemon, &cmd, out); 838 break; 839 case CMD_SIGNAL: 840 ret = cmd_session_kill(daemon, &cmd, out); 841 break; 842 case CMD_STOP: 843 done = 1; 844 ret = 0; 845 pr_debug("perf daemon is exciting\n"); 846 break; 847 case CMD_PING: 848 ret = cmd_session_ping(daemon, &cmd, out); 849 break; 850 default: 851 break; 852 } 853 854 fclose(out); 855 out: 856 /* If out is defined, then fd is closed via fclose. */ 857 if (!out) 858 close(fd); 859 return ret; 860 } 861 862 static int setup_client_socket(struct daemon *daemon) 863 { 864 struct sockaddr_un addr; 865 char path[PATH_MAX]; 866 int fd = socket(AF_UNIX, SOCK_STREAM, 0); 867 868 if (fd == -1) { 869 perror("failed: socket"); 870 return -1; 871 } 872 873 scnprintf(path, sizeof(path), "%s/control", daemon->base); 874 875 if (strlen(path) + 1 >= sizeof(addr.sun_path)) { 876 pr_err("failed: control path too long '%s'\n", path); 877 close(fd); 878 return -1; 879 } 880 881 memset(&addr, 0, sizeof(addr)); 882 addr.sun_family = AF_UNIX; 883 strlcpy(addr.sun_path, path, sizeof(addr.sun_path) - 1); 884 885 if (connect(fd, (struct sockaddr *) &addr, sizeof(addr)) == -1) { 886 perror("failed: connect"); 887 close(fd); 888 return -1; 889 } 890 891 return fd; 892 } 893 894 static void daemon_session__kill(struct daemon_session *session, 895 struct daemon *daemon) 896 { 897 int how = 0; 898 899 do { 900 switch (how) { 901 case 0: 902 daemon_session__control(session, "stop", false); 903 break; 904 case 1: 905 daemon_session__signal(session, SIGTERM); 906 break; 907 case 2: 908 daemon_session__signal(session, SIGKILL); 909 break; 910 default: 911 pr_err("failed to wait for session %s\n", 912 session->name); 913 return; 914 } 915 how++; 916 917 } while (daemon_session__wait(session, daemon, 10)); 918 } 919 920 static void daemon__signal(struct daemon *daemon, int sig) 921 { 922 struct daemon_session *session; 923 924 list_for_each_entry(session, &daemon->sessions, list) 925 daemon_session__signal(session, sig); 926 } 927 928 static void daemon_session__delete(struct daemon_session *session) 929 { 930 free(session->base); 931 free(session->name); 932 free(session->run); 933 free(session); 934 } 935 936 static void daemon_session__remove(struct daemon_session *session) 937 { 938 list_del(&session->list); 939 daemon_session__delete(session); 940 } 941 942 static void daemon__stop(struct daemon *daemon) 943 { 944 struct daemon_session *session; 945 946 list_for_each_entry(session, &daemon->sessions, list) 947 daemon_session__control(session, "stop", false); 948 } 949 950 static void daemon__kill(struct daemon *daemon) 951 { 952 int how = 0; 953 954 do { 955 switch (how) { 956 case 0: 957 daemon__stop(daemon); 958 break; 959 case 1: 960 daemon__signal(daemon, SIGTERM); 961 break; 962 case 2: 963 daemon__signal(daemon, SIGKILL); 964 break; 965 default: 966 pr_err("failed to wait for sessions\n"); 967 return; 968 } 969 how++; 970 971 } while (daemon__wait(daemon, 10)); 972 } 973 974 static void daemon__exit(struct daemon *daemon) 975 { 976 struct daemon_session *session, *h; 977 978 list_for_each_entry_safe(session, h, &daemon->sessions, list) 979 daemon_session__remove(session); 980 981 free(daemon->config_real); 982 free(daemon->config_base); 983 free(daemon->base); 984 } 985 986 static int daemon__reconfig(struct daemon *daemon) 987 { 988 struct daemon_session *session, *n; 989 990 list_for_each_entry_safe(session, n, &daemon->sessions, list) { 991 /* No change. */ 992 if (session->state == OK) 993 continue; 994 995 /* Remove session. */ 996 if (session->state == KILL) { 997 if (session->pid > 0) { 998 daemon_session__kill(session, daemon); 999 pr_info("reconfig: session '%s' killed\n", session->name); 1000 } 1001 daemon_session__remove(session); 1002 continue; 1003 } 1004 1005 /* Reconfig session. */ 1006 if (session->pid > 0) { 1007 daemon_session__kill(session, daemon); 1008 pr_info("reconfig: session '%s' killed\n", session->name); 1009 } 1010 if (daemon_session__run(session, daemon)) 1011 return -1; 1012 1013 session->state = OK; 1014 } 1015 1016 return 0; 1017 } 1018 1019 static int setup_config_changes(struct daemon *daemon) 1020 { 1021 char *basen = strdup(daemon->config_real); 1022 char *dirn = strdup(daemon->config_real); 1023 char *base, *dir; 1024 int fd, wd = -1; 1025 1026 if (!dirn || !basen) 1027 goto out; 1028 1029 fd = inotify_init1(IN_NONBLOCK|O_CLOEXEC); 1030 if (fd < 0) { 1031 perror("failed: inotify_init"); 1032 goto out; 1033 } 1034 1035 dir = dirname(dirn); 1036 base = basename(basen); 1037 pr_debug("config file: %s, dir: %s\n", base, dir); 1038 1039 wd = inotify_add_watch(fd, dir, IN_CLOSE_WRITE); 1040 if (wd >= 0) { 1041 daemon->config_base = strdup(base); 1042 if (!daemon->config_base) { 1043 close(fd); 1044 wd = -1; 1045 } 1046 } else { 1047 perror("failed: inotify_add_watch"); 1048 } 1049 1050 out: 1051 free(basen); 1052 free(dirn); 1053 return wd < 0 ? -1 : fd; 1054 } 1055 1056 static bool process_inotify_event(struct daemon *daemon, char *buf, ssize_t len) 1057 { 1058 char *p = buf; 1059 1060 while (p < (buf + len)) { 1061 struct inotify_event *event = (struct inotify_event *) p; 1062 1063 /* 1064 * We monitor config directory, check if our 1065 * config file was changes. 1066 */ 1067 if ((event->mask & IN_CLOSE_WRITE) && 1068 !(event->mask & IN_ISDIR)) { 1069 if (!strcmp(event->name, daemon->config_base)) 1070 return true; 1071 } 1072 p += sizeof(*event) + event->len; 1073 } 1074 return false; 1075 } 1076 1077 static int handle_config_changes(struct daemon *daemon, int conf_fd, 1078 bool *config_changed) 1079 { 1080 char buf[4096]; 1081 ssize_t len; 1082 1083 while (!(*config_changed)) { 1084 len = read(conf_fd, buf, sizeof(buf)); 1085 if (len == -1) { 1086 if (errno != EAGAIN) { 1087 perror("failed: read"); 1088 return -1; 1089 } 1090 return 0; 1091 } 1092 *config_changed = process_inotify_event(daemon, buf, len); 1093 } 1094 return 0; 1095 } 1096 1097 static int setup_config(struct daemon *daemon) 1098 { 1099 if (daemon->base_user) { 1100 daemon->base = strdup(daemon->base_user); 1101 if (!daemon->base) 1102 return -ENOMEM; 1103 } 1104 1105 if (daemon->config) { 1106 char *real = realpath(daemon->config, NULL); 1107 1108 if (!real) { 1109 perror("failed: realpath"); 1110 return -1; 1111 } 1112 daemon->config_real = real; 1113 return 0; 1114 } 1115 1116 if (perf_config_system() && !access(perf_etc_perfconfig(), R_OK)) 1117 daemon->config_real = strdup(perf_etc_perfconfig()); 1118 else if (perf_config_global() && perf_home_perfconfig()) 1119 daemon->config_real = strdup(perf_home_perfconfig()); 1120 1121 return daemon->config_real ? 0 : -1; 1122 } 1123 1124 #ifndef F_TLOCK 1125 #define F_TLOCK 2 1126 1127 #include <sys/file.h> 1128 1129 static int lockf(int fd, int cmd, off_t len) 1130 { 1131 if (cmd != F_TLOCK || len != 0) 1132 return -1; 1133 1134 return flock(fd, LOCK_EX | LOCK_NB); 1135 } 1136 #endif // F_TLOCK 1137 1138 /* 1139 * Each daemon tries to create and lock BASE/lock file, 1140 * if it's successful we are sure we're the only daemon 1141 * running over the BASE. 1142 * 1143 * Once daemon is finished, file descriptor to lock file 1144 * is closed and lock is released. 1145 */ 1146 static int check_lock(struct daemon *daemon) 1147 { 1148 char path[PATH_MAX]; 1149 char buf[20]; 1150 int fd, pid; 1151 ssize_t len; 1152 1153 scnprintf(path, sizeof(path), "%s/lock", daemon->base); 1154 1155 fd = open(path, O_RDWR|O_CREAT|O_CLOEXEC, 0640); 1156 if (fd < 0) 1157 return -1; 1158 1159 if (lockf(fd, F_TLOCK, 0) < 0) { 1160 filename__read_int(path, &pid); 1161 fprintf(stderr, "failed: another perf daemon (pid %d) owns %s\n", 1162 pid, daemon->base); 1163 close(fd); 1164 return -1; 1165 } 1166 1167 scnprintf(buf, sizeof(buf), "%d", getpid()); 1168 len = strlen(buf); 1169 1170 if (write(fd, buf, len) != len) { 1171 perror("failed: write"); 1172 close(fd); 1173 return -1; 1174 } 1175 1176 if (ftruncate(fd, len)) { 1177 perror("failed: ftruncate"); 1178 close(fd); 1179 return -1; 1180 } 1181 1182 return 0; 1183 } 1184 1185 static int go_background(struct daemon *daemon) 1186 { 1187 int pid, fd; 1188 1189 pid = fork(); 1190 if (pid < 0) 1191 return -1; 1192 1193 if (pid > 0) 1194 return 1; 1195 1196 if (setsid() < 0) 1197 return -1; 1198 1199 if (check_lock(daemon)) 1200 return -1; 1201 1202 umask(0); 1203 1204 if (chdir(daemon->base)) { 1205 perror("failed: chdir"); 1206 return -1; 1207 } 1208 1209 fd = open("output", O_RDWR|O_CREAT|O_TRUNC, 0644); 1210 if (fd < 0) { 1211 perror("failed: open"); 1212 return -1; 1213 } 1214 1215 if (fcntl(fd, F_SETFD, FD_CLOEXEC)) { 1216 perror("failed: fcntl FD_CLOEXEC"); 1217 close(fd); 1218 return -1; 1219 } 1220 1221 close(0); 1222 dup2(fd, 1); 1223 dup2(fd, 2); 1224 close(fd); 1225 1226 daemon->out = fdopen(1, "w"); 1227 if (!daemon->out) { 1228 close(1); 1229 close(2); 1230 return -1; 1231 } 1232 1233 setbuf(daemon->out, NULL); 1234 return 0; 1235 } 1236 1237 static int setup_signalfd(struct daemon *daemon) 1238 { 1239 sigset_t mask; 1240 1241 sigemptyset(&mask); 1242 sigaddset(&mask, SIGCHLD); 1243 1244 if (sigprocmask(SIG_BLOCK, &mask, NULL) == -1) 1245 return -1; 1246 1247 daemon->signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC); 1248 return daemon->signal_fd; 1249 } 1250 1251 static int __cmd_start(struct daemon *daemon, struct option parent_options[], 1252 int argc, const char **argv) 1253 { 1254 bool foreground = false; 1255 struct option start_options[] = { 1256 OPT_BOOLEAN('f', "foreground", &foreground, "stay on console"), 1257 OPT_PARENT(parent_options), 1258 OPT_END() 1259 }; 1260 int sock_fd = -1, conf_fd = -1, signal_fd = -1; 1261 int sock_pos, file_pos, signal_pos; 1262 struct fdarray fda; 1263 int err = 0; 1264 1265 argc = parse_options(argc, argv, start_options, daemon_usage, 0); 1266 if (argc) 1267 usage_with_options(daemon_usage, start_options); 1268 1269 daemon->start = time(NULL); 1270 1271 if (setup_config(daemon)) { 1272 pr_err("failed: config not found\n"); 1273 return -1; 1274 } 1275 1276 if (setup_server_config(daemon)) 1277 return -1; 1278 1279 if (foreground && check_lock(daemon)) 1280 return -1; 1281 1282 if (!foreground) { 1283 err = go_background(daemon); 1284 if (err) { 1285 /* original process, exit normally */ 1286 if (err == 1) 1287 err = 0; 1288 daemon__exit(daemon); 1289 return err; 1290 } 1291 } 1292 1293 debug_set_file(daemon->out); 1294 debug_set_display_time(true); 1295 1296 pr_info("daemon started (pid %d)\n", getpid()); 1297 1298 fdarray__init(&fda, 3); 1299 1300 sock_fd = setup_server_socket(daemon); 1301 if (sock_fd < 0) 1302 goto out; 1303 1304 conf_fd = setup_config_changes(daemon); 1305 if (conf_fd < 0) 1306 goto out; 1307 1308 signal_fd = setup_signalfd(daemon); 1309 if (signal_fd < 0) 1310 goto out; 1311 1312 sock_pos = fdarray__add(&fda, sock_fd, POLLIN|POLLERR|POLLHUP, 0); 1313 if (sock_pos < 0) 1314 goto out; 1315 1316 file_pos = fdarray__add(&fda, conf_fd, POLLIN|POLLERR|POLLHUP, 0); 1317 if (file_pos < 0) 1318 goto out; 1319 1320 signal_pos = fdarray__add(&fda, signal_fd, POLLIN|POLLERR|POLLHUP, 0); 1321 if (signal_pos < 0) 1322 goto out; 1323 1324 signal(SIGINT, sig_handler); 1325 signal(SIGTERM, sig_handler); 1326 signal(SIGPIPE, SIG_IGN); 1327 1328 while (!done && !err) { 1329 err = daemon__reconfig(daemon); 1330 1331 if (!err && fdarray__poll(&fda, -1)) { 1332 bool reconfig = false; 1333 1334 if (fda.entries[sock_pos].revents & POLLIN) 1335 err = handle_server_socket(daemon, sock_fd); 1336 if (fda.entries[file_pos].revents & POLLIN) 1337 err = handle_config_changes(daemon, conf_fd, &reconfig); 1338 if (fda.entries[signal_pos].revents & POLLIN) 1339 err = handle_signalfd(daemon) < 0; 1340 1341 if (reconfig) 1342 err = setup_server_config(daemon); 1343 } 1344 } 1345 1346 out: 1347 fdarray__exit(&fda); 1348 1349 daemon__kill(daemon); 1350 daemon__exit(daemon); 1351 1352 if (sock_fd != -1) 1353 close(sock_fd); 1354 if (conf_fd != -1) 1355 close(conf_fd); 1356 if (signal_fd != -1) 1357 close(signal_fd); 1358 1359 pr_info("daemon exited\n"); 1360 fclose(daemon->out); 1361 return err; 1362 } 1363 1364 static int send_cmd(struct daemon *daemon, union cmd *cmd) 1365 { 1366 int ret = -1, fd; 1367 char *line = NULL; 1368 size_t len = 0; 1369 ssize_t nread; 1370 FILE *in = NULL; 1371 1372 if (setup_client_config(daemon)) 1373 return -1; 1374 1375 fd = setup_client_socket(daemon); 1376 if (fd < 0) 1377 return -1; 1378 1379 if (sizeof(*cmd) != writen(fd, cmd, sizeof(*cmd))) { 1380 perror("failed: write"); 1381 goto out; 1382 } 1383 1384 in = fdopen(fd, "r"); 1385 if (!in) { 1386 perror("failed: fdopen"); 1387 goto out; 1388 } 1389 1390 while ((nread = getline(&line, &len, in)) != -1) { 1391 if (fwrite(line, nread, 1, stdout) != 1) 1392 goto out_fclose; 1393 fflush(stdout); 1394 } 1395 1396 ret = 0; 1397 out_fclose: 1398 fclose(in); 1399 free(line); 1400 out: 1401 /* If in is defined, then fd is closed via fclose. */ 1402 if (!in) 1403 close(fd); 1404 return ret; 1405 } 1406 1407 static int send_cmd_list(struct daemon *daemon) 1408 { 1409 union cmd cmd = { .cmd = CMD_LIST, }; 1410 1411 cmd.list.verbose = verbose; 1412 cmd.list.csv_sep = daemon->csv_sep ? *daemon->csv_sep : 0; 1413 1414 return send_cmd(daemon, &cmd); 1415 } 1416 1417 static int __cmd_signal(struct daemon *daemon, struct option parent_options[], 1418 int argc, const char **argv) 1419 { 1420 const char *name = "all"; 1421 struct option start_options[] = { 1422 OPT_STRING(0, "session", &name, "session", 1423 "Sent signal to specific session"), 1424 OPT_PARENT(parent_options), 1425 OPT_END() 1426 }; 1427 union cmd cmd; 1428 1429 argc = parse_options(argc, argv, start_options, daemon_usage, 0); 1430 if (argc) 1431 usage_with_options(daemon_usage, start_options); 1432 1433 if (setup_config(daemon)) { 1434 pr_err("failed: config not found\n"); 1435 return -1; 1436 } 1437 1438 cmd.signal.cmd = CMD_SIGNAL, 1439 cmd.signal.sig = SIGUSR2; 1440 strncpy(cmd.signal.name, name, sizeof(cmd.signal.name) - 1); 1441 1442 return send_cmd(daemon, &cmd); 1443 } 1444 1445 static int __cmd_stop(struct daemon *daemon, struct option parent_options[], 1446 int argc, const char **argv) 1447 { 1448 struct option start_options[] = { 1449 OPT_PARENT(parent_options), 1450 OPT_END() 1451 }; 1452 union cmd cmd = { .cmd = CMD_STOP, }; 1453 1454 argc = parse_options(argc, argv, start_options, daemon_usage, 0); 1455 if (argc) 1456 usage_with_options(daemon_usage, start_options); 1457 1458 if (setup_config(daemon)) { 1459 pr_err("failed: config not found\n"); 1460 return -1; 1461 } 1462 1463 return send_cmd(daemon, &cmd); 1464 } 1465 1466 static int __cmd_ping(struct daemon *daemon, struct option parent_options[], 1467 int argc, const char **argv) 1468 { 1469 const char *name = "all"; 1470 struct option ping_options[] = { 1471 OPT_STRING(0, "session", &name, "session", 1472 "Ping to specific session"), 1473 OPT_PARENT(parent_options), 1474 OPT_END() 1475 }; 1476 union cmd cmd = { .cmd = CMD_PING, }; 1477 1478 argc = parse_options(argc, argv, ping_options, daemon_usage, 0); 1479 if (argc) 1480 usage_with_options(daemon_usage, ping_options); 1481 1482 if (setup_config(daemon)) { 1483 pr_err("failed: config not found\n"); 1484 return -1; 1485 } 1486 1487 scnprintf(cmd.ping.name, sizeof(cmd.ping.name), "%s", name); 1488 return send_cmd(daemon, &cmd); 1489 } 1490 1491 int cmd_daemon(int argc, const char **argv) 1492 { 1493 struct option daemon_options[] = { 1494 OPT_INCR('v', "verbose", &verbose, "be more verbose"), 1495 OPT_STRING(0, "config", &__daemon.config, 1496 "config file", "config file path"), 1497 OPT_STRING(0, "base", &__daemon.base_user, 1498 "directory", "base directory"), 1499 OPT_STRING_OPTARG('x', "field-separator", &__daemon.csv_sep, 1500 "field separator", "print counts with custom separator", ","), 1501 OPT_END() 1502 }; 1503 1504 perf_exe(__daemon.perf, sizeof(__daemon.perf)); 1505 __daemon.out = stdout; 1506 1507 argc = parse_options(argc, argv, daemon_options, daemon_usage, 1508 PARSE_OPT_STOP_AT_NON_OPTION); 1509 1510 if (argc) { 1511 if (!strcmp(argv[0], "start")) 1512 return __cmd_start(&__daemon, daemon_options, argc, argv); 1513 if (!strcmp(argv[0], "signal")) 1514 return __cmd_signal(&__daemon, daemon_options, argc, argv); 1515 else if (!strcmp(argv[0], "stop")) 1516 return __cmd_stop(&__daemon, daemon_options, argc, argv); 1517 else if (!strcmp(argv[0], "ping")) 1518 return __cmd_ping(&__daemon, daemon_options, argc, argv); 1519 1520 pr_err("failed: unknown command '%s'\n", argv[0]); 1521 return -1; 1522 } 1523 1524 if (setup_config(&__daemon)) { 1525 pr_err("failed: config not found\n"); 1526 return -1; 1527 } 1528 1529 return send_cmd_list(&__daemon); 1530 } 1531