add .gitreview
[src/app-framework-binder.git] / doc / afb-plugin-writing.md
1 HOWTO WRITE a PLUGIN for AFB-DAEMON
2 ===================================
3     version: 1
4     Date:    09 juin 2016
5     Author:  José Bollo
6
7
8
9 Summary
10 -------
11
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.
15
16 Binder plugins are used to add API to afb-daemon.
17 This part describes how to write a plugin for afb-daemon.
18
19 Excepting this summary, this document target developers.
20
21 Before moving further through an example, here after
22 a short overview of binder plugins fundamentals.
23
24 ### Nature of a plugin
25
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.
28
29 Technically, a binder plugin does not reference and is not linked with any afb-daemon library.
30
31 ### Class of plugins
32
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.
35
36 #### Application-plugins
37
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.
42
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.
46
47 #### Service-plugins
48
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.
51
52 Service-plugins can either be stateless or manage client context. When managing context each client get a private context.
53
54 Sharing may either be global to the platform (ie: GPS service) or dedicated to a given user (ie: user preferences)
55  
56 ### Live cycle of plugins within afb-daemon
57
58 Application and service plugins are loaded and activated each time a new afb-daemon is started.
59
60 At launch time, every loaded plugin initialise itself.
61 If a single plugin initialisation fail corresponding instance of afb-daemon self aborts.
62
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.
65
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.
68
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.
71
72 ### Plugin Contend
73
74 Afb-daemon's plugin register two classes of objects: names and functions.
75
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.
79
80 Plugins declare two categories of functions:
81  - function use for the initialisation
82  - functions implementing exposed API methods
83
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.
88
89 Afb-daemon ignores letter case when parsing URI. Thus **TicTacToe/Board** and **tictactoe/board** are equivalent.
90
91 #### The name of the plugin
92
93 The name of a given plugin is also known as the name
94 of the API prefix that defines the plugin.
95
96 The name of a plugin SHOULD be unique within a given afb-daemon instance.
97
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.
100
101 #### Names of methods
102
103 Each plugin exposes a set of methods that can be called
104 by the clients of a given afb-daemon.
105
106 VERB's name attached to a given plugin (API) MUST be unique within a plugin.
107
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.
110
111 #### Initialisation function
112
113 Plugin's initialisation function serves several purposes.
114
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.
118
119 2. It allows plugins to initialise itself.
120
121 3. It enables names declarations: descriptions, requirements and implementations of exposed API/VERB.
122
123 #### Functions instantiation of API/VERBs
124
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.
128
129 An implementation function receives a request object that
130 is used to: get arguments of the request, send
131 answer, store session data.
132
133 A plugin MUST set an answer to every received requests.
134
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.
138
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*.
141
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.
144
145 The Tic-Tac-Toe example
146 -----------------------
147
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*.
152
153 This plugin is named ***tictactoe***.
154
155 Dependencies when compiling
156 ---------------------------
157
158 Afb-daemon provides a configuration file for *pkg-config*.
159 Typing the command
160
161         pkg-config --cflags afb-daemon
162
163 Print flags use for compilation:
164
165         $ pkg-config --cflags afb-daemon
166         -I/opt/local/include -I/usr/include/json-c 
167
168 For linking, you should use
169
170         $ pkg-config --libs afb-daemon
171         -ljson-c
172
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.
176
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.
182
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
185 > memory feature.
186
187 Header files to include
188 -----------------------
189
190 Plugin *tictactoe* has following includes:
191
192 ```C
193 #define _GNU_SOURCE
194 #include <stdio.h>
195 #include <string.h>
196 #include <json-c/json.h>
197 #include <afb/afb-plugin.h>
198 ```
199
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:
203
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.
207
208 The *tictactoe* plugin does not leverage systemd features, also only json.h
209 is used on top of mandatory afb/afb-plugin.h.
210
211 When including *afb/afb-plugin.h*, the macro **_GNU_SOURCE** MUST be
212 defined.
213
214 Choosing names
215 --------------
216
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.
220
221 While forging names, designers should respect few rules to
222 ensure that created names are valid and easy to use across platforms.
223
224 All names and strings are UTF-8 encoded.
225
226 ### Names for API (plugin)
227
228 Plugin API name are checked.
229 All characters are authorised except:
230
231 - the control characters (\u0000 .. \u001f)
232 - the characters of the set { ' ', '"', '#', '%', '&',
233   '\'', '/', '?', '`', '\x7f' }
234
235 In other words the set of forbidden characters is
236 { \u0000..\u0020, \u0022, \u0023, \u0025..\u0027,
237   \u002f, \u003f, \u0060, \u007f }.
238
239 Afb-daemon makes no distinction between lower case
240 and upper case when searching for API/VERB.
241
242 ### Names for methods
243
244 The names of methods VERBs are totally free and not checked.
245
246 However, the validity rules for method's VERB name are the
247 same as for Plugin API name except that the dot(.) character
248 is forbidden.
249
250 Afb-daemon makes no case distinction when searching for an API by name.
251
252 ### Names for arguments
253
254 Argument's name are not restricted and can be everything you wish.
255
256 > Warning arguments search is case sensitive and "index" and "Index"
257 > are not two different arguments.
258
259 ### Forging names widely available
260
261 The key names of javascript object can be almost
262 anything using the arrayed notation:
263
264         object[key] = value
265
266 Nevertheless this is not the case with javascript dot notation:
267
268         object.key = value
269
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.
272
273 For this reason, we advise developper to chose name compatible with both javascript and HTML notation.
274
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.
278
279 Writing a synchronous method implementation
280 -----------------------------------------
281
282 The method **tictactoe/board** is a synchronous implementation.
283 Here is its listing:
284
285 ```C
286 /*
287  * get the board
288  */
289 static void board(struct afb_req req)
290 {
291         struct board *board;
292         struct json_object *description;
293
294         /* retrieves the context for the session */
295         board = board_of_req(req);
296         INFO(afbitf, "method 'board' called for boardid %d", board->id);
297
298         /* describe the board */
299         description = describe(board);
300
301         /* send the board's description */
302         afb_req_success(req, description, NULL);
303 }
304 ```
305
306 This example shows many aspects of a synchronous
307 method implementation. Let summarise it:
308
309 1. The function **board_of_req** retrieves the context stored
310 for the plugin: the board.
311
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.
315
316 3. The function **describe** creates a json_object representing
317 the board.
318
319 4. The function **afb_req_success** sends the reply, attaching to
320 it the object *description*.
321
322 ### The incoming request
323
324 For any implementation, the request is received by a structure of type
325 **struct afb_req**.
326
327 > Note that this is a PLAIN structure, not a pointer to a structure.
328
329 The definition of **struct afb_req** is:
330
331 ```C
332 /*
333  * Describes the request by plugins from afb-daemon
334  */
335 struct afb_req {
336         const struct afb_req_itf *itf;  /* the interfacing functions */
337         void *closure;                  /* the closure for functions */
338 };
339 ```
340
341 It contains two pointers: first one *itf*, points to functions used
342 to handle internal request. Second one *closure* point onto function closure. 
343
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.
347
348 *req* is used to get arguments of the request, to send
349 answer, to store session data.
350
351 This object and its interface is defined and documented
352 in the file names *afb/afb-req-itf.h*
353
354 The above example uses twice *req* object request.
355
356 The first time, to retrieve the board attached to the session of the request.
357
358 The second time, to send the reply: an object that describes the current board.
359
360 ### Associating a client context to a session
361
362 When *tic-tac-toe* plugin receives a request, it musts get
363 the board describing the game associated to the session.
364
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.
368
369 Requests *afb_req* offer four functions for storing and retrieving session associated context.
370
371 These functions are:
372
373 - **afb_req_context_get**:
374   retrieves context data stored for current plugin.
375
376 - **afb_req_context_set**:
377   store context data of current plugin.
378
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.
382
383 - **afb_req_context_clear**:
384   reset the stored context data.
385
386 The plugin *tictactoe* use a convenient function to retrieve
387 its context: the board. This function is *board_of_req*:
388
389 ```C
390 /*
391  * retrieves the board of the request
392  */
393 static inline struct board *board_of_req(struct afb_req req)
394 {
395         return afb_req_context(req, (void*)get_new_board, (void*)release_board);
396 }
397 ```
398
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.
403
404 Here is the definition of the function **afb_req_context**
405
406 ```C
407 /*
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
412  * 'free_context'.
413  */
414 static inline void *afb_req_context(struct afb_req req, void *(*create_context)(), void (*free_context)(void*))
415 {
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);
420         }
421         return result;
422 }
423 ```
424
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.
429
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.
434
435 Definition of other functions dealing with contexts:
436
437 ```C
438 /*
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.
441  */
442 void *afb_req_context_get(struct afb_req req);
443
444 /*
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.
448  */
449 void afb_req_context_set(struct afb_req req, void *context, void (*free_context)(void*));
450
451 /*
452  * Frees the pointer stored by the plugin for the session of 'req'
453  * and sets it to NULL.
454  *
455  * Shortcut for: afb_req_context_set(req, NULL, NULL)
456  */
457 static inline void afb_req_context_clear(struct afb_req req)
458 {
459         afb_req_context_set(req, NULL, NULL);
460 }
461 ```
462
463 ### Sending reply to a request
464
465 Two kinds of replies: successful or failure.
466
467 > Sending a reply to a request MUST be done once and only once.
468
469 It exists two functions for "success" replies: **afb_req_success** and **afb_req_success_f**.
470
471 ```C
472 /*
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).
477  *
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.
481  */
482 void afb_req_success(struct afb_req req, struct json_object *obj, const char *info);
483
484 /*
485  * Same as 'afb_req_success' but the 'info' is a formatting
486  * string followed by arguments.
487  *
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.
491  */
492 void afb_req_success_f(struct afb_req req, struct json_object *obj, const char *info, ...);
493 ```
494
495 It exists two functions for "failure" replies: **afb_req_fail** and **afb_req_fail_f**.
496
497 ```C
498 /*
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.
502  *
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.
506  *
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.
510  */
511 void afb_req_fail(struct afb_req req, const char *status, const char *info);
512
513 /*
514  * Same as 'afb_req_fail' but the 'info' is a formatting
515  * string followed by arguments.
516  *
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.
520  */
521 void afb_req_fail_f(struct afb_req req, const char *status, const char *info, ...);
522 ```
523
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.
528
529 Getting argument of invocation
530 ------------------------------
531
532 Many methods expect arguments. Afb-daemon's plugins
533 retrieve arguments by name and not by position.
534
535 Arguments are passed by requests through either HTTP
536 or WebSockets.
537
538 For example, the method **join** of plugin **tic-tac-toe**
539 expects one argument: the *boardid* to join. Here is an extract:
540
541 ```C
542 /*
543  * Join a board
544  */
545 static void join(struct afb_req req)
546 {
547         struct board *board, *new_board;
548         const char *id;
549
550         /* retrieves the context for the session */
551         board = board_of_req(req);
552         INFO(afbitf, "method 'join' called for boardid %d", board->id);
553
554         /* retrieves the argument */
555         id = afb_req_value(req, "boardid");
556         if (id == NULL)
557                 goto bad_request;
558         ...
559 ```
560
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.
564
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.
567
568 ### Basic functions for querying arguments
569
570 The function **afb_req_value** is defined here after:
571
572 ```C
573 /*
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.
577  *
578  * Shortcut for: afb_req_get(req, name).value
579  */
580 static inline const char *afb_req_value(struct afb_req req, const char *name)
581 {
582         return afb_req_get(req, name).value;
583 }
584 ```
585
586 It is defined as a shortcut to call the function **afb_req_get**.
587 That function is defined here after:
588
589 ```C
590 /*
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'.
596  *
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.
601  */
602 struct afb_arg afb_req_get(struct afb_req req, const char *name);
603 ```
604
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**.
608
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.
614
615 The definition of **struct afb_arg** is:
616
617 ```C
618 /*
619  * Describes an argument (or parameter) of a request
620  */
621 struct afb_arg {
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 */
627 };
628 ```
629
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:
633
634 ```C
635 /*
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.
639  *
640  * Shortcut for: afb_req_get(req, name).path
641  */
642 static inline const char *afb_req_path(struct afb_req req, const char *name)
643 {
644         return afb_req_get(req, name).path;
645 }
646 ```
647
648 The path is only defined for HTTP/POST requests that send file.
649
650 ### Arguments for received files
651
652 As it is explained above, clients can send files using HTTP/POST requests.
653
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
658 *hidden*.
659
660 ```html
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" />
665     <br>
666     <button formmethod="POST" formaction="api/post/upload-image">Post File</button>
667 </form>
668 ```
669
670 Argument named **file** should have both its value and path defined.
671
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.
674
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.
678
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
682 path is destroyed.
683
684 ### Arguments as a JSON object
685
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:
688
689 ```C
690 /*
691  * Gets from the request 'req' the json object hashing the arguments.
692  * The returned object must not be released using 'json_object_put'.
693  */
694 struct json_object *afb_req_json(struct afb_req req);
695 ```
696
697 It returns a json object. This object depends on how the request was built:
698
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": "..." }
701
702 - For WebSockets requests, returned directly the object as provided by the client.
703
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))***
707
708 Initialisation of the plugin and declaration of methods
709 -----------------------------------------------------
710
711 To be active, plugin's methods should be declared to
712 afb-daemon. Furthermore, the plugin itself must be recorded.
713
714 The registration mechanism is very basic: when afb-need starts,
715 it loads all plugins listed in: command line or configuration file.
716
717 Loading a plugin follows the following steps:
718
719 1. Afb-daemon loads the plugin with *dlopen*.
720
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.
723
724 3. Afb-daemon builds an interface object for the plugin.
725
726 4. Afb-daemon calls the found function **pluginAfbV1Register** with interface pointer
727 as parameter.
728
729 5. Function **pluginAfbV1Register** setups the plugin and initialises it.
730
731 6. Function **pluginAfbV1Register** returns the pointer to a structure
732 describing the plugin: version, name (prefix or API name), and list of methods.
733
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.
737
738 Here after the code used for **pluginAfbV1Register** from plugin *tic-tac-toe*:
739
740 ```C
741 /*
742  * activation function for registering the plugin called by afb-daemon
743  */
744 const struct AFB_plugin *pluginAfbV1Register(const struct AFB_interface *itf)
745 {
746    afbitf = itf;         // records the interface for accessing afb-daemon
747    return &plugin_description;  // returns the description of the plugin
748 }
749 ```
750
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.
754
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:
758
759 ```C
760 /*
761  * the interface to afb-daemon
762  */
763 const struct AFB_interface *afbitf;
764 ```
765
766 The description of the plugin is defined here after.
767
768 ```C
769 /*
770  * array of the methods exported to afb-daemon
771  */
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 */
783 };
784
785 /*
786  * description of the plugin for afb-daemon
787  */
788 static const struct AFB_plugin plugin_description =
789 {
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 */
796    }
797 };
798 ```
799
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.
803
804 The list of methods is an array of structures describing the methods and terminated by a NULL marker.
805
806 In version one of afb-damon plugin, a method description contains 4 fields:
807
808 - the name of the method,
809
810 - the session management flags,
811
812 - the implementation function to be call for the method,
813
814 - a short description.
815
816 The structure describing methods is defined as follows:
817
818 ```C
819 /*
820  * Description of one method of the API provided by the plugin
821  * This enumeration is valid for plugins of type 1
822  */
823 struct AFB_method_desc_v1
824 {
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 */
829 };
830 ```
831
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
834 (the C operator |).
835
836 The constants that can bit mixed are:
837
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
856
857 If any of this flag is set, afb-daemon requires an authentication token
858 as if **AFB_SESSION_CHECK** flag was also set.
859
860 The special value **AFB_SESSION_NONE** is zero and can be used to bypass token check.
861
862 > Note that **AFB_SESSION_CREATE** and **AFB_SESSION_CLOSE** might be removed in later versions.
863
864 Sending messages to the log system
865 ----------------------------------
866
867 Afb-daemon provides 4 levels of verbosity and 5 methods for logging messages.
868
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.
871
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.
876
877 ### Verbs for logging messages
878
879 The 5 logging methods are:
880
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
888
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.
892
893 All of these methods have the same signature:
894
895 ```C
896 void ERROR(const struct AFB_interface *afbitf, const char *message, ...);
897 ```
898
899 The first argument **afbitf** is the interface to afb daemon that the
900 plugin received at initialisation time when **pluginAfbV1Register** is called.
901
902 The second argument **message** is a formatting string compatible with printf/sprintf.
903
904 The remaining arguments are arguments of the formating message like with printf.
905
906 ### Managing verbosity
907
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.
911
912 Level of verbosity | Outputed macro
913 :-----------------:|--------------------------
914 0                  | ERROR
915 1                  | ERROR + WARNING + NOTICE
916 2                  | ERROR + WARNING + NOTICE + INFO
917 3                  | ERROR + WARNING + NOTICE + INFO + DEBUG
918
919 ### Output format and destination
920
921 The syslog level is used for forging a prefix to the message.
922 The prefixes are:
923
924 syslog level | prefix
925 :-----------:|---------------
926 0            | <0> EMERGENCY
927 1            | <1> ALERT
928 2            | <2> CRITICAL
929 3            | <3> ERROR
930 4            | <4> WARNING
931 5            | <5> NOTICE
932 6            | <6> INFO
933 7            | <7> DEBUG
934
935
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).
940
941 Sending events
942 --------------
943
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
946 coming version.
947
948 The plugin *tic-tac-toe* broadcasts events when the board changes.
949 This is done in the function **changed**:
950
951 ```C
952 /*
953  * signals a change of the board
954  */
955 static void changed(struct board *board, const char *reason)
956 {
957         ...
958         struct json_object *description;
959
960         /* get the description */
961         description = describe(board);
962
963         ...
964
965         afb_daemon_broadcast_event(afbitf->daemon, reason, description);
966 }
967 ```
968
969 The description of the changed board is pushed via the daemon interface.
970
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.
975
976 Function **afb_daemon_broadcast_event** is defined here after:
977
978 ```C
979 /*
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.
983  *
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.
987  */
988 void afb_daemon_broadcast_event(struct afb_daemon daemon, const char *name, struct json_object *object);
989 ```
990
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.
995
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**.
999
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.
1004
1005
1006
1007 Writing an asynchronous method implementation
1008 -------------------------------------------
1009
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
1012 retrieve arguments.
1013
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.
1017
1018 In this case, the reply to the wait is sent only when the board changes.
1019 See the diagram below:
1020
1021         CLIENT A       CLIENT B         TIC-TAC-TOE
1022            |              |                  |
1023            +--------------|----------------->| wait . . . . . . . .
1024            |              |                  |                     .
1025            :              :                  :                      .
1026            :              :                  :                      .
1027            |              |                  |                      .
1028            |              +----------------->| move . . .           .
1029            |              |                  |          V           .
1030            |              |<-----------------+ success of move      .
1031            |              |                  |                    .
1032            |<-------------|------------------+ success of wait  <
1033
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, ...
1038
1039 Common case of an asynchronous implementation.
1040
1041 Here is the listing of the function **wait**:
1042
1043 ```C
1044 static void wait(struct afb_req req)
1045 {
1046         struct board *board;
1047         struct waiter *waiter;
1048
1049         /* retrieves the context for the session */
1050         board = board_of_req(req);
1051         INFO(afbitf, "method 'wait' called for boardid %d", board->id);
1052
1053         /* creates the waiter and enqueues it */
1054         waiter = calloc(1, sizeof *waiter);
1055         waiter->req = req;
1056         waiter->next = board->waiters;
1057         afb_req_addref(req);
1058         board->waiters = waiter;
1059 }
1060 ```
1061
1062 After retrieving the board, the function adds a new waiter to
1063 waiters list and returns without setting a reply.
1064
1065 Before returning, it increases **req** request's reference count using **afb_req_addref** function.
1066
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.
1070
1071 Later, when a board changes, it calls *tic-tac-toe* **changed** function
1072 with reason of change in parameter.
1073
1074 Here is the full listing of the function **changed**:
1075
1076 ```C
1077 /*
1078  * signals a change of the board
1079  */
1080 static void changed(struct board *board, const char *reason)
1081 {
1082         struct waiter *waiter, *next;
1083         struct json_object *description;
1084
1085         /* get the description */
1086         description = describe(board);
1087
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);
1094                 free(waiter);
1095                 waiter = next;
1096         }
1097
1098         afb_event_sender_push(afb_daemon_get_event_sender(afbitf->daemon), reason, description);
1099 }
1100 ```
1101
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.
1105
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.
1110
1111 How to build a plugin
1112 ---------------------
1113
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:
1118
1119 ```bash
1120 $ pkg-config --cflags afb-daemon
1121 $ pkg-config --libs afb-daemon
1122 ```
1123
1124 ### Example for cmake meta build system
1125
1126 This example is the extract for building the plugin *afm-main* using *CMAKE*.
1127
1128 ```cmake
1129 pkg_check_modules(afb afb-daemon)
1130 if(afb_FOUND)
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
1137                 PREFIX ""
1138                 LINK_FLAGS "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/afm-main-plugin.export-map"
1139         )
1140         install(TARGETS afm-main-plugin LIBRARY DESTINATION ${plugin_dir})
1141 else()
1142         message(STATUS "Not creating the plugin for AFB-DAEMON")
1143 endif()
1144 ```
1145
1146 Let now describe some of these lines.
1147
1148 ```cmake
1149 pkg_check_modules(afb afb-daemon)
1150 ```
1151
1152 This first lines searches to the *pkg-config* configuration file for
1153 **afb-daemon**. Resulting data are stored in the following variables:
1154
1155 Variable          | Meaning
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
1163
1164 If development files are found, the plugin can be added to the set of
1165 target to build.
1166
1167 ```cmake
1168 add_library(afm-main-plugin MODULE afm-main-plugin.c)
1169 ```
1170
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**.
1175
1176 ```cmake
1177 set_target_properties(afm-main-plugin PROPERTIES
1178         PREFIX ""
1179         LINK_FLAGS "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/afm-main-plugin.export-map"
1180 )
1181 ```
1182
1183 This lines are doing two things:
1184
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.
1190
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**).
1194
1195 Next line are:
1196
1197 ```cmake
1198 target_include_directories(afm-main-plugin PRIVATE ${afb_INCLUDE_DIRS})
1199 target_link_libraries(afm-main-plugin utils ${afb_LIBRARIES})
1200 ```
1201
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.
1204
1205 ### Exporting the function pluginAfbV1Register
1206
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).
1210
1211         { global: pluginAfbV1Register; local: *; };
1212
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
1215 other symbols.
1216
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.
1221
1222 ### Building within yocto
1223
1224 Adding a dependency to afb-daemon is enough. See below:
1225
1226         DEPENDS += " afb-daemon "
1227