aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/supervisor-api.c
blob: c143d69434879f650a2d28cd77721ade16d40ea0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
/*
 * Copyright (C) 2018-2019 "IoT.bzh"
 * Author "Sebastien Douheret" <sebastien@iot.bzh>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *	 http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#define _GNU_SOURCE
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

#include "ctl-plugin.h"
#include "supervisor-api.h"
#include "supervisor.h"
#include "wrap-json.h"

// TODO: replace by a chained list of DAEMON_T*
static int TracePidsNum = 0;
static int* TracePidsArr = NULL;

#define TRACE_DAEMON(src, nb, dd, lvl, res)                                               \
    {                                                                                     \
        nb++;                                                                             \
        json_object_array_add(res, json_object_new_int(dd->pid));                         \
        if ((rc = trace_daemon(src->api, dd, lvl)) < 0) {                                 \
            afb_req_fail_f(src->request, "failed", "Trace pid %d error %d", dd->pid, rc); \
            goto error;                                                                   \
        }                                                                                 \
    }

CTLP_CAPI_REGISTER("supervisor");

CTLP_ONLOAD(plugin, ret)
{
    return 0;
}

CTLP_CAPI(list, source, argsJ, eventJ)
{
    json_object *result, *item = NULL;
    DAEMONS_T* daemons = NULL;

    getDaemons(source->api, &daemons);
    if (daemons == NULL) {
        afb_req_fail(source->request, "Failed", "Error daemon list null");
        return ERROR;
    }

    AFB_API_INFO(source->api, "Build response (nb daemons %d)", daemons->count);
    result = json_object_new_array();

    for (int i = 0; i < daemons->count; i++) {
        int rc = wrap_json_pack(&item, "{si ss sb sb s?o s?o so}",
            "pid", daemons->daemons[i]->pid,
            "name", daemons->daemons[i]->name,
            "isServer", daemons->daemons[i]->isServer,
            "isClient", daemons->daemons[i]->isClient,
            "ws_servers", daemons->daemons[i]->ws_servers,
            "ws_clients", daemons->daemons[i]->ws_clients,
            "apis", daemons->daemons[i]->apis);
        //, "config", daemons->daemons[i]->config);
        if (rc) {
            AFB_API_ERROR(source->api, "wrap_json_pack error %d: %s", rc, wrap_json_get_error_string(rc));
        }
        json_object_array_add(result, item);
    }

    AFB_API_INFO(source->api, "Send response");
    afb_req_success(source->request, result, NULL);
    return 0;
}

CTLP_CAPI(trace_start, source, argsJ, queryJ)
{
    int rc;
    json_object* result = NULL;
    DAEMONS_T* daemons = NULL;
    const char* ws_name = "";
    const char* level = NULL;
    pid_t pid = -1;
    json_object* j_pids = NULL;
    int nb_traced_daemons = 0;

    // User can ask to trace either
    //  a specific pid or an array of pids or a specific ws name
    if (wrap_json_unpack(queryJ, "{s:?i s:?o s:?s s:?s}",
            "pid", &pid, "pids", &j_pids, "ws", &ws_name, "level", &level)) {
        afb_req_fail(source->request, "Failed", "Error processing arguments.");
        return ERROR;
    }

    if (pid == -1 && j_pids == NULL && strlen(ws_name) == 0) {
        afb_req_fail(source->request, "failed", "one of pid or pids or ws parameter must be set");
        return ERROR;
    }

    if (TracePidsNum > 0) {
        afb_req_fail(source->request, "failed", "already tracing");
        return ERROR;
    }

    AFB_API_DEBUG(source->api, "Trace ws=%s, pid=%d, pids=%s", ws_name, pid, json_object_to_json_string(j_pids));

    if (j_pids != NULL && json_object_is_type(j_pids, json_type_array)) {
        TracePidsNum = (int)json_object_array_length(j_pids);
        TracePidsArr = malloc(sizeof(int) * TracePidsNum);
        if (TracePidsArr == NULL) {
            afb_req_fail(source->request, "failed", "out of memory");
            goto error;
        }
        int i = 0;
        while (i < TracePidsNum) {
            json_object* j_ppid = json_object_array_get_idx(j_pids, i);
            TracePidsArr[i++] = json_object_get_int(j_ppid);
        }
    }

    getDaemons(source->api, &daemons);
    if (daemons == NULL || daemons->count <= 0) {
        afb_req_fail(source->request, "failed", "No daemon found");
        goto error;
    }

    // search which daemons should be traced
    const char* wsn;
    nb_traced_daemons = 0;
    result = json_object_new_array();
    for (int i = 0; i < daemons->count; i++) {
        AFB_API_DEBUG(source->api, "_DEBUG_ svr %s",
            json_object_to_json_string(daemons->daemons[i]->ws_servers));
        AFB_API_DEBUG(source->api, "_DEBUG_ cli %s",
            json_object_to_json_string(daemons->daemons[i]->ws_clients));

        if (pid != -1 && pid == daemons->daemons[i]->pid) {
            // Trace a specific pid
            TRACE_DAEMON(source, nb_traced_daemons, daemons->daemons[i], level, result);
            TracePidsNum = 1;
            TracePidsArr = malloc(sizeof(int) * TracePidsNum);
            if (TracePidsArr == NULL) {
                afb_req_fail(source->request, "failed", "out of memory");
                goto error;
            }
            TracePidsArr[0] = daemons->daemons[i]->pid;
            break;

        } else if (j_pids != NULL) {
            // Trace from a list of pids
            for (int j = 0; j < TracePidsNum; j++) {
                if (TracePidsArr[j] == daemons->daemons[i]->pid) {
                    TRACE_DAEMON(source, nb_traced_daemons, daemons->daemons[i], level, result);
                }
            }
        } else if (ws_name != NULL) {
            // Trace based on WS name
            json_object* ws_servers = daemons->daemons[i]->ws_servers;
            for (int j = 0; j < json_object_array_length(ws_servers); j++) {
                wsn = json_object_get_string(json_object_array_get_idx(ws_servers, j));
                if (wsn && strstr(wsn, ws_name) != NULL) {
                    TRACE_DAEMON(source, nb_traced_daemons, daemons->daemons[i], level, result);

                    TracePidsNum++;
                    int* tmpPtr = realloc(TracePidsArr, sizeof(int) * TracePidsNum);
                    if (tmpPtr == NULL) {
                        afb_req_fail(source->request, "failed", "out of memory");
                        goto error;
                    }
                    TracePidsArr = tmpPtr;
                    TracePidsArr[TracePidsNum - 1] = daemons->daemons[i]->pid;
                    break;
                }
            }

            json_object* ws_clients = daemons->daemons[i]->ws_clients;
            for (int j = 0; j < json_object_array_length(ws_clients); j++) {
                wsn = json_object_get_string(json_object_array_get_idx(ws_clients, j));
                if (wsn && strstr(wsn, ws_name) != NULL) {
                    TRACE_DAEMON(source, nb_traced_daemons, daemons->daemons[i], level, result);

                    TracePidsNum++;
                    int* tmpPtr = realloc(TracePidsArr, sizeof(int) * TracePidsNum);
                    if (tmpPtr == NULL) {
                        afb_req_fail(source->request, "failed", "out of memory");
                        goto error;
                    }
                    TracePidsArr = tmpPtr;
                    TracePidsArr[TracePidsNum - 1] = daemons->daemons[i]->pid;
                    break;
                }
            }
        }
    }

    if (nb_traced_daemons == 0) {
        afb_req_fail(source->request, "failed", "No daemon found match criteria");
        goto error;
    }

    afb_req_success(source->request, result, "Trace successfully started");

    return 0;

error:
    if (TracePidsNum > 0)
        free(TracePidsArr);
    TracePidsNum = 0;
    TracePidsArr = NULL;
    return ERROR;
}

CTLP_CAPI(trace_stop, source, argsJ, queryJ)
{
    int rc, nbErr = 0;
    json_object* result = NULL;

    if (TracePidsNum == 0) {
        afb_req_fail(source->request, "failed", "Trace already stopped");
        return ERROR;
    }

    for (int j = 0; j < TracePidsNum; j++) {
        rc = trace_drop(source->api, TracePidsArr[j]);
        if (rc < 0) {
            // FIMXE - return list of error messages
            nbErr++;
        }
    }
    if (TracePidsNum > 0)
        free(TracePidsArr);
    TracePidsNum = 0;
    TracePidsArr = NULL;

    if (nbErr) {
        afb_req_fail_f(source->request, "failed", "Error while stopping tracing (%d)", nbErr);
        return ERROR;
    }
    afb_req_success(source->request, result, "Trace successfully stopped");

    return 0;
}

static inline uint64_t get_ts()
{
    struct timespec ts;
    clock_gettime(CLOCK_REALTIME, &ts);

    return (uint64_t)(ts.tv_sec) * (uint64_t)1000000000 + (uint64_t)(ts.tv_nsec);
}

static void cb_harvester_write(void* closure, int status, struct json_object* result, struct afb_api* api)
{
    json_object* err = NULL;
    if (result) {
        wrap_json_unpack(result, "{s:{s:o}}", "request", "info", &err);
    }

    AFB_API_DEBUG(api, "cb_harvester_write status: %d, %s", status, json_object_to_json_string(err));
}

CTLP_CAPI(tracing_events, source, argsJ, eventJ)
{
    int rc;
    json_object* request = NULL;
    json_object* event = NULL;
    json_object* data = NULL;
    json_object* timestamp = NULL;
    json_object *j_res, *j_query, *j_metric;
    json_object *j_metadata, *j_values;
    int id = 0;
    const char* type = NULL;
    const char* tag = NULL;
    const char* cdata = NULL;

    AFB_API_DEBUG(source->api, ">>> RECV Event uid %s : %s", source->uid,
        json_object_to_json_string(eventJ));

    if (strcmp(source->uid, "supervisor/xds-trace") != 0) {
        AFB_API_NOTICE(source->api, "WARNING: un-handle uid '%s'", source->uid);
        return 0;
    }

    if ((rc = wrap_json_unpack(eventJ, "{so ss si ss s?o s?o s?o}",
             "time", &timestamp,
             "tag", &tag,
             "id", &id,
             "type", &type,
             "request", &request,
             "event", &event,
             "data", &data))
        < 0) {
        AFB_API_ERROR(source->api, "Cannot decode event object : %s", wrap_json_get_error_string(rc));
        return ERROR;
    }

    if (!timestamp) {
        timestamp = json_object_new_int64(get_ts());
    }

    rc = wrap_json_pack(&j_metadata, "{s:s s:s}",
        "identity", "xds_supervisor",
        "tag", tag);
    if (rc < 0) {
        AFB_API_ERROR(source->api, "Error packing j_metadata, rc=%d", rc);
        goto _EXIT_TRACE_EVT;
    }
    rc = wrap_json_pack(&j_values, "{si}", "id", id);
    if (rc < 0) {
        AFB_API_ERROR(source->api, "Error packing j_values, rc=%d", rc);
        goto _EXIT_TRACE_EVT;
    }

    if (!strncmp(type, "request", 6) && request) {
        // Process "request" type

        json_object* j_action = json_object_object_get(request, "action");

        // Filter out some traces
#if 0 // TO Test
        const char* action = json_object_get_string(j_action);
        if (action && (!strncmp(action, "begin", 5) || !strncmp(action, "end", 3) || !strncmp(action, "json", 4))) {
            AFB_API_DEBUG(source->api, "trace_events IGNORED event=%s", json_object_to_json_string(request));
            rc = 0;
            free(action);
            goto _EXIT_TRACE_EVT;
        }
        if (action)
            free(action);
#endif

        json_object_object_add(j_metadata, "type", json_object_new_string("request"));
        json_object_object_add(j_metadata, "api", json_object_object_get(request, "api"));
        json_object_object_add(j_metadata, "verb", json_object_object_get(request, "verb"));
        json_object_object_add(j_metadata, "action", j_action);
        json_object_object_add(j_metadata, "session", json_object_object_get(request, "session"));
        json_object_object_add(j_metadata, "req_index", json_object_new_string(json_object_to_json_string(json_object_object_get(request, "index"))));

        AFB_API_DEBUG(source->api, "Type request, j_metadata=%s", json_object_to_json_string(j_metadata));

    } else if (!strncmp(type, "event", 5) && event) {
        // Process "event" type

        json_object_object_add(j_metadata, "type", json_object_new_string("event"));
        json_object_object_add(j_metadata, "id", json_object_object_get(event, "id"));
        json_object_object_add(j_metadata, "name", json_object_object_get(event, "name"));
        json_object_object_add(j_metadata, "action", json_object_object_get(event, "action"));

        AFB_API_DEBUG(source->api, "Type event, j_metadata=%s", json_object_to_json_string(j_metadata));
    } else {
        AFB_API_ERROR(source->api, "Null request or event field");
        rc = ERROR;
        goto _EXIT_TRACE_EVT;
    }

    if (data) {
        // Serialized data (IOW an JSON object pass as a string)
        cdata = json_object_to_json_string(data);
        json_object_object_add(j_values, "data", json_object_new_string(cdata));
        json_object_object_add(j_values, "data_bytes", json_object_new_int((int32_t)strlen(cdata)));
    }

    rc = wrap_json_pack(&j_metric, "{s:s s:o s:o s:o }",
        "name", "xds/supervisor/trace",
        "metadata", j_metadata,
        "values", j_values,
        "timestamp", timestamp);

    if (rc < 0) {
        AFB_API_ERROR(source->api, "Error packing j_metric, rc=%d", rc);
        goto _EXIT_TRACE_EVT;
    }

    rc = wrap_json_pack(&j_query, "{s:s s:i s:[o] }",
        "host", "localhost", // FIXME - configurable
        "port", 8086, // FIXME - configurable
        "metric", j_metric);
    if (rc < 0) {
        AFB_API_ERROR(source->api, "Error packing query, rc=%d", rc);
        goto _EXIT_TRACE_EVT;
    }

    AFB_API_DEBUG(source->api, "%s write: %s", SRV_HARVESTER_NAME,
        json_object_to_json_string(j_query));

#if 0 // SYNC_CALL - for debugging purpose
    rc = afb_api_call_sync_legacy(source->api, SRV_HARVESTER_NAME, "write", j_query, &j_res);
    if (rc < 0) {
        AFB_API_ERROR(source->api, "Error %s write : rc=%d, j_res=%s", SRV_HARVESTER_NAME, rc,
            json_object_to_json_string(j_res));
        goto _EXIT_TRACE_EVT;
    }
#else
    afb_api_call_legacy(source->api, SRV_HARVESTER_NAME, "write", j_query, cb_harvester_write, &j_res);
#endif

    // No error
    rc = 0;

_EXIT_TRACE_EVT:
    // no need to free type, tag and cdata (already managed by json_object_generic_delete)

    return rc;
}