perf daemon: Add config file support
[linux-2.6-microblaze.git] / tools / perf / builtin-daemon.c
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 <linux/zalloc.h>
6 #include <linux/string.h>
7 #include <linux/limits.h>
8 #include <linux/string.h>
9 #include <string.h>
10 #include <signal.h>
11 #include <stdlib.h>
12 #include <stdio.h>
13 #include <unistd.h>
14 #include <errno.h>
15 #include <sys/types.h>
16 #include <sys/socket.h>
17 #include <sys/un.h>
18 #include <sys/stat.h>
19 #include <poll.h>
20 #include <sys/stat.h>
21 #include "builtin.h"
22 #include "perf.h"
23 #include "debug.h"
24 #include "config.h"
25 #include "util.h"
26
27 #define SESSION_OUTPUT  "output"
28
29 /*
30  * Session states:
31  *
32  *   OK       - session is up and running
33  *   RECONFIG - session is pending for reconfiguration,
34  *              new values are already loaded in session object
35  *   KILL     - session is pending to be killed
36  *
37  * Session object life and its state is maintained by
38  * following functions:
39  *
40  *  setup_server_config
41  *    - reads config file and setup session objects
42  *      with following states:
43  *
44  *      OK       - no change needed
45  *      RECONFIG - session needs to be changed
46  *                 (run variable changed)
47  *      KILL     - session needs to be killed
48  *                 (session is no longer in config file)
49  *
50  *  daemon__reconfig
51  *    - scans session objects and does following actions
52  *      for states:
53  *
54  *      OK       - skip
55  *      RECONFIG - session is killed and re-run with new config
56  *      KILL     - session is killed
57  *
58  *    - all sessions have OK state on the function exit
59  */
60 enum daemon_session_state {
61         OK,
62         RECONFIG,
63         KILL,
64 };
65
66 struct daemon_session {
67         char                            *base;
68         char                            *name;
69         char                            *run;
70         int                              pid;
71         struct list_head                 list;
72         enum daemon_session_state        state;
73 };
74
75 struct daemon {
76         const char              *config;
77         char                    *config_real;
78         const char              *base_user;
79         char                    *base;
80         struct list_head         sessions;
81         FILE                    *out;
82         char                     perf[PATH_MAX];
83 };
84
85 static struct daemon __daemon = {
86         .sessions = LIST_HEAD_INIT(__daemon.sessions),
87 };
88
89 static const char * const daemon_usage[] = {
90         "perf daemon start [<options>]",
91         "perf daemon [<options>]",
92         NULL
93 };
94
95 static bool done;
96
97 static void sig_handler(int sig __maybe_unused)
98 {
99         done = true;
100 }
101
102 static struct daemon_session *daemon__add_session(struct daemon *config, char *name)
103 {
104         struct daemon_session *session = zalloc(sizeof(*session));
105
106         if (!session)
107                 return NULL;
108
109         session->name = strdup(name);
110         if (!session->name) {
111                 free(session);
112                 return NULL;
113         }
114
115         session->pid = -1;
116         list_add_tail(&session->list, &config->sessions);
117         return session;
118 }
119
120 static struct daemon_session *daemon__find_session(struct daemon *daemon, char *name)
121 {
122         struct daemon_session *session;
123
124         list_for_each_entry(session, &daemon->sessions, list) {
125                 if (!strcmp(session->name, name))
126                         return session;
127         }
128
129         return NULL;
130 }
131
132 static int get_session_name(const char *var, char *session, int len)
133 {
134         const char *p = var + sizeof("session-") - 1;
135
136         while (*p != '.' && *p != 0x0 && len--)
137                 *session++ = *p++;
138
139         *session = 0;
140         return *p == '.' ? 0 : -EINVAL;
141 }
142
143 static int session_config(struct daemon *daemon, const char *var, const char *value)
144 {
145         struct daemon_session *session;
146         char name[100];
147
148         if (get_session_name(var, name, sizeof(name)))
149                 return -EINVAL;
150
151         var = strchr(var, '.');
152         if (!var)
153                 return -EINVAL;
154
155         var++;
156
157         session = daemon__find_session(daemon, name);
158
159         if (!session) {
160                 /* New session is defined. */
161                 session = daemon__add_session(daemon, name);
162                 if (!session)
163                         return -ENOMEM;
164
165                 pr_debug("reconfig: found new session %s\n", name);
166
167                 /* Trigger reconfig to start it. */
168                 session->state = RECONFIG;
169         } else if (session->state == KILL) {
170                 /* Current session is defined, no action needed. */
171                 pr_debug("reconfig: found current session %s\n", name);
172                 session->state = OK;
173         }
174
175         if (!strcmp(var, "run")) {
176                 bool same = false;
177
178                 if (session->run)
179                         same = !strcmp(session->run, value);
180
181                 if (!same) {
182                         if (session->run) {
183                                 free(session->run);
184                                 pr_debug("reconfig: session %s is changed\n", name);
185                         }
186
187                         session->run = strdup(value);
188                         if (!session->run)
189                                 return -ENOMEM;
190
191                         /*
192                          * Either new or changed run value is defined,
193                          * trigger reconfig for the session.
194                          */
195                         session->state = RECONFIG;
196                 }
197         }
198
199         return 0;
200 }
201
202 static int server_config(const char *var, const char *value, void *cb)
203 {
204         struct daemon *daemon = cb;
205
206         if (strstarts(var, "session-")) {
207                 return session_config(daemon, var, value);
208         } else if (!strcmp(var, "daemon.base") && !daemon->base_user) {
209                 if (daemon->base && strcmp(daemon->base, value)) {
210                         pr_err("failed: can't redefine base, bailing out\n");
211                         return -EINVAL;
212                 }
213                 daemon->base = strdup(value);
214                 if (!daemon->base)
215                         return -ENOMEM;
216         }
217
218         return 0;
219 }
220
221 static int client_config(const char *var, const char *value, void *cb)
222 {
223         struct daemon *daemon = cb;
224
225         if (!strcmp(var, "daemon.base") && !daemon->base_user) {
226                 daemon->base = strdup(value);
227                 if (!daemon->base)
228                         return -ENOMEM;
229         }
230
231         return 0;
232 }
233
234 static int check_base(struct daemon *daemon)
235 {
236         struct stat st;
237
238         if (!daemon->base) {
239                 pr_err("failed: base not defined\n");
240                 return -EINVAL;
241         }
242
243         if (stat(daemon->base, &st)) {
244                 switch (errno) {
245                 case EACCES:
246                         pr_err("failed: permission denied for '%s' base\n",
247                                daemon->base);
248                         return -EACCES;
249                 case ENOENT:
250                         pr_err("failed: base '%s' does not exists\n",
251                                daemon->base);
252                         return -EACCES;
253                 default:
254                         pr_err("failed: can't access base '%s': %s\n",
255                                daemon->base, strerror(errno));
256                         return -errno;
257                 }
258         }
259
260         if ((st.st_mode & S_IFMT) != S_IFDIR) {
261                 pr_err("failed: base '%s' is not directory\n",
262                        daemon->base);
263                 return -EINVAL;
264         }
265
266         return 0;
267 }
268
269 static int setup_client_config(struct daemon *daemon)
270 {
271         struct perf_config_set *set = perf_config_set__load_file(daemon->config_real);
272         int err = -ENOMEM;
273
274         if (set) {
275                 err = perf_config_set(set, client_config, daemon);
276                 perf_config_set__delete(set);
277         }
278
279         return err ?: check_base(daemon);
280 }
281
282 static int setup_server_config(struct daemon *daemon)
283 {
284         struct perf_config_set *set;
285         struct daemon_session *session;
286         int err = -ENOMEM;
287
288         pr_debug("reconfig: started\n");
289
290         /*
291          * Mark all sessions for kill, the server config
292          * will set following states, see explanation at
293          * enum daemon_session_state declaration.
294          */
295         list_for_each_entry(session, &daemon->sessions, list)
296                 session->state = KILL;
297
298         set = perf_config_set__load_file(daemon->config_real);
299         if (set) {
300                 err = perf_config_set(set, server_config, daemon);
301                 perf_config_set__delete(set);
302         }
303
304         return err ?: check_base(daemon);
305 }
306
307 static int daemon_session__run(struct daemon_session *session,
308                                struct daemon *daemon)
309 {
310         char buf[PATH_MAX];
311         char **argv;
312         int argc, fd;
313
314         if (asprintf(&session->base, "%s/session-%s",
315                      daemon->base, session->name) < 0) {
316                 perror("failed: asprintf");
317                 return -1;
318         }
319
320         if (mkdir(session->base, 0755) && errno != EEXIST) {
321                 perror("failed: mkdir");
322                 return -1;
323         }
324
325         session->pid = fork();
326         if (session->pid < 0)
327                 return -1;
328         if (session->pid > 0) {
329                 pr_info("reconfig: ruining session [%s:%d]: %s\n",
330                         session->name, session->pid, session->run);
331                 return 0;
332         }
333
334         if (chdir(session->base)) {
335                 perror("failed: chdir");
336                 return -1;
337         }
338
339         fd = open("/dev/null", O_RDONLY);
340         if (fd < 0) {
341                 perror("failed: open /dev/null");
342                 return -1;
343         }
344
345         dup2(fd, 0);
346         close(fd);
347
348         fd = open(SESSION_OUTPUT, O_RDWR|O_CREAT|O_TRUNC, 0644);
349         if (fd < 0) {
350                 perror("failed: open session output");
351                 return -1;
352         }
353
354         dup2(fd, 1);
355         dup2(fd, 2);
356         close(fd);
357
358         scnprintf(buf, sizeof(buf), "%s record %s", daemon->perf, session->run);
359
360         argv = argv_split(buf, &argc);
361         if (!argv)
362                 exit(-1);
363
364         exit(execve(daemon->perf, argv, NULL));
365         return -1;
366 }
367
368 static int setup_server_socket(struct daemon *daemon)
369 {
370         struct sockaddr_un addr;
371         char path[PATH_MAX];
372         int fd = socket(AF_UNIX, SOCK_STREAM, 0);
373
374         if (fd < 0) {
375                 fprintf(stderr, "socket: %s\n", strerror(errno));
376                 return -1;
377         }
378
379         if (fcntl(fd, F_SETFD, FD_CLOEXEC)) {
380                 perror("failed: fcntl FD_CLOEXEC");
381                 close(fd);
382                 return -1;
383         }
384
385         scnprintf(path, sizeof(path), "%s/control", daemon->base);
386
387         if (strlen(path) + 1 >= sizeof(addr.sun_path)) {
388                 pr_err("failed: control path too long '%s'\n", path);
389                 close(fd);
390                 return -1;
391         }
392
393         memset(&addr, 0, sizeof(addr));
394         addr.sun_family = AF_UNIX;
395
396         strlcpy(addr.sun_path, path, sizeof(addr.sun_path) - 1);
397         unlink(path);
398
399         if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
400                 perror("failed: bind");
401                 close(fd);
402                 return -1;
403         }
404
405         if (listen(fd, 1) == -1) {
406                 perror("failed: listen");
407                 close(fd);
408                 return -1;
409         }
410
411         return fd;
412 }
413
414 union cmd {
415         int cmd;
416 };
417
418 static int handle_server_socket(struct daemon *daemon __maybe_unused, int sock_fd)
419 {
420         int ret = -1, fd;
421         FILE *out = NULL;
422         union cmd cmd;
423
424         fd = accept(sock_fd, NULL, NULL);
425         if (fd < 0) {
426                 perror("failed: accept");
427                 return -1;
428         }
429
430         if (sizeof(cmd) != readn(fd, &cmd, sizeof(cmd))) {
431                 perror("failed: read");
432                 goto out;
433         }
434
435         out = fdopen(fd, "w");
436         if (!out) {
437                 perror("failed: fdopen");
438                 goto out;
439         }
440
441         switch (cmd.cmd) {
442         default:
443                 break;
444         }
445
446         fclose(out);
447 out:
448         /* If out is defined, then fd is closed via fclose. */
449         if (!out)
450                 close(fd);
451         return ret;
452 }
453
454 static int setup_client_socket(struct daemon *daemon)
455 {
456         struct sockaddr_un addr;
457         char path[PATH_MAX];
458         int fd = socket(AF_UNIX, SOCK_STREAM, 0);
459
460         if (fd == -1) {
461                 perror("failed: socket");
462                 return -1;
463         }
464
465         scnprintf(path, sizeof(path), "%s/control", daemon->base);
466
467         if (strlen(path) + 1 >= sizeof(addr.sun_path)) {
468                 pr_err("failed: control path too long '%s'\n", path);
469                 close(fd);
470                 return -1;
471         }
472
473         memset(&addr, 0, sizeof(addr));
474         addr.sun_family = AF_UNIX;
475         strlcpy(addr.sun_path, path, sizeof(addr.sun_path) - 1);
476
477         if (connect(fd, (struct sockaddr *) &addr, sizeof(addr)) == -1) {
478                 perror("failed: connect");
479                 close(fd);
480                 return -1;
481         }
482
483         return fd;
484 }
485
486 static int daemon_session__signal(struct daemon_session *session, int sig)
487 {
488         if (session->pid < 0)
489                 return -1;
490         return kill(session->pid, sig);
491 }
492
493 static void daemon_session__kill(struct daemon_session *session)
494 {
495         daemon_session__signal(session, SIGTERM);
496 }
497
498 static void daemon__signal(struct daemon *daemon, int sig)
499 {
500         struct daemon_session *session;
501
502         list_for_each_entry(session, &daemon->sessions, list)
503                 daemon_session__signal(session, sig);
504 }
505
506 static void daemon_session__delete(struct daemon_session *session)
507 {
508         free(session->base);
509         free(session->name);
510         free(session->run);
511         free(session);
512 }
513
514 static void daemon_session__remove(struct daemon_session *session)
515 {
516         list_del(&session->list);
517         daemon_session__delete(session);
518 }
519
520 static void daemon__kill(struct daemon *daemon)
521 {
522         daemon__signal(daemon, SIGTERM);
523 }
524
525 static void daemon__exit(struct daemon *daemon)
526 {
527         struct daemon_session *session, *h;
528
529         list_for_each_entry_safe(session, h, &daemon->sessions, list)
530                 daemon_session__remove(session);
531
532         free(daemon->config_real);
533         free(daemon->base);
534 }
535
536 static int daemon__reconfig(struct daemon *daemon)
537 {
538         struct daemon_session *session, *n;
539
540         list_for_each_entry_safe(session, n, &daemon->sessions, list) {
541                 /* No change. */
542                 if (session->state == OK)
543                         continue;
544
545                 /* Remove session. */
546                 if (session->state == KILL) {
547                         if (session->pid > 0) {
548                                 daemon_session__kill(session);
549                                 pr_info("reconfig: session '%s' killed\n", session->name);
550                         }
551                         daemon_session__remove(session);
552                         continue;
553                 }
554
555                 /* Reconfig session. */
556                 if (session->pid > 0) {
557                         daemon_session__kill(session);
558                         pr_info("reconfig: session '%s' killed\n", session->name);
559                 }
560                 if (daemon_session__run(session, daemon))
561                         return -1;
562
563                 session->state = OK;
564         }
565
566         return 0;
567 }
568
569 static int setup_config(struct daemon *daemon)
570 {
571         if (daemon->base_user) {
572                 daemon->base = strdup(daemon->base_user);
573                 if (!daemon->base)
574                         return -ENOMEM;
575         }
576
577         if (daemon->config) {
578                 char *real = realpath(daemon->config, NULL);
579
580                 if (!real) {
581                         perror("failed: realpath");
582                         return -1;
583                 }
584                 daemon->config_real = real;
585                 return 0;
586         }
587
588         if (perf_config_system() && !access(perf_etc_perfconfig(), R_OK))
589                 daemon->config_real = strdup(perf_etc_perfconfig());
590         else if (perf_config_global() && perf_home_perfconfig())
591                 daemon->config_real = strdup(perf_home_perfconfig());
592
593         return daemon->config_real ? 0 : -1;
594 }
595
596 static int __cmd_start(struct daemon *daemon, struct option parent_options[],
597                        int argc, const char **argv)
598 {
599         struct option start_options[] = {
600                 OPT_PARENT(parent_options),
601                 OPT_END()
602         };
603         int sock_fd = -1;
604         int sock_pos;
605         struct fdarray fda;
606         int err = 0;
607
608         argc = parse_options(argc, argv, start_options, daemon_usage, 0);
609         if (argc)
610                 usage_with_options(daemon_usage, start_options);
611
612         if (setup_config(daemon)) {
613                 pr_err("failed: config not found\n");
614                 return -1;
615         }
616
617         if (setup_server_config(daemon))
618                 return -1;
619
620         debug_set_file(daemon->out);
621         debug_set_display_time(true);
622
623         pr_info("daemon started (pid %d)\n", getpid());
624
625         fdarray__init(&fda, 1);
626
627         sock_fd = setup_server_socket(daemon);
628         if (sock_fd < 0)
629                 goto out;
630
631         sock_pos = fdarray__add(&fda, sock_fd, POLLIN|POLLERR|POLLHUP, 0);
632         if (sock_pos < 0)
633                 goto out;
634
635         signal(SIGINT, sig_handler);
636         signal(SIGTERM, sig_handler);
637
638         while (!done && !err) {
639                 err = daemon__reconfig(daemon);
640
641                 if (!err && fdarray__poll(&fda, -1)) {
642                         bool reconfig = false;
643
644                         if (fda.entries[sock_pos].revents & POLLIN)
645                                 err = handle_server_socket(daemon, sock_fd);
646
647                         if (reconfig)
648                                 err = setup_server_config(daemon);
649                 }
650         }
651
652 out:
653         fdarray__exit(&fda);
654
655         daemon__kill(daemon);
656         daemon__exit(daemon);
657
658         if (sock_fd != -1)
659                 close(sock_fd);
660
661         pr_info("daemon exited\n");
662         fclose(daemon->out);
663         return err;
664 }
665
666 __maybe_unused
667 static int send_cmd(struct daemon *daemon, union cmd *cmd)
668 {
669         int ret = -1, fd;
670         char *line = NULL;
671         size_t len = 0;
672         ssize_t nread;
673         FILE *in = NULL;
674
675         if (setup_client_config(daemon))
676                 return -1;
677
678         fd = setup_client_socket(daemon);
679         if (fd < 0)
680                 return -1;
681
682         if (sizeof(*cmd) != writen(fd, cmd, sizeof(*cmd))) {
683                 perror("failed: write");
684                 goto out;
685         }
686
687         in = fdopen(fd, "r");
688         if (!in) {
689                 perror("failed: fdopen");
690                 goto out;
691         }
692
693         while ((nread = getline(&line, &len, in)) != -1) {
694                 if (fwrite(line, nread, 1, stdout) != 1)
695                         goto out_fclose;
696                 fflush(stdout);
697         }
698
699         ret = 0;
700 out_fclose:
701         fclose(in);
702         free(line);
703 out:
704         /* If in is defined, then fd is closed via fclose. */
705         if (!in)
706                 close(fd);
707         return ret;
708 }
709
710 int cmd_daemon(int argc, const char **argv)
711 {
712         struct option daemon_options[] = {
713                 OPT_INCR('v', "verbose", &verbose, "be more verbose"),
714                 OPT_STRING(0, "config", &__daemon.config,
715                         "config file", "config file path"),
716                 OPT_STRING(0, "base", &__daemon.base_user,
717                         "directory", "base directory"),
718                 OPT_END()
719         };
720
721         perf_exe(__daemon.perf, sizeof(__daemon.perf));
722         __daemon.out = stdout;
723
724         argc = parse_options(argc, argv, daemon_options, daemon_usage,
725                              PARSE_OPT_STOP_AT_NON_OPTION);
726
727         if (argc) {
728                 if (!strcmp(argv[0], "start"))
729                         return __cmd_start(&__daemon, daemon_options, argc, argv);
730
731                 pr_err("failed: unknown command '%s'\n", argv[0]);
732                 return -1;
733         }
734
735         if (setup_config(&__daemon)) {
736                 pr_err("failed: config not found\n");
737                 return -1;
738         }
739
740         return -1;
741 }