aboutsummaryrefslogtreecommitdiffstats
path: root/lavalab-gen.py
blob: 35b10c7c5476f2c00e8d7d05d2e067e28b369679 (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
415
#!/usr/bin/env python
#
from __future__ import print_function
import os, sys, time
import subprocess
import yaml
import string
import socket
import shutil

# Defaults
boards_yaml = "boards.yaml"
tokens_yaml = "tokens.yaml"
baud_default = 115200
    
template_conmux = string.Template("""#
# auto-generated by lavalab-gen.py for ${board}
#
listener ${board}
application console '${board} console' 'exec sg dialout "cu-loop /dev/${board} ${baud}"'
""")

#no comment it is volontary
template_device = string.Template("""{% extends '${devicetype}.jinja2' %}
""")

template_device_conmux = string.Template("""
{% set connection_command = 'conmux-console ${board}' %}
""")
template_device_connection_command = string.Template("""#
{% set connection_command = '${connection_command}' %}
""")
template_device_pdu_generic = string.Template("""
{% set hard_reset_command = '${hard_reset_command}' %}
{% set power_off_command = '${power_off_command}' %}
{% set power_on_command = '${power_on_command}' %}
""")

template_ser2net = string.Template("""
${port}:telnet:600:/dev/${board}:${baud} 8DATABITS NONE 1STOPBIT banner
""")
template_device_ser2net = string.Template("""
{% set connection_command = 'telnet 127.0.0.1 ${port}' %}
""")

template_device_screen = string.Template("""
{% set connection_command = 'ssh -o StrictHostKeyChecking=no -t root@127.0.0.1 "TERM=xterm screen -x ${board}"' %}
""")

template_udev_serial = string.Template("""#
SUBSYSTEM=="tty", ATTRS{idVendor}=="${idvendor}", ATTRS{idProduct}=="${idproduct}", ATTRS{serial}=="${serial}", MODE="0664", OWNER="uucp", SYMLINK+="${board}"
""")
template_udev_devpath = string.Template("""#
SUBSYSTEM=="tty", ATTRS{idVendor}=="${idvendor}", ATTRS{idProduct}=="${idproduct}", ATTRS{devpath}=="${devpath}", MODE="0664", OWNER="uucp", SYMLINK+="${board}"
""")

template_settings_conf = string.Template("""
{
    "DEBUG": false,
    "STATICFILES_DIRS": [
        ["lava-server", "/usr/share/pyshared/lava_server/htdocs/"]
    ],
    "MEDIA_ROOT": "/var/lib/lava-server/default/media",
    "ARCHIVE_ROOT": "/var/lib/lava-server/default/archive",
    "STATIC_ROOT": "/usr/share/lava-server/static",
    "STATIC_URL": "/static/",
    "MOUNT_POINT": "/",
    "HTTPS_XML_RPC": false,
    "LOGIN_URL": "/accounts/login/",
    "LOGIN_REDIRECT_URL": "/",
    "CSRF_COOKIE_SECURE": $cookie_secure,
    "SESSION_COOKIE_SECURE": $session_cookie_secure
}
""")

def main():
    fp = open(boards_yaml, "r")
    workers = yaml.load(fp)
    fp.close()

    os.mkdir("output")

    if "masters" not in workers:
        print("Missing masters entry in boards.yaml")
        sys.exit(1)
    masters = workers["masters"]
    for master in masters:
        keywords_master = [ "name", "type", "host", "users", "tokens", "webadmin_https" ]
        for keyword in master:
            if not keyword in keywords_master:
                print("WARNING: unknown keyword %s" % keyword)
        name = master["name"]
        print("Handle %s\n" % name)
        if not "host" in master:
            host = "local"
        else:
            host = master["host"]
        workerdir = "output/%s/%s" % (host, name)
        os.mkdir("output/%s" % host)
        shutil.copy("deploy.sh", "output/%s/" % host)
        dockcomp = {}
        dockcomp["version"] = "2.0"
        dockcomp["services"] = {}
        dockcomposeymlpath = "output/%s/docker-compose.yml" % host
        dockcomp["services"][name] = {}
        dockcomp["services"][name]["hostname"] = name
        dockcomp["services"][name]["ports"] = [ "10080:80", "5555:5555", "5556:5556", "5500:5500" ]
        dockcomp["services"][name]["volumes"] = [ "/boot:/boot", "/lib/modules:/lib/modules" ]
        dockcomp["services"][name]["build"] = {}
        dockcomp["services"][name]["build"]["context"] = name
        with open(dockcomposeymlpath, 'w') as f:
            yaml.dump(dockcomp, f)

        shutil.copytree("lava-master", workerdir)
        os.mkdir("%s/devices" % workerdir)
        # handle users / tokens
        userdir = "%s/users" % workerdir
        os.mkdir(userdir)
        worker = master
        webadmin_https = False
        if "webadmin_https" in worker:
            webadmin_https = worker["webadmin_https"]
        if webadmin_https:
            cookie_secure = "true"
            session_cookie_secure = "true"
        else:
            cookie_secure = "false"
            session_cookie_secure = "false"
        fsettings = open("%s/settings.conf" % workerdir, 'w')
        fsettings.write(template_settings_conf.substitute(cookie_secure=cookie_secure, session_cookie_secure=session_cookie_secure))
        fsettings.close()
        if "users" in worker:
            for user in worker["users"]:
                keywords_users = [ "name", "staff", "superuser", "password", "token" ]
                for keyword in user:
                    if not keyword in keywords_users:
                        print("WARNING: unknown keyword %s" % keyword)
                username = user["name"]
                ftok = open("%s/%s" % (userdir, username), "w")
                token = user["token"]
                ftok.write("TOKEN=" + token + "\n")
                if "password" in user:
                    password = user["password"]
                    ftok.write("PASSWORD=" + password + "\n")
                    # libyaml convert yes/no to true/false...
                if "staff" in user:
                    value = user["staff"]
                    if value is True:
                        ftok.write("STAFF=1\n")
                if "superuser" in user:
                    value = user["superuser"]
                    if value is True:
                        ftok.write("SUPERUSER=1\n")
                ftok.close()
        tokendir = "%s/tokens" % workerdir
        os.mkdir(tokendir)
        if "tokens" in worker:
            filename_num = {}
            print("Found tokens")
            for token in worker["tokens"]:
                keywords_tokens = [ "username", "token", "description" ]
                for keyword in token:
                    if not keyword in keywords_tokens:
                        print("WARNING: unknown keyword %s" % keyword)
                username = token["username"]
                description = token["description"]
                if username in filename_num:
                    number = filename_num[username]
                    filename_num[username] = filename_num[username] + 1
                else:
                    filename_num[username] = 1
                    number = 0
                filename = "%s-%d" % (username, number)
                print("\tAdd token for %s in %s" % (username, filename))
                ftok = open("%s/%s" % (tokendir, filename), "w")
                ftok.write("USER=" + username + "\n")
                vtoken = token["token"]
                ftok.write("TOKEN=" + vtoken + "\n")
                ftok.write("DESCRIPTION=\"%s\"" % description)
                ftok.close()

    default_slave = "lab-slave-0"
    if "slaves" not in workers:
        print("Missing slaves entry in boards.yaml")
        sys.exit(1)
    slaves = workers["slaves"]
    for slave in slaves:
        keywords_slaves = [ "name", "host", "dispatcher_ip", "remote_user", "remote_master", "remote_address", "remote_rpc_port", "remote_proto", "extra_actions" ]
        for keyword in slave:
            if not keyword in keywords_slaves:
                print("WARNING: unknown keyword %s" % keyword)
        name = slave["name"]
        if len(slaves) == 1:
            default_slave = name
        print("Handle %s" % name)
        if not "host" in slave:
            host = "local"
        else:
            host = slave["host"]
        if slave.get("default_slave") and slave["default_slave"]:
             default_slave = name
        workerdir = "output/%s/%s" % (host, name)
        dockcomposeymlpath = "output/%s/docker-compose.yml" % host
        if not os.path.isdir("output/%s" % host):
            os.mkdir("output/%s" % host)
            shutil.copy("deploy.sh", "output/%s/" % host)
            dockcomp = {}
            dockcomp["version"] = "2.0"
            dockcomp["services"] = {}
        else:
            #master exists
            fp = open(dockcomposeymlpath, "r")
            dockcomp = yaml.load(fp)
            fp.close()
        dockcomp["services"][name] = {}
        dockcomp["services"][name]["hostname"] = name
        dockcomp["services"][name]["dns_search"] = ""
        dockcomp["services"][name]["ports"] = [ "69:69/udp", "80:80", "61950-62000:61950-62000" ]
        dockcomp["services"][name]["volumes"] = [ "/boot:/boot", "/lib/modules:/lib/modules" ]
        dockcomp["services"][name]["environment"] = {}
        dockcomp["services"][name]["build"] = {}
        dockcomp["services"][name]["build"]["context"] = name
        # insert here remote

        shutil.copytree("lava-slave", workerdir)
        fp = open("%s/phyhostname" % workerdir, "w")
        fp.write(host)
        fp.close()
        conmuxpath = "%s/conmux" % workerdir
        if not os.path.isdir(conmuxpath):
            os.mkdir(conmuxpath)

        worker = slave
        worker_name = name
        #NOTE remote_master is on slave
        if not "remote_master" in worker:
            remote_master = "lava-master"
        else:
            remote_master = worker["remote_master"]
        if not "remote_address" in worker:
            remote_address = remote_master
        else:
            remote_address = worker["remote_address"]
        if not "remote_rpc_port" in worker:
            remote_rpc_port = "80"
        else:
            remote_rpc_port = worker["remote_rpc_port"]
        dockcomp["services"][worker_name]["environment"]["LAVA_MASTER"] = remote_address
        remote_user = worker["remote_user"]
        # find master
        remote_token = "BAD"
        for fm in workers["masters"]:
            if fm["name"] == remote_master:
                for fuser in fm["users"]:
                    if fuser["name"] == remote_user:
                        remote_token = fuser["token"]
        if remote_token is "BAD":
            print("Cannot find %s on %s" % (remote_user, remote_master))
            sys.exit(1)
        if not "remote_proto" in worker:
            remote_proto = "http"
        else:
            remote_proto = worker["remote_proto"]
        remote_uri = "%s://%s:%s@%s:%s/RPC2" % (remote_proto, remote_user, remote_token, remote_address, remote_rpc_port)
        dockcomp["services"][worker_name]["environment"]["LAVA_MASTER_URI"] = remote_uri

        if "dispatcher_ip" in worker:
            dockcomp["services"][worker_name]["environment"]["LAVA_DISPATCHER_IP"] = worker["dispatcher_ip"]
        with open(dockcomposeymlpath, 'w') as f:
            yaml.dump(dockcomp, f)
        if "extra_actions" in worker:
            fp = open("%s/scripts/extra_actions" % workerdir, "w")
            for eaction in worker["extra_actions"]:
                fp.write(eaction)
                fp.write("\n")
            fp.close()
            os.chmod("%s/scripts/extra_actions" % workerdir, 0o755)

    if "boards" not in workers:
        print("Missing boards")
        sys.exit(1)
    ser2net_port = 60000
    boards = workers["boards"]
    for board in boards:
        board_name = board["name"]
        if "slave" in board:
            slave_name = board["slave"]
        else:
            slave_name = default_slave
        print("\tFound %s on %s" % (board_name, slave_name))
        found_slave = False
        for fs in workers["slaves"]:
            if fs["name"] == slave_name:
                slave = fs
                found_slave = True
        if not found_slave:
            print("Cannot find slave %s" % slave_name)
            sys.exit(1)
        if not "host" in slave:
            host = "local"
        else:
            host = slave["host"]
        workerdir = "output/%s/%s" % (host, slave_name)
        dockcomposeymlpath = "output/%s/docker-compose.yml" % host
        fp = open(dockcomposeymlpath, "r")
        dockcomp = yaml.load(fp)
        fp.close()
        device_path = "%s/devices/" % workerdir
        devices_path = "%s/devices/%s" % (workerdir, slave_name)
        devicetype = board["type"]
        device_line = template_device.substitute(devicetype=devicetype)
        if "pdu_generic" in board:
            hard_reset_command = board["pdu_generic"]["hard_reset_command"]
            power_off_command = board["pdu_generic"]["power_off_command"]
            power_on_command = board["pdu_generic"]["power_on_command"]
            device_line += template_device_pdu_generic.substitute(hard_reset_command=hard_reset_command, power_off_command=power_off_command, power_on_command=power_on_command)
        use_kvm = False
        if "kvm" in board:
            use_kvm = board["kvm"]
        if use_kvm:
            if "devices" in dockcomp["services"][worker_name]:
                dc_devices = dockcomp["services"][worker_name]["devices"]
            else:
                dockcomp["services"][worker_name]["devices"] = []
                dc_devices = dockcomp["services"][worker_name]["devices"]
            dc_devices.append("/dev/kvm:/dev/kvm")
            # board specific hacks
        if devicetype == "qemu" and not use_kvm:
            device_line += "{% set no_kvm = True %}\n"
        if "uart" in board:
            uart = board["uart"]
            baud = board["uart"].get("baud", baud_default)
            idvendor = board["uart"]["idvendor"]
            idproduct = board["uart"]["idproduct"]
            if type(idproduct) == str:
                print("Please put hexadecimal IDs for product %s (like 0x%s)" % (board_name, idproduct))
                sys.exit(1)
            if type(idvendor) == str:
                print("Please put hexadecimal IDs for vendor %s (like 0x%s)" % (board_name, idvendor))
                sys.exit(1)
            if "serial" in uart:
                serial = board["uart"]["serial"]
                udev_line = template_udev_serial.substitute(board=board_name, serial=serial, idvendor="%04x" % idvendor, idproduct="%04x" % idproduct)
            else:
                devpath = board["uart"]["devpath"]
                udev_line = template_udev_devpath.substitute(board=board_name, devpath=devpath, idvendor="%04x" % idvendor, idproduct="%04x" % idproduct)
            if not os.path.isdir("output/%s/udev" % host):
                os.mkdir("output/%s/udev" % host)
            fp = open("output/%s/udev/99-lavaworker-udev.rules" % host, "a")
            fp.write(udev_line)
            fp.close()
            if "devices" in dockcomp["services"][worker_name]:
                dc_devices = dockcomp["services"][worker_name]["devices"]
            else:
                dockcomp["services"][worker_name]["devices"] = []
                dc_devices = dockcomp["services"][worker_name]["devices"]
            dc_devices.append("/dev/%s:/dev/%s" % (board_name, board_name))
            use_conmux = True
            use_ser2net = False
            use_screen = False
            if "use_ser2net" in uart:
                use_conmux = False
                use_ser2net = True
            if "use_screen" in uart:
                use_conmux = False
                use_screen = True
            if use_conmux:
                conmuxline = template_conmux.substitute(board=board_name, baud=baud)
                device_line += template_device_conmux.substitute(board=board_name)
                fp = open("%s/conmux/%s.cf" % (workerdir, board_name), "w")
                fp.write(conmuxline)
                fp.close()
            if use_ser2net:
                ser2net_line = template_ser2net.substitute(port=ser2net_port,baud=baud,board=board_name)
                device_line += template_device_ser2net.substitute(port=ser2net_port)
                ser2net_port += 1
                fp = open("%s/ser2net.conf" % workerdir, "a")
                fp.write(ser2net_line)
                fp.close()
            if use_screen:
                device_line += template_device_screen.substitute(board=board_name)
                fp = open("%s/lava-screen.conf" % workerdir, "a")
                fp.write("%s\n" % board_name)
                fp.close()
        elif "connection_command" in board:
            connection_command = board["connection_command"]
            device_line += template_device_connection_command.substitute(connection_command=connection_command)
        if "uboot_ipaddr" in board:
            device_line += "{%% set uboot_ipaddr_cmd = 'setenv ipaddr %s' %%}\n" % board["uboot_ipaddr"]
        if "uboot_macaddr" in board:
            device_line += '{% set uboot_set_mac = true %}'
            device_line += "{%% set uboot_mac_addr = '%s' %%}\n" % board["uboot_macaddr"]
        if "fastboot_serial_number" in board:
            fserial = board["fastboot_serial_number"]
            device_line += "{%% set fastboot_serial_number = '%s' %%}" % fserial
        if "custom_option" in board:
            for coption in board["custom_option"]:
                device_line += "{%% %s %%}" % coption
        if not os.path.isdir(device_path):
            os.mkdir(device_path)
        if not os.path.isdir(devices_path):
            os.mkdir(devices_path)
        board_device_file = "%s/%s.jinja2" % (devices_path, board_name)
        fp = open(board_device_file, "w")
        fp.write(device_line)
        fp.close()
        with open(dockcomposeymlpath, 'w') as f:
            yaml.dump(dockcomp, f)


if __name__ == "__main__":
    shutil.copy("common/build-lava", "lava-slave/scripts/build-lava")
    shutil.copy("common/build-lava", "lava-master/scripts/build-lava")
    main()
>return afb_req_context(req, (void*)get_new_board, (void*)release_board); } ``` The function **afb_req_context** ensures an existing context for the session of the request. Its two last arguments are functions to allocate and free context. Note function type casts to avoid compilation warnings. Here is the definition of the function **afb_req_context** ```C /* * Gets the pointer stored by the binding for the session of 'req'. * If the stored pointer is NULL, indicating that no pointer was * already stored, afb_req_context creates a new context by calling * the function 'create_context' and stores it with the freeing function * 'free_context'. */ static inline void *afb_req_context(struct afb_req req, void *(*create_context)(), void (*free_context)(void*)) { void *result = afb_req_context_get(req); if (result == NULL) { result = create_context(); afb_req_context_set(req, result, free_context); } return result; } ``` The second argument if the function that creates the context. For binding *tic-tac-toe* (function **get_new_board**). The function **get_new_board** creates a new board and set usage its count to 1. The boards are checking usage count to free resources when not used. The third argument is a function that frees context resources. For binding *tic-tac-toe* (function **release_board**). The function **release_board** decrease usage count of the board passed in argument. When usage count falls to zero, data board are freed. Definition of other functions dealing with contexts: ```C /* * Gets the pointer stored by the binding for the session of 'req'. * When the binding has not yet recorded a pointer, NULL is returned. */ void *afb_req_context_get(struct afb_req req); /* * Stores for the binding the pointer 'context' to the session of 'req'. * The function 'free_context' will be called when the session is closed * or if binding stores an other pointer. */ void afb_req_context_set(struct afb_req req, void *context, void (*free_context)(void*)); /* * Frees the pointer stored by the binding for the session of 'req' * and sets it to NULL. * * Shortcut for: afb_req_context_set(req, NULL, NULL) */ static inline void afb_req_context_clear(struct afb_req req) { afb_req_context_set(req, NULL, NULL); } ``` ### Sending reply to a request Two kinds of replies: successful or failure. > Sending a reply to a request MUST be done once and only once. It exists two functions for "success" replies: **afb_req_success** and **afb_req_success_f**. ```C /* * Sends a reply of kind success to the request 'req'. * The status of the reply is automatically set to "success". * Its send the object 'obj' (can be NULL) with an * informationnal comment 'info (can also be NULL). * * For convenience, the function calls 'json_object_put' for 'obj'. * Thus, in the case where 'obj' should remain available after * the function returns, the function 'json_object_get' shall be used. */ void afb_req_success(struct afb_req req, struct json_object *obj, const char *info); /* * Same as 'afb_req_success' but the 'info' is a formatting * string followed by arguments. * * For convenience, the function calls 'json_object_put' for 'obj'. * Thus, in the case where 'obj' should remain available after * the function returns, the function 'json_object_get' shall be used. */ void afb_req_success_f(struct afb_req req, struct json_object *obj, const char *info, ...); ``` It exists two functions for "failure" replies: **afb_req_fail** and **afb_req_fail_f**. ```C /* * Sends a reply of kind failure to the request 'req'. * The status of the reply is set to 'status' and an * informational comment 'info' (can also be NULL) can be added. * * Note that calling afb_req_fail("success", info) is equivalent * to call afb_req_success(NULL, info). Thus even if possible it * is strongly recommended to NEVER use "success" for status. * * For convenience, the function calls 'json_object_put' for 'obj'. * Thus, in the case where 'obj' should remain available after * the function returns, the function 'json_object_get' shall be used. */ void afb_req_fail(struct afb_req req, const char *status, const char *info); /* * Same as 'afb_req_fail' but the 'info' is a formatting * string followed by arguments. * * For convenience, the function calls 'json_object_put' for 'obj'. * Thus, in the case where 'obj' should remain available after * the function returns, the function 'json_object_get' shall be used. */ void afb_req_fail_f(struct afb_req req, const char *status, const char *info, ...); ``` > For convenience, these functions automatically call **json_object_put** to release **obj**. > Because **obj** usage count is null after being passed to a reply function, it SHOULD not be used anymore. > If exceptionally **obj** needs to remain usable after reply function then using **json_object_get** on **obj** > to increase usage count and cancels the effect the **json_object_put** is possible. Getting argument of invocation ------------------------------ Many methods expect arguments. Afb-daemon's bindings retrieve arguments by name and not by position. Arguments are passed by requests through either HTTP or WebSockets. For example, the method **join** of binding **tic-tac-toe** expects one argument: the *boardid* to join. Here is an extract: ```C /* * Join a board */ static void join(struct afb_req req) { struct board *board, *new_board; const char *id; /* retrieves the context for the session */ board = board_of_req(req); INFO(afbitf, "method 'join' called for boardid %d", board->id); /* retrieves the argument */ id = afb_req_value(req, "boardid"); if (id == NULL) goto bad_request; ... ``` The function **afb_req_value** searches in the request *req* for argument name passed in the second argument. When argument name is not passed, **afb_req_value** returns NULL. > The search is case sensitive and *boardid* is not equivalent to *BoardId*. > Nevertheless having argument names that only differ by name case is not a good idea. ### Basic functions for querying arguments The function **afb_req_value** is defined here after: ```C /* * Gets from the request 'req' the string value of the argument of 'name'. * Returns NULL if when there is no argument of 'name'. * Returns the value of the argument of 'name' otherwise. * * Shortcut for: afb_req_get(req, name).value */ static inline const char *afb_req_value(struct afb_req req, const char *name) { return afb_req_get(req, name).value; } ``` It is defined as a shortcut to call the function **afb_req_get**. That function is defined here after: ```C /* * Gets from the request 'req' the argument of 'name'. * Returns a PLAIN structure of type 'struct afb_arg'. * When the argument of 'name' is not found, all fields of result are set to NULL. * When the argument of 'name' is found, the fields are filled, * in particular, the field 'result.name' is set to 'name'. * * There is a special name value: the empty string. * The argument of name "" is defined only if the request was made using * an HTTP POST of Content-Type "application/json". In that case, the * argument of name "" receives the value of the body of the HTTP request. */ struct afb_arg afb_req_get(struct afb_req req, const char *name); ``` That function takes 2 parameters: the request and the name of the argument to retrieve. It returns a PLAIN structure of type **struct afb_arg**. There is a special name that is defined when the request is of type HTTP/POST with a Content-Type being application/json. This name is **""** (the empty string). In that case, the value of this argument of empty name is the string received as a body of the post and is supposed to be a JSON string. The definition of **struct afb_arg** is: ```C /* * Describes an argument (or parameter) of a request */ struct afb_arg { const char *name; /* name of the argument or NULL if invalid */ const char *value; /* string representation of the value of the argument */ /* original filename of the argument if path != NULL */ const char *path; /* if not NULL, path of the received file for the argument */ /* when the request is finalized this file is removed */ }; ``` The structure returns the data arguments that are known for the request. This data include a field named **path**. This **path** can be accessed using the function **afb_req_path** defined here after: ```C /* * Gets from the request 'req' the path for file attached to the argument of 'name'. * Returns NULL if when there is no argument of 'name' or when there is no file. * Returns the path of the argument of 'name' otherwise. * * Shortcut for: afb_req_get(req, name).path */ static inline const char *afb_req_path(struct afb_req req, const char *name) { return afb_req_get(req, name).path; } ``` The path is only defined for HTTP/POST requests that send file. ### Arguments for received files As it is explained above, clients can send files using HTTP/POST requests. Received files are attached to "file" argument name. For example, the following HTTP fragment (from test/sample-post.html) will send an HTTP/POST request to the method **post/upload-image** with 2 arguments named *file* and *hidden*. ```html <h2>Sample Post File</h2> <form enctype="multipart/form-data"> <input type="file" name="file" /> <input type="hidden" name="hidden" value="bollobollo" /> <br> <button formmethod="POST" formaction="api/post/upload-image">Post File</button> </form> ``` Argument named **file** should have both its value and path defined. The value is the name of the file as it was set by the HTTP client. Generally it is the filename on client side. The path is the effective path of saved file on the temporary local storage area of the application. This is a randomly generated and unique filename. It is not linked with the original filename as used on client side. After success the binding can use the uploaded file directly from local storage path with no restriction: read, write, remove, copy, rename... Nevertheless when request reply is set and query terminated, the uploaded temporary file at path is destroyed. ### Arguments as a JSON object Bindings may also request every arguments of a given call as one single object. This feature is provided by the function **afb_req_json** defined here after: ```C /* * Gets from the request 'req' the json object hashing the arguments. * The returned object must not be released using 'json_object_put'. */ struct json_object *afb_req_json(struct afb_req req); ``` It returns a json object. This object depends on how the request was built: - For HTTP requests, this json object uses key names mapped on argument name. Values are either string for common arguments or object ie: { "file": "...", "path": "..." } - For WebSockets requests, returned directly the object as provided by the client. > In fact, for Websockets requests, the function **afb_req_value** > can be seen as a shortcut to > ***json_object_get_string(json_object_object_get(afb_req_json(req), name))*** Writing an asynchronous method implementation ------------------------------------------- The *tic-tac-toe* example allows two clients or more to share the same board. This is implemented by the method **join** that illustrated partly how to retrieve arguments. When two or more clients are sharing a same board, one of them can wait until the state of the board changes, but this could also be implemented using events because an event is generated each time the board changes. In this case, the reply to the wait is sent only when the board changes. See the diagram below: ![tic-tac-toe_diagram][tic-tac-toe_diagram] Here, this is an invocation of the binding by an other client that unblock the suspended *wait* call. Nevertheless in most case this should be a timer, a hardware event, a sync with a concurrent process or thread, ... Common case of an asynchronous implementation. Here is the listing of the function **wait**: ```C static void wait(struct afb_req req) { struct board *board; struct waiter *waiter; /* retrieves the context for the session */ board = board_of_req(req); INFO(afbitf, "method 'wait' called for boardid %d", board->id); /* creates the waiter and enqueues it */ waiter = calloc(1, sizeof *waiter); waiter->req = req; waiter->next = board->waiters; afb_req_addref(req); board->waiters = waiter; } ``` After retrieving the board, the function adds a new waiter to waiters list and returns without setting a reply. Before returning, it increases **req** request's reference count using **afb_req_addref** function. > When a method returns without setting a reply, > it **MUST** increment request's reference count > using **afb_req_addref**. If unpredictable behaviour may pop up. Later, when a board changes, it calls *tic-tac-toe* **changed** function with reason of change in parameter. Here is the full listing of the function **changed**: ```C /* * signals a change of the board */ static void changed(struct board *board, const char *reason) { struct waiter *waiter, *next; struct json_object *description; /* get the description */ description = describe(board); waiter = board->waiters; board->waiters = NULL; while (waiter != NULL) { next = waiter->next; afb_req_success(waiter->req, json_object_get(description), reason); afb_req_unref(waiter->req); free(waiter); waiter = next; } afb_event_sender_push(afb_daemon_get_event_sender(afbitf->daemon), reason, description); } ``` The list of waiters is walked and a reply is sent to each waiter. After sending the reply, the reference count of the request is decremented using **afb_req_unref** to allow resources to be freed. > The reference count **MUST** be decremented using **afb_req_unref** to free > resources and avoid memory leaks. > This usage count decrement should happen **AFTER** setting reply or > bad things may happen. Sending messages to the log system ---------------------------------- Afb-daemon provides 4 levels of verbosity and 5 methods for logging messages. The verbosity is managed. Options allow the change the verbosity of ***afb-daemon*** and the verbosity of the bindings can be set binding by binding. The methods for logging messages are defined as macros that test the verbosity level and that call the real logging function only if the message must be output. This avoid evaluation of arguments of the formatting messages if the message must not be output. ### Verbs for logging messages The 5 logging methods are: Macro | Verbosity | Meaning | syslog level --------|:---------:|-----------------------------------|:-----------: ERROR | 0 | Error conditions | 3 WARNING | 1 | Warning conditions | 4 NOTICE | 1 | Normal but significant condition | 5 INFO | 2 | Informational | 6 DEBUG | 3 | Debug-level messages | 7 You can note that the 2 methods **WARNING** and **NOTICE** have the same level of verbosity. But they don't have the same *syslog level*. It means that they are output with a different level on the logging system. All of these methods have the same signature: ```C void ERROR(const struct afb_binding_interface *afbitf, const char *message, ...); ``` The first argument **afbitf** is the interface to afb daemon that the binding received at initialisation time when **afbBindingV1Register** is called. The second argument **message** is a formatting string compatible with printf/sprintf. The remaining arguments are arguments of the formating message like with printf. ### Managing verbosity Depending on the level of verbosity, the messages are output or not. The following table explains what messages will be output depending ont the verbosity level. Level of verbosity | Outputed macro :-----------------:|-------------------------- 0 | ERROR 1 | ERROR + WARNING + NOTICE 2 | ERROR + WARNING + NOTICE + INFO 3 | ERROR + WARNING + NOTICE + INFO + DEBUG ### Output format and destination The syslog level is used for forging a prefix to the message. The prefixes are: syslog level | prefix :-----------:|--------------- 0 | <0> EMERGENCY 1 | <1> ALERT 2 | <2> CRITICAL 3 | <3> ERROR 4 | <4> WARNING 5 | <5> NOTICE 6 | <6> INFO 7 | <7> DEBUG The message is pushed to standard error. The final destination of the message depends on how systemd service was configured through its variable **StandardError**. It can be journal, syslog or kmsg. (See man sd-daemon). Sending events -------------- Since version 0.5, bindings can broadcast events to any potential listener. As today only unattended events are supported. Targeted events are expected for next coming version. The binding *tic-tac-toe* broadcasts events when the board changes. This is done in the function **changed**: ```C /* * signals a change of the board */ static void changed(struct board *board, const char *reason) { ... struct json_object *description; /* get the description */ description = describe(board); ... afb_daemon_broadcast_event(afbitf->daemon, reason, description); } ``` The description of the changed board is pushed via the daemon interface. Within binding *tic-tac-toe*, *reason* indicates the origin of the change. In function **afb_daemon_broadcast_event** the second parameter is the name of broadcasted event. The third argument is the object that is transmitted with the event. Function **afb_daemon_broadcast_event** is defined here after: ```C /* * Broadcasts widely the event of 'name' with the data 'object'. * 'object' can be NULL. * 'daemon' MUST be the daemon given in interface when activating the binding. * * For convenience, the function calls 'json_object_put' for 'object'. * Thus, in the case where 'object' should remain available after * the function returns, the function 'json_object_get' shall be used. */ void afb_daemon_broadcast_event(struct afb_daemon daemon, const char *name, struct json_object *object); ``` > Be aware, as with reply functions **object** is automatically released using > **json_object_put** when using this function. Call **json_object_get** before > calling **afb_daemon_broadcast_event** to keep **object** available > after function returns. Event name received by listeners is prefixed with binding name. So when a change occurs after a move, the reason is **move** and every clients receive an event **tictactoe/move**. > Note that nothing is said about case sensitivity of event names. > However, the event is always prefixed with the name that the binding > declared, with the same case, followed with a slash /. > Thus it is safe to compare event using a case sensitive comparison. How to build a binding --------------------- Afb-daemon provides a *pkg-config* configuration file that can be queried by providing ***afb-daemon*** in command line arguments. This configuration file provides data that should be used for bindings compilation. Examples: ```bash $ pkg-config --cflags afb-daemon $ pkg-config --libs afb-daemon ``` ### Example for cmake meta build system This example is the extract for building the binding *afm-main* using *CMAKE*. ```cmake pkg_check_modules(afb afb-daemon) if(afb_FOUND) message(STATUS "Creation afm-main-binding for AFB-DAEMON") add_library(afm-main-binding MODULE afm-main-binding.c) target_compile_options(afm-main-binding PRIVATE ${afb_CFLAGS}) target_include_directories(afm-main-binding PRIVATE ${afb_INCLUDE_DIRS}) target_link_libraries(afm-main-binding utils ${afb_LIBRARIES}) set_target_properties(afm-main-binding PROPERTIES PREFIX "" LINK_FLAGS "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/afm-main-binding.export-map" ) install(TARGETS afm-main-binding LIBRARY DESTINATION ${binding_dir}) else() message(STATUS "Not creating the binding for AFB-DAEMON") endif() ``` Let now describe some of these lines. ```cmake pkg_check_modules(afb afb-daemon) ``` This first lines searches to the *pkg-config* configuration file for **afb-daemon**. Resulting data are stored in the following variables: Variable | Meaning ------------------|------------------------------------------------ afb_FOUND | Set to 1 if afb-daemon binding development files exist afb_LIBRARIES | Only the libraries (w/o the '-l') for compiling afb-daemon bindings afb_LIBRARY_DIRS | The paths of the libraries (w/o the '-L') for compiling afb-daemon bindings afb_LDFLAGS | All required linker flags for compiling afb-daemon bindings afb_INCLUDE_DIRS | The '-I' preprocessor flags (w/o the '-I') for compiling afb-daemon bindings afb_CFLAGS | All required cflags for compiling afb-daemon bindings If development files are found, the binding can be added to the set of target to build. ```cmake add_library(afm-main-binding MODULE afm-main-binding.c) ``` This line asks to create a shared library having a single source file named afm-main-binding.c to be compiled. The default name of the created shared object is **libafm-main-binding.so**. ```cmake set_target_properties(afm-main-binding PROPERTIES PREFIX "" LINK_FLAGS "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/afm-main-binding.export-map" ) ``` This lines are doing two things: 1. It renames the built library from **libafm-main-binding.so** to **afm-main-binding.so** by removing the implicitly added prefix *lib*. This step is not mandatory because afb-daemon doesn't check names of files at load time. The only filename convention used by afb-daemon relates to **.so** termination. *.so pattern is used when afb-daemon automatically discovers binding from a directory hierarchy. 2. It applies a version script at link time to only export the reserved name **afbBindingV1Register** for registration entry point. By default, when building a shared library linker exports all the public symbols (C functions that are not **static**). Next line are: ```cmake target_include_directories(afm-main-binding PRIVATE ${afb_INCLUDE_DIRS}) target_link_libraries(afm-main-binding utils ${afb_LIBRARIES}) ``` As you can see it uses the variables computed by ***pkg_check_modules(afb afb-daemon)*** to configure the compiler and the linker. ### Exporting the function afbBindingV1Register The function **afbBindingV1Register** MUST be exported. This can be achieved using a version script at link time. Here after is a version script used for *tic-tac-toe* (bindings/samples/export.map). { global: afbBindingV1Register; local: *; }; This sample [version script](https://sourceware.org/binutils/docs-2.26/ld/VERSION.html#VERSION) exports as global the symbol *afbBindingV1Register* and hides any other symbols. This version script is added to the link options using the option **--version-script=export.map** is given directly to the linker or using the option **-Wl,--version-script=export.map** when the option is given to the C compiler. ### Building within yocto Adding a dependency to afb-daemon is enough. See below: DEPENDS += " afb-daemon " [tic-tac-toe_diagram]: pictures/tic-tac-toe.svg