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