raise ubusd priority to speed up message processing under load
[project/procd.git] / ubus.c
1 #include <sys/resource.h>
2 #include <stdlib.h>
3 #include <unistd.h>
4 #include <signal.h>
5
6 #include "procd.h"
7
8 char *ubus_socket = NULL;
9 static struct ubus_context *ctx;
10 static struct uloop_process ubus_proc;
11 static bool ubus_connected = false;
12
13 static void procd_ubus_connection_lost(struct ubus_context *old_ctx);
14
15 static void ubus_proc_cb(struct uloop_process *proc, int ret)
16 {
17         /* nothing to do here */
18 }
19
20 static void procd_restart_ubus(void)
21 {
22         char *argv[] = { "ubusd", NULL, ubus_socket, NULL };
23
24         if (ubus_proc.pending) {
25                 DPRINTF("Killing existing ubus instance, pid=%d\n", (int) ubus_proc.pid);
26                 kill(ubus_proc.pid, SIGKILL);
27                 uloop_process_delete(&ubus_proc);
28         }
29
30         if (ubus_socket)
31                 argv[1] = "-s";
32
33         ubus_proc.pid = fork();
34         if (!ubus_proc.pid) {
35                 setpriority(PRIO_PROCESS, 0, -20);
36                 execvp(argv[0], argv);
37                 exit(-1);
38         }
39
40         if (ubus_proc.pid <= 0) {
41                 DPRINTF("Failed to start new ubus instance\n");
42                 return;
43         }
44
45         DPRINTF("Launched new ubus instance, pid=%d\n", (int) ubus_proc.pid);
46         uloop_process_add(&ubus_proc);
47 }
48
49 static void procd_ubus_try_connect(void)
50 {
51         if (ctx) {
52                 ubus_connected = !ubus_reconnect(ctx, ubus_socket);
53                 return;
54         }
55
56         ctx = ubus_connect(ubus_socket);
57         if (!ctx) {
58                 DPRINTF("Connection to ubus failed\n");
59                 return;
60         }
61
62         ctx->connection_lost = procd_ubus_connection_lost;
63         ubus_connected = true;
64         procd_init_service(ctx);
65 }
66
67 static void procd_ubus_connection_lost(struct ubus_context *old_ctx)
68 {
69         procd_ubus_try_connect();
70         while (!ubus_connected) {
71                 procd_restart_ubus();
72                 sleep(1);
73                 procd_ubus_try_connect();
74         }
75
76         DPRINTF("Connected to ubus, id=%08x\n", ctx->local_id);
77         ubus_add_uloop(ctx);
78 }
79
80 void procd_connect_ubus(void)
81 {
82         ubus_proc.cb = ubus_proc_cb;
83         procd_ubus_connection_lost(NULL);
84 }
85