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:
196 #include <json-c/json.h>
197 #include <afb/afb-plugin.h>
200 Header *afb/afb-plugin.h* is the only hard dependency, it includes all features
201 that a plugin MUST HAVE. Outside of includes used to support application logic,
202 common external headers used within plugins are:
204 - *json-c/json.h*: should be include to handle json objects;
205 - *systemd/sd-event.h*: should be include to access event main loop;
206 - *systemd/sd-bus.h*: should be include for dbus connections.
208 The *tictactoe* plugin does not leverage systemd features, also only json.h
209 is used on top of mandatory afb/afb-plugin.h.
211 When including *afb/afb-plugin.h*, the macro **_GNU_SOURCE** MUST be
217 Designers of plugins should define a unique name for every API plugin
218 as well as for methods VERBs. They should also define names for request
219 arguments passed as name/value pair in URI.
221 While forging names, designers should respect few rules to
222 ensure that created names are valid and easy to use across platforms.
224 All names and strings are UTF-8 encoded.
226 ### Names for API (plugin)
228 Plugin API name are checked.
229 All characters are authorised except:
231 - the control characters (\u0000 .. \u001f)
232 - the characters of the set { ' ', '"', '#', '%', '&',
233 '\'', '/', '?', '`', '\x7f' }
235 In other words the set of forbidden characters is
236 { \u0000..\u0020, \u0022, \u0023, \u0025..\u0027,
237 \u002f, \u003f, \u0060, \u007f }.
239 Afb-daemon makes no distinction between lower case
240 and upper case when searching for API/VERB.
242 ### Names for methods
244 The names of methods VERBs are totally free and not checked.
246 However, the validity rules for method's VERB name are the
247 same as for Plugin API name except that the dot(.) character
250 Afb-daemon makes no case distinction when searching for an API by name.
252 ### Names for arguments
254 Argument's name are not restricted and can be everything you wish.
256 > Warning arguments search is case sensitive and "index" and "Index"
257 > are not two different arguments.
259 ### Forging names widely available
261 The key names of javascript object can be almost
262 anything using the arrayed notation:
266 Nevertheless this is not the case with javascript dot notation:
270 Using the dot notation, the key must be a valid javascript
271 identifier and dash(-) as well as few other reserved characters cannot be used.
273 For this reason, we advise developper to chose name compatible with both javascript and HTML notation.
275 It is a good practice, even for arguments not to rely on case sensitivity.
276 This may reduce headache strength at debug time, especially with interpreted language like
277 javascript that may not warn you that a variable was not defined.
279 Writing a synchronous method implementation
280 -----------------------------------------
282 The method **tictactoe/board** is a synchronous implementation.
289 static void board(struct afb_req req)
292 struct json_object *description;
294 /* retrieves the context for the session */
295 board = board_of_req(req);
296 INFO(afbitf, "method 'board' called for boardid %d", board->id);
298 /* describe the board */
299 description = describe(board);
301 /* send the board's description */
302 afb_req_success(req, description, NULL);
306 This example shows many aspects of a synchronous
307 method implementation. Let summarise it:
309 1. The function **board_of_req** retrieves the context stored
310 for the plugin: the board.
312 2. The macro **INFO** sends a message of kind *INFO*
313 to the logging system. The global variable named **afbitf**
314 used represents the interface to afb-daemon.
316 3. The function **describe** creates a json_object representing
319 4. The function **afb_req_success** sends the reply, attaching to
320 it the object *description*.
322 ### The incoming request
324 For any implementation, the request is received by a structure of type
327 > Note that this is a PLAIN structure, not a pointer to a structure.
329 The definition of **struct afb_req** is:
333 * Describes the request by plugins from afb-daemon
336 const struct afb_req_itf *itf; /* the interfacing functions */
337 void *closure; /* the closure for functions */
341 It contains two pointers: first one *itf*, points to functions used
342 to handle internal request. Second one *closure* point onto function closure.
344 > The structure must never be used directly.
345 > Instead developer should use the intended functions provided
346 > by afb-daemon as described here after.
348 *req* is used to get arguments of the request, to send
349 answer, to store session data.
351 This object and its interface is defined and documented
352 in the file names *afb/afb-req-itf.h*
354 The above example uses twice *req* object request.
356 The first time, to retrieve the board attached to the session of the request.
358 The second time, to send the reply: an object that describes the current board.
360 ### Associating a client context to a session
362 When *tic-tac-toe* plugin receives a request, it musts get
363 the board describing the game associated to the session.
365 For a plugin, having data associated to a session is common.
366 This data is called "plugin context" for the session.
367 Within *tic-tac-toe* plugin the context is the board.
369 Requests *afb_req* offer four functions for storing and retrieving session associated context.
373 - **afb_req_context_get**:
374 retrieves context data stored for current plugin.
376 - **afb_req_context_set**:
377 store context data of current plugin.
379 - **afb_req_context**:
380 if exist retrieves context data of current plugin.
381 if context does not yet exist, creates a new context and store it.
383 - **afb_req_context_clear**:
384 reset the stored context data.
386 The plugin *tictactoe* use a convenient function to retrieve
387 its context: the board. This function is *board_of_req*:
391 * retrieves the board of the request
393 static inline struct board *board_of_req(struct afb_req req)
395 return afb_req_context(req, (void*)get_new_board, (void*)release_board);
399 The function **afb_req_context** ensures an existing context
400 for the session of the request.
401 Its two last arguments are functions to allocate and free context.
402 Note function type casts to avoid compilation warnings.
404 Here is the definition of the function **afb_req_context**
408 * Gets the pointer stored by the plugin for the session of 'req'.
409 * If the stored pointer is NULL, indicating that no pointer was
410 * already stored, afb_req_context creates a new context by calling
411 * the function 'create_context' and stores it with the freeing function
414 static inline void *afb_req_context(struct afb_req req, void *(*create_context)(), void (*free_context)(void*))
416 void *result = afb_req_context_get(req);
417 if (result == NULL) {
418 result = create_context();
419 afb_req_context_set(req, result, free_context);
425 The second argument if the function that creates the context.
426 For plugin *tic-tac-toe* (function **get_new_board**).
427 The function **get_new_board** creates a new board and set usage its count to 1.
428 The boards are checking usage count to free resources when not used.
430 The third argument is a function that frees context resources.
431 For plugin *tic-tac-toe* (function **release_board**).
432 The function **release_board** decrease usage count of the board passed in argument.
433 When usage count falls to zero, data board are freed.
435 Definition of other functions dealing with contexts:
439 * Gets the pointer stored by the plugin for the session of 'req'.
440 * When the plugin has not yet recorded a pointer, NULL is returned.
442 void *afb_req_context_get(struct afb_req req);
445 * Stores for the plugin the pointer 'context' to the session of 'req'.
446 * The function 'free_context' will be called when the session is closed
447 * or if plugin stores an other pointer.
449 void afb_req_context_set(struct afb_req req, void *context, void (*free_context)(void*));
452 * Frees the pointer stored by the plugin for the session of 'req'
453 * and sets it to NULL.
455 * Shortcut for: afb_req_context_set(req, NULL, NULL)
457 static inline void afb_req_context_clear(struct afb_req req)
459 afb_req_context_set(req, NULL, NULL);
463 ### Sending reply to a request
465 Two kinds of replies: successful or failure.
467 > Sending a reply to a request MUST be done once and only once.
469 It exists two functions for "success" replies: **afb_req_success** and **afb_req_success_f**.
473 * Sends a reply of kind success to the request 'req'.
474 * The status of the reply is automatically set to "success".
475 * Its send the object 'obj' (can be NULL) with an
476 * informationnal comment 'info (can also be NULL).
478 * For conveniency, the function calls 'json_object_put' for 'obj'.
479 * Thus, in the case where 'obj' should remain available after
480 * the function returns, the function 'json_object_get' shall be used.
482 void afb_req_success(struct afb_req req, struct json_object *obj, const char *info);
485 * Same as 'afb_req_success' but the 'info' is a formatting
486 * string followed by arguments.
488 * For conveniency, the function calls 'json_object_put' for 'obj'.
489 * Thus, in the case where 'obj' should remain available after
490 * the function returns, the function 'json_object_get' shall be used.
492 void afb_req_success_f(struct afb_req req, struct json_object *obj, const char *info, ...);
495 It exists two functions for "failure" replies: **afb_req_fail** and **afb_req_fail_f**.
499 * Sends a reply of kind failure to the request 'req'.
500 * The status of the reply is set to 'status' and an
501 * informational comment 'info' (can also be NULL) can be added.
503 * Note that calling afb_req_fail("success", info) is equivalent
504 * to call afb_req_success(NULL, info). Thus even if possible it
505 * is strongly recommended to NEVER use "success" for status.
507 * For conveniency, the function calls 'json_object_put' for 'obj'.
508 * Thus, in the case where 'obj' should remain available after
509 * the function returns, the function 'json_object_get' shall be used.
511 void afb_req_fail(struct afb_req req, const char *status, const char *info);
514 * Same as 'afb_req_fail' but the 'info' is a formatting
515 * string followed by arguments.
517 * For conveniency, the function calls 'json_object_put' for 'obj'.
518 * Thus, in the case where 'obj' should remain available after
519 * the function returns, the function 'json_object_get' shall be used.
521 void afb_req_fail_f(struct afb_req req, const char *status, const char *info, ...);
524 > For conveniency, these functions automatically call **json_object_put** to release **obj**.
525 > Because **obj** usage count is null after being passed to a reply function, it SHOULD not be used anymore.
526 > If exceptionally **obj** needs to remain usable after reply function then using **json_object_get** on **obj**
527 > to increase usage count and cancels the effect the **json_object_put** is possible.
529 Getting argument of invocation
530 ------------------------------
532 Many methods expect arguments. Afb-daemon's plugins
533 retrieve arguments by name and not by position.
535 Arguments are passed by requests through either HTTP
538 For example, the method **join** of plugin **tic-tac-toe**
539 expects one argument: the *boardid* to join. Here is an extract:
545 static void join(struct afb_req req)
547 struct board *board, *new_board;
550 /* retrieves the context for the session */
551 board = board_of_req(req);
552 INFO(afbitf, "method 'join' called for boardid %d", board->id);
554 /* retrieves the argument */
555 id = afb_req_value(req, "boardid");
561 The function **afb_req_value** searches in the request *req*
562 for argument name passed in the second argument. When argument name
563 is not passed, **afb_req_value** returns NULL.
565 > The search is case sensitive and *boardid* is not equivalent to *BoardId*.
566 > Nevertheless having argument names that only differ by name case is not a good idea.
568 ### Basic functions for querying arguments
570 The function **afb_req_value** is defined here after:
574 * Gets from the request 'req' the string value of the argument of 'name'.
575 * Returns NULL if when there is no argument of 'name'.
576 * Returns the value of the argument of 'name' otherwise.
578 * Shortcut for: afb_req_get(req, name).value
580 static inline const char *afb_req_value(struct afb_req req, const char *name)
582 return afb_req_get(req, name).value;
586 It is defined as a shortcut to call the function **afb_req_get**.
587 That function is defined here after:
591 * Gets from the request 'req' the argument of 'name'.
592 * Returns a PLAIN structure of type 'struct afb_arg'.
593 * When the argument of 'name' is not found, all fields of result are set to NULL.
594 * When the argument of 'name' is found, the fields are filled,
595 * in particular, the field 'result.name' is set to 'name'.
597 * There is a special name value: the empty string.
598 * The argument of name "" is defined only if the request was made using
599 * an HTTP POST of Content-Type "application/json". In that case, the
600 * argument of name "" receives the value of the body of the HTTP request.
602 struct afb_arg afb_req_get(struct afb_req req, const char *name);
605 That function takes 2 parameters: the request and the name
606 of the argument to retrieve. It returns a PLAIN structure of
607 type **struct afb_arg**.
609 There is a special name that is defined when the request is
610 of type HTTP/POST with a Content-Type being application/json.
611 This name is **""** (the empty string). In that case, the value
612 of this argument of empty name is the string received as a body
613 of the post and is supposed to be a JSON string.
615 The definition of **struct afb_arg** is:
619 * Describes an argument (or parameter) of a request
622 const char *name; /* name of the argument or NULL if invalid */
623 const char *value; /* string representation of the value of the argument */
624 /* original filename of the argument if path != NULL */
625 const char *path; /* if not NULL, path of the received file for the argument */
626 /* when the request is finalized this file is removed */
630 The structure returns the data arguments that are known for the
631 request. This data include a field named **path**. This **path**
632 can be accessed using the function **afb_req_path** defined here after:
636 * Gets from the request 'req' the path for file attached to the argument of 'name'.
637 * Returns NULL if when there is no argument of 'name' or when there is no file.
638 * Returns the path of the argument of 'name' otherwise.
640 * Shortcut for: afb_req_get(req, name).path
642 static inline const char *afb_req_path(struct afb_req req, const char *name)
644 return afb_req_get(req, name).path;
648 The path is only defined for HTTP/POST requests that send file.
650 ### Arguments for received files
652 As it is explained above, clients can send files using HTTP/POST requests.
654 Received files are attached to "file" argument name. For example, the
655 following HTTP fragment (from test/sample-post.html)
656 will send an HTTP/POST request to the method
657 **post/upload-image** with 2 arguments named *file* and
661 <h2>Sample Post File</h2>
662 <form enctype="multipart/form-data">
663 <input type="file" name="file" />
664 <input type="hidden" name="hidden" value="bollobollo" />
666 <button formmethod="POST" formaction="api/post/upload-image">Post File</button>
670 Argument named **file** should have both its value and path defined.
672 The value is the name of the file as it was set by the HTTP client.
673 Generally it is the filename on client side.
675 The path is the effective path of saved file on the temporary local storage
676 area of the application. This is a randomly generated and unique filename.
677 It is not linked with the original filename as used on client side.
679 After success the plugin can use the uploaded file directly from local storage path with no restriction:
680 read, write, remove, copy, rename...
681 Nevertheless when request reply is set and query terminated, the uploaded temporary file at
684 ### Arguments as a JSON object
686 Plugins may also request every arguments of a given call as one single object.
687 This feature is provided by the function **afb_req_json** defined here after:
691 * Gets from the request 'req' the json object hashing the arguments.
692 * The returned object must not be released using 'json_object_put'.
694 struct json_object *afb_req_json(struct afb_req req);
697 It returns a json object. This object depends on how the request was built:
699 - For HTTP requests, this json object uses key names mapped on argument name.
700 Values are either string for common arguments or object ie: { "file": "...", "path": "..." }
702 - For WebSockets requests, returned directly the object as provided by the client.
704 > In fact, for Websockets requests, the function **afb_req_value**
705 > can be seen as a shortcut to
706 > ***json_object_get_string(json_object_object_get(afb_req_json(req), name))***
708 Initialisation of the plugin and declaration of methods
709 -----------------------------------------------------
711 To be active, plugin's methods should be declared to
712 afb-daemon. Furthermore, the plugin itself must be recorded.
714 The registration mechanism is very basic: when afb-need starts,
715 it loads all plugins listed in: command line or configuration file.
717 Loading a plugin follows the following steps:
719 1. Afb-daemon loads the plugin with *dlopen*.
721 2. Afb-daemon searches for a symbol named **pluginAfbV1Register** using *dlsym*.
722 This symbol is assumed to be the exported initialisation function of the plugin.
724 3. Afb-daemon builds an interface object for the plugin.
726 4. Afb-daemon calls the found function **pluginAfbV1Register** with interface pointer
729 5. Function **pluginAfbV1Register** setups the plugin and initialises it.
731 6. Function **pluginAfbV1Register** returns the pointer to a structure
732 describing the plugin: version, name (prefix or API name), and list of methods.
734 7. Afb-daemon checks that the returned version and name can be managed.
735 If so, plugin and its methods are register to become usable as soon as
736 afb-daemon initialisation is finished.
738 Here after the code used for **pluginAfbV1Register** from plugin *tic-tac-toe*:
742 * activation function for registering the plugin called by afb-daemon
744 const struct AFB_plugin *pluginAfbV1Register(const struct AFB_interface *itf)
746 afbitf = itf; // records the interface for accessing afb-daemon
747 return &plugin_description; // returns the description of the plugin
751 It is a very minimal initialisation function because *tic-tac-toe* plugin doesn't
752 have any application related initialisation step. It merely record daemon's interface
753 and returns its description.
755 The variable **afbitf** is a plugin global variable. It keeps the
756 interface to afb-daemon that should be used for logging and pushing events.
757 Here is its declaration:
761 * the interface to afb-daemon
763 const struct AFB_interface *afbitf;
766 The description of the plugin is defined here after.
770 * array of the methods exported to afb-daemon
772 static const struct AFB_method_desc_v1 plugin_methods[] = {
773 /* VERB'S NAME SESSION MANAGEMENT FUNCTION TO CALL SHORT DESCRIPTION */
774 { .name= "new", .session= AFB_SESSION_NONE, .callback= new, .info= "Starts a new game" },
775 { .name= "play", .session= AFB_SESSION_NONE, .callback= play, .info= "Asks the server to play" },
776 { .name= "move", .session= AFB_SESSION_NONE, .callback= move, .info= "Tells the client move" },
777 { .name= "board", .session= AFB_SESSION_NONE, .callback= board, .info= "Get the current board" },
778 { .name= "level", .session= AFB_SESSION_NONE, .callback= level, .info= "Set the server level" },
779 { .name= "join", .session= AFB_SESSION_CHECK,.callback= join, .info= "Join a board" },
780 { .name= "undo", .session= AFB_SESSION_NONE, .callback= undo, .info= "Undo the last move" },
781 { .name= "wait", .session= AFB_SESSION_NONE, .callback= wait, .info= "Wait for a change" },
782 { .name= NULL } /* marker for end of the array */
786 * description of the plugin for afb-daemon
788 static const struct AFB_plugin plugin_description =
790 /* description conforms to VERSION 1 */
791 .type= AFB_PLUGIN_VERSION_1,
792 .v1= { /* fills the v1 field of the union when AFB_PLUGIN_VERSION_1 */
793 .prefix= "tictactoe", /* the API name (or plugin name or prefix) */
794 .info= "Sample tac-tac-toe game", /* short description of of the plugin */
795 .methods = plugin_methods /* the array describing the methods of the API */
800 The structure **plugin_description** describes the plugin.
801 It declares the type and version of the plugin, its name, a short description
802 and its methods list.
804 The list of methods is an array of structures describing the methods and terminated by a NULL marker.
806 In version one of afb-damon plugin, a method description contains 4 fields:
808 - the name of the method,
810 - the session management flags,
812 - the implementation function to be call for the method,
814 - a short description.
816 The structure describing methods is defined as follows:
820 * Description of one method of the API provided by the plugin
821 * This enumeration is valid for plugins of type 1
823 struct AFB_method_desc_v1
825 const char *name; /* name of the method */
826 enum AFB_session_v1 session; /* authorisation and session requirements of the method */
827 void (*callback)(struct afb_req req); /* callback function implementing the method */
828 const char *info; /* textual description of the method */
832 For technical reasons, the enumeration **enum AFB_session_v1** is not exactly an
833 enumeration but the wrapper of constant definitions that can be mixed using bitwise or
836 The constants that can bit mixed are:
838 Constant name | Meaning
839 -------------------------|-------------------------------------------------------------
840 **AFB_SESSION_CREATE** | Equals to AFB_SESSION_LOA_EQ_0|AFB_SESSION_RENEW
841 **AFB_SESSION_CLOSE** | Closes the session after the reply and set the LOA to 0
842 **AFB_SESSION_RENEW** | Refreshes the token of authentification
843 **AFB_SESSION_CHECK** | Just requires the token authentification
844 **AFB_SESSION_LOA_LE_0** | Requires the current LOA to be lesser then or equal to 0
845 **AFB_SESSION_LOA_LE_1** | Requires the current LOA to be lesser then or equal to 1
846 **AFB_SESSION_LOA_LE_2** | Requires the current LOA to be lesser then or equal to 2
847 **AFB_SESSION_LOA_LE_3** | Requires the current LOA to be lesser then or equal to 3
848 **AFB_SESSION_LOA_GE_0** | Requires the current LOA to be greater then or equal to 0
849 **AFB_SESSION_LOA_GE_1** | Requires the current LOA to be greater then or equal to 1
850 **AFB_SESSION_LOA_GE_2** | Requires the current LOA to be greater then or equal to 2
851 **AFB_SESSION_LOA_GE_3** | Requires the current LOA to be greater then or equal to 3
852 **AFB_SESSION_LOA_EQ_0** | Requires the current LOA to be equal to 0
853 **AFB_SESSION_LOA_EQ_1** | Requires the current LOA to be equal to 1
854 **AFB_SESSION_LOA_EQ_2** | Requires the current LOA to be equal to 2
855 **AFB_SESSION_LOA_EQ_3** | Requires the current LOA to be equal to 3
857 If any of this flag is set, afb-daemon requires an authentication token
858 as if **AFB_SESSION_CHECK** flag was also set.
860 The special value **AFB_SESSION_NONE** is zero and can be used to bypass token check.
862 > Note that **AFB_SESSION_CREATE** and **AFB_SESSION_CLOSE** might be removed in later versions.
864 Sending messages to the log system
865 ----------------------------------
867 Afb-daemon provides 4 levels of verbosity and 5 methods for logging messages.
869 The verbosity is managed. Options allow the change the verbosity of afb-daemon
870 and the verbosity of the plugins can be set plugin by plugin.
872 The methods for logging messages are defined as macros that test the
873 verbosity level and that call the real logging function only if the
874 message must be output. This avoid evaluation of arguments of the
875 formatting messages if the message must not be output.
877 ### Verbs for logging messages
879 The 5 logging methods are:
881 Macro | Verbosity | Meaning | syslog level
882 --------|:---------:|-----------------------------------|:-----------:
883 ERROR | 0 | Error conditions | 3
884 WARNING | 1 | Warning conditions | 4
885 NOTICE | 1 | Normal but significant condition | 5
886 INFO | 2 | Informational | 6
887 DEBUG | 3 | Debug-level messages | 7
889 You can note that the 2 methods **WARNING** and **INFO** have the same level
890 of verbosity. But they don't have the same *syslog level*. It means that
891 they are output with a different level on the logging system.
893 All of these methods have the same signature:
896 void ERROR(const struct AFB_interface *afbitf, const char *message, ...);
899 The first argument **afbitf** is the interface to afb daemon that the
900 plugin received at initialisation time when **pluginAfbV1Register** is called.
902 The second argument **message** is a formatting string compatible with printf/sprintf.
904 The remaining arguments are arguments of the formating message like with printf.
906 ### Managing verbosity
908 Depending on the level of verbosity, the messages are output or not.
909 The following table explains what messages will be output depending
910 ont the verbosity level.
912 Level of verbosity | Outputed macro
913 :-----------------:|--------------------------
915 1 | ERROR + WARNING + NOTICE
916 2 | ERROR + WARNING + NOTICE + INFO
917 3 | ERROR + WARNING + NOTICE + INFO + DEBUG
919 ### Output format and destination
921 The syslog level is used for forging a prefix to the message.
924 syslog level | prefix
925 :-----------:|---------------
936 The message is pushed to standard error.
937 The final destination of the message depends on how systemd service
938 was configured through its variable **StandardError**. It can be
939 journal, syslog or kmsg. (See man sd-daemon).
944 Since version 0.5, plugins can broadcast events to any potential listener.
945 As today only unattended even are supported. Targeted events are expected for next
948 The plugin *tic-tac-toe* broadcasts events when the board changes.
949 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);
969 The description of the changed board is pushed via the daemon interface.
971 Within plugin *tic-tac-toe*, *reason* indicates the origin of
972 the change. In function **afb_daemon_broadcast_event** the second
973 parameter is the name of broadcasted event. The third argument is the
974 object that is transmitted with the event.
976 Function **afb_daemon_broadcast_event** is defined here after:
980 * Broadcasts widely the event of 'name' with the data 'object'.
981 * 'object' can be NULL.
982 * 'daemon' MUST be the daemon given in interface when activating the plugin.
984 * For conveniency, the function calls 'json_object_put' for 'object'.
985 * Thus, in the case where 'object' should remain available after
986 * the function returns, the function 'json_object_get' shall be used.
988 void afb_daemon_broadcast_event(struct afb_daemon daemon, const char *name, struct json_object *object);
991 > Be aware, as with reply functions **object** is automatically released using
992 > **json_object_put** when using this function. Call **json_object_get** before
993 > calling **afb_daemon_broadcast_event** to keep **object** available
994 > after function returns.
996 Event name received by listeners is prefixed with plugin name.
997 So when a change occurs after a move, the reason is **move** and every clients
998 receive an event **tictactoe/move**.
1000 > Note that nothing is said about case sensitivity of event names.
1001 > However, the event is always prefixed with the name that the plugin
1002 > declared, with the same case, followed with a slash /.
1003 > Thus it is safe to compare event using a case sensitive comparison.
1007 Writing an asynchronous method implementation
1008 -------------------------------------------
1010 The *tic-tac-toe* example allows two clients or more to share the same board.
1011 This is implemented by the method **join** that illustrated partly how to
1014 When two or more clients are sharing a same board, one of them can wait
1015 until the state of the board changes, but this could also be implemented using
1016 events because an even is generated each time the board changes.
1018 In this case, the reply to the wait is sent only when the board changes.
1019 See the diagram below:
1021 CLIENT A CLIENT B TIC-TAC-TOE
1023 +--------------|----------------->| wait . . . . . . . .
1028 | +----------------->| move . . . .
1030 | |<-----------------+ success of move .
1032 |<-------------|------------------+ success of wait <
1034 Here, this is an invocation of the plugin by an other client that
1035 unblock the suspended *wait* call.
1036 Nevertheless in most case this should be a timer, a hardware event, a sync with
1037 a concurrent process or thread, ...
1039 Common case of an asynchronous implementation.
1041 Here is the listing of the function **wait**:
1044 static void wait(struct afb_req req)
1046 struct board *board;
1047 struct waiter *waiter;
1049 /* retrieves the context for the session */
1050 board = board_of_req(req);
1051 INFO(afbitf, "method 'wait' called for boardid %d", board->id);
1053 /* creates the waiter and enqueues it */
1054 waiter = calloc(1, sizeof *waiter);
1056 waiter->next = board->waiters;
1057 afb_req_addref(req);
1058 board->waiters = waiter;
1062 After retrieving the board, the function adds a new waiter to
1063 waiters list and returns without setting a reply.
1065 Before returning, it increases **req** request's reference count using **afb_req_addref** function.
1067 > When a method returns without setting a reply,
1068 > it **MUST** increment request's reference count
1069 > using **afb_req_addref**. If unpredictable behaviour may pop up.
1071 Later, when a board changes, it calls *tic-tac-toe* **changed** function
1072 with reason of change in parameter.
1074 Here is the full listing of the function **changed**:
1078 * signals a change of the board
1080 static void changed(struct board *board, const char *reason)
1082 struct waiter *waiter, *next;
1083 struct json_object *description;
1085 /* get the description */
1086 description = describe(board);
1088 waiter = board->waiters;
1089 board->waiters = NULL;
1090 while (waiter != NULL) {
1091 next = waiter->next;
1092 afb_req_success(waiter->req, json_object_get(description), reason);
1093 afb_req_unref(waiter->req);
1098 afb_event_sender_push(afb_daemon_get_event_sender(afbitf->daemon), reason, description);
1102 The list of waiters is walked and a reply is sent to each waiter.
1103 After sending the reply, the reference count of the request
1104 is decremented using **afb_req_unref** to allow resources to be freed.
1106 > The reference count **MUST** be decremented using **afb_req_unref** to free
1107 > resources and avoid memory leaks.
1108 > This usage count decrement should happen **AFTER** setting reply or
1109 > bad things may happen.
1111 How to build a plugin
1112 ---------------------
1114 Afb-daemon provides a *pkg-config* configuration file that can be
1115 queried by providing **afb-daemon** in command line arguments.
1116 This configuration file provides data that should be used
1117 for plugins compilation. Examples:
1120 $ pkg-config --cflags afb-daemon
1121 $ pkg-config --libs afb-daemon
1124 ### Example for cmake meta build system
1126 This example is the extract for building the plugin *afm-main* using *CMAKE*.
1129 pkg_check_modules(afb afb-daemon)
1131 message(STATUS "Creation afm-main-plugin for AFB-DAEMON")
1132 add_library(afm-main-plugin MODULE afm-main-plugin.c)
1133 target_compile_options(afm-main-plugin PRIVATE ${afb_CFLAGS})
1134 target_include_directories(afm-main-plugin PRIVATE ${afb_INCLUDE_DIRS})
1135 target_link_libraries(afm-main-plugin utils ${afb_LIBRARIES})
1136 set_target_properties(afm-main-plugin PROPERTIES
1138 LINK_FLAGS "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/afm-main-plugin.export-map"
1140 install(TARGETS afm-main-plugin LIBRARY DESTINATION ${plugin_dir})
1142 message(STATUS "Not creating the plugin for AFB-DAEMON")
1146 Let now describe some of these lines.
1149 pkg_check_modules(afb afb-daemon)
1152 This first lines searches to the *pkg-config* configuration file for
1153 **afb-daemon**. Resulting data are stored in the following variables:
1156 ------------------|------------------------------------------------
1157 afb_FOUND | Set to 1 if afb-daemon plugin development files exist
1158 afb_LIBRARIES | Only the libraries (w/o the '-l') for compiling afb-daemon plugins
1159 afb_LIBRARY_DIRS | The paths of the libraries (w/o the '-L') for compiling afb-daemon plugins
1160 afb_LDFLAGS | All required linker flags for compiling afb-daemon plugins
1161 afb_INCLUDE_DIRS | The '-I' preprocessor flags (w/o the '-I') for compiling afb-daemon plugins
1162 afb_CFLAGS | All required cflags for compiling afb-daemon plugins
1164 If development files are found, the plugin can be added to the set of
1168 add_library(afm-main-plugin MODULE afm-main-plugin.c)
1171 This line asks to create a shared library having a single
1172 source file named afm-main-plugin.c to be compiled.
1173 The default name of the created shared object is
1174 **libafm-main-plugin.so**.
1177 set_target_properties(afm-main-plugin PROPERTIES
1179 LINK_FLAGS "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/afm-main-plugin.export-map"
1183 This lines are doing two things:
1185 1. It renames the built library from **libafm-main-plugin.so** to **afm-main-plugin.so**
1186 by removing the implicitly added prefix *lib*. This step is not mandatory
1187 because afb-daemon doesn't check names of files at load time.
1188 The only filename convention used by afb-daemon relates to **.so** termination.
1189 *.so pattern is used when afb-daemon automatically discovers plugin from a directory hierarchy.
1191 2. It applies a version script at link time to only export the reserved name
1192 **pluginAfbV1Register** for registration entry point. By default, when building
1193 a shared library linker exports all the public symbols (C functions that are not **static**).
1198 target_include_directories(afm-main-plugin PRIVATE ${afb_INCLUDE_DIRS})
1199 target_link_libraries(afm-main-plugin utils ${afb_LIBRARIES})
1202 As you can see it uses the variables computed by ***pkg_check_modules(afb afb-daemon)***
1203 to configure the compiler and the linker.
1205 ### Exporting the function pluginAfbV1Register
1207 The function **pluginAfbV1Register** MUST be exported. This can be achieved
1208 using a version script at link time. Here after is a version script used for
1209 *tic-tac-toe* (plugins/samples/export.map).
1211 { global: pluginAfbV1Register; local: *; };
1213 This sample [version script](https://sourceware.org/binutils/docs-2.26/ld/VERSION.html#VERSION)
1214 exports as global the symbol *pluginAfbV1Register* and hides any
1217 This version script is added to the link options using the
1218 option **--version-script=export.map** is given directly to the
1219 linker or using the option **-Wl,--version-script=export.map**
1220 when the option is given to the C compiler.
1222 ### Building within yocto
1224 Adding a dependency to afb-daemon is enough. See below:
1226 DEPENDS += " afb-daemon "