1 HOWTO WRITE a PLUGIN for AFB-DAEMON
2 ===================================
12 The binder afb-daemon serves files through HTTP protocol
13 and offers to developers the capability to expose application APIs through
14 HTTP or WebSocket protocol.
16 Binder plugins are used to add API to afb-daemon.
17 This part describes how to write a plugin for afb-daemon.
18 Excepting this summary, this part is intended to be read
21 Before moving further through an example, here after
22 a short overview of binder plugins fundamentals.
24 ### Nature of a plugin
26 A plugin is an independent piece of software, self contain and expose as a dynamically loadable library.
27 A plugin is loaded by afb-daemon that exposes contained API dynamically at runtime.
29 Technically, a binder plugins does not reference and is not linked with any library from afb-daemon.
33 Application binder supports two kinds of plugins: application plugins and service
34 plugins. Technically both class of plugin are equivalent and coding API is shared. Only sharing mode and security context diverge.
36 #### Application-plugins
38 Application-plugins implements the glue in between application's UI and services. Every AGL application
39 has a corresponding binder that typically activates one or many plugins to interface the application logic with lower platform services.
40 When an application is started by AGL application framework, a dedicate binder is started that loads/activates application plugin(s).
41 The API expose by application-plugin are executed within corresponding application security context.
43 Application plugins generally handle a unique context for a unique client. As the application framework start
44 a dedicated instance of afb_daemon for each AGL application, if a given plugin is used within multiple application each of those
45 application get a new and private instance of this "shared" plugin.
49 Service-plugins enable API activation within corresponding service security context and not within calling application context.
50 Service-plugins are intended to run as a unique instance that is shared in between multiple clients.
52 Service-plugins can either be stateless or manage client context. When managing context each client get a private context.
54 Sharing may either be global to the platform (ie: GPS service) or dedicated to a given user (ie: preference management)
56 ### Live cycle of plugins within afb-daemon
58 Application and service plugins are loaded and activated each time a new afb-daemon is started.
60 At launch time, every loaded plugin initialise itself.
61 If a single plugin initialisation fail corresponding instance of afb-daemon self aborts.
63 Conversely, when plugin initialisation succeeds, it should register
64 its unique name and the list of API verbs it exposes.
66 When initialised, on request from clients plugin's function corresponding to expose API verbs
67 are activated by the afb-daemon instance attached to the application or service.
69 At exit time, no special action is enforced by afb-daemon. When a specific actions is required at afb-daemon stop,
70 developers should use 'atexit/on_exit' during plugin initialisation sequence to register a custom exit function.
74 Afb-daemon's plugin register two classes of objects: names and functions.
76 Plugins declare categories of names:
77 - A unique plugin name,
78 - Multiple API verb's names.
80 Plugins declare two categories of functions:
81 - initialisation function
82 - API functions implementing verbs
84 Afb-daemon parses URI requests to extract plugin name and API verb.
85 As an example, URI **foo/bar** translates to API verb named **bar** within plugin named **foo**.
86 To serve such a request, afb-daemon looks for an active plugin named **foo** and then within this plugin for an API verb named **bar**.
87 When find afb-daemon calls corresponding function with attached parameter if any.
89 Afb-daemon ignores letter case when parsing URI. Thus **TicTacToe/Board** and **tictactoe/board** are equivalent.
91 #### The name of the plugin
93 The name of the plugin is also known as the name
94 of the API that defines the plugin.
96 This name is also known as the prefix.
98 The name of a plugin MUST be unique within afb-daemon.
100 For example, when a client of afb-daemon
101 calls a method named **foo/bar**. Afb-daemon
102 extracts the prefix **foo** and the suffix **bar**.
103 **foo** is the API name and must match a plugin name,
104 the plugin that implements the verb **bar**.
108 Each plugin exposes a set of verbs that can be called
109 by client of afb-daemon.
111 The name of a verb MUST be unique within a plugin.
113 Plugins link verbs to functions that are called
114 when clients emit requests for that verb.
116 For example, when a client of afb-daemon
117 calls a method named **foo/bar**.
119 #### The initialisation function
121 The initialisation function serves several purposes.
123 1. It allows afb-daemon to check the version
124 of the plugin using the name of the initialisation
125 functions that it found. Currently, the initialisation
126 function is named **pluginAfbV1Register**. It identifies
127 the first version of plugins.
129 2. It allows the plugin to initialise itself.
131 3. It serves to the plugin to declare names, descriptions,
132 requirements and implmentations of the verbs that it exposes.
134 #### Functions implementing verbs
136 When a method is called, afb-daemon constructs a request
137 object and pass it to the implementation function for verb
138 within the plugin of the API.
140 An implementation function receives a request object that
141 is used to get arguments of the request, to send
142 answer, to store session data.
144 A plugin MUST send an answer to the request.
146 But it is not mandatory to send the answer
147 before to return from the implementing function.
148 This behaviour is important for implementing
149 asynchronous actions.
151 Implementation functions that always reply to the request
152 before returning are named *synchronous implementations*.
153 Those that don't always reply to the request before
154 returning are named *asynchronous implementations*.
156 Asynchronous implementations typically initiate an
157 asynchronous action and record to send the reply
158 on completion of this action.
160 The Tic-Tac-Toe example
161 -----------------------
163 This part explains how to write an afb-plugin.
164 For the sake of being practical we will use many
165 examples from the tic-tac-toe example.
166 This plugin example is in *plugins/samples/tic-tac-toe.c*.
168 This plugin is named ***tictactoe***.
170 Dependencies when compiling
171 ---------------------------
173 Afb-daemon provides a configuration file for *pkg-config*.
176 pkg-config --cflags afb-daemon
178 will print the flags to use for compiling, like this:
180 $ pkg-config --cflags afb-daemon
181 -I/opt/local/include -I/usr/include/json-c
183 For linking, you should use
185 $ pkg-config --libs afb-daemon
188 As you see, afb-daemon automatically includes dependency to json-c.
189 This is done through the **Requires** keyword of pkg-config
190 because almost all plugin will use **json-c**.
192 If this behaviour is a problem, let us know.
194 Internally, afb-daemon uses **libsystemd** for its event loop
195 and for its binding to D-Bus.
196 Plugins developpers are encouraged to also use this library.
197 But it is a matter of choice.
198 Thus there is no dependency to **libsystemd**.
200 > Afb-daemon provides no library for plugins.
201 > The functions that the plugin need to have are given
202 > to the plugin at runtime through pointer using read-only
205 Header files to include
206 -----------------------
208 The plugin *tictactoe* has the following lines for its includes:
213 #include <json-c/json.h>
214 #include <afb/afb-plugin.h>
216 The header *afb/afb-plugin.h* includes all the features that a plugin
217 needs except two foreign header that must be included by the plugin
220 - *json-c/json.h*: this header must be include to handle json objects;
221 - *systemd/sd-event.h*: this must be include to access the main loop;
222 - *systemd/sd-bus.h*: this may be include to use dbus connections.
224 The *tictactoe* plugin does not use systemd features so it is not included.
226 When including *afb/afb-plugin.h*, the macro **_GNU_SOURCE** must be
232 The designer of a plugin must defines names for its plugin
233 (or its API) and for the verbs of its API. He also
234 must defines names for arguments given by name.
236 While forging names, the designer should take into account
237 the rules for making valid names and some rules that make
238 the names easy to use across plaforms.
240 The names and strings used ALL are UTF-8 encoded.
242 ### Names for API (plugin)
244 The names of the API are checked.
245 All characters are authorised except:
247 - the control characters (\u0000 .. \u001f)
248 - the characters of the set { ' ', '"', '#', '%', '&',
249 '\'', '/', '?', '`', '\x7f' }
251 In other words the set of forbidden characters is
252 { \u0000..\u0020, \u0022, \u0023, \u0025..\u0027,
253 \u002f, \u003f, \u0060, \u007f }.
255 Afb-daemon make no distinction between lower case
256 and upper case when searching for an API by its name.
260 The names of the verbs are not checked.
262 However, the validity rules for verb's names are the
263 same as for API names except that the dot (.) character
266 Afb-daemon make no distinction between lower case
267 and upper case when searching for an API by its name.
269 ### Names for arguments
271 The names for arguments are not restricted and can be
274 The arguments are searched with the case sensitive
275 string comparison. Thus the names "index" and "Index"
278 ### Forging names widely available
280 The key names of javascript object can be almost
281 anything using the arrayed notation:
285 That is not the case with the dot notation:
289 Using the dot notation, the key must be a valid javascript
292 For this reason, the chosen names should better be
293 valid javascript identifier.
295 It is also a good practice, even for arguments, to not
296 rely on the case sensitivity and to avoid the use of
297 names different only by the case.
299 Writing a synchronous verb implementation
300 -----------------------------------------
302 The verb **tictactoe/board** is a synchronous implementation.
308 static void board(struct afb_req req)
311 struct json_object *description;
313 /* retrieves the context for the session */
314 board = board_of_req(req);
315 INFO(afbitf, "method 'board' called for boardid %d", board->id);
317 /* describe the board */
318 description = describe(board);
320 /* send the board's description */
321 afb_req_success(req, description, NULL);
324 This examples show many aspects of writing a synchronous
325 verb implementation. Let summarize it:
327 1. The function **board_of_req** retrieves the context stored
328 for the plugin: the board.
330 2. The macro **INFO** sends a message of kind *INFO*
331 to the logging system. The global variable named **afbitf**
332 used represents the interface to afb-daemon.
334 3. The function **describe** creates a json_object representing
337 4. The function **afb_req_success** sends the reply, attaching to
338 it the object *description*.
340 ### The incoming request
342 For any implementation, the request is received by a structure of type
345 > Note that this is a PLAIN structure, not a pointer to a structure.
347 The definition of **struct afb_req** is:
350 * Describes the request by plugins from afb-daemon
353 const struct afb_req_itf *itf; /* the interfacing functions */
354 void *closure; /* the closure for functions */
357 It contains two pointers: one, *itf*, points to the functions needed
358 to handle the internal request represented by the second pointer, *closure*.
360 > The structure must never be used directly.
361 > Insted, use the intended functions provided
362 > by afb-daemon and described here.
364 *req* is used to get arguments of the request, to send
365 answer, to store session data.
367 This object and its interface is defined and documented
368 in the file names *afb/afb-req-itf.h*
370 The above example uses 2 times the request object *req*.
372 The first time, it is used for retrieving the board attached to
373 the session of the request.
375 The second time, it is used to send the reply: an object that
376 describes the current board.
378 ### Associating a context to the session
380 When the plugin *tic-tac-toe* receives a request, it musts regain
381 the board that describes the game associated to the session.
383 For a plugin, having data associated to a session is a common case.
384 This data is called the context of the plugin for the session.
385 For the plugin *tic-tac-toe*, the context is the board.
387 The requests *afb_req* offer four functions for
388 storing and retrieving the context associated to the session.
392 - **afb_req_context_get**:
393 retrieves the context data stored for the plugin.
395 - **afb_req_context_set**:
396 store the context data of the plugin.
398 - **afb_req_context**:
399 retrieves the context data of the plugin,
400 if needed, creates the context and store it.
402 - **afb_req_context_clear**:
403 reset the stored data.
405 The plugin *tictactoe* use a convenient function to retrieve
406 its context: the board. This function is *board_of_req*:
409 * retrieves the board of the request
411 static inline struct board *board_of_req(struct afb_req req)
413 return afb_req_context(req, (void*)get_new_board, (void*)release_board);
416 The function **afb_req_context** ensure an existing context
417 for the session of the request.
418 Its two last arguments are functions. Here, the casts are required
419 to avoid a warning when compiling.
421 Here is the definition of the function **afb_req_context**
424 * Gets the pointer stored by the plugin for the session of 'req'.
425 * If the stored pointer is NULL, indicating that no pointer was
426 * already stored, afb_req_context creates a new context by calling
427 * the function 'create_context' and stores it with the freeing function
430 static inline void *afb_req_context(struct afb_req req, void *(*create_context)(), void (*free_context)(void*))
432 void *result = afb_req_context_get(req);
433 if (result == NULL) {
434 result = create_context();
435 afb_req_context_set(req, result, free_context);
440 The second argument if the function that creates the context.
441 For the plugin *tic-tac-toe* it is the function **get_new_board**.
442 The function **get_new_board** creates a new board and set its
443 count of use to 1. The boards are counting their count of use
444 to free there ressources when no more used.
446 The third argument if the function that frees the context.
447 For the plugin *tic-tac-toe* it is the function **release_board**.
448 The function **release_board** decrease the the count of use of
449 the board given as argument. If the use count decrease to zero,
450 the board data are freed.
452 The definition of the other functions for dealing with contexts are:
455 * Gets the pointer stored by the plugin for the session of 'req'.
456 * When the plugin has not yet recorded a pointer, NULL is returned.
458 void *afb_req_context_get(struct afb_req req);
461 * Stores for the plugin the pointer 'context' to the session of 'req'.
462 * The function 'free_context' will be called when the session is closed
463 * or if plugin stores an other pointer.
465 void afb_req_context_set(struct afb_req req, void *context, void (*free_context)(void*));
468 * Frees the pointer stored by the plugin for the session of 'req'
469 * and sets it to NULL.
471 * Shortcut for: afb_req_context_set(req, NULL, NULL)
473 static inline void afb_req_context_clear(struct afb_req req)
475 afb_req_context_set(req, NULL, NULL);
478 ### Sending the reply to a request
480 Two kinds of replies can be made: successful replies and
483 > Sending a reply to a request must be done at most one time.
485 The two functions to send a reply of kind "success" are
486 **afb_req_success** and **afb_req_success_f**.
489 * Sends a reply of kind success to the request 'req'.
490 * The status of the reply is automatically set to "success".
491 * Its send the object 'obj' (can be NULL) with an
492 * informationnal comment 'info (can also be NULL).
494 * For conveniency, the function calls 'json_object_put' for 'obj'.
495 * Thus, in the case where 'obj' should remain available after
496 * the function returns, the function 'json_object_get' shall be used.
498 void afb_req_success(struct afb_req req, struct json_object *obj, const char *info);
501 * Same as 'afb_req_success' but the 'info' is a formatting
502 * string followed by arguments.
504 * For conveniency, the function calls 'json_object_put' for 'obj'.
505 * Thus, in the case where 'obj' should remain available after
506 * the function returns, the function 'json_object_get' shall be used.
508 void afb_req_success_f(struct afb_req req, struct json_object *obj, const char *info, ...);
510 The two functions to send a reply of kind "failure" are
511 **afb_req_fail** and **afb_req_fail_f**.
514 * Sends a reply of kind failure to the request 'req'.
515 * The status of the reply is set to 'status' and an
516 * informationnal comment 'info' (can also be NULL) can be added.
518 * Note that calling afb_req_fail("success", info) is equivalent
519 * to call afb_req_success(NULL, info). Thus even if possible it
520 * is strongly recommanded to NEVER use "success" for status.
522 * For conveniency, the function calls 'json_object_put' for 'obj'.
523 * Thus, in the case where 'obj' should remain available after
524 * the function returns, the function 'json_object_get' shall be used.
526 void afb_req_fail(struct afb_req req, const char *status, const char *info);
529 * Same as 'afb_req_fail' but the 'info' is a formatting
530 * string followed by arguments.
532 * For conveniency, the function calls 'json_object_put' for 'obj'.
533 * Thus, in the case where 'obj' should remain available after
534 * the function returns, the function 'json_object_get' shall be used.
536 void afb_req_fail_f(struct afb_req req, const char *status, const char *info, ...);
538 > For conveniency, these functions call **json_object_put** to release the object **obj**
539 > that they send. Then **obj** can not be used after calling one of these reply functions.
540 > When it is not the expected behaviour, calling the function **json_object_get** on the object **obj**
541 > before cancels the effect of **json_object_put**.
543 Getting argument of invocation
544 ------------------------------
546 Many verbs expect arguments. Afb-daemon let plugins
547 retrieve their arguments by name not by position.
549 Arguments are given by the requests either through HTTP
550 or through WebSockets.
552 For example, the verb **join** of the plugin **tic-tac-toe**
553 expects one argument: the *boardid* to join. Here is an extract:
558 static void join(struct afb_req req)
560 struct board *board, *new_board;
563 /* retrieves the context for the session */
564 board = board_of_req(req);
565 INFO(afbitf, "method 'join' called for boardid %d", board->id);
567 /* retrieves the argument */
568 id = afb_req_value(req, "boardid");
573 The function **afb_req_value** search in the request *req*
574 for an argument whose name is given. When no argument of the
575 given name was passed, **afb_req_value** returns NULL.
577 > The search is case sensitive. So the name *boardid* is not the
578 > same name than *BoardId*. But this must not be assumed so two
579 > expected names of argument should not differ only by case.
581 ### Basic functions for querying arguments
583 The function **afb_req_value** is defined as below:
586 * Gets from the request 'req' the string value of the argument of 'name'.
587 * Returns NULL if when there is no argument of 'name'.
588 * Returns the value of the argument of 'name' otherwise.
590 * Shortcut for: afb_req_get(req, name).value
592 static inline const char *afb_req_value(struct afb_req req, const char *name)
594 return afb_req_get(req, name).value;
597 It is defined as a shortcut to call the function **afb_req_get**.
598 That function is defined as below:
601 * Gets from the request 'req' the argument of 'name'.
602 * Returns a PLAIN structure of type 'struct afb_arg'.
603 * When the argument of 'name' is not found, all fields of result are set to NULL.
604 * When the argument of 'name' is found, the fields are filled,
605 * in particular, the field 'result.name' is set to 'name'.
607 * There is a special name value: the empty string.
608 * The argument of name "" is defined only if the request was made using
609 * an HTTP POST of Content-Type "application/json". In that case, the
610 * argument of name "" receives the value of the body of the HTTP request.
612 struct afb_arg afb_req_get(struct afb_req req, const char *name);
614 That function takes 2 parameters: the request and the name
615 of the argument to retrieve. It returns a PLAIN structure of
616 type **struct afb_arg**.
618 There is a special name that is defined when the request is
619 of type HTTP/POST with a Content-Type being application/json.
620 This name is **""** (the empty string). In that case, the value
621 of this argument of empty name is the string received as a body
622 of the post and is supposed to be a JSON string.
624 The definition of **struct afb_arg** is:
627 * Describes an argument (or parameter) of a request
630 const char *name; /* name of the argument or NULL if invalid */
631 const char *value; /* string representation of the value of the argument */
632 /* original filename of the argument if path != NULL */
633 const char *path; /* if not NULL, path of the received file for the argument */
634 /* when the request is finalized this file is removed */
637 The structure returns the data arguments that are known for the
638 request. This data include a field named **path**. This **path**
639 can be accessed using the function **afb_req_path** defined as
643 * Gets from the request 'req' the path for file attached to the argument of 'name'.
644 * Returns NULL if when there is no argument of 'name' or when there is no file.
645 * Returns the path of the argument of 'name' otherwise.
647 * Shortcut for: afb_req_get(req, name).path
649 static inline const char *afb_req_path(struct afb_req req, const char *name)
651 return afb_req_get(req, name).path;
654 The path is only defined for HTTP/POST requests that send file.
656 ### Arguments for received files
658 As it is explained just above, clients can send files using
661 Received files are attached to a arguments. For example, the
662 following HTTP fragment (from test/sample-post.html)
663 will send an HTTP/POST request to the method
664 **post/upload-image** with 2 arguments named *file* and
667 <h2>Sample Post File</h2>
668 <form enctype="multipart/form-data">
669 <input type="file" name="file" />
670 <input type="hidden" name="hidden" value="bollobollo" />
672 <button formmethod="POST" formaction="api/post/upload-image">Post File</button>
675 In that case, the argument named **file** has its value and its
676 path defined and not NULL.
678 The value is the name of the file as it was
679 set by the HTTP client and is generally the filename on the
682 The path is the path of the file saved on the temporary local storage
683 area of the application. This is a randomly generated and unic filename
684 not linked in any way with the original filename on the client.
686 The plugin can use the file at the given path the way that it wants:
687 read, write, remove, copy, rename...
688 But when the reply is sent and the query is terminated, the file at
689 this path is destroyed if it still exist.
691 ### Arguments as a JSON object
693 Plugins can get all the arguments as one single object.
694 This feature is provided by the function **afb_req_json**
695 that is defined as below:
698 * Gets from the request 'req' the json object hashing the arguments.
699 * The returned object must not be released using 'json_object_put'.
701 struct json_object *afb_req_json(struct afb_req req);
703 It returns a json object. This object depends on how the request was
706 - For HTTP requests, this is an object whose keys are the names of the
707 arguments and whose values are either a string for common arguments or
708 an object like { "file": "...", "path": "..." }
710 - For WebSockets requests, the returned object is the object
711 given by the client transparently transported.
713 > In fact, for Websockets requests, the function **afb_req_value**
714 > can be seen as a shortcut to
715 > ***json_object_get_string(json_object_object_get(afb_req_json(req), name))***
717 Initialisation of the plugin and declaration of verbs
718 -----------------------------------------------------
720 To be active, the verbs of the plugin should be declared to
721 afb-daemon. And even more, the plugin itself must be recorded.
723 The mechanism for doing this is very simple: when afb-need starts,
724 it loads the plugins that are listed in its argument or configuration.
726 Loading a plugin follows the following steps:
728 1. It loads the plugin using *dlopen*.
730 2. It searchs for the symbol named **pluginAfbV1Register** using *dlsym*.
731 This symbol is assumed to be the exported initialisation function of the plugin.
733 3. It build an interface object for the plugin.
735 4. It calls the found function **pluginAfbV1Register** and pass it the pointer
738 5. The function **pluginAfbV1Register** setup the plugin, initialize it.
740 6. The function **pluginAfbV1Register** returns the pointer to a structure
741 that describes the plugin: its version, its name (prefix or API name), and the
744 7. Afb-daemon checks that the returned version and name can be managed.
745 If it can manage it, the plugin and its verbs are recorded and can be used
746 when afb-daemon finishes it initialisation.
748 Here is the listing of the function **pluginAfbV1Register** of the plugin
752 * activation function for registering the plugin called by afb-daemon
754 const struct AFB_plugin *pluginAfbV1Register(const struct AFB_interface *itf)
756 afbitf = itf; // records the interface for accessing afb-daemon
757 return &plugin_description; // returns the description of the plugin
760 This is a very small function because the *tic-tac-toe* plugin doesn't have initialisation step.
761 It merely record the daemon's interface and returns its descritption.
763 The variable **afbitf** is a variable global to the plugin. It records the
764 interface to afb-daemon and is used for logging and pushing events.
765 Here is its declaration:
768 * the interface to afb-daemon
770 const struct AFB_interface *afbitf;
772 The description of the plugin is defined as below.
775 * array of the verbs exported to afb-daemon
777 static const struct AFB_verb_desc_v1 plugin_verbs[] = {
778 /* VERB'S NAME SESSION MANAGEMENT FUNCTION TO CALL SHORT DESCRIPTION */
779 { .name= "new", .session= AFB_SESSION_NONE, .callback= new, .info= "Starts a new game" },
780 { .name= "play", .session= AFB_SESSION_NONE, .callback= play, .info= "Asks the server to play" },
781 { .name= "move", .session= AFB_SESSION_NONE, .callback= move, .info= "Tells the client move" },
782 { .name= "board", .session= AFB_SESSION_NONE, .callback= board, .info= "Get the current board" },
783 { .name= "level", .session= AFB_SESSION_NONE, .callback= level, .info= "Set the server level" },
784 { .name= "join", .session= AFB_SESSION_CHECK,.callback= join, .info= "Join a board" },
785 { .name= "undo", .session= AFB_SESSION_NONE, .callback= undo, .info= "Undo the last move" },
786 { .name= "wait", .session= AFB_SESSION_NONE, .callback= wait, .info= "Wait for a change" },
787 { .name= NULL } /* marker for end of the array */
791 * description of the plugin for afb-daemon
793 static const struct AFB_plugin plugin_description =
795 /* description conforms to VERSION 1 */
796 .type= AFB_PLUGIN_VERSION_1,
797 .v1= { /* fills the v1 field of the union when AFB_PLUGIN_VERSION_1 */
798 .prefix= "tictactoe", /* the API name (or plugin name or prefix) */
799 .info= "Sample tac-tac-toe game", /* short description of of the plugin */
800 .verbs = plugin_verbs /* the array describing the verbs of the API */
804 The structure **plugin_description** describes the plugin.
805 It declares the type and version of the plugin, its name, a description
806 and a list of its verbs.
808 The list of verbs is an array of structures describing the verbs and terminated by a marker:
809 a verb whose name is NULL.
811 The description of the verbs for this version is made of 4 fields:
813 - the name of the verbs,
815 - the session management flags,
817 - the implementation function to be call for the verb,
819 - a short description.
821 The structure describing verbs is defined as follows:
824 * Description of one verb of the API provided by the plugin
825 * This enumeration is valid for plugins of type 1
827 struct AFB_verb_desc_v1
829 const char *name; /* name of the verb */
830 enum AFB_session_v1 session; /* authorisation and session requirements of the verb */
831 void (*callback)(struct afb_req req); /* callback function implementing the verb */
832 const char *info; /* textual description of the verb */
835 For technical reasons, the enumeration **enum AFB_session_v1** is not exactly an
836 enumeration but the wrapper of constant definitions that can be mixed using bitwise or
839 The constants that can bit mixed are:
841 Constant name | Meaning
842 -------------------------|-------------------------------------------------------------
843 **AFB_SESSION_CREATE** | Equals to AFB_SESSION_LOA_EQ_0|AFB_SESSION_RENEW
844 **AFB_SESSION_CLOSE** | Closes the session after the reply and set the LOA to 0
845 **AFB_SESSION_RENEW** | Refreshes the token of authentification
846 **AFB_SESSION_CHECK** | Just requires the token authentification
847 **AFB_SESSION_LOA_LE_0** | Requires the current LOA to be lesser then or equal to 0
848 **AFB_SESSION_LOA_LE_1** | Requires the current LOA to be lesser then or equal to 1
849 **AFB_SESSION_LOA_LE_2** | Requires the current LOA to be lesser then or equal to 2
850 **AFB_SESSION_LOA_LE_3** | Requires the current LOA to be lesser then or equal to 3
851 **AFB_SESSION_LOA_GE_0** | Requires the current LOA to be greater then or equal to 0
852 **AFB_SESSION_LOA_GE_1** | Requires the current LOA to be greater then or equal to 1
853 **AFB_SESSION_LOA_GE_2** | Requires the current LOA to be greater then or equal to 2
854 **AFB_SESSION_LOA_GE_3** | Requires the current LOA to be greater then or equal to 3
855 **AFB_SESSION_LOA_EQ_0** | Requires the current LOA to be equal to 0
856 **AFB_SESSION_LOA_EQ_1** | Requires the current LOA to be equal to 1
857 **AFB_SESSION_LOA_EQ_2** | Requires the current LOA to be equal to 2
858 **AFB_SESSION_LOA_EQ_3** | Requires the current LOA to be equal to 3
860 If any of this flags is set, afb-daemon requires the token authentification
861 as if the flag **AFB_SESSION_CHECK** had been set.
863 The special value **AFB_SESSION_NONE** is zero and can be used to avoid any check.
865 > Note that **AFB_SESSION_CREATE** and **AFB_SESSION_CLOSE** might be removed in later versions.
867 Sending messages to the log system
868 ----------------------------------
870 Afb-daemon provides 4 levels of verbosity and 5 verbs for logging messages.
872 The verbosity is managed. Options allow the change the verbosity of afb-daemon
873 and the verbosity of the plugins can be set plugin by plugin.
875 The verbs for logging messages are defined as macros that test the
876 verbosity level and that call the real logging function only if the
877 message must be output. This avoid evaluation of arguments of the
878 formatting messages if the message must not be output.
880 ### Verbs for logging messages
882 The 5 logging verbs are:
884 Macro | Verbosity | Meaning | syslog level
885 --------|:---------:|-----------------------------------|:-----------:
886 ERROR | 0 | Error conditions | 3
887 WARNING | 1 | Warning conditions | 4
888 NOTICE | 1 | Normal but significant condition | 5
889 INFO | 2 | Informational | 6
890 DEBUG | 3 | Debug-level messages | 7
892 You can note that the 2 verbs **WARNING** and **INFO** have the same level
893 of verbosity. But they don't have the same *syslog level*. It means that
894 they are output with a different level on the logging system.
896 All of these verbs have the same signature:
898 void ERROR(const struct AFB_interface *afbitf, const char *message, ...);
900 The first argument **afbitf** is the interface to afb daemon that the
901 plugin received at its initialisation when **pluginAfbV1Register** was called.
903 The second argument **message** is a formatting string compatible with printf/sprintf.
905 The remaining arguments are arguments of the formating message like for printf.
907 ### Managing verbosity
909 Depending on the level of verbosity, the messages are output or not.
910 The following table explains what messages will be output depending
911 ont the verbosity level.
913 Level of verbosity | Outputed macro
914 :-----------------:|--------------------------
916 1 | ERROR + WARNING + NOTICE
917 2 | ERROR + WARNING + NOTICE + INFO
918 3 | ERROR + WARNING + NOTICE + INFO + DEBUG
920 ### Output format and destination
922 The syslog level is used for forging a prefix to the message.
925 syslog level | prefix
926 :-----------:|---------------
937 The message is issued to the standard error.
938 The final destination of the message depends on how the systemd service
939 was configured through the variable **StandardError**: It can be
940 journal, syslog or kmsg. (See man sd-daemon).
945 Since version 0.5, plugins can broadcast events to any potential listener.
946 This kind of bradcast is not targeted. Event targeted will come in a future
947 version of afb-daemon.
949 The plugin *tic-tac-toe* broadcasts events when the board changes.
950 This is done in the function **changed**:
953 * signals a change of the board
955 static void changed(struct board *board, const char *reason)
958 struct json_object *description;
960 /* get the description */
961 description = describe(board);
965 afb_daemon_broadcast_event(afbitf->daemon, reason, description);
968 The description of the changed board is pushed via the daemon interface.
970 Within the plugin *tic-tac-toe*, the *reason* indicates the origin of
971 the change. For the function **afb_daemon_broadcast_event**, the second
972 parameter is the name of the broadcasted event. The third argument is the
973 object that is transmitted with the event.
975 The function **afb_daemon_broadcast_event** is defined as below:
978 * Broadcasts widely the event of 'name' with the data 'object'.
979 * 'object' can be NULL.
980 * 'daemon' MUST be the daemon given in interface when activating the plugin.
982 * For conveniency, the function calls 'json_object_put' for 'object'.
983 * Thus, in the case where 'object' should remain available after
984 * the function returns, the function 'json_object_get' shall be used.
986 void afb_daemon_broadcast_event(struct afb_daemon daemon, const char *name, struct json_object *object);
988 > Be aware, as for reply functions, the **object** is automatically released using
989 > **json_object_put** by the function. Then call **json_object_get** before
990 > calling **afb_daemon_broadcast_event** to keep **object** available
991 > after the returning of the function.
993 In fact the event name received by the listener is prefixed with
994 the name of the plugin. So when the change occurs after a move, the
995 reason is **move** and then the clients receive the event **tictactoe/move**.
997 > Note that nothing is said about the case sensitivity of event names.
998 > However, the event is always prefixed with the name that the plugin
999 > declared, with the same case, followed with a slash /.
1000 > Thus it is safe to compare event using a case sensitive comparison.
1004 Writing an asynchronous verb implementation
1005 -------------------------------------------
1007 The *tic-tac-toe* example allows two clients or more to share the same board.
1008 This is implemented by the verb **join** that illustrated partly the how to
1011 When two or more clients are sharing a same board, one of them can wait
1012 until the state of the board changes. (This coulded also be implemented using
1013 events because an even is generated each time the board changes).
1015 In this case, the reply to the wait is sent only when the board changes.
1016 See the diagram below:
1018 CLIENT A CLIENT B TIC-TAC-TOE
1020 +--------------|----------------->| wait . . . . . . . .
1025 | +----------------->| move . . . .
1027 | |<-----------------+ success of move .
1029 |<-------------|------------------+ success of wait <
1031 Here, this is an invocation of the plugin by an other client that
1032 unblock the suspended *wait* call.
1033 But in general, this will be a timer, a hardware event, the sync with
1034 a concurrent process or thread, ...
1036 So the case is common, this is an asynchronous implementation.
1038 Here is the listing of the function **wait**:
1040 static void wait(struct afb_req req)
1042 struct board *board;
1043 struct waiter *waiter;
1045 /* retrieves the context for the session */
1046 board = board_of_req(req);
1047 INFO(afbitf, "method 'wait' called for boardid %d", board->id);
1049 /* creates the waiter and enqueues it */
1050 waiter = calloc(1, sizeof *waiter);
1052 waiter->next = board->waiters;
1053 afb_req_addref(req);
1054 board->waiters = waiter;
1057 After retrieving the board, the function adds a new waiter to the
1058 current list of waiters and returns without sending a reply.
1060 Before returning, it increases the reference count of the
1061 request **req** using the function **afb_req_addref**.
1063 > When the implentation of a verb returns without sending a reply,
1064 > it **MUST** increment the reference count of the request
1065 > using **afb_req_addref**. If it doesn't bad things can happen.
1067 Later, when the board changes, it calls the function **changed**
1068 of *tic-tac-toe* with the reason of the change.
1070 Here is the full listing of the function **changed**:
1073 * signals a change of the board
1075 static void changed(struct board *board, const char *reason)
1077 struct waiter *waiter, *next;
1078 struct json_object *description;
1080 /* get the description */
1081 description = describe(board);
1083 waiter = board->waiters;
1084 board->waiters = NULL;
1085 while (waiter != NULL) {
1086 next = waiter->next;
1087 afb_req_success(waiter->req, json_object_get(description), reason);
1088 afb_req_unref(waiter->req);
1093 afb_event_sender_push(afb_daemon_get_event_sender(afbitf->daemon), reason, description);
1096 The list of waiters is walked and a reply is sent to each waiter.
1097 After the sending the reply, the reference count of the request
1098 is decremented using **afb_req_unref** to allow its resources to be freed.
1100 > The reference count **MUST** be decremented using **afb_req_unref** because,
1101 > otherwise, there is a leak of resources.
1102 > It must be decremented **AFTER** the sending of the reply, because, otherwise,
1103 > bad things may happen.
1105 How to build a plugin
1106 ---------------------
1108 Afb-daemon provides a *pkg-config* configuration file that can be
1109 queried by the name **afb-daemon**.
1110 This configuration file provides data that should be used
1111 for compiling plugins. Examples:
1113 $ pkg-config --cflags afb-daemon
1114 $ pkg-config --libs afb-daemon
1116 ### Example for cmake meta build system
1118 This example is the extract for building the plugin *afm-main* using *CMAKE*.
1120 pkg_check_modules(afb afb-daemon)
1122 message(STATUS "Creation afm-main-plugin for AFB-DAEMON")
1123 add_library(afm-main-plugin MODULE afm-main-plugin.c)
1124 target_compile_options(afm-main-plugin PRIVATE ${afb_CFLAGS})
1125 target_include_directories(afm-main-plugin PRIVATE ${afb_INCLUDE_DIRS})
1126 target_link_libraries(afm-main-plugin utils ${afb_LIBRARIES})
1127 set_target_properties(afm-main-plugin PROPERTIES
1129 LINK_FLAGS "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/afm-main-plugin.export-map"
1131 install(TARGETS afm-main-plugin LIBRARY DESTINATION ${plugin_dir})
1133 message(STATUS "Not creating the plugin for AFB-DAEMON")
1136 Let now describe some of these lines.
1138 pkg_check_modules(afb afb-daemon)
1140 This first lines searches to the *pkg-config* configuration file for
1141 **afb-daemon**. Resulting data are stored in the following variables:
1144 ------------------|------------------------------------------------
1145 afb_FOUND | Set to 1 if afb-daemon plugin development files exist
1146 afb_LIBRARIES | Only the libraries (w/o the '-l') for compiling afb-daemon plugins
1147 afb_LIBRARY_DIRS | The paths of the libraries (w/o the '-L') for compiling afb-daemon plugins
1148 afb_LDFLAGS | All required linker flags for compiling afb-daemon plugins
1149 afb_INCLUDE_DIRS | The '-I' preprocessor flags (w/o the '-I') for compiling afb-daemon plugins
1150 afb_CFLAGS | All required cflags for compiling afb-daemon plugins
1152 If development files are found, the plugin can be added to the set of
1155 add_library(afm-main-plugin MODULE afm-main-plugin.c)
1157 This line asks to create a shared library having only the
1158 source file afm-main-plugin.c (that is compiled).
1159 The default name of the created shared object is
1160 **libafm-main-plugin.so**.
1162 set_target_properties(afm-main-plugin PROPERTIES
1164 LINK_FLAGS "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/afm-main-plugin.export-map"
1167 This lines are doing two things:
1169 1. It renames the built library from **libafm-main-plugin.so** to **afm-main-plugin.so**
1170 by removing the implicitely added prefix *lib*. This step is not mandatory
1171 at all because afb-daemon doesn't check names of files when loading it.
1172 The only convention that use afb-daemon is that extension is **.so**
1173 but this convention is used only when afb-daemon discovers plugin
1174 from a directory hierarchy.
1176 2. It applies a version script at link to only export the conventional name
1177 of the entry point: **pluginAfbV1Register**. See below. By default, the linker
1178 that creates the shared object exports all the public symbols (C functions that
1179 are not **static**).
1183 target_include_directories(afm-main-plugin PRIVATE ${afb_INCLUDE_DIRS})
1184 target_link_libraries(afm-main-plugin utils ${afb_LIBRARIES})
1186 As you can see it uses the variables computed by ***pkg_check_modules(afb afb-daemon)***
1187 to configure the compiler and the linker.
1189 ### Exporting the function pluginAfbV1Register
1191 The function **pluginAfbV1Register** must be exported. This can be achieved
1192 using a version script when linking. Here is the version script that is
1193 used for *tic-tac-toe* (plugins/samples/export.map).
1195 { global: pluginAfbV1Register; local: *; };
1197 This sample [version script](https://sourceware.org/binutils/docs-2.26/ld/VERSION.html#VERSION)
1198 exports as global the symbol *pluginAfbV1Register* and hides any
1201 This version script is added to the link options using the
1202 option **--version-script=export.map** is given directly to the
1203 linker or using th option **-Wl,--version-script=export.map**
1204 when the option is given to the C compiler.
1206 ### Building within yocto
1208 Adding a dependency to afb-daemon is enough. See below:
1210 DEPENDS += " afb-daemon "