afb-supervision: Fix error on 'trace'
[src/app-framework-binder.git] / src / afb-supervision.c
1 /*
2  * Copyright (C) 2016, 2017 "IoT.bzh"
3  * Author José Bollo <jose.bollo@iot.bzh>
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *   http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 #define _GNU_SOURCE
19 #define AFB_BINDING_PRAGMA_NO_VERBOSE_MACRO
20
21 #include <string.h>
22 #include <errno.h>
23 #include <signal.h>
24 #include <unistd.h>
25 #include <fcntl.h>
26 #include <pthread.h>
27 #include <sys/types.h>
28 #include <sys/socket.h>
29 #include <sys/un.h>
30
31 #include <json-c/json.h>
32 #include <afb/afb-binding-v2.h>
33
34 #include "afb-cred.h"
35 #include "afb-api.h"
36 #include "afb-apiset.h"
37 #include "afb-api-so-v2.h"
38 #include "afb-xreq.h"
39 #include "afb-trace.h"
40 #include "afb-session.h"
41 #include "afb-config.h"
42 #include "afb-supervision.h"
43 #include "afs-supervision.h"
44 #include "afb-stub-ws.h"
45 #include "afb-debug.h"
46 #include "afb-fdev.h"
47 #include "verbose.h"
48 #include "wrap-json.h"
49 #include "jobs.h"
50
51 extern struct afb_config *main_config;
52
53 /* api and apiset name */
54 static const char supervision_apiname[] = AFS_SURPERVISION_APINAME_INTERNAL;
55
56 /* path of the supervision socket */
57 static const char supervisor_socket_path[] = AFS_SURPERVISION_SOCKET;
58
59 /* mutual exclusion */
60 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
61
62 /* the standard apiset */
63 extern struct afb_apiset *main_apiset;
64
65 /* the supervision apiset (not exported) */
66 static struct afb_apiset *supervision_apiset;
67
68 /* local api implementation */
69 static void on_supervision_call(void *closure, struct afb_xreq *xreq);
70 static struct afb_api_itf supervision_api_itf =
71 {
72         .call = on_supervision_call
73 };
74
75 /* the supervisor link */
76 static struct afb_stub_ws *supervisor;
77
78 /* the trace api */
79 static struct afb_trace *trace;
80
81 /* open the socket */
82 static int open_supervisor_socket(const char *path)
83 {
84         int fd, rc;
85         struct sockaddr_un addr;
86         size_t length;
87
88         /* check path length */
89         length = strlen(path);
90         if (length >= 108) {
91                 errno = ENAMETOOLONG;
92                 return -1;
93         }
94
95         /* create the unix socket */
96         fd = socket(AF_UNIX, SOCK_STREAM, 0);
97         if (fd < 0)
98                 return fd;
99
100         /* prepare the connection address */
101         memset(&addr, 0, sizeof addr);
102         addr.sun_family = AF_UNIX;
103         strcpy(addr.sun_path, path);
104         if (addr.sun_path[0] == '@')
105                 addr.sun_path[0] = 0; /* implement abstract sockets */
106
107         /* connect the socket */
108         rc = connect(fd, (struct sockaddr *) &addr, (socklen_t)(sizeof addr));
109         if (rc < 0) {
110                 close(fd);
111                 return rc;
112         }
113         return fd;
114 }
115
116 static void disconnect_supervisor()
117 {
118         struct afb_stub_ws *s;
119         struct afb_trace *t;
120
121         INFO("Disconnecting supervision");
122         s = __atomic_exchange_n(&supervisor, NULL, __ATOMIC_RELAXED);
123         t = __atomic_exchange_n(&trace, NULL, __ATOMIC_RELAXED);
124         if (s)
125                 afb_stub_ws_unref(s);
126         if (t)
127                 afb_trace_unref(t);
128 }
129
130 static void on_supervisor_hangup(struct afb_stub_ws *s)
131 {
132         if (s && s == supervisor)
133                 disconnect_supervisor();
134 }
135
136 /* try to connect to supervisor */
137 static void try_connect_supervisor()
138 {
139         int fd;
140         ssize_t srd;
141         struct afs_supervision_initiator initiator;
142         struct fdev *fdev;
143
144         /* get the mutex */
145         pthread_mutex_lock(&mutex);
146
147         /* needs to connect? */
148         if (supervisor || !supervision_apiset)
149                 goto end;
150
151         /* check existing path */
152         if (supervisor_socket_path[0] != '@' && access(supervisor_socket_path, F_OK)) {
153                 NOTICE("Can't acces socket path %s: %m", supervisor_socket_path);
154                 goto end;
155         }
156
157         /* socket connection */
158         fd = open_supervisor_socket(supervisor_socket_path);
159         if (fd < 0) {
160                 NOTICE("Can't connect supervision socket to %s: %m", supervisor_socket_path);
161                 goto end;
162         }
163
164         /* negociation */
165         do { srd = read(fd, &initiator, sizeof initiator); } while(srd < 0 && errno == EINTR);
166         if (srd < 0) {
167                 NOTICE("Can't read supervisor %s: %m", supervisor_socket_path);
168                 goto end2;
169         }
170         if ((size_t)srd != sizeof initiator) {
171                 ERROR("When reading supervisor %s: %m", supervisor_socket_path);
172                 goto end2;
173         }
174         if (strnlen(initiator.interface, sizeof initiator.interface) == sizeof initiator.interface) {
175                 ERROR("Bad interface of supervisor %s", supervisor_socket_path);
176                 goto end2;
177         }
178         if (strcmp(initiator.interface, AFS_SURPERVISION_INTERFACE_1)) {
179                 ERROR("Unknown interface %s for supervisor %s", initiator.interface, supervisor_socket_path);
180                 goto end2;
181         }
182         if (strnlen(initiator.extra, sizeof initiator.extra) == sizeof initiator.extra) {
183                 ERROR("Bad extra of supervisor %s", supervisor_socket_path);
184                 goto end2;
185         }
186
187         /* interprets extras */
188         if (!strcmp(initiator.extra, "CLOSE")) {
189                 INFO("Supervisor asks to CLOSE");
190                 goto end2;
191         }
192         if (!strcmp(initiator.extra, "WAIT")) {
193                 afb_debug_wait("supervisor");
194         }
195         if (!strcmp(initiator.extra, "BREAK")) {
196                 afb_debug_break("supervisor");
197         }
198
199         /* make the supervisor link */
200         fdev = afb_fdev_create(fd);
201         if (!fdev) {
202                 ERROR("Creation of fdev failed: %m");
203                 goto end2;
204         }
205         supervisor = afb_stub_ws_create_server(fdev, supervision_apiname, supervision_apiset);
206         if (!supervisor) {
207                 ERROR("Creation of supervisor failed: %m");
208                 goto end;
209         }
210         afb_stub_ws_on_hangup(supervisor, on_supervisor_hangup);
211
212         /* successful termination */
213         goto end;
214
215 end2:
216         close(fd);
217 end:
218         pthread_mutex_unlock(&mutex);
219 }
220
221 static void try_connect_supervisor_job(int signum, void *args)
222 {
223         INFO("Try to connect supervisor after SIGHUP");
224         try_connect_supervisor();
225 }
226
227 static void on_sighup(int signum)
228 {
229         INFO("Supervision received a SIGHUP");
230         jobs_queue(NULL, 0, try_connect_supervisor_job, NULL);
231 }
232
233 /**
234  * initalize the supervision
235  */
236 int afb_supervision_init()
237 {
238         int rc;
239         struct sigaction sa;
240
241         /* don't reinit */
242         if (supervision_apiset)
243                 return 0;
244
245         /* create the apiset */
246         supervision_apiset = afb_apiset_create(supervision_apiname, 0);
247         if (!supervision_apiset) {
248                 ERROR("Can't create supervision's apiset");
249                 return -1;
250         }
251
252         /* init the apiset */
253         rc = afb_apiset_add(supervision_apiset, supervision_apiname,
254                         (struct afb_api){ .itf = &supervision_api_itf, .closure = NULL});
255         if (rc < 0) {
256                 ERROR("Can't create supervision's apiset: %m");
257                 afb_apiset_unref(supervision_apiset);
258                 supervision_apiset = NULL;
259                 return rc;
260         }
261
262         /* get SIGHUP */
263         memset(&sa, 0, sizeof sa);
264         sa.sa_handler = on_sighup;
265         rc = sigaction(SIGHUP, &sa, NULL);
266         if (rc < 0)
267                 ERROR("Can't connect supervision to SIGHUP: %m");
268
269         /* connect to supervision */
270         try_connect_supervisor();
271         return 0;
272 }
273
274 /******************************************************************************
275 **** Implementation monitoring verbs
276 ******************************************************************************/
277 static void slist(void *closure, struct afb_session *session)
278 {
279         struct json_object *list = closure;
280         struct json_object *item;
281
282         wrap_json_pack(&item, "{ss}", "token", afb_session_token(session));
283         json_object_object_add(list, afb_session_uuid(session), item);
284 }
285
286 /******************************************************************************
287 **** Implementation monitoring verbs
288 ******************************************************************************/
289
290 static const char *verbs[] = {
291         "break", "config", "do", "exit", "sclose", "slist", "trace", "wait" };
292 enum  {  Break ,  Config ,  Do ,  Exit ,  Sclose ,  Slist ,  Trace ,  Wait  };
293
294 static void on_supervision_call(void *closure, struct afb_xreq *xreq)
295 {
296         int i, rc;
297         struct json_object *args, *drop, *add, *sub, *list;
298         const char *api, *verb, *uuid;
299         struct afb_session *session;
300         const struct afb_api *xapi;
301         struct afb_req req;
302
303         /* search the verb */
304         i = (int)(sizeof verbs / sizeof *verbs);
305         while(--i >= 0 && strcasecmp(verbs[i], xreq->request.verb));
306         if (i < 0) {
307                 afb_xreq_fail_unknown_verb(xreq);
308                 return;
309         }
310
311         /* process */
312         args = afb_xreq_json(xreq);
313         switch(i) {
314         case Exit:
315                 i = 0;
316                 if (wrap_json_unpack(args, "i", &i))
317                         wrap_json_unpack(args, "{si}", "code", &i);
318                 ERROR("existing from supervision with code %d -> %d", i, i & 127);
319                 exit(i & 127);
320                 break;
321         case Sclose:
322                 uuid = NULL;
323                 if (wrap_json_unpack(args, "s", &uuid))
324                         wrap_json_unpack(args, "{ss}", "uuid", &uuid);
325                 if (!uuid)
326                         afb_xreq_fail(xreq, "invalid", NULL);
327                 else {
328                         session = afb_session_search(uuid);
329                         if (!session)
330                                 afb_xreq_fail(xreq, "not-found", NULL);
331                         else {
332                                 afb_session_close(session);
333                                 afb_session_unref(session);
334                                 afb_session_purge();
335                                 afb_xreq_success(xreq, NULL, NULL);
336                         }
337                 }
338                 break;
339         case Slist:
340                 list = json_object_new_object();
341                 afb_session_foreach(slist, list);
342                 afb_xreq_success(xreq, list, NULL);
343                 break;
344         case Config:
345                 afb_xreq_success(xreq, afb_config_json(main_config), NULL);
346                 break;
347         case Trace:
348                 if (!trace)
349                         trace = afb_trace_create(supervision_apiname, NULL /* not bound to any session */);
350
351                 req = xreq_to_req(xreq);
352                 add = drop = NULL;
353                 wrap_json_unpack(args, "{s?o s?o}", "add", &add, "drop", &drop);
354                 if (add) {
355                         rc = afb_trace_add(req, add, trace);
356                         if (rc)
357                                 return;
358                 }
359                 if (drop) {
360                         rc = afb_trace_drop(req, drop, trace);
361                         if (rc)
362                                 return;
363                 }
364                 afb_req_success(req, NULL, NULL);
365                 break;
366         case Do:
367                 sub = NULL;
368                 if (wrap_json_unpack(args, "{ss ss s?o*}", "api", &api, "verb", &verb, "args", &sub))
369                         afb_xreq_fail(xreq, "error", "bad request");
370                 else {
371                         xapi = afb_apiset_lookup_started(main_apiset, api, 1);
372                         if (!xapi)
373                                 afb_xreq_fail_unknown_api(xreq);
374                         else {
375                                 afb_cred_unref(xreq->cred);
376                                 xreq->cred = NULL;
377                                 xreq->request.api = api;
378                                 xreq->request.verb = verb;
379                                 xreq->json = json_object_get(sub);
380                                 xapi->itf->call(xapi->closure, xreq);
381                                 json_object_put(args);
382                         }
383                 }
384                 break;
385         case Wait:
386                 afb_req_success(req, NULL, NULL);
387                 afb_debug_wait("supervisor");
388                 break;
389         case Break:
390                 afb_req_success(req, NULL, NULL);
391                 afb_debug_break("supervisor");
392                 break;
393         }
394 }
395