add new main.c and fix Makefile/headers
[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 ERROR("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 ERROR("Failed to start new ubus instance\n");
42 return;
43 }
44
45 LOG("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 DEBUG(2, "Connection to ubus failed\n");
59 return;
60 }
61
62 ctx->connection_lost = procd_ubus_connection_lost;
63 ubus_connected = true;
64 ubus_init_service(ctx);
65 if (getpid() == 1) {
66 ubus_init_log(ctx);
67 ubus_init_system(ctx);
68 }
69 }
70
71 static void procd_ubus_connection_lost(struct ubus_context *old_ctx)
72 {
73 procd_ubus_try_connect();
74 while (!ubus_connected) {
75 procd_restart_ubus();
76 sleep(1);
77 procd_ubus_try_connect();
78 }
79
80 LOG("Connected to ubus, id=%08x\n", ctx->local_id);
81 ubus_add_uloop(ctx);
82 }
83
84 void procd_connect_ubus(void)
85 {
86 ubus_proc.cb = ubus_proc_cb;
87 procd_ubus_connection_lost(NULL);
88 }
89