1 HOWTO WRITE a PLUGIN for AFB-DAEMON
2 ===================================
12 Afb-daemon binders serve files through HTTP protocol
13 and offers to developers the capability to expose application API methods 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.
19 Excepting this summary, this document target developers.
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. A plugin is self contain and exposes application logic as sharable library.
27 A plugin is intended to be dynamically loaded by afb-daemon to expose application API.
29 Technically, a binder plugin does not reference and is not linked with any afb-daemon library.
33 Application binder supports two kinds of plugins: application plugins and service plugins.
34 Technically both class of plugin are equivalent are use the same coding convention. 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 the AGL application framework, a dedicate binder is started that loads/activates application plugin(s).
41 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 eventually "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. Service-plugins can be 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: user preferences)
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 a plugin initialisation succeeds, it should register
64 its unique name as well as the list of verbs attached to the methods it exposes.
66 When initialised, on request from application clients to the right API/verb, plugin methods
67 are activated by the afb-daemon 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 to access all API expose by this plugin,
78 - One name for each methods/verbs provided by this plugin.
80 Plugins declare two categories of functions:
81 - function use for the initialisation
82 - functions implementing exposed API methods
84 Afb-daemon parses URI requests to extract the API(plugin name) and the VERB(method to activate).
85 As an example, URI **foo/bar** translates to plugin named **foo** and method named **bar**.
86 To serve such a request, afb-daemon looks for an active plugin named **foo** and then within this plugin for a method named **bar**.
87 When find afb-daemon calls corresponding method 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 a given plugin is also known as the name
94 of the API prefix that defines the plugin.
96 The name of a plugin SHOULD be unique within a given afb-daemon instance.
98 For example, when a client of afb-daemon calls a URI named **foo/bar**. Afb-daemon
99 extracts the prefix **foo** and the suffix **bar**. **foo** must match a plugin name and **bar** a VERB attached to some method.
101 #### Names of methods
103 Each plugin exposes a set of methods that can be called
104 by the clients of a given afb-daemon.
106 VERB's name attached to a given plugin (API) MUST be unique within a plugin.
108 Plugins static declaration link VERBS to corresponding methods.
109 When clients emit requests on a given API/VERB corresponding method is called by afb-daemon.
111 #### Initialisation function
113 Plugin's initialisation function serves several purposes.
115 1. It allows afb-daemon to control plugin version depending on initialisation function name.
116 As today, the only supported initialisation function is **pluginAfbV1Register**. This identifies
117 version "one" of plugins.
119 2. It allows plugins to initialise itself.
121 3. It enables names declarations: descriptions, requirements and implementations of exposed API/VERB.
123 #### Functions instantiation of API/VERBs
125 When an API/VERB is called, afb-daemon constructs a request object. Then it
126 passes this request object to the implementation function corresponding to requested method, this
127 within attached API plugin.
129 An implementation function receives a request object that
130 is used to: get arguments of the request, send
131 answer, store session data.
133 A plugin MUST set an answer to every received requests.
135 Nevertheless it is not mandatory to set the answer
136 before returning from API/VERB implementing function.
137 This behaviour is important for asynchronous actions.
139 API/VERB implementation that set an answer before returning are called *synchronous implementations*.
140 Those that do not systematically set an answer before returning are called *asynchronous implementations*.
142 Asynchronous implementations typically launch asynchronous actions. They record some context at
143 request time and provide answer to the request only at completion of asynchronous actions.
145 The Tic-Tac-Toe example
146 -----------------------
148 This part explains how to write an afb-plugin.
149 For the sake of being practical it uses many
150 examples based on tic-tac-toe.
151 This plugin example is in *plugins/samples/tic-tac-toe.c*.
153 This plugin is named ***tictactoe***.
155 Dependencies when compiling
156 ---------------------------
158 Afb-daemon provides a configuration file for *pkg-config*.
161 pkg-config --cflags afb-daemon
163 Print flags use for compilation:
165 $ pkg-config --cflags afb-daemon
166 -I/opt/local/include -I/usr/include/json-c
168 For linking, you should use
170 $ pkg-config --libs afb-daemon
173 Afb-daemon automatically includes dependency to json-c.
174 This is activated through **Requires** keyword in pkg-config.
175 While almost every plugin replies on **json-c** this is not a must have dependency.
177 Internally, afb-daemon relies on **libsystemd** for its event loop, as well
178 as for its binding to D-Bus.
179 Plugins developers are encouraged to leverage **libsystemd** when possible.
180 Nevertheless there is no hard dependency to **libsystemd** if ever
181 you rather not use it, feel free to do so.
183 > Afb-daemon plugin are fully self contain. They do not enforce dependency on any libraries from the application framework.
184 > Afb-daemon dependencies requirer to run AGL plugins are given at runtime through pointers leveraging read-only
187 Header files to include
188 -----------------------
190 Plugin *tictactoe* has following includes:
195 #include <json-c/json.h>
196 #include <afb/afb-plugin.h>
198 Header *afb/afb-plugin.h* is the only hard dependency, it includes all features
199 that a plugin MUST HAVE. Outside of includes used to support application logic,
200 common external headers used within plugins are:
202 - *json-c/json.h*: should be include to handle json objects;
203 - *systemd/sd-event.h*: should be include to access event main loop;
204 - *systemd/sd-bus.h*: should be include for dbus connections.
206 The *tictactoe* plugin does not leverage systemd features, also only json.h
207 is used on top of mandatory afb/afb-plugin.h.
209 When including *afb/afb-plugin.h*, the macro **_GNU_SOURCE** MUST be
215 Designers of plugins should define a unique name for every API plugin
216 as well as for methods VERBs. They should also define names for request
217 arguments passed as name/value pair in URI.
219 While forging names, designers should respect few rules to
220 ensure that created names are valid and easy to use across platforms.
222 All names and strings are UTF-8 encoded.
224 ### Names for API (plugin)
226 Plugin API name are checked.
227 All characters are authorised except:
229 - the control characters (\u0000 .. \u001f)
230 - the characters of the set { ' ', '"', '#', '%', '&',
231 '\'', '/', '?', '`', '\x7f' }
233 In other words the set of forbidden characters is
234 { \u0000..\u0020, \u0022, \u0023, \u0025..\u0027,
235 \u002f, \u003f, \u0060, \u007f }.
237 Afb-daemon makes no distinction between lower case
238 and upper case when searching for API/VERB.
240 ### Names for methods
242 The names of methods VERBs are totally free and not checked.
244 However, the validity rules for method's VERB name are the
245 same as for Plugin API name except that the dot(.) character
248 Afb-daemon makes no case distinction when searching for an API by name.
250 ### Names for arguments
252 Argument's name are not restricted and can be everything you wish.
254 > Warning arguments search is case sensitive and "index" and "Index"
255 > are not two different arguments.
257 ### Forging names widely available
259 The key names of javascript object can be almost
260 anything using the arrayed notation:
264 Nevertheless this is not the case with javascript dot notation:
268 Using the dot notation, the key must be a valid javascript
269 identifier and dash(-) as well as few other reserved characters cannot be used.
271 For this reason, we advise developper to chose name compatible with both javascript and HTML notation.
273 It is a good practice, even for arguments not to rely on case sensitivity.
274 This may reduce headache strength at debug time, especially with interpreted language like
275 javascript that may not warn you that a variable was not defined.
277 Writing a synchronous method implementation
278 -----------------------------------------
280 The method **tictactoe/board** is a synchronous implementation.
286 static void board(struct afb_req req)
289 struct json_object *description;
291 /* retrieves the context for the session */
292 board = board_of_req(req);
293 INFO(afbitf, "method 'board' called for boardid %d", board->id);
295 /* describe the board */
296 description = describe(board);
298 /* send the board's description */
299 afb_req_success(req, description, NULL);
302 This example shows many aspects of a synchronous
303 method implementation. Let summarise it:
305 1. The function **board_of_req** retrieves the context stored
306 for the plugin: the board.
308 2. The macro **INFO** sends a message of kind *INFO*
309 to the logging system. The global variable named **afbitf**
310 used represents the interface to afb-daemon.
312 3. The function **describe** creates a json_object representing
315 4. The function **afb_req_success** sends the reply, attaching to
316 it the object *description*.
318 ### The incoming request
320 For any implementation, the request is received by a structure of type
323 > Note that this is a PLAIN structure, not a pointer to a structure.
325 The definition of **struct afb_req** is:
328 * Describes the request by plugins from afb-daemon
331 const struct afb_req_itf *itf; /* the interfacing functions */
332 void *closure; /* the closure for functions */
335 It contains two pointers: first one *itf*, points to functions used
336 to handle internal request. Second one *closure* point onto function closure.
338 > The structure must never be used directly.
339 > Instead developer should use the intended functions provided
340 > by afb-daemon as described here after.
342 *req* is used to get arguments of the request, to send
343 answer, to store session data.
345 This object and its interface is defined and documented
346 in the file names *afb/afb-req-itf.h*
348 The above example uses twice *req* object request.
350 The first time, to retrieve the board attached to the session of the request.
352 The second time, to send the reply: an object that describes the current board.
354 ### Associating a client context to a session
356 When *tic-tac-toe* plugin receives a request, it musts get
357 the board describing the game associated to the session.
359 For a plugin, having data associated to a session is common.
360 This data is called "plugin context" for the session.
361 Within *tic-tac-toe* plugin the context is the board.
363 Requests *afb_req* offer four functions for storing and retrieving session associated context.
367 - **afb_req_context_get**:
368 retrieves context data stored for current plugin.
370 - **afb_req_context_set**:
371 store context data of current plugin.
373 - **afb_req_context**:
374 if exist retrieves context data of current plugin.
375 if context does not yet exist, creates a new context and store it.
377 - **afb_req_context_clear**:
378 reset the stored context data.
380 The plugin *tictactoe* use a convenient function to retrieve
381 its context: the board. This function is *board_of_req*:
384 * retrieves the board of the request
386 static inline struct board *board_of_req(struct afb_req req)
388 return afb_req_context(req, (void*)get_new_board, (void*)release_board);
391 The function **afb_req_context** ensures an existing context
392 for the session of the request.
393 Its two last arguments are functions to allocate and free context.
394 Note function type casts to avoid compilation warnings.
396 Here is the definition of the function **afb_req_context**
399 * Gets the pointer stored by the plugin for the session of 'req'.
400 * If the stored pointer is NULL, indicating that no pointer was
401 * already stored, afb_req_context creates a new context by calling
402 * the function 'create_context' and stores it with the freeing function
405 static inline void *afb_req_context(struct afb_req req, void *(*create_context)(), void (*free_context)(void*))
407 void *result = afb_req_context_get(req);
408 if (result == NULL) {
409 result = create_context();
410 afb_req_context_set(req, result, free_context);
415 The second argument if the function that creates the context.
416 For plugin *tic-tac-toe* (function **get_new_board**).
417 The function **get_new_board** creates a new board and set usage its count to 1.
418 The boards are checking usage count to free resources when not used.
420 The third argument is a function that frees context resources.
421 For plugin *tic-tac-toe* (function **release_board**).
422 The function **release_board** decrease usage count of the board passed in argument.
423 When usage count falls to zero, data board are freed.
425 Definition of other functions dealing with contexts:
428 * Gets the pointer stored by the plugin for the session of 'req'.
429 * When the plugin has not yet recorded a pointer, NULL is returned.
431 void *afb_req_context_get(struct afb_req req);
434 * Stores for the plugin the pointer 'context' to the session of 'req'.
435 * The function 'free_context' will be called when the session is closed
436 * or if plugin stores an other pointer.
438 void afb_req_context_set(struct afb_req req, void *context, void (*free_context)(void*));
441 * Frees the pointer stored by the plugin for the session of 'req'
442 * and sets it to NULL.
444 * Shortcut for: afb_req_context_set(req, NULL, NULL)
446 static inline void afb_req_context_clear(struct afb_req req)
448 afb_req_context_set(req, NULL, NULL);
451 ### Sending reply to a request
453 Two kinds of replies: successful or failure.
455 > Sending a reply to a request MUST be done once and only once.
457 It exists two functions for "success" replies: **afb_req_success** and **afb_req_success_f**.
460 * Sends a reply of kind success to the request 'req'.
461 * The status of the reply is automatically set to "success".
462 * Its send the object 'obj' (can be NULL) with an
463 * informationnal comment 'info (can also be NULL).
465 * For conveniency, the function calls 'json_object_put' for 'obj'.
466 * Thus, in the case where 'obj' should remain available after
467 * the function returns, the function 'json_object_get' shall be used.
469 void afb_req_success(struct afb_req req, struct json_object *obj, const char *info);
472 * Same as 'afb_req_success' but the 'info' is a formatting
473 * string followed by arguments.
475 * For conveniency, the function calls 'json_object_put' for 'obj'.
476 * Thus, in the case where 'obj' should remain available after
477 * the function returns, the function 'json_object_get' shall be used.
479 void afb_req_success_f(struct afb_req req, struct json_object *obj, const char *info, ...);
481 It exists two functions for "failure" replies: **afb_req_fail** and **afb_req_fail_f**.
484 * Sends a reply of kind failure to the request 'req'.
485 * The status of the reply is set to 'status' and an
486 * informational comment 'info' (can also be NULL) can be added.
488 * Note that calling afb_req_fail("success", info) is equivalent
489 * to call afb_req_success(NULL, info). Thus even if possible it
490 * is strongly recommended to NEVER use "success" for status.
492 * For conveniency, the function calls 'json_object_put' for 'obj'.
493 * Thus, in the case where 'obj' should remain available after
494 * the function returns, the function 'json_object_get' shall be used.
496 void afb_req_fail(struct afb_req req, const char *status, const char *info);
499 * Same as 'afb_req_fail' but the 'info' is a formatting
500 * string followed by arguments.
502 * For conveniency, the function calls 'json_object_put' for 'obj'.
503 * Thus, in the case where 'obj' should remain available after
504 * the function returns, the function 'json_object_get' shall be used.
506 void afb_req_fail_f(struct afb_req req, const char *status, const char *info, ...);
508 > For conveniency, these functions automatically call **json_object_put** to release **obj**.
509 > Because **obj** usage count is null after being passed to a reply function, it SHOULD not be used anymore.
510 > If exceptionally **obj** needs to remain usable after reply function then using **json_object_get** on **obj**
511 > to increase usage count and cancels the effect the **json_object_put** is possible.
513 Getting argument of invocation
514 ------------------------------
516 Many methods expect arguments. Afb-daemon's plugins
517 retrieve arguments by name and not by position.
519 Arguments are passed by requests through either HTTP
522 For example, the method **join** of plugin **tic-tac-toe**
523 expects one argument: the *boardid* to join. Here is an extract:
528 static void join(struct afb_req req)
530 struct board *board, *new_board;
533 /* retrieves the context for the session */
534 board = board_of_req(req);
535 INFO(afbitf, "method 'join' called for boardid %d", board->id);
537 /* retrieves the argument */
538 id = afb_req_value(req, "boardid");
543 The function **afb_req_value** searches in the request *req*
544 for argument name passed in the second argument. When argument name
545 is not passed, **afb_req_value** returns NULL.
547 > The search is case sensitive and *boardid* is not equivalent to *BoardId*.
548 > Nevertheless having argument names that only differ by name case is not a good idea.
550 ### Basic functions for querying arguments
552 The function **afb_req_value** is defined here after:
555 * Gets from the request 'req' the string value of the argument of 'name'.
556 * Returns NULL if when there is no argument of 'name'.
557 * Returns the value of the argument of 'name' otherwise.
559 * Shortcut for: afb_req_get(req, name).value
561 static inline const char *afb_req_value(struct afb_req req, const char *name)
563 return afb_req_get(req, name).value;
566 It is defined as a shortcut to call the function **afb_req_get**.
567 That function is defined here after:
570 * Gets from the request 'req' the argument of 'name'.
571 * Returns a PLAIN structure of type 'struct afb_arg'.
572 * When the argument of 'name' is not found, all fields of result are set to NULL.
573 * When the argument of 'name' is found, the fields are filled,
574 * in particular, the field 'result.name' is set to 'name'.
576 * There is a special name value: the empty string.
577 * The argument of name "" is defined only if the request was made using
578 * an HTTP POST of Content-Type "application/json". In that case, the
579 * argument of name "" receives the value of the body of the HTTP request.
581 struct afb_arg afb_req_get(struct afb_req req, const char *name);
583 That function takes 2 parameters: the request and the name
584 of the argument to retrieve. It returns a PLAIN structure of
585 type **struct afb_arg**.
587 There is a special name that is defined when the request is
588 of type HTTP/POST with a Content-Type being application/json.
589 This name is **""** (the empty string). In that case, the value
590 of this argument of empty name is the string received as a body
591 of the post and is supposed to be a JSON string.
593 The definition of **struct afb_arg** is:
596 * Describes an argument (or parameter) of a request
599 const char *name; /* name of the argument or NULL if invalid */
600 const char *value; /* string representation of the value of the argument */
601 /* original filename of the argument if path != NULL */
602 const char *path; /* if not NULL, path of the received file for the argument */
603 /* when the request is finalized this file is removed */
606 The structure returns the data arguments that are known for the
607 request. This data include a field named **path**. This **path**
608 can be accessed using the function **afb_req_path** defined here after:
611 * Gets from the request 'req' the path for file attached to the argument of 'name'.
612 * Returns NULL if when there is no argument of 'name' or when there is no file.
613 * Returns the path of the argument of 'name' otherwise.
615 * Shortcut for: afb_req_get(req, name).path
617 static inline const char *afb_req_path(struct afb_req req, const char *name)
619 return afb_req_get(req, name).path;
622 The path is only defined for HTTP/POST requests that send file.
624 ### Arguments for received files
626 As it is explained above, clients can send files using HTTP/POST requests.
628 Received files are attached to "file" argument name. For example, the
629 following HTTP fragment (from test/sample-post.html)
630 will send an HTTP/POST request to the method
631 **post/upload-image** with 2 arguments named *file* and
634 <h2>Sample Post File</h2>
635 <form enctype="multipart/form-data">
636 <input type="file" name="file" />
637 <input type="hidden" name="hidden" value="bollobollo" />
639 <button formmethod="POST" formaction="api/post/upload-image">Post File</button>
642 Argument named **file** should have both its value and path defined.
644 The value is the name of the file as it was set by the HTTP client.
645 Generally it is the filename on client side.
647 The path is the effective path of saved file on the temporary local storage
648 area of the application. This is a randomly generated and unique filename.
649 It is not linked with the original filename as used on client side.
651 After success the plugin can use the uploaded file directly from local storage path with no restriction:
652 read, write, remove, copy, rename...
653 Nevertheless when request reply is set and query terminated, the uploaded temporary file at
656 ### Arguments as a JSON object
658 Plugins may also request every arguments of a given call as one single object.
659 This feature is provided by the function **afb_req_json** defined here after:
662 * Gets from the request 'req' the json object hashing the arguments.
663 * The returned object must not be released using 'json_object_put'.
665 struct json_object *afb_req_json(struct afb_req req);
667 It returns a json object. This object depends on how the request was built:
669 - For HTTP requests, this json object uses key names mapped on argument name.
670 Values are either string for common arguments or object ie: { "file": "...", "path": "..." }
672 - For WebSockets requests, returned directly the object as provided by the client.
674 > In fact, for Websockets requests, the function **afb_req_value**
675 > can be seen as a shortcut to
676 > ***json_object_get_string(json_object_object_get(afb_req_json(req), name))***
678 Initialisation of the plugin and declaration of methods
679 -----------------------------------------------------
681 To be active, plugin's methods should be declared to
682 afb-daemon. Furthermore, the plugin itself must be recorded.
684 The registration mechanism is very basic: when afb-need starts,
685 it loads all plugins listed in: command line or configuration file.
687 Loading a plugin follows the following steps:
689 1. Afb-daemon loads the plugin with *dlopen*.
691 2. Afb-daemon searches for a symbol named **pluginAfbV1Register** using *dlsym*.
692 This symbol is assumed to be the exported initialisation function of the plugin.
694 3. Afb-daemon builds an interface object for the plugin.
696 4. Afb-daemon calls the found function **pluginAfbV1Register** with interface pointer
699 5. Function **pluginAfbV1Register** setups the plugin and initialises it.
701 6. Function **pluginAfbV1Register** returns the pointer to a structure
702 describing the plugin: version, name (prefix or API name), and list of methods.
704 7. Afb-daemon checks that the returned version and name can be managed.
705 If so, plugin and its methods are register to become usable as soon as
706 afb-daemon initialisation is finished.
708 Here after the code used for **pluginAfbV1Register** from plugin *tic-tac-toe*:
711 * activation function for registering the plugin called by afb-daemon
713 const struct AFB_plugin *pluginAfbV1Register(const struct AFB_interface *itf)
715 afbitf = itf; // records the interface for accessing afb-daemon
716 return &plugin_description; // returns the description of the plugin
719 It is a very minimal initialisation function because *tic-tac-toe* plugin doesn't
720 have any application related initialisation step. It merely record daemon's interface
721 and returns its description.
723 The variable **afbitf** is a plugin global variable. It keeps the
724 interface to afb-daemon that should be used for logging and pushing events.
725 Here is its declaration:
728 * the interface to afb-daemon
730 const struct AFB_interface *afbitf;
732 The description of the plugin is defined here after.
735 * array of the methods exported to afb-daemon
737 static const struct AFB_method_desc_v1 plugin_methods[] = {
738 /* VERB'S NAME SESSION MANAGEMENT FUNCTION TO CALL SHORT DESCRIPTION */
739 { .name= "new", .session= AFB_SESSION_NONE, .callback= new, .info= "Starts a new game" },
740 { .name= "play", .session= AFB_SESSION_NONE, .callback= play, .info= "Asks the server to play" },
741 { .name= "move", .session= AFB_SESSION_NONE, .callback= move, .info= "Tells the client move" },
742 { .name= "board", .session= AFB_SESSION_NONE, .callback= board, .info= "Get the current board" },
743 { .name= "level", .session= AFB_SESSION_NONE, .callback= level, .info= "Set the server level" },
744 { .name= "join", .session= AFB_SESSION_CHECK,.callback= join, .info= "Join a board" },
745 { .name= "undo", .session= AFB_SESSION_NONE, .callback= undo, .info= "Undo the last move" },
746 { .name= "wait", .session= AFB_SESSION_NONE, .callback= wait, .info= "Wait for a change" },
747 { .name= NULL } /* marker for end of the array */
751 * description of the plugin for afb-daemon
753 static const struct AFB_plugin plugin_description =
755 /* description conforms to VERSION 1 */
756 .type= AFB_PLUGIN_VERSION_1,
757 .v1= { /* fills the v1 field of the union when AFB_PLUGIN_VERSION_1 */
758 .prefix= "tictactoe", /* the API name (or plugin name or prefix) */
759 .info= "Sample tac-tac-toe game", /* short description of of the plugin */
760 .methods = plugin_methods /* the array describing the methods of the API */
764 The structure **plugin_description** describes the plugin.
765 It declares the type and version of the plugin, its name, a short description
766 and its methods list.
768 The list of methods is an array of structures describing the methods and terminated by a NULL marker.
770 In version one of afb-damon plugin, a method description contains 4 fields:
772 - the name of the method,
774 - the session management flags,
776 - the implementation function to be call for the method,
778 - a short description.
780 The structure describing methods is defined as follows:
783 * Description of one method of the API provided by the plugin
784 * This enumeration is valid for plugins of type 1
786 struct AFB_method_desc_v1
788 const char *name; /* name of the method */
789 enum AFB_session_v1 session; /* authorisation and session requirements of the method */
790 void (*callback)(struct afb_req req); /* callback function implementing the method */
791 const char *info; /* textual description of the method */
794 For technical reasons, the enumeration **enum AFB_session_v1** is not exactly an
795 enumeration but the wrapper of constant definitions that can be mixed using bitwise or
798 The constants that can bit mixed are:
800 Constant name | Meaning
801 -------------------------|-------------------------------------------------------------
802 **AFB_SESSION_CREATE** | Equals to AFB_SESSION_LOA_EQ_0|AFB_SESSION_RENEW
803 **AFB_SESSION_CLOSE** | Closes the session after the reply and set the LOA to 0
804 **AFB_SESSION_RENEW** | Refreshes the token of authentification
805 **AFB_SESSION_CHECK** | Just requires the token authentification
806 **AFB_SESSION_LOA_LE_0** | Requires the current LOA to be lesser then or equal to 0
807 **AFB_SESSION_LOA_LE_1** | Requires the current LOA to be lesser then or equal to 1
808 **AFB_SESSION_LOA_LE_2** | Requires the current LOA to be lesser then or equal to 2
809 **AFB_SESSION_LOA_LE_3** | Requires the current LOA to be lesser then or equal to 3
810 **AFB_SESSION_LOA_GE_0** | Requires the current LOA to be greater then or equal to 0
811 **AFB_SESSION_LOA_GE_1** | Requires the current LOA to be greater then or equal to 1
812 **AFB_SESSION_LOA_GE_2** | Requires the current LOA to be greater then or equal to 2
813 **AFB_SESSION_LOA_GE_3** | Requires the current LOA to be greater then or equal to 3
814 **AFB_SESSION_LOA_EQ_0** | Requires the current LOA to be equal to 0
815 **AFB_SESSION_LOA_EQ_1** | Requires the current LOA to be equal to 1
816 **AFB_SESSION_LOA_EQ_2** | Requires the current LOA to be equal to 2
817 **AFB_SESSION_LOA_EQ_3** | Requires the current LOA to be equal to 3
819 If any of this flag is set, afb-daemon requires an authentication token
820 as if **AFB_SESSION_CHECK** flag was also set.
822 The special value **AFB_SESSION_NONE** is zero and can be used to bypass token check.
824 > Note that **AFB_SESSION_CREATE** and **AFB_SESSION_CLOSE** might be removed in later versions.
826 Sending messages to the log system
827 ----------------------------------
829 Afb-daemon provides 4 levels of methodosity and 5 methods for logging messages.
831 The methodosity is managed. Options allow the change the methodosity of afb-daemon
832 and the methodosity of the plugins can be set plugin by plugin.
834 The methods for logging messages are defined as macros that test the
835 methodosity level and that call the real logging function only if the
836 message must be output. This avoid evaluation of arguments of the
837 formatting messages if the message must not be output.
839 ### Verbs for logging messages
841 The 5 logging methods are:
843 Macro | Verbosity | Meaning | syslog level
844 --------|:---------:|-----------------------------------|:-----------:
845 ERROR | 0 | Error conditions | 3
846 WARNING | 1 | Warning conditions | 4
847 NOTICE | 1 | Normal but significant condition | 5
848 INFO | 2 | Informational | 6
849 DEBUG | 3 | Debug-level messages | 7
851 You can note that the 2 methods **WARNING** and **INFO** have the same level
852 of methodosity. But they don't have the same *syslog level*. It means that
853 they are output with a different level on the logging system.
855 All of these methods have the same signature:
857 void ERROR(const struct AFB_interface *afbitf, const char *message, ...);
859 The first argument **afbitf** is the interface to afb daemon that the
860 plugin received at initialisation time when **pluginAfbV1Register** is called.
862 The second argument **message** is a formatting string compatible with printf/sprintf.
864 The remaining arguments are arguments of the formating message like with printf.
866 ### Managing methodosity
868 Depending on the level of methodosity, the messages are output or not.
869 The following table explains what messages will be output depending
870 ont the methodosity level.
872 Level of methodosity | Outputed macro
873 :-----------------:|--------------------------
875 1 | ERROR + WARNING + NOTICE
876 2 | ERROR + WARNING + NOTICE + INFO
877 3 | ERROR + WARNING + NOTICE + INFO + DEBUG
879 ### Output format and destination
881 The syslog level is used for forging a prefix to the message.
884 syslog level | prefix
885 :-----------:|---------------
896 The message is pushed to standard error.
897 The final destination of the message depends on how systemd service
898 was configured through its variable **StandardError**. It can be
899 journal, syslog or kmsg. (See man sd-daemon).
904 Since version 0.5, plugins can broadcast events to any potential listener.
905 As today only unattended even are supported. Targeted events are expected for next
908 The plugin *tic-tac-toe* broadcasts events when the board changes.
909 This is done in the function **changed**:
912 * signals a change of the board
914 static void changed(struct board *board, const char *reason)
917 struct json_object *description;
919 /* get the description */
920 description = describe(board);
924 afb_daemon_broadcast_event(afbitf->daemon, reason, description);
927 The description of the changed board is pushed via the daemon interface.
929 Within plugin *tic-tac-toe*, *reason* indicates the origin of
930 the change. In function **afb_daemon_broadcast_event** the second
931 parameter is the name of broadcasted event. The third argument is the
932 object that is transmitted with the event.
934 Function **afb_daemon_broadcast_event** is defined here after:
937 * Broadcasts widely the event of 'name' with the data 'object'.
938 * 'object' can be NULL.
939 * 'daemon' MUST be the daemon given in interface when activating the plugin.
941 * For conveniency, the function calls 'json_object_put' for 'object'.
942 * Thus, in the case where 'object' should remain available after
943 * the function returns, the function 'json_object_get' shall be used.
945 void afb_daemon_broadcast_event(struct afb_daemon daemon, const char *name, struct json_object *object);
947 > Be aware, as with reply functions **object** is automatically released using
948 > **json_object_put** when using this function. Call **json_object_get** before
949 > calling **afb_daemon_broadcast_event** to keep **object** available
950 > after function returns.
952 Event name received by listeners is prefixed with plugin name.
953 So when a change occurs after a move, the reason is **move** and every clients
954 receive an event **tictactoe/move**.
956 > Note that nothing is said about case sensitivity of event names.
957 > However, the event is always prefixed with the name that the plugin
958 > declared, with the same case, followed with a slash /.
959 > Thus it is safe to compare event using a case sensitive comparison.
963 Writing an asynchronous method implementation
964 -------------------------------------------
966 The *tic-tac-toe* example allows two clients or more to share the same board.
967 This is implemented by the method **join** that illustrated partly how to
970 When two or more clients are sharing a same board, one of them can wait
971 until the state of the board changes, but this could also be implemented using
972 events because an even is generated each time the board changes.
974 In this case, the reply to the wait is sent only when the board changes.
975 See the diagram below:
977 CLIENT A CLIENT B TIC-TAC-TOE
979 +--------------|----------------->| wait . . . . . . . .
984 | +----------------->| move . . . .
986 | |<-----------------+ success of move .
988 |<-------------|------------------+ success of wait <
990 Here, this is an invocation of the plugin by an other client that
991 unblock the suspended *wait* call.
992 Nevertheless in most case this should be a timer, a hardware event, a sync with
993 a concurrent process or thread, ...
995 Common case of an asynchronous implementation.
997 Here is the listing of the function **wait**:
999 static void wait(struct afb_req req)
1001 struct board *board;
1002 struct waiter *waiter;
1004 /* retrieves the context for the session */
1005 board = board_of_req(req);
1006 INFO(afbitf, "method 'wait' called for boardid %d", board->id);
1008 /* creates the waiter and enqueues it */
1009 waiter = calloc(1, sizeof *waiter);
1011 waiter->next = board->waiters;
1012 afb_req_addref(req);
1013 board->waiters = waiter;
1016 After retrieving the board, the function adds a new waiter to
1017 waiters list and returns without setting a reply.
1019 Before returning, it increases **req** request's reference count using **afb_req_addref** function.
1021 > When a method returns without setting a reply,
1022 > it **MUST** increment request's reference count
1023 > using **afb_req_addref**. If unpredictable behaviour may pop up.
1025 Later, when a board changes, it calls *tic-tac-toe* **changed** function
1026 with reason of change in parameter.
1028 Here is the full listing of the function **changed**:
1031 * signals a change of the board
1033 static void changed(struct board *board, const char *reason)
1035 struct waiter *waiter, *next;
1036 struct json_object *description;
1038 /* get the description */
1039 description = describe(board);
1041 waiter = board->waiters;
1042 board->waiters = NULL;
1043 while (waiter != NULL) {
1044 next = waiter->next;
1045 afb_req_success(waiter->req, json_object_get(description), reason);
1046 afb_req_unref(waiter->req);
1051 afb_event_sender_push(afb_daemon_get_event_sender(afbitf->daemon), reason, description);
1054 The list of waiters is walked and a reply is sent to each waiter.
1055 After sending the reply, the reference count of the request
1056 is decremented using **afb_req_unref** to allow resources to be freed.
1058 > The reference count **MUST** be decremented using **afb_req_unref** to free
1059 > resources and avoid memory leaks.
1060 > This usage count decrement should happen **AFTER** setting reply or
1061 > bad things may happen.
1063 How to build a plugin
1064 ---------------------
1066 Afb-daemon provides a *pkg-config* configuration file that can be
1067 queried by providing **afb-daemon** in command line arguments.
1068 This configuration file provides data that should be used
1069 for plugins compilation. Examples:
1071 $ pkg-config --cflags afb-daemon
1072 $ pkg-config --libs afb-daemon
1074 ### Example for cmake meta build system
1076 This example is the extract for building the plugin *afm-main* using *CMAKE*.
1078 pkg_check_modules(afb afb-daemon)
1080 message(STATUS "Creation afm-main-plugin for AFB-DAEMON")
1081 add_library(afm-main-plugin MODULE afm-main-plugin.c)
1082 target_compile_options(afm-main-plugin PRIVATE ${afb_CFLAGS})
1083 target_include_directories(afm-main-plugin PRIVATE ${afb_INCLUDE_DIRS})
1084 target_link_libraries(afm-main-plugin utils ${afb_LIBRARIES})
1085 set_target_properties(afm-main-plugin PROPERTIES
1087 LINK_FLAGS "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/afm-main-plugin.export-map"
1089 install(TARGETS afm-main-plugin LIBRARY DESTINATION ${plugin_dir})
1091 message(STATUS "Not creating the plugin for AFB-DAEMON")
1094 Let now describe some of these lines.
1096 pkg_check_modules(afb afb-daemon)
1098 This first lines searches to the *pkg-config* configuration file for
1099 **afb-daemon**. Resulting data are stored in the following variables:
1102 ------------------|------------------------------------------------
1103 afb_FOUND | Set to 1 if afb-daemon plugin development files exist
1104 afb_LIBRARIES | Only the libraries (w/o the '-l') for compiling afb-daemon plugins
1105 afb_LIBRARY_DIRS | The paths of the libraries (w/o the '-L') for compiling afb-daemon plugins
1106 afb_LDFLAGS | All required linker flags for compiling afb-daemon plugins
1107 afb_INCLUDE_DIRS | The '-I' preprocessor flags (w/o the '-I') for compiling afb-daemon plugins
1108 afb_CFLAGS | All required cflags for compiling afb-daemon plugins
1110 If development files are found, the plugin can be added to the set of
1113 add_library(afm-main-plugin MODULE afm-main-plugin.c)
1115 This line asks to create a shared library having a single
1116 source file named afm-main-plugin.c to be compiled.
1117 The default name of the created shared object is
1118 **libafm-main-plugin.so**.
1120 set_target_properties(afm-main-plugin PROPERTIES
1122 LINK_FLAGS "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/afm-main-plugin.export-map"
1125 This lines are doing two things:
1127 1. It renames the built library from **libafm-main-plugin.so** to **afm-main-plugin.so**
1128 by removing the implicitly added prefix *lib*. This step is not mandatory
1129 because afb-daemon doesn't check names of files at load time.
1130 The only filename convention used by afb-daemon relates to **.so** termination.
1131 *.so pattern is used when afb-daemon automatically discovers plugin from a directory hierarchy.
1133 2. It applies a version script at link time to only export the reserved name
1134 **pluginAfbV1Register** for registration entry point. By default, when building
1135 a shared library linker exports all the public symbols (C functions that are not **static**).
1139 target_include_directories(afm-main-plugin PRIVATE ${afb_INCLUDE_DIRS})
1140 target_link_libraries(afm-main-plugin utils ${afb_LIBRARIES})
1142 As you can see it uses the variables computed by ***pkg_check_modules(afb afb-daemon)***
1143 to configure the compiler and the linker.
1145 ### Exporting the function pluginAfbV1Register
1147 The function **pluginAfbV1Register** MUST be exported. This can be achieved
1148 using a version script at link time. Here after is a version script used for
1149 *tic-tac-toe* (plugins/samples/export.map).
1151 { global: pluginAfbV1Register; local: *; };
1153 This sample [version script](https://sourceware.org/binutils/docs-2.26/ld/VERSION.html#VERSION)
1154 exports as global the symbol *pluginAfbV1Register* and hides any
1157 This version script is added to the link options using the
1158 option **--version-script=export.map** is given directly to the
1159 linker or using the option **-Wl,--version-script=export.map**
1160 when the option is given to the C compiler.
1162 ### Building within yocto
1164 Adding a dependency to afb-daemon is enough. See below:
1166 DEPENDS += " afb-daemon "