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