initial import: starts and connects to ubus
[project/procd.git] / ubus.c
1 #include <stdlib.h>
2 #include <unistd.h>
3 #include <signal.h>
4
5 #include <libubus.h>
6
7 #include "procd.h"
8
9 char *ubus_socket = NULL;
10 static struct ubus_context *ctx;
11 static struct uloop_process ubus_proc;
12 static bool ubus_connected = false;
13
14 static void procd_ubus_connection_lost(struct ubus_context *old_ctx);
15
16 static void ubus_proc_cb(struct uloop_process *proc, int ret)
17 {
18         /* nothing to do here */
19 }
20
21 static void procd_restart_ubus(void)
22 {
23         char *argv[] = { "ubusd", NULL, ubus_socket, NULL };
24
25         if (ubus_proc.pending) {
26                 DPRINTF("Killing existing ubus instance, pid=%d\n", (int) ubus_proc.pid);
27                 kill(ubus_proc.pid, SIGKILL);
28                 uloop_process_delete(&ubus_proc);
29         }
30
31         if (ubus_socket)
32                 argv[1] = "-s";
33
34         ubus_proc.pid = fork();
35         if (!ubus_proc.pid) {
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 }
65
66 static void procd_ubus_connection_lost(struct ubus_context *old_ctx)
67 {
68         procd_ubus_try_connect();
69         while (!ubus_connected) {
70                 procd_restart_ubus();
71                 sleep(1);
72                 procd_ubus_try_connect();
73         }
74
75         DPRINTF("Connected to ubus, id=%08x\n", ctx->local_id);
76         ubus_add_uloop(ctx);
77 }
78
79 void procd_connect_ubus(void)
80 {
81         ubus_proc.cb = ubus_proc_cb;
82         procd_ubus_connection_lost(NULL);
83 }
84