procd: service gets deleted when its last instance is freed
[project/procd.git] / ubus.c
1 /*
2 * Copyright (C) 2013 Felix Fietkau <nbd@openwrt.org>
3 * Copyright (C) 2013 John Crispin <blogic@openwrt.org>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU Lesser General Public License version 2.1
7 * as published by the Free Software Foundation
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 */
14
15 #include <sys/resource.h>
16 #include <stdlib.h>
17 #include <unistd.h>
18 #include <signal.h>
19
20 #include "procd.h"
21
22 char *ubus_socket = NULL;
23 static struct ubus_context *ctx;
24 static struct uloop_timeout ubus_timer;
25 static int timeout;
26
27 static void reset_timeout(void)
28 {
29 timeout = 50;
30 }
31
32 static void timeout_retry(void)
33 {
34 uloop_timeout_set(&ubus_timer, timeout);
35 timeout *= 2;
36 if (timeout > 1000)
37 timeout = 1000;
38 }
39
40 static void
41 ubus_reconnect_cb(struct uloop_timeout *timeout)
42 {
43 if (!ubus_reconnect(ctx, ubus_socket)) {
44 ubus_add_uloop(ctx);
45 return;
46 }
47
48 timeout_retry();
49 }
50
51 static void
52 ubus_disconnect_cb(struct ubus_context *ctx)
53 {
54 ubus_timer.cb = ubus_reconnect_cb;
55 reset_timeout();
56 timeout_retry();
57 }
58
59 static void
60 ubus_connect_cb(struct uloop_timeout *timeout)
61 {
62 ctx = ubus_connect(ubus_socket);
63
64 if (!ctx) {
65 DEBUG(4, "Connection to ubus failed\n");
66 timeout_retry();
67 return;
68 }
69
70 ctx->connection_lost = ubus_disconnect_cb;
71 ubus_init_service(ctx);
72 ubus_init_system(ctx);
73 watch_ubus(ctx);
74
75 DEBUG(2, "Connected to ubus, id=%08x\n", ctx->local_id);
76 reset_timeout();
77 ubus_add_uloop(ctx);
78 procd_state_ubus_connect();
79 }
80
81 void
82 procd_connect_ubus(void)
83 {
84 ubus_timer.cb = ubus_connect_cb;
85 reset_timeout();
86 timeout_retry();
87 }