adds documentation for websocket C clients
[src/app-framework-binder.git] / doc / afb-plugin-writing.html
1 <html>
2 <head>
3   <link rel="stylesheet" type="text/css" href="doc.css">
4   <meta charset="UTF-8">
5 </head>
6 <body>
7 <a name="HOWTO.WRITE.a.PLUGIN.for.AFB-DAEMON"></a>
8 <h1>HOWTO WRITE a PLUGIN for AFB-DAEMON</h1>
9
10 <pre><code>version: 1
11 Date:    29 mai 2016
12 Author:  José Bollo
13 </code></pre>
14
15 <p><ul>
16  <li><a href="#HOWTO.WRITE.a.PLUGIN.for.AFB-DAEMON">HOWTO WRITE a PLUGIN for AFB-DAEMON</a>
17  <ul>
18   <li><a href="#Summary">Summary</a>
19   <ul>
20    <li><a href="#Nature.of.a.plugin">Nature of a plugin</a></li>
21    <li><a href="#Class.of.plugins">Class of plugins</a>
22    <ul>
23     <li><a href="#Application-plugins">Application-plugins</a></li>
24     <li><a href="#Service-plugins">Service-plugins</a></li>
25    </ul>
26    </li>
27    <li><a href="#Live.cycle.of.plugins.within.afb-daemon">Live cycle of plugins within afb-daemon</a></li>
28    <li><a href="#Plugin.Contend">Plugin Contend</a>
29    <ul>
30     <li><a href="#The.name.of.the.plugin">The name of the plugin</a></li>
31     <li><a href="#Names.of.verbs">Names of verbs</a></li>
32     <li><a href="#The.initialisation.function">The initialisation function</a></li>
33     <li><a href="#Functions.implementing.verbs">Functions implementing verbs</a>
34 </li>
35    </ul>
36    </li>
37   </ul>
38   </li>
39   <li><a href="#The.Tic-Tac-Toe.example">The Tic-Tac-Toe example</a></li>
40   <li><a href="#Dependencies.when.compiling">Dependencies when compiling</a></li>
41   <li><a href="#Header.files.to.include">Header files to include</a></li>
42   <li><a href="#Choosing.names">Choosing names</a>
43   <ul>
44    <li><a href="#Names.for.API..plugin.">Names for API (plugin)</a></li>
45    <li><a href="#Names.for.verbs">Names for verbs</a></li>
46    <li><a href="#Names.for.arguments">Names for arguments</a></li>
47    <li><a href="#Forging.names.widely.available">Forging names widely available</a></li>
48   </ul>
49   </li>
50   <li><a href="#Writing.a.synchronous.verb.implementation">Writing a synchronous verb implementation</a>
51   <ul>
52    <li><a href="#The.incoming.request">The incoming request</a></li>
53    <li><a href="#Associating.a.context.to.the.session">Associating a context to the session</a></li>
54    <li><a href="#Sending.the.reply.to.a.request">Sending the reply to a request</a></li>
55   </ul>
56   </li>
57   <li><a href="#Getting.argument.of.invocation">Getting argument of invocation</a>
58   <ul>
59    <li><a href="#Basic.functions.for.querying.arguments">Basic functions for querying arguments</a></li>
60    <li><a href="#Arguments.for.received.files">Arguments for received files</a></li>
61    <li><a href="#Arguments.as.a.JSON.object">Arguments as a JSON object</a></li>
62   </ul>
63   </li>
64   <li><a href="#Initialisation.of.the.plugin.and.declaration.of.verbs">Initialisation of the plugin and declaration of verbs</a></li>
65   <li><a href="#Sending.messages.to.the.log.system">Sending messages to the log system</a>
66   <ul>
67    <li><a href="#Verbs.for.logging.messages">Verbs for logging messages</a></li>
68    <li><a href="#Managing.verbosity">Managing verbosity</a></li>
69    <li><a href="#Output.format.and.destination">Output format and destination</a></li>
70   </ul>
71   </li>
72   <li><a href="#Sending.events">Sending events</a></li>
73   <li><a href="#Writing.an.asynchronous.verb.implementation">Writing an asynchronous verb implementation</a></li>
74   <li><a href="#How.to.build.a.plugin">How to build a plugin</a>
75   <ul>
76    <li><a href="#Example.for.cmake.meta.build.system">Example for cmake meta build system</a></li>
77    <li><a href="#Exporting.the.function.pluginAfbV1Register">Exporting the function pluginAfbV1Register</a></li>
78    <li><a href="#Building.within.yocto">Building within yocto</a></li>
79   </ul>
80   </li>
81  </ul>
82  </li>
83 </ul></p>
84
85 <a name="Summary"></a>
86 <h2>Summary</h2>
87
88 <p>The binder afb-daemon serves files through HTTP protocol
89 and offers to developers the capability to expose application APIs through
90 HTTP or WebSocket protocol.</p>
91
92 <p>Binder plugins are used to add API to afb-daemon.
93 This part describes how to write a plugin for afb-daemon.
94 Excepting this summary, this part is intended to be read
95 by developers.</p>
96
97 <p>Before moving further through an example, here after
98 a short overview of binder plugins fundamentals.</p>
99
100 <a name="Nature.of.a.plugin"></a>
101 <h3>Nature of a plugin</h3>
102
103 <p>A plugin is an independent piece of software, self contain and expose as a dynamically loadable library.
104 A plugin is loaded by afb-daemon that exposes contained API dynamically at runtime.</p>
105
106 <p>Technically, a binder plugins does not reference and is not linked with any library from afb-daemon.</p>
107
108 <a name="Class.of.plugins"></a>
109 <h3>Class of plugins</h3>
110
111 <p>Application binder supports two kinds of plugins: application plugins and service
112 plugins. Technically both class of plugin are equivalent and coding API is shared. Only sharing mode and security context diverge.</p>
113
114 <a name="Application-plugins"></a>
115 <h4>Application-plugins</h4>
116
117 <p>Application-plugins implements the glue in between application&rsquo;s UI and services. Every AGL application
118 has a corresponding binder that typically activates one or many plugins to interface the application logic with lower platform services.
119 When an application is started by AGL application framework, a dedicate binder is started that loads/activates application plugin(s).
120 The API expose by application-plugin are executed within corresponding application security context.</p>
121
122 <p>Application plugins generally handle a unique context for a unique client. As the application framework start
123 a dedicated instance of afb_daemon for each AGL application, if a given plugin is used within multiple application each of those
124 application get a new and private instance of this &ldquo;shared&rdquo; plugin.</p>
125
126 <a name="Service-plugins"></a>
127 <h4>Service-plugins</h4>
128
129 <p>Service-plugins enable API activation within corresponding service security context and not within calling application context.
130 Service-plugins are intended to run as a unique instance that is shared in between multiple clients.</p>
131
132 <p>Service-plugins can either be stateless or manage client context. When managing context each client get a private context.</p>
133
134 <p>Sharing may either be global to the platform (ie: GPS service) or dedicated to a given user (ie: preference management)</p>
135
136 <a name="Live.cycle.of.plugins.within.afb-daemon"></a>
137 <h3>Live cycle of plugins within afb-daemon</h3>
138
139 <p>Application and service plugins are loaded and activated each time a new afb-daemon is started.</p>
140
141 <p>At launch time, every loaded plugin initialise itself.
142 If a single plugin initialisation fail corresponding instance of afb-daemon self aborts.</p>
143
144 <p>Conversely, when plugin initialisation succeeds, it should register
145 its unique name and the list of API verbs it exposes.</p>
146
147 <p>When initialised, on request from clients plugin&rsquo;s function corresponding to expose API verbs
148 are activated by the afb-daemon instance attached to the application or service.</p>
149
150 <p>At exit time, no special action is enforced by afb-daemon. When a specific actions is required at afb-daemon stop,
151 developers should use &lsquo;atexit/on_exit&rsquo; during plugin initialisation sequence to register a custom exit function.</p>
152
153 <a name="Plugin.Contend"></a>
154 <h3>Plugin Contend</h3>
155
156 <p>Afb-daemon&rsquo;s plugin register two classes of objects: names and functions.</p>
157
158 <p>Plugins declare categories of names:
159  - A unique plugin name,
160  - Multiple API verb&rsquo;s names.</p>
161
162 <p>Plugins declare two categories of functions:
163  - initialisation function
164  - API functions implementing verbs</p>
165
166 <p>Afb-daemon parses URI requests to extract plugin name and API verb.
167 As an example, URI <strong>foo/bar</strong> translates to API verb named <strong>bar</strong> within plugin named <strong>foo</strong>.
168 To serve such a request, afb-daemon looks for an active plugin named <strong>foo</strong> and then within this plugin for an API verb named <strong>bar</strong>.
169 When find afb-daemon calls corresponding function with attached parameter if any.</p>
170
171 <p>Afb-daemon ignores letter case when parsing URI. Thus <strong>TicTacToe/Board</strong> and <strong>tictactoe/board</strong> are equivalent.</p>
172
173 <a name="The.name.of.the.plugin"></a>
174 <h4>The name of the plugin</h4>
175
176 <p>The name of the plugin is also known as the name
177 of the API that defines the plugin.</p>
178
179 <p>This name is also known as the prefix.</p>
180
181 <p>The name of a plugin MUST be unique within afb-daemon.</p>
182
183 <p>For example, when a client of afb-daemon
184 calls a method named <strong>foo/bar</strong>. Afb-daemon
185 extracts the prefix <strong>foo</strong> and the suffix <strong>bar</strong>.
186 <strong>foo</strong> is the API name and must match a plugin name,
187 the plugin that implements the verb <strong>bar</strong>.</p>
188
189 <a name="Names.of.verbs"></a>
190 <h4>Names of verbs</h4>
191
192 <p>Each plugin exposes a set of verbs that can be called
193 by client of afb-daemon.</p>
194
195 <p>The name of a verb MUST be unique within a plugin.</p>
196
197 <p>Plugins link verbs to functions that are called
198 when clients emit requests for that verb.</p>
199
200 <p>For example, when a client of afb-daemon
201 calls a method named <strong>foo/bar</strong>.</p>
202
203 <a name="The.initialisation.function"></a>
204 <h4>The initialisation function</h4>
205
206 <p>The initialisation function serves several purposes.</p>
207
208 <ol>
209 <li><p>It allows afb-daemon to check the version
210 of the plugin using the name of the initialisation
211 functions that it found. Currently, the initialisation
212 function is named <strong>pluginAfbV1Register</strong>. It identifies
213 the first version of plugins.</p></li>
214 <li><p>It allows the plugin to initialise itself.</p></li>
215 <li><p>It serves to the plugin to declare names, descriptions,
216 requirements and implmentations of the verbs that it exposes.</p></li>
217 </ol>
218
219
220 <a name="Functions.implementing.verbs"></a>
221 <h4>Functions implementing verbs</h4>
222
223 <p>When a method is called, afb-daemon constructs a request
224 object and pass it to the implementation function for verb
225 within the plugin of the API.</p>
226
227 <p>An implementation function receives a request object that
228 is used to get arguments of the request, to send
229 answer, to store session data.</p>
230
231 <p>A plugin MUST send an answer to the request.</p>
232
233 <p>But it is not mandatory to send the answer
234 before to return from the implementing function.
235 This behaviour is important for implementing
236 asynchronous actions.</p>
237
238 <p>Implementation functions that always reply to the request
239 before returning are named <em>synchronous implementations</em>.
240 Those that don&rsquo;t always reply to the request before
241 returning are named <em>asynchronous implementations</em>.</p>
242
243 <p>Asynchronous implementations typically initiate an
244 asynchronous action and record to send the reply
245 on completion of this action.</p>
246
247 <a name="The.Tic-Tac-Toe.example"></a>
248 <h2>The Tic-Tac-Toe example</h2>
249
250 <p>This part explains how to write an afb-plugin.
251 For the sake of being practical we will use many
252 examples from the tic-tac-toe example.
253 This plugin example is in <em>plugins/samples/tic-tac-toe.c</em>.</p>
254
255 <p>This plugin is named <strong><em>tictactoe</em></strong>.</p>
256
257 <a name="Dependencies.when.compiling"></a>
258 <h2>Dependencies when compiling</h2>
259
260 <p>Afb-daemon provides a configuration file for <em>pkg-config</em>.
261 Typing the command</p>
262
263 <pre><code>pkg-config --cflags afb-daemon
264 </code></pre>
265
266 <p>will print the flags to use for compiling, like this:</p>
267
268 <pre><code>$ pkg-config --cflags afb-daemon
269 -I/opt/local/include -I/usr/include/json-c 
270 </code></pre>
271
272 <p>For linking, you should use</p>
273
274 <pre><code>$ pkg-config --libs afb-daemon
275 -ljson-c
276 </code></pre>
277
278 <p>As you see, afb-daemon automatically includes dependency to json-c.
279 This is done through the <strong>Requires</strong> keyword of pkg-config
280 because almost all plugin will use <strong>json-c</strong>.</p>
281
282 <p>If this behaviour is a problem, let us know.</p>
283
284 <p>Internally, afb-daemon uses <strong>libsystemd</strong> for its event loop
285 and for its binding to D-Bus.
286 Plugins developpers are encouraged to also use this library.
287 But it is a matter of choice.
288 Thus there is no dependency to <strong>libsystemd</strong>.</p>
289
290 <blockquote><p>Afb-daemon provides no library for plugins.
291 The functions that the plugin need to have are given
292 to the plugin at runtime through pointer using read-only
293 memory.</p></blockquote>
294
295 <a name="Header.files.to.include"></a>
296 <h2>Header files to include</h2>
297
298 <p>The plugin <em>tictactoe</em> has the following lines for its includes:</p>
299
300 <pre><code>#define _GNU_SOURCE
301 #include &lt;stdio.h&gt;
302 #include &lt;string.h&gt;
303 #include &lt;json-c/json.h&gt;
304 #include &lt;afb/afb-plugin.h&gt;
305 </code></pre>
306
307 <p>The header <em>afb/afb-plugin.h</em> includes all the features that a plugin
308 needs except two foreign header that must be included by the plugin
309 if it needs it:</p>
310
311 <ul>
312 <li><em>json-c/json.h</em>: this header must be include to handle json objects;</li>
313 <li><em>systemd/sd-event.h</em>: this must be include to access the main loop;</li>
314 <li><em>systemd/sd-bus.h</em>: this may be include to use dbus connections.</li>
315 </ul>
316
317
318 <p>The <em>tictactoe</em> plugin does not use systemd features so it is not included.</p>
319
320 <p>When including <em>afb/afb-plugin.h</em>, the macro <strong>_GNU_SOURCE</strong> must be
321 defined.</p>
322
323 <a name="Choosing.names"></a>
324 <h2>Choosing names</h2>
325
326 <p>The designer of a plugin must defines names for its plugin
327 (or its API) and for the verbs of its API. He also
328 must defines names for arguments given by name.</p>
329
330 <p>While forging names, the designer should take into account
331 the rules for making valid names and some rules that make
332 the names easy to use across plaforms.</p>
333
334 <p>The names and strings used ALL are UTF-8 encoded.</p>
335
336 <a name="Names.for.API..plugin."></a>
337 <h3>Names for API (plugin)</h3>
338
339 <p>The names of the API are checked.
340 All characters are authorised except:</p>
341
342 <ul>
343 <li>the control characters (\u0000 .. \u001f)</li>
344 <li>the characters of the set { &lsquo; &rsquo;, &lsquo;&ldquo;&rsquo;, &lsquo;#&rsquo;, &lsquo;%&rsquo;, &lsquo;&amp;&rsquo;,
345 &lsquo;&rsquo;&lsquo;, &rsquo;/&lsquo;, &rsquo;?&lsquo;, &rsquo;`&lsquo;, &rsquo;\x7f' }</li>
346 </ul>
347
348
349 <p>In other words the set of forbidden characters is
350 { \u0000..\u0020, \u0022, \u0023, \u0025..\u0027,
351   \u002f, \u003f, \u0060, \u007f }.</p>
352
353 <p>Afb-daemon make no distinction between lower case
354 and upper case when searching for an API by its name.</p>
355
356 <a name="Names.for.verbs"></a>
357 <h3>Names for verbs</h3>
358
359 <p>The names of the verbs are not checked.</p>
360
361 <p>However, the validity rules for verb&rsquo;s names are the
362 same as for API names except that the dot (.) character
363 is forbidden.</p>
364
365 <p>Afb-daemon make no distinction between lower case
366 and upper case when searching for an API by its name.</p>
367
368 <a name="Names.for.arguments"></a>
369 <h3>Names for arguments</h3>
370
371 <p>The names for arguments are not restricted and can be
372 anything.</p>
373
374 <p>The arguments are searched with the case sensitive
375 string comparison. Thus the names &ldquo;index&rdquo; and &ldquo;Index&rdquo;
376 are not the same.</p>
377
378 <a name="Forging.names.widely.available"></a>
379 <h3>Forging names widely available</h3>
380
381 <p>The key names of javascript object can be almost
382 anything using the arrayed notation:</p>
383
384 <pre><code>object[key] = value
385 </code></pre>
386
387 <p>That is not the case with the dot notation:</p>
388
389 <pre><code>object.key = value
390 </code></pre>
391
392 <p>Using the dot notation, the key must be a valid javascript
393 identifier.</p>
394
395 <p>For this reason, the chosen names should better be
396 valid javascript identifier.</p>
397
398 <p>It is also a good practice, even for arguments, to not
399 rely on the case sensitivity and to avoid the use of
400 names different only by the case.</p>
401
402 <a name="Writing.a.synchronous.verb.implementation"></a>
403 <h2>Writing a synchronous verb implementation</h2>
404
405 <p>The verb <strong>tictactoe/board</strong> is a synchronous implementation.
406 Here is its listing:</p>
407
408 <pre><code>/*
409  * get the board
410  */
411 static void board(struct afb_req req)
412 {
413         struct board *board;
414         struct json_object *description;
415
416         /* retrieves the context for the session */
417         board = board_of_req(req);
418         INFO(afbitf, "method 'board' called for boardid %d", board-&gt;id);
419
420         /* describe the board */
421         description = describe(board);
422
423         /* send the board's description */
424         afb_req_success(req, description, NULL);
425 }
426 </code></pre>
427
428 <p>This examples show many aspects of writing a synchronous
429 verb implementation. Let summarize it:</p>
430
431 <ol>
432 <li><p>The function <strong>board_of_req</strong> retrieves the context stored
433 for the plugin: the board.</p></li>
434 <li><p>The macro <strong>INFO</strong> sends a message of kind <em>INFO</em>
435 to the logging system. The global variable named <strong>afbitf</strong>
436 used represents the interface to afb-daemon.</p></li>
437 <li><p>The function <strong>describe</strong> creates a json_object representing
438 the board.</p></li>
439 <li><p>The function <strong>afb_req_success</strong> sends the reply, attaching to
440 it the object <em>description</em>.</p></li>
441 </ol>
442
443
444 <a name="The.incoming.request"></a>
445 <h3>The incoming request</h3>
446
447 <p>For any implementation, the request is received by a structure of type
448 <strong>struct afb_req</strong>.</p>
449
450 <blockquote><p>Note that this is a PLAIN structure, not a pointer to a structure.</p></blockquote>
451
452 <p>The definition of <strong>struct afb_req</strong> is:</p>
453
454 <pre><code>/*
455  * Describes the request by plugins from afb-daemon
456  */
457 struct afb_req {
458         const struct afb_req_itf *itf;  /* the interfacing functions */
459         void *closure;          /* the closure for functions */
460 };
461 </code></pre>
462
463 <p>It contains two pointers: one, <em>itf</em>, points to the functions needed
464 to handle the internal request represented by the second pointer, <em>closure</em>.</p>
465
466 <blockquote><p>The structure must never be used directly.
467 Insted, use the intended functions provided
468 by afb-daemon and described here.</p></blockquote>
469
470 <p><em>req</em> is used to get arguments of the request, to send
471 answer, to store session data.</p>
472
473 <p>This object and its interface is defined and documented
474 in the file names <em>afb/afb-req-itf.h</em></p>
475
476 <p>The above example uses 2 times the request object <em>req</em>.</p>
477
478 <p>The first time, it is used for retrieving the board attached to
479 the session of the request.</p>
480
481 <p>The second time, it is used to send the reply: an object that
482 describes the current board.</p>
483
484 <a name="Associating.a.context.to.the.session"></a>
485 <h3>Associating a context to the session</h3>
486
487 <p>When the plugin <em>tic-tac-toe</em> receives a request, it musts regain
488 the board that describes the game associated to the session.</p>
489
490 <p>For a plugin, having data associated to a session is a common case.
491 This data is called the context of the plugin for the session.
492 For the plugin <em>tic-tac-toe</em>, the context is the board.</p>
493
494 <p>The requests <em>afb_req</em> offer four functions for
495 storing and retrieving the context associated to the session.</p>
496
497 <p>These functions are:</p>
498
499 <ul>
500 <li><p><strong>afb_req_context_get</strong>:
501 retrieves the context data stored for the plugin.</p></li>
502 <li><p><strong>afb_req_context_set</strong>:
503 store the context data of the plugin.</p></li>
504 <li><p><strong>afb_req_context</strong>:
505 retrieves the context data of the plugin,
506 if needed, creates the context and store it.</p></li>
507 <li><p><strong>afb_req_context_clear</strong>:
508 reset the stored data.</p></li>
509 </ul>
510
511
512 <p>The plugin <em>tictactoe</em> use a convenient function to retrieve
513 its context: the board. This function is <em>board_of_req</em>:</p>
514
515 <pre><code>/*
516  * retrieves the board of the request
517  */
518 static inline struct board *board_of_req(struct afb_req req)
519 {
520         return afb_req_context(req, (void*)get_new_board, (void*)release_board);
521 }
522 </code></pre>
523
524 <p>The function <strong>afb_req_context</strong> ensure an existing context
525 for the session of the request.
526 Its two last arguments are functions. Here, the casts are required
527 to avoid a warning when compiling.</p>
528
529 <p>Here is the definition of the function <strong>afb_req_context</strong></p>
530
531 <pre><code>/*
532  * Gets the pointer stored by the plugin for the session of 'req'.
533  * If the stored pointer is NULL, indicating that no pointer was
534  * already stored, afb_req_context creates a new context by calling
535  * the function 'create_context' and stores it with the freeing function
536  * 'free_context'.
537  */
538 static inline void *afb_req_context(struct afb_req req, void *(*create_context)(), void (*free_context)(void*))
539 {
540         void *result = afb_req_context_get(req);
541         if (result == NULL) {
542                 result = create_context();
543                 afb_req_context_set(req, result, free_context);
544         }
545         return result;
546 }
547 </code></pre>
548
549 <p>The second argument if the function that creates the context.
550 For the plugin <em>tic-tac-toe</em> it is the function <strong>get_new_board</strong>.
551 The function <strong>get_new_board</strong> creates a new board and set its
552 count of use to 1. The boards are counting their count of use
553 to free there ressources when no more used.</p>
554
555 <p>The third argument if the function that frees the context.
556 For the plugin <em>tic-tac-toe</em> it is the function <strong>release_board</strong>.
557 The function <strong>release_board</strong> decrease the the count of use of
558 the board given as argument. If the use count decrease to zero,
559 the board data are freed.</p>
560
561 <p>The definition of the other functions for dealing with contexts are:</p>
562
563 <pre><code>/*
564  * Gets the pointer stored by the plugin for the session of 'req'.
565  * When the plugin has not yet recorded a pointer, NULL is returned.
566  */
567 void *afb_req_context_get(struct afb_req req);
568
569 /*
570  * Stores for the plugin the pointer 'context' to the session of 'req'.
571  * The function 'free_context' will be called when the session is closed
572  * or if plugin stores an other pointer.
573  */
574 void afb_req_context_set(struct afb_req req, void *context, void (*free_context)(void*));
575
576 /*
577  * Frees the pointer stored by the plugin for the session of 'req'
578  * and sets it to NULL.
579  *
580  * Shortcut for: afb_req_context_set(req, NULL, NULL)
581  */
582 static inline void afb_req_context_clear(struct afb_req req)
583 {
584         afb_req_context_set(req, NULL, NULL);
585 }
586 </code></pre>
587
588 <a name="Sending.the.reply.to.a.request"></a>
589 <h3>Sending the reply to a request</h3>
590
591 <p>Two kinds of replies can be made: successful replies and
592 failure replies.</p>
593
594 <blockquote><p>Sending a reply to a request must be done at most one time.</p></blockquote>
595
596 <p>The two functions to send a reply of kind &ldquo;success&rdquo; are
597 <strong>afb_req_success</strong> and <strong>afb_req_success_f</strong>.</p>
598
599 <pre><code>/*
600  * Sends a reply of kind success to the request 'req'.
601  * The status of the reply is automatically set to "success".
602  * Its send the object 'obj' (can be NULL) with an
603  * informationnal comment 'info (can also be NULL).
604  *
605  * For conveniency, the function calls 'json_object_put' for 'obj'.
606  * Thus, in the case where 'obj' should remain available after
607  * the function returns, the function 'json_object_get' shall be used.
608  */
609 void afb_req_success(struct afb_req req, struct json_object *obj, const char *info);
610
611 /*
612  * Same as 'afb_req_success' but the 'info' is a formatting
613  * string followed by arguments.
614  *
615  * For conveniency, the function calls 'json_object_put' for 'obj'.
616  * Thus, in the case where 'obj' should remain available after
617  * the function returns, the function 'json_object_get' shall be used.
618  */
619 void afb_req_success_f(struct afb_req req, struct json_object *obj, const char *info, ...);
620 </code></pre>
621
622 <p>The two functions to send a reply of kind &ldquo;failure&rdquo; are
623 <strong>afb_req_fail</strong> and <strong>afb_req_fail_f</strong>.</p>
624
625 <pre><code>/*
626  * Sends a reply of kind failure to the request 'req'.
627  * The status of the reply is set to 'status' and an
628  * informationnal comment 'info' (can also be NULL) can be added.
629  *
630  * Note that calling afb_req_fail("success", info) is equivalent
631  * to call afb_req_success(NULL, info). Thus even if possible it
632  * is strongly recommanded to NEVER use "success" for status.
633  *
634  * For conveniency, the function calls 'json_object_put' for 'obj'.
635  * Thus, in the case where 'obj' should remain available after
636  * the function returns, the function 'json_object_get' shall be used.
637  */
638 void afb_req_fail(struct afb_req req, const char *status, const char *info);
639
640 /*
641  * Same as 'afb_req_fail' but the 'info' is a formatting
642  * string followed by arguments.
643  *
644  * For conveniency, the function calls 'json_object_put' for 'obj'.
645  * Thus, in the case where 'obj' should remain available after
646  * the function returns, the function 'json_object_get' shall be used.
647  */
648 void afb_req_fail_f(struct afb_req req, const char *status, const char *info, ...);
649 </code></pre>
650
651 <blockquote><p>For conveniency, these functions call <strong>json_object_put</strong> to release the object <strong>obj</strong>
652 that they send. Then <strong>obj</strong> can not be used after calling one of these reply functions.
653 When it is not the expected behaviour, calling the function <strong>json_object_get</strong> on the object <strong>obj</strong>
654 before cancels the effect of <strong>json_object_put</strong>.</p></blockquote>
655
656 <a name="Getting.argument.of.invocation"></a>
657 <h2>Getting argument of invocation</h2>
658
659 <p>Many verbs expect arguments. Afb-daemon let plugins
660 retrieve their arguments by name not by position.</p>
661
662 <p>Arguments are given by the requests either through HTTP
663 or through WebSockets.</p>
664
665 <p>For example, the verb <strong>join</strong> of the plugin <strong>tic-tac-toe</strong>
666 expects one argument: the <em>boardid</em> to join. Here is an extract:</p>
667
668 <pre><code>/*
669  * Join a board
670  */
671 static void join(struct afb_req req)
672 {
673         struct board *board, *new_board;
674         const char *id;
675
676         /* retrieves the context for the session */
677         board = board_of_req(req);
678         INFO(afbitf, "method 'join' called for boardid %d", board-&gt;id);
679
680         /* retrieves the argument */
681         id = afb_req_value(req, "boardid");
682         if (id == NULL)
683                 goto bad_request;
684         ...
685 </code></pre>
686
687 <p>The function <strong>afb_req_value</strong> search in the request <em>req</em>
688 for an argument whose name is given. When no argument of the
689 given name was passed, <strong>afb_req_value</strong> returns NULL.</p>
690
691 <blockquote><p>The search is case sensitive. So the name <em>boardid</em> is not the
692 same name than <em>BoardId</em>. But this must not be assumed so two
693 expected names of argument should not differ only by case.</p></blockquote>
694
695 <a name="Basic.functions.for.querying.arguments"></a>
696 <h3>Basic functions for querying arguments</h3>
697
698 <p>The function <strong>afb_req_value</strong> is defined as below:</p>
699
700 <pre><code>/*
701  * Gets from the request 'req' the string value of the argument of 'name'.
702  * Returns NULL if when there is no argument of 'name'.
703  * Returns the value of the argument of 'name' otherwise.
704  *
705  * Shortcut for: afb_req_get(req, name).value
706  */
707 static inline const char *afb_req_value(struct afb_req req, const char *name)
708 {
709         return afb_req_get(req, name).value;
710 }
711 </code></pre>
712
713 <p>It is defined as a shortcut to call the function <strong>afb_req_get</strong>.
714 That function is defined as below:</p>
715
716 <pre><code>/*
717  * Gets from the request 'req' the argument of 'name'.
718  * Returns a PLAIN structure of type 'struct afb_arg'.
719  * When the argument of 'name' is not found, all fields of result are set to NULL.
720  * When the argument of 'name' is found, the fields are filled,
721  * in particular, the field 'result.name' is set to 'name'.
722  *
723  * There is a special name value: the empty string.
724  * The argument of name "" is defined only if the request was made using
725  * an HTTP POST of Content-Type "application/json". In that case, the
726  * argument of name "" receives the value of the body of the HTTP request.
727  */
728 struct afb_arg afb_req_get(struct afb_req req, const char *name);
729 </code></pre>
730
731 <p>That function takes 2 parameters: the request and the name
732 of the argument to retrieve. It returns a PLAIN structure of
733 type <strong>struct afb_arg</strong>.</p>
734
735 <p>There is a special name that is defined when the request is
736 of type HTTP/POST with a Content-Type being application/json.
737 This name is <strong>&ldquo;&rdquo;</strong> (the empty string). In that case, the value
738 of this argument of empty name is the string received as a body
739 of the post and is supposed to be a JSON string.</p>
740
741 <p>The definition of <strong>struct afb_arg</strong> is:</p>
742
743 <pre><code>/*
744  * Describes an argument (or parameter) of a request
745  */
746 struct afb_arg {
747         const char *name;   /* name of the argument or NULL if invalid */
748         const char *value;  /* string representation of the value of the argument */
749                                 /* original filename of the argument if path != NULL */
750         const char *path;   /* if not NULL, path of the received file for the argument */
751                                 /* when the request is finalized this file is removed */
752 };
753 </code></pre>
754
755 <p>The structure returns the data arguments that are known for the
756 request. This data include a field named <strong>path</strong>. This <strong>path</strong>
757 can be accessed using the function <strong>afb_req_path</strong> defined as
758 below:</p>
759
760 <pre><code>/*
761  * Gets from the request 'req' the path for file attached to the argument of 'name'.
762  * Returns NULL if when there is no argument of 'name' or when there is no file.
763  * Returns the path of the argument of 'name' otherwise.
764  *
765  * Shortcut for: afb_req_get(req, name).path
766  */
767 static inline const char *afb_req_path(struct afb_req req, const char *name)
768 {
769         return afb_req_get(req, name).path;
770 }
771 </code></pre>
772
773 <p>The path is only defined for HTTP/POST requests that send file.</p>
774
775 <a name="Arguments.for.received.files"></a>
776 <h3>Arguments for received files</h3>
777
778 <p>As it is explained just above, clients can send files using
779 HTTP/POST requests.</p>
780
781 <p>Received files are attached to a arguments. For example, the
782 following HTTP fragment (from test/sample-post.html)
783 will send an HTTP/POST request to the method
784 <strong>post/upload-image</strong> with 2 arguments named <em>file</em> and
785 <em>hidden</em>.</p>
786
787 <pre><code>&lt;h2&gt;Sample Post File&lt;/h2&gt;
788 &lt;form enctype="multipart/form-data"&gt;
789     &lt;input type="file" name="file" /&gt;
790     &lt;input type="hidden" name="hidden" value="bollobollo" /&gt;
791     &lt;br&gt;
792     &lt;button formmethod="POST" formaction="api/post/upload-image"&gt;Post File&lt;/button&gt;
793 &lt;/form&gt;
794 </code></pre>
795
796 <p>In that case, the argument named <strong>file</strong> has its value and its
797 path defined and not NULL.</p>
798
799 <p>The value is the name of the file as it was
800 set by the HTTP client and is generally the filename on the
801 client side.</p>
802
803 <p>The path is the path of the file saved on the temporary local storage
804 area of the application. This is a randomly generated and unic filename
805 not linked in any way with the original filename on the client.</p>
806
807 <p>The plugin can use the file at the given path the way that it wants:
808 read, write, remove, copy, rename&hellip;
809 But when the reply is sent and the query is terminated, the file at
810 this path is destroyed if it still exist.</p>
811
812 <a name="Arguments.as.a.JSON.object"></a>
813 <h3>Arguments as a JSON object</h3>
814
815 <p>Plugins can get all the arguments as one single object.
816 This feature is provided by the function <strong>afb_req_json</strong>
817 that is defined as below:</p>
818
819 <pre><code>/*
820  * Gets from the request 'req' the json object hashing the arguments.
821  * The returned object must not be released using 'json_object_put'.
822  */
823 struct json_object *afb_req_json(struct afb_req req);
824 </code></pre>
825
826 <p>It returns a json object. This object depends on how the request was
827 made:</p>
828
829 <ul>
830 <li><p>For HTTP requests, this is an object whose keys are the names of the
831 arguments and whose values are either a string for common arguments or
832 an object like { &ldquo;file&rdquo;: &ldquo;&hellip;&rdquo;, &ldquo;path&rdquo;: &ldquo;&hellip;&rdquo; }</p></li>
833 <li><p>For WebSockets requests, the returned object is the object
834 given by the client transparently transported.</p></li>
835 </ul>
836
837
838 <blockquote><p>In fact, for Websockets requests, the function <strong>afb_req_value</strong>
839 can be seen as a shortcut to
840 <strong><em>json_object_get_string(json_object_object_get(afb_req_json(req), name))</em></strong></p></blockquote>
841
842 <a name="Initialisation.of.the.plugin.and.declaration.of.verbs"></a>
843 <h2>Initialisation of the plugin and declaration of verbs</h2>
844
845 <p>To be active, the verbs of the plugin should be declared to
846 afb-daemon. And even more, the plugin itself must be recorded.</p>
847
848 <p>The mechanism for doing this is very simple: when afb-need starts,
849 it loads the plugins that are listed in its argument or configuration.</p>
850
851 <p>Loading a plugin follows the following steps:</p>
852
853 <ol>
854 <li><p>It loads the plugin using <em>dlopen</em>.</p></li>
855 <li><p>It searchs for the symbol named <strong>pluginAfbV1Register</strong> using <em>dlsym</em>.
856 This symbol is assumed to be the exported initialisation function of the plugin.</p></li>
857 <li><p>It build an interface object for the plugin.</p></li>
858 <li><p>It calls the found function <strong>pluginAfbV1Register</strong> and pass it the pointer
859 to its interface.</p></li>
860 <li><p>The function <strong>pluginAfbV1Register</strong> setup the plugin, initialize it.</p></li>
861 <li><p>The function <strong>pluginAfbV1Register</strong> returns the pointer to a structure
862 that describes the plugin: its version, its name (prefix or API name), and the
863 list of its verbs.</p></li>
864 <li><p>Afb-daemon checks that the returned version and name can be managed.
865 If it can manage it, the plugin and its verbs are recorded and can be used
866 when afb-daemon finishes it initialisation.</p></li>
867 </ol>
868
869
870 <p>Here is the listing of the function <strong>pluginAfbV1Register</strong> of the plugin
871 <em>tic-tac-toe</em>:</p>
872
873 <pre><code>/*
874  * activation function for registering the plugin called by afb-daemon
875  */
876 const struct AFB_plugin *pluginAfbV1Register(const struct AFB_interface *itf)
877 {
878    afbitf = itf;         // records the interface for accessing afb-daemon
879    return &amp;plugin_description;  // returns the description of the plugin
880 }
881 </code></pre>
882
883 <p>This is a very small function because the <em>tic-tac-toe</em> plugin doesn&rsquo;t have initialisation step.
884 It merely record the daemon&rsquo;s interface and returns its descritption.</p>
885
886 <p>The variable <strong>afbitf</strong> is a variable global to the plugin. It records the
887 interface to afb-daemon and is used for logging and pushing events.
888 Here is its declaration:</p>
889
890 <pre><code>/*
891  * the interface to afb-daemon
892  */
893 const struct AFB_interface *afbitf;
894 </code></pre>
895
896 <p>The description of the plugin is defined as below.</p>
897
898 <pre><code>/*
899  * array of the verbs exported to afb-daemon
900  */
901 static const struct AFB_verb_desc_v1 plugin_verbs[] = {
902    /* VERB'S NAME     SESSION MANAGEMENT          FUNCTION TO CALL  SHORT DESCRIPTION */
903    { .name= "new",   .session= AFB_SESSION_NONE, .callback= new,   .info= "Starts a new game" },
904    { .name= "play",  .session= AFB_SESSION_NONE, .callback= play,  .info= "Asks the server to play" },
905    { .name= "move",  .session= AFB_SESSION_NONE, .callback= move,  .info= "Tells the client move" },
906    { .name= "board", .session= AFB_SESSION_NONE, .callback= board, .info= "Get the current board" },
907    { .name= "level", .session= AFB_SESSION_NONE, .callback= level, .info= "Set the server level" },
908    { .name= "join",  .session= AFB_SESSION_CHECK,.callback= join,  .info= "Join a board" },
909    { .name= "undo",  .session= AFB_SESSION_NONE, .callback= undo,  .info= "Undo the last move" },
910    { .name= "wait",  .session= AFB_SESSION_NONE, .callback= wait,  .info= "Wait for a change" },
911    { .name= NULL } /* marker for end of the array */
912 };
913
914 /*
915  * description of the plugin for afb-daemon
916  */
917 static const struct AFB_plugin plugin_description =
918 {
919    /* description conforms to VERSION 1 */
920    .type= AFB_PLUGIN_VERSION_1,
921    .v1= {               /* fills the v1 field of the union when AFB_PLUGIN_VERSION_1 */
922       .prefix= "tictactoe",     /* the API name (or plugin name or prefix) */
923       .info= "Sample tac-tac-toe game", /* short description of of the plugin */
924       .verbs = plugin_verbs     /* the array describing the verbs of the API */
925    }
926 };
927 </code></pre>
928
929 <p>The structure <strong>plugin_description</strong> describes the plugin.
930 It declares the type and version of the plugin, its name, a description
931 and a list of its verbs.</p>
932
933 <p>The list of verbs is an array of structures describing the verbs and terminated by a marker:
934 a verb whose name is NULL.</p>
935
936 <p>The description of the verbs for this version is made of 4 fields:</p>
937
938 <ul>
939 <li><p>the name of the verbs,</p></li>
940 <li><p>the session management flags,</p></li>
941 <li><p>the implementation function to be call for the verb,</p></li>
942 <li><p>a short description.</p></li>
943 </ul>
944
945
946 <p>The structure describing verbs is defined as follows:</p>
947
948 <pre><code>/*
949  * Description of one verb of the API provided by the plugin
950  * This enumeration is valid for plugins of type 1
951  */
952 struct AFB_verb_desc_v1
953 {
954        const char *name;                       /* name of the verb */
955        enum AFB_session_v1 session;            /* authorisation and session requirements of the verb */
956        void (*callback)(struct afb_req req);   /* callback function implementing the verb */
957        const char *info;                       /* textual description of the verb */
958 };
959 </code></pre>
960
961 <p>For technical reasons, the enumeration <strong>enum AFB_session_v1</strong> is not exactly an
962 enumeration but the wrapper of constant definitions that can be mixed using bitwise or
963 (the C operator |).</p>
964
965 <p>The constants that can bit mixed are:</p>
966
967 <table>
968 <thead>
969 <tr>
970 <th>Constant name        </th>
971 <th> Meaning</th>
972 </tr>
973 </thead>
974 <tbody>
975 <tr>
976 <td><strong>AFB_SESSION_CREATE</strong>   </td>
977 <td> Equals to AFB_SESSION_LOA_EQ_0|AFB_SESSION_RENEW</td>
978 </tr>
979 <tr>
980 <td><strong>AFB_SESSION_CLOSE</strong>    </td>
981 <td> Closes the session after the reply and set the LOA to 0</td>
982 </tr>
983 <tr>
984 <td><strong>AFB_SESSION_RENEW</strong>    </td>
985 <td> Refreshes the token of authentification</td>
986 </tr>
987 <tr>
988 <td><strong>AFB_SESSION_CHECK</strong>    </td>
989 <td> Just requires the token authentification</td>
990 </tr>
991 <tr>
992 <td><strong>AFB_SESSION_LOA_LE_0</strong> </td>
993 <td> Requires the current LOA to be lesser then or equal to 0</td>
994 </tr>
995 <tr>
996 <td><strong>AFB_SESSION_LOA_LE_1</strong> </td>
997 <td> Requires the current LOA to be lesser then or equal to 1</td>
998 </tr>
999 <tr>
1000 <td><strong>AFB_SESSION_LOA_LE_2</strong> </td>
1001 <td> Requires the current LOA to be lesser then or equal to 2</td>
1002 </tr>
1003 <tr>
1004 <td><strong>AFB_SESSION_LOA_LE_3</strong> </td>
1005 <td> Requires the current LOA to be lesser then or equal to 3</td>
1006 </tr>
1007 <tr>
1008 <td><strong>AFB_SESSION_LOA_GE_0</strong> </td>
1009 <td> Requires the current LOA to be greater then or equal to 0</td>
1010 </tr>
1011 <tr>
1012 <td><strong>AFB_SESSION_LOA_GE_1</strong> </td>
1013 <td> Requires the current LOA to be greater then or equal to 1</td>
1014 </tr>
1015 <tr>
1016 <td><strong>AFB_SESSION_LOA_GE_2</strong> </td>
1017 <td> Requires the current LOA to be greater then or equal to 2</td>
1018 </tr>
1019 <tr>
1020 <td><strong>AFB_SESSION_LOA_GE_3</strong> </td>
1021 <td> Requires the current LOA to be greater then or equal to 3</td>
1022 </tr>
1023 <tr>
1024 <td><strong>AFB_SESSION_LOA_EQ_0</strong> </td>
1025 <td> Requires the current LOA to be equal to 0</td>
1026 </tr>
1027 <tr>
1028 <td><strong>AFB_SESSION_LOA_EQ_1</strong> </td>
1029 <td> Requires the current LOA to be equal to 1</td>
1030 </tr>
1031 <tr>
1032 <td><strong>AFB_SESSION_LOA_EQ_2</strong> </td>
1033 <td> Requires the current LOA to be equal to 2</td>
1034 </tr>
1035 <tr>
1036 <td><strong>AFB_SESSION_LOA_EQ_3</strong> </td>
1037 <td> Requires the current LOA to be equal to 3</td>
1038 </tr>
1039 </tbody>
1040 </table>
1041
1042
1043 <p>If any of this flags is set, afb-daemon requires the token authentification
1044 as if the flag <strong>AFB_SESSION_CHECK</strong> had been set.</p>
1045
1046 <p>The special value <strong>AFB_SESSION_NONE</strong> is zero and can be used to avoid any check.</p>
1047
1048 <blockquote><p>Note that <strong>AFB_SESSION_CREATE</strong> and <strong>AFB_SESSION_CLOSE</strong> might be removed in later versions.</p></blockquote>
1049
1050 <a name="Sending.messages.to.the.log.system"></a>
1051 <h2>Sending messages to the log system</h2>
1052
1053 <p>Afb-daemon provides 4 levels of verbosity and 5 verbs for logging messages.</p>
1054
1055 <p>The verbosity is managed. Options allow the change the verbosity of afb-daemon
1056 and the verbosity of the plugins can be set plugin by plugin.</p>
1057
1058 <p>The verbs for logging messages are defined as macros that test the
1059 verbosity level and that call the real logging function only if the
1060 message must be output. This avoid evaluation of arguments of the
1061 formatting messages if the message must not be output.</p>
1062
1063 <a name="Verbs.for.logging.messages"></a>
1064 <h3>Verbs for logging messages</h3>
1065
1066 <p>The 5 logging verbs are:</p>
1067
1068 <table>
1069 <thead>
1070 <tr>
1071 <th>Macro   </th>
1072 <th style="text-align:center;"> Verbosity </th>
1073 <th> Meaning                       </th>
1074 <th style="text-align:center;"> syslog level</th>
1075 </tr>
1076 </thead>
1077 <tbody>
1078 <tr>
1079 <td>ERROR   </td>
1080 <td style="text-align:center;">     0     </td>
1081 <td> Error conditions              </td>
1082 <td style="text-align:center;">     3</td>
1083 </tr>
1084 <tr>
1085 <td>WARNING </td>
1086 <td style="text-align:center;">     1     </td>
1087 <td> Warning conditions            </td>
1088 <td style="text-align:center;">     4</td>
1089 </tr>
1090 <tr>
1091 <td>NOTICE  </td>
1092 <td style="text-align:center;">     1     </td>
1093 <td> Normal but significant condition  </td>
1094 <td style="text-align:center;">     5</td>
1095 </tr>
1096 <tr>
1097 <td>INFO    </td>
1098 <td style="text-align:center;">     2     </td>
1099 <td> Informational                 </td>
1100 <td style="text-align:center;">     6</td>
1101 </tr>
1102 <tr>
1103 <td>DEBUG   </td>
1104 <td style="text-align:center;">     3     </td>
1105 <td> Debug-level messages          </td>
1106 <td style="text-align:center;">     7</td>
1107 </tr>
1108 </tbody>
1109 </table>
1110
1111
1112 <p>You can note that the 2 verbs <strong>WARNING</strong> and <strong>INFO</strong> have the same level
1113 of verbosity. But they don&rsquo;t have the same <em>syslog level</em>. It means that
1114 they are output with a different level on the logging system.</p>
1115
1116 <p>All of these verbs have the same signature:</p>
1117
1118 <pre><code>void ERROR(const struct AFB_interface *afbitf, const char *message, ...);
1119 </code></pre>
1120
1121 <p>The first argument <strong>afbitf</strong> is the interface to afb daemon that the
1122 plugin received at its initialisation when <strong>pluginAfbV1Register</strong> was called.</p>
1123
1124 <p>The second argument <strong>message</strong> is a formatting string compatible with printf/sprintf.</p>
1125
1126 <p>The remaining arguments are arguments of the formating message like for printf.</p>
1127
1128 <a name="Managing.verbosity"></a>
1129 <h3>Managing verbosity</h3>
1130
1131 <p>Depending on the level of verbosity, the messages are output or not.
1132 The following table explains what messages will be output depending
1133 ont the verbosity level.</p>
1134
1135 <table>
1136 <thead>
1137 <tr>
1138 <th style="text-align:center;">Level of verbosity </th>
1139 <th> Outputed macro</th>
1140 </tr>
1141 </thead>
1142 <tbody>
1143 <tr>
1144 <td style="text-align:center;">0          </td>
1145 <td> ERROR</td>
1146 </tr>
1147 <tr>
1148 <td style="text-align:center;">1          </td>
1149 <td> ERROR + WARNING + NOTICE</td>
1150 </tr>
1151 <tr>
1152 <td style="text-align:center;">2          </td>
1153 <td> ERROR + WARNING + NOTICE + INFO</td>
1154 </tr>
1155 <tr>
1156 <td style="text-align:center;">3          </td>
1157 <td> ERROR + WARNING + NOTICE + INFO + DEBUG</td>
1158 </tr>
1159 </tbody>
1160 </table>
1161
1162
1163 <a name="Output.format.and.destination"></a>
1164 <h3>Output format and destination</h3>
1165
1166 <p>The syslog level is used for forging a prefix to the message.
1167 The prefixes are:</p>
1168
1169 <table>
1170 <thead>
1171 <tr>
1172 <th style="text-align:center;">syslog level </th>
1173 <th> prefix</th>
1174 </tr>
1175 </thead>
1176 <tbody>
1177 <tr>
1178 <td style="text-align:center;">0      </td>
1179 <td> <0> EMERGENCY</td>
1180 </tr>
1181 <tr>
1182 <td style="text-align:center;">1      </td>
1183 <td> <1> ALERT</td>
1184 </tr>
1185 <tr>
1186 <td style="text-align:center;">2      </td>
1187 <td> <2> CRITICAL</td>
1188 </tr>
1189 <tr>
1190 <td style="text-align:center;">3      </td>
1191 <td> <3> ERROR</td>
1192 </tr>
1193 <tr>
1194 <td style="text-align:center;">4      </td>
1195 <td> <4> WARNING</td>
1196 </tr>
1197 <tr>
1198 <td style="text-align:center;">5      </td>
1199 <td> <5> NOTICE</td>
1200 </tr>
1201 <tr>
1202 <td style="text-align:center;">6      </td>
1203 <td> <6> INFO</td>
1204 </tr>
1205 <tr>
1206 <td style="text-align:center;">7      </td>
1207 <td> <7> DEBUG</td>
1208 </tr>
1209 </tbody>
1210 </table>
1211
1212
1213 <p>The message is issued to the standard error.
1214 The final destination of the message depends on how the systemd service
1215 was configured through the variable <strong>StandardError</strong>: It can be
1216 journal, syslog or kmsg. (See man sd-daemon).</p>
1217
1218 <a name="Sending.events"></a>
1219 <h2>Sending events</h2>
1220
1221 <p>Since version 0.5, plugins can broadcast events to any potential listener.
1222 This kind of bradcast is not targeted. Event targeted will come in a future
1223 version of afb-daemon.</p>
1224
1225 <p>The plugin <em>tic-tac-toe</em> broadcasts events when the board changes.
1226 This is done in the function <strong>changed</strong>:</p>
1227
1228 <pre><code>/*
1229  * signals a change of the board
1230  */
1231 static void changed(struct board *board, const char *reason)
1232 {
1233         ...
1234         struct json_object *description;
1235
1236         /* get the description */
1237         description = describe(board);
1238
1239         ...
1240
1241         afb_daemon_broadcast_event(afbitf-&gt;daemon, reason, description);
1242 }
1243 </code></pre>
1244
1245 <p>The description of the changed board is pushed via the daemon interface.</p>
1246
1247 <p>Within the plugin <em>tic-tac-toe</em>, the <em>reason</em> indicates the origin of
1248 the change. For the function <strong>afb_daemon_broadcast_event</strong>, the second
1249 parameter is the name of the broadcasted event. The third argument is the
1250 object that is transmitted with the event.</p>
1251
1252 <p>The function <strong>afb_daemon_broadcast_event</strong> is defined as below:</p>
1253
1254 <pre><code>/*
1255  * Broadcasts widely the event of 'name' with the data 'object'.
1256  * 'object' can be NULL.
1257  * 'daemon' MUST be the daemon given in interface when activating the plugin.
1258  *
1259  * For conveniency, the function calls 'json_object_put' for 'object'.
1260  * Thus, in the case where 'object' should remain available after
1261  * the function returns, the function 'json_object_get' shall be used.
1262  */
1263 void afb_daemon_broadcast_event(struct afb_daemon daemon, const char *name, struct json_object *object);
1264 </code></pre>
1265
1266 <blockquote><p>Be aware, as for reply functions, the <strong>object</strong> is automatically released using
1267 <strong>json_object_put</strong> by the function. Then call <strong>json_object_get</strong> before
1268 calling <strong>afb_daemon_broadcast_event</strong> to keep <strong>object</strong> available
1269 after the returning of the function.</p></blockquote>
1270
1271 <p>In fact the event name received by the listener is prefixed with
1272 the name of the plugin. So when the change occurs after a move, the
1273 reason is <strong>move</strong> and then the clients receive the event <strong>tictactoe/move</strong>.</p>
1274
1275 <blockquote><p>Note that nothing is said about the case sensitivity of event names.
1276 However, the event is always prefixed with the name that the plugin
1277 declared, with the same case, followed with a slash /.
1278 Thus it is safe to compare event using a case sensitive comparison.</p></blockquote>
1279
1280 <a name="Writing.an.asynchronous.verb.implementation"></a>
1281 <h2>Writing an asynchronous verb implementation</h2>
1282
1283 <p>The <em>tic-tac-toe</em> example allows two clients or more to share the same board.
1284 This is implemented by the verb <strong>join</strong> that illustrated partly the how to
1285 retrieve arguments.</p>
1286
1287 <p>When two or more clients are sharing a same board, one of them can wait
1288 until the state of the board changes. (This coulded also be implemented using
1289 events because an even is generated each time the board changes).</p>
1290
1291 <p>In this case, the reply to the wait is sent only when the board changes.
1292 See the diagram below:</p>
1293
1294 <pre><code>CLIENT A       CLIENT B         TIC-TAC-TOE
1295    |              |                  |
1296    +--------------|-----------------&gt;| wait . . . . . . . .
1297    |              |                  |                     .
1298    :              :                  :                      .
1299    :              :                  :                      .
1300    |              |                  |                      .
1301    |              +-----------------&gt;| move . . .           .
1302    |              |                  |          V           .
1303    |              |&lt;-----------------+ success of move      .
1304    |              |                  |                    .
1305    |&lt;-------------|------------------+ success of wait  &lt;
1306 </code></pre>
1307
1308 <p>Here, this is an invocation of the plugin by an other client that
1309 unblock the suspended <em>wait</em> call.
1310 But in general, this will be a timer, a hardware event, the sync with
1311 a concurrent process or thread, &hellip;</p>
1312
1313 <p>So the case is common, this is an asynchronous implementation.</p>
1314
1315 <p>Here is the listing of the function <strong>wait</strong>:</p>
1316
1317 <pre><code>static void wait(struct afb_req req)
1318 {
1319         struct board *board;
1320         struct waiter *waiter;
1321
1322         /* retrieves the context for the session */
1323         board = board_of_req(req);
1324         INFO(afbitf, "method 'wait' called for boardid %d", board-&gt;id);
1325
1326         /* creates the waiter and enqueues it */
1327         waiter = calloc(1, sizeof *waiter);
1328         waiter-&gt;req = req;
1329         waiter-&gt;next = board-&gt;waiters;
1330         afb_req_addref(req);
1331         board-&gt;waiters = waiter;
1332 }
1333 </code></pre>
1334
1335 <p>After retrieving the board, the function adds a new waiter to the
1336 current list of waiters and returns without sending a reply.</p>
1337
1338 <p>Before returning, it increases the reference count of the
1339 request <strong>req</strong> using the function <strong>afb_req_addref</strong>.</p>
1340
1341 <blockquote><p>When the implentation of a verb returns without sending a reply,
1342 it <strong>MUST</strong> increment the reference count of the request
1343 using <strong>afb_req_addref</strong>. If it doesn&rsquo;t bad things can happen.</p></blockquote>
1344
1345 <p>Later, when the board changes, it calls the function <strong>changed</strong>
1346 of <em>tic-tac-toe</em> with the reason of the change.</p>
1347
1348 <p>Here is the full listing of the function <strong>changed</strong>:</p>
1349
1350 <pre><code>/*
1351  * signals a change of the board
1352  */
1353 static void changed(struct board *board, const char *reason)
1354 {
1355         struct waiter *waiter, *next;
1356         struct json_object *description;
1357
1358         /* get the description */
1359         description = describe(board);
1360
1361         waiter = board-&gt;waiters;
1362         board-&gt;waiters = NULL;
1363         while (waiter != NULL) {
1364                 next = waiter-&gt;next;
1365                 afb_req_success(waiter-&gt;req, json_object_get(description), reason);
1366                 afb_req_unref(waiter-&gt;req);
1367                 free(waiter);
1368                 waiter = next;
1369         }
1370
1371         afb_event_sender_push(afb_daemon_get_event_sender(afbitf-&gt;daemon), reason, description);
1372 }
1373 </code></pre>
1374
1375 <p>The list of waiters is walked and a reply is sent to each waiter.
1376 After the sending the reply, the reference count of the request
1377 is decremented using <strong>afb_req_unref</strong> to allow its resources to be freed.</p>
1378
1379 <blockquote><p>The reference count <strong>MUST</strong> be decremented using <strong>afb_req_unref</strong> because,
1380 otherwise, there is a leak of resources.
1381 It must be decremented <strong>AFTER</strong> the sending of the reply, because, otherwise,
1382 bad things may happen.</p></blockquote>
1383
1384 <a name="How.to.build.a.plugin"></a>
1385 <h2>How to build a plugin</h2>
1386
1387 <p>Afb-daemon provides a <em>pkg-config</em> configuration file that can be
1388 queried by the name <strong>afb-daemon</strong>.
1389 This configuration file provides data that should be used
1390 for compiling plugins. Examples:</p>
1391
1392 <pre><code>$ pkg-config --cflags afb-daemon
1393 $ pkg-config --libs afb-daemon
1394 </code></pre>
1395
1396 <a name="Example.for.cmake.meta.build.system"></a>
1397 <h3>Example for cmake meta build system</h3>
1398
1399 <p>This example is the extract for building the plugin <em>afm-main</em> using <em>CMAKE</em>.</p>
1400
1401 <pre><code>pkg_check_modules(afb afb-daemon)
1402 if(afb_FOUND)
1403         message(STATUS "Creation afm-main-plugin for AFB-DAEMON")
1404         add_library(afm-main-plugin MODULE afm-main-plugin.c)
1405         target_compile_options(afm-main-plugin PRIVATE ${afb_CFLAGS})
1406         target_include_directories(afm-main-plugin PRIVATE ${afb_INCLUDE_DIRS})
1407         target_link_libraries(afm-main-plugin utils ${afb_LIBRARIES})
1408         set_target_properties(afm-main-plugin PROPERTIES
1409                 PREFIX ""
1410                 LINK_FLAGS "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/afm-main-plugin.export-map"
1411         )
1412         install(TARGETS afm-main-plugin LIBRARY DESTINATION ${plugin_dir})
1413 else()
1414         message(STATUS "Not creating the plugin for AFB-DAEMON")
1415 endif()
1416 </code></pre>
1417
1418 <p>Let now describe some of these lines.</p>
1419
1420 <pre><code>pkg_check_modules(afb afb-daemon)
1421 </code></pre>
1422
1423 <p>This first lines searches to the <em>pkg-config</em> configuration file for
1424 <strong>afb-daemon</strong>. Resulting data are stored in the following variables:</p>
1425
1426 <table>
1427 <thead>
1428 <tr>
1429 <th>Variable      </th>
1430 <th> Meaning</th>
1431 </tr>
1432 </thead>
1433 <tbody>
1434 <tr>
1435 <td>afb_FOUND     </td>
1436 <td> Set to 1 if afb-daemon plugin development files exist</td>
1437 </tr>
1438 <tr>
1439 <td>afb_LIBRARIES     </td>
1440 <td> Only the libraries (w/o the &lsquo;-l&rsquo;) for compiling afb-daemon plugins</td>
1441 </tr>
1442 <tr>
1443 <td>afb_LIBRARY_DIRS  </td>
1444 <td> The paths of the libraries (w/o the &lsquo;-L&rsquo;) for compiling afb-daemon plugins</td>
1445 </tr>
1446 <tr>
1447 <td>afb_LDFLAGS       </td>
1448 <td> All required linker flags for compiling afb-daemon plugins</td>
1449 </tr>
1450 <tr>
1451 <td>afb_INCLUDE_DIRS  </td>
1452 <td> The &lsquo;-I&rsquo; preprocessor flags (w/o the &lsquo;-I&rsquo;) for compiling afb-daemon plugins</td>
1453 </tr>
1454 <tr>
1455 <td>afb_CFLAGS    </td>
1456 <td> All required cflags for compiling afb-daemon plugins</td>
1457 </tr>
1458 </tbody>
1459 </table>
1460
1461
1462 <p>If development files are found, the plugin can be added to the set of
1463 target to build.</p>
1464
1465 <pre><code>add_library(afm-main-plugin MODULE afm-main-plugin.c)
1466 </code></pre>
1467
1468 <p>This line asks to create a shared library having only the
1469 source file afm-main-plugin.c (that is compiled).
1470 The default name of the created shared object is
1471 <strong>libafm-main-plugin.so</strong>.</p>
1472
1473 <pre><code>set_target_properties(afm-main-plugin PROPERTIES
1474         PREFIX ""
1475         LINK_FLAGS "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/afm-main-plugin.export-map"
1476 )
1477 </code></pre>
1478
1479 <p>This lines are doing two things:</p>
1480
1481 <ol>
1482 <li><p>It renames the built library from <strong>libafm-main-plugin.so</strong> to <strong>afm-main-plugin.so</strong>
1483 by removing the implicitely added prefix <em>lib</em>. This step is not mandatory
1484 at all because afb-daemon doesn&rsquo;t check names of files when loading it.
1485 The only convention that use afb-daemon is that extension is <strong>.so</strong>
1486 but this convention is used only when afb-daemon discovers plugin
1487 from a directory hierarchy.</p></li>
1488 <li><p>It applies a version script at link to only export the conventional name
1489 of the entry point: <strong>pluginAfbV1Register</strong>. See below. By default, the linker
1490 that creates the shared object exports all the public symbols (C functions that
1491 are not <strong>static</strong>).</p></li>
1492 </ol>
1493
1494
1495 <p>Next line are:</p>
1496
1497 <pre><code>target_include_directories(afm-main-plugin PRIVATE ${afb_INCLUDE_DIRS})
1498 target_link_libraries(afm-main-plugin utils ${afb_LIBRARIES})
1499 </code></pre>
1500
1501 <p>As you can see it uses the variables computed by <strong><em>pkg_check_modules(afb afb-daemon)</em></strong>
1502 to configure the compiler and the linker.</p>
1503
1504 <a name="Exporting.the.function.pluginAfbV1Register"></a>
1505 <h3>Exporting the function pluginAfbV1Register</h3>
1506
1507 <p>The function <strong>pluginAfbV1Register</strong> must be exported. This can be achieved
1508 using a version script when linking. Here is the version script that is
1509 used for <em>tic-tac-toe</em> (plugins/samples/export.map).</p>
1510
1511 <pre><code>{ global: pluginAfbV1Register; local: *; };
1512 </code></pre>
1513
1514 <p>This sample <a href="https://sourceware.org/binutils/docs-2.26/ld/VERSION.html#VERSION">version script</a>
1515 exports as global the symbol <em>pluginAfbV1Register</em> and hides any
1516 other symbols.</p>
1517
1518 <p>This version script is added to the link options using the
1519 option <strong>&ndash;version-script=export.map</strong> is given directly to the
1520 linker or using th option <strong>-Wl,&ndash;version-script=export.map</strong>
1521 when the option is given to the C compiler.</p>
1522
1523 <a name="Building.within.yocto"></a>
1524 <h3>Building within yocto</h3>
1525
1526 <p>Adding a dependency to afb-daemon is enough. See below:</p>
1527
1528 <pre><code>DEPENDS += " afb-daemon "
1529 </code></pre>
1530 </body>
1531 </html>