X-Git-Url: https://gerrit.automotivelinux.org/gerrit/gitweb?a=blobdiff_plain;ds=sidebyside;f=doc%2Fafb-bindings-writing.html;h=ea03801f8df184d8f6164c01bc3477fb8c25875f;hb=refs%2Fheads%2Fblowfish;hp=8017e190ff69815d1ef8add128a63d60a650aaab;hpb=7059e59cddc1c81321639875636e88895bc14309;p=src%2Fapp-framework-binder.git diff --git a/doc/afb-bindings-writing.html b/doc/afb-bindings-writing.html index 8017e190..ea03801f 100644 --- a/doc/afb-bindings-writing.html +++ b/doc/afb-bindings-writing.html @@ -7,35 +7,53 @@ HOWTO WRITE a BINDING for AFB-DAEMON - +

HOWTO WRITE a BINDING for AFB-DAEMON

José Bollo

-

23 juin 2016

+

27 juillet 2016

HOWTO WRITE a BINDING for AFB-DAEMON

-
version: 1
-Date:    09 juin 2016
-Author:  José Bollo

Summary

Afb-daemon binders serve files through HTTP protocol and offers to developers the capability to expose application API methods through HTTP or WebSocket protocol.

Binder bindings are used to add API to afb-daemon. This part describes how to write a binding for afb-daemon.

@@ -155,11 +170,11 @@ Author: José Bollo

Header files to include

Binding tictactoe has following includes:

-
#define _GNU_SOURCE
+
#define _GNU_SOURCE
 #include <stdio.h>
 #include <string.h>
 #include <json-c/json.h>
-#include <afb/afb-binding.h>
+#include <afb/afb-binding.h>

Header afb/afb-binding.h is the only hard dependency, it includes all features that a binding MUST HAVE. Outside of includes used to support application logic, common external headers used within bindings are:

The binding tictactoe use a convenient function to retrieve its context: the board. This function is board_of_req:

-
/*
+
/*
  * retrieves the board of the request
  */
 static inline struct board *board_of_req(struct afb_req req)
 {
     return afb_req_context(req, (void*)get_new_board, (void*)release_board);
-}
+}

The function afb_req_context ensures an existing context for the session of the request. Its two last arguments are functions to allocate and free context. Note function type casts to avoid compilation warnings.

Here is the definition of the function afb_req_context

-
/*
+
/*
  * Gets the pointer stored by the binding for the session of 'req'.
  * If the stored pointer is NULL, indicating that no pointer was
  * already stored, afb_req_context creates a new context by calling
@@ -282,11 +297,11 @@ Author:  José Bollo
afb_req_context_set(req, result, free_context); } return result; -}
+}

The second argument if the function that creates the context. For binding tic-tac-toe (function get_new_board). The function get_new_board creates a new board and set usage its count to 1. The boards are checking usage count to free resources when not used.

The third argument is a function that frees context resources. For binding tic-tac-toe (function release_board). The function release_board decrease usage count of the board passed in argument. When usage count falls to zero, data board are freed.

Definition of other functions dealing with contexts:

-
/*
+
/*
  * Gets the pointer stored by the binding for the session of 'req'.
  * When the binding has not yet recorded a pointer, NULL is returned.
  */
@@ -308,20 +323,20 @@ Author:  José Bollo
static inline void afb_req_context_clear(struct afb_req req) { afb_req_context_set(req, NULL, NULL); -}
+}

Sending reply to a request

Two kinds of replies: successful or failure.

Sending a reply to a request MUST be done once and only once.

It exists two functions for "success" replies: afb_req_success and afb_req_success_f.

-
/*
+
/*
  * Sends a reply of kind success to the request 'req'.
  * The status of the reply is automatically set to "success".
  * Its send the object 'obj' (can be NULL) with an
  * informationnal comment 'info (can also be NULL).
  *
- * For conveniency, the function calls 'json_object_put' for 'obj'.
+ * For convenience, the function calls 'json_object_put' for 'obj'.
  * Thus, in the case where 'obj' should remain available after
  * the function returns, the function 'json_object_get' shall be used.
  */
@@ -331,13 +346,13 @@ Author:  José Bollo
* Same as 'afb_req_success' but the 'info' is a formatting * string followed by arguments. * - * For conveniency, the function calls 'json_object_put' for 'obj'. + * For convenience, the function calls 'json_object_put' for 'obj'. * Thus, in the case where 'obj' should remain available after * the function returns, the function 'json_object_get' shall be used. */ -void afb_req_success_f(struct afb_req req, struct json_object *obj, const char *info, ...);
+void afb_req_success_f(struct afb_req req, struct json_object *obj, const char *info, ...);

It exists two functions for "failure" replies: afb_req_fail and afb_req_fail_f.

-
/*
+
/*
  * Sends a reply of kind failure to the request 'req'.
  * The status of the reply is set to 'status' and an
  * informational comment 'info' (can also be NULL) can be added.
@@ -346,7 +361,7 @@ Author:  José Bollo
* to call afb_req_success(NULL, info). Thus even if possible it * is strongly recommended to NEVER use "success" for status. * - * For conveniency, the function calls 'json_object_put' for 'obj'. + * For convenience, the function calls 'json_object_put' for 'obj'. * Thus, in the case where 'obj' should remain available after * the function returns, the function 'json_object_get' shall be used. */ @@ -356,19 +371,19 @@ Author: José Bollo
* Same as 'afb_req_fail' but the 'info' is a formatting * string followed by arguments. * - * For conveniency, the function calls 'json_object_put' for 'obj'. + * For convenience, the function calls 'json_object_put' for 'obj'. * Thus, in the case where 'obj' should remain available after * the function returns, the function 'json_object_get' shall be used. */ -void afb_req_fail_f(struct afb_req req, const char *status, const char *info, ...); +void afb_req_fail_f(struct afb_req req, const char *status, const char *info, ...);
-

For conveniency, these functions automatically call json_object_put to release obj. Because obj usage count is null after being passed to a reply function, it SHOULD not be used anymore. If exceptionally obj needs to remain usable after reply function then using json_object_get on obj to increase usage count and cancels the effect the json_object_put is possible.

+

For convenience, these functions automatically call json_object_put to release obj. Because obj usage count is null after being passed to a reply function, it SHOULD not be used anymore. If exceptionally obj needs to remain usable after reply function then using json_object_get on obj to increase usage count and cancels the effect the json_object_put is possible.

Getting argument of invocation

Many methods expect arguments. Afb-daemon's bindings retrieve arguments by name and not by position.

Arguments are passed by requests through either HTTP or WebSockets.

For example, the method join of binding tic-tac-toe expects one argument: the boardid to join. Here is an extract:

-
/*
+
/*
  * Join a board
  */
 static void join(struct afb_req req)
@@ -384,14 +399,14 @@ Author:  José Bollo
id = afb_req_value(req, "boardid"); if (id == NULL) goto bad_request; - ...
+ ...

The function afb_req_value searches in the request req for argument name passed in the second argument. When argument name is not passed, afb_req_value returns NULL.

The search is case sensitive and boardid is not equivalent to BoardId. Nevertheless having argument names that only differ by name case is not a good idea.

Basic functions for querying arguments

The function afb_req_value is defined here after:

-
/*
+
/*
  * Gets from the request 'req' the string value of the argument of 'name'.
  * Returns NULL if when there is no argument of 'name'.
  * Returns the value of the argument of 'name' otherwise.
@@ -401,9 +416,9 @@ Author:  José Bollo
static inline const char *afb_req_value(struct afb_req req, const char *name) { return afb_req_get(req, name).value; -}
+}

It is defined as a shortcut to call the function afb_req_get. That function is defined here after:

-
/*
+
/*
  * Gets from the request 'req' the argument of 'name'.
  * Returns a PLAIN structure of type 'struct afb_arg'.
  * When the argument of 'name' is not found, all fields of result are set to NULL.
@@ -415,11 +430,11 @@ Author:  José Bollo
* an HTTP POST of Content-Type "application/json". In that case, the * argument of name "" receives the value of the body of the HTTP request. */ -struct afb_arg afb_req_get(struct afb_req req, const char *name);
+struct afb_arg afb_req_get(struct afb_req req, const char *name);

That function takes 2 parameters: the request and the name of the argument to retrieve. It returns a PLAIN structure of type struct afb_arg.

There is a special name that is defined when the request is of type HTTP/POST with a Content-Type being application/json. This name is "" (the empty string). In that case, the value of this argument of empty name is the string received as a body of the post and is supposed to be a JSON string.

The definition of struct afb_arg is:

-
/*
+
/*
  * Describes an argument (or parameter) of a request
  */
 struct afb_arg {
@@ -428,9 +443,9 @@ Author:  José Bollo
/* original filename of the argument if path != NULL */ const char *path; /* if not NULL, path of the received file for the argument */ /* when the request is finalized this file is removed */ -};
+};

The structure returns the data arguments that are known for the request. This data include a field named path. This path can be accessed using the function afb_req_path defined here after:

-
/*
+
/*
  * Gets from the request 'req' the path for file attached to the argument of 'name'.
  * Returns NULL if when there is no argument of 'name' or when there is no file.
  * Returns the path of the argument of 'name' otherwise.
@@ -440,29 +455,29 @@ Author:  José Bollo
static inline const char *afb_req_path(struct afb_req req, const char *name) { return afb_req_get(req, name).path; -}
+}

The path is only defined for HTTP/POST requests that send file.

Arguments for received files

As it is explained above, clients can send files using HTTP/POST requests.

Received files are attached to "file" argument name. For example, the following HTTP fragment (from test/sample-post.html) will send an HTTP/POST request to the method post/upload-image with 2 arguments named file and hidden.

-
<h2>Sample Post File</h2>
+
<h2>Sample Post File</h2>
 <form enctype="multipart/form-data">
     <input type="file" name="file" />
     <input type="hidden" name="hidden" value="bollobollo" />
     <br>
     <button formmethod="POST" formaction="api/post/upload-image">Post File</button>
-</form>
+</form>

Argument named file should have both its value and path defined.

The value is the name of the file as it was set by the HTTP client. Generally it is the filename on client side.

The path is the effective path of saved file on the temporary local storage area of the application. This is a randomly generated and unique filename. It is not linked with the original filename as used on client side.

After success the binding can use the uploaded file directly from local storage path with no restriction: read, write, remove, copy, rename... Nevertheless when request reply is set and query terminated, the uploaded temporary file at path is destroyed.

Arguments as a JSON object

Bindings may also request every arguments of a given call as one single object. This feature is provided by the function afb_req_json defined here after:

-
/*
+
/*
  * Gets from the request 'req' the json object hashing the arguments.
  * The returned object must not be released using 'json_object_put'.
  */
-struct json_object *afb_req_json(struct afb_req req);
+struct json_object *afb_req_json(struct afb_req req);

It returns a json object. This object depends on how the request was built:

The structure describing methods is defined as follows:

-
/*
+
/*
  * Description of one method of the API provided by the binding
  * This enumeration is valid for bindings of type 1
  */
@@ -549,10 +564,14 @@ Author:  José Bollo
enum AFB_session_v1 session; /* authorisation and session requirements of the method */ void (*callback)(struct afb_req req); /* callback function implementing the method */ const char *info; /* textual description of the method */ -};
+};

For technical reasons, the enumeration enum AFB_session_v1 is not exactly an enumeration but the wrapper of constant definitions that can be mixed using bitwise or (the C operator |).

The constants that can bit mixed are:

- +
++++ @@ -681,7 +700,7 @@ Author: José Bollo
Constant name

You can note that the 2 methods WARNING and INFO have the same level of verbosity. But they don't have the same syslog level. It means that they are output with a different level on the logging system.

All of these methods have the same signature:

-
void ERROR(const struct afb_binding_interface *afbitf, const char *message, ...);
+
void ERROR(const struct afb_binding_interface *afbitf, const char *message, ...);

The first argument afbitf is the interface to afb daemon that the binding received at initialisation time when afbBindingV1Register is called.

The second argument message is a formatting string compatible with printf/sprintf.

The remaining arguments are arguments of the formating message like with printf.

@@ -761,7 +780,7 @@ Author: José Bollo

Sending events

Since version 0.5, bindings can broadcast events to any potential listener. As today only unattended even are supported. Targeted events are expected for next coming version.

The binding tic-tac-toe broadcasts events when the board changes. This is done in the function changed:

-
/*
+
/*
  * signals a change of the board
  */
 static void changed(struct board *board, const char *reason)
@@ -775,20 +794,20 @@ Author:  José Bollo
... afb_daemon_broadcast_event(afbitf->daemon, reason, description); -}
+}

The description of the changed board is pushed via the daemon interface.

Within binding tic-tac-toe, reason indicates the origin of the change. In function afb_daemon_broadcast_event the second parameter is the name of broadcasted event. The third argument is the object that is transmitted with the event.

Function afb_daemon_broadcast_event is defined here after:

-
/*
+
/*
  * Broadcasts widely the event of 'name' with the data 'object'.
  * 'object' can be NULL.
  * 'daemon' MUST be the daemon given in interface when activating the binding.
  *
- * For conveniency, the function calls 'json_object_put' for 'object'.
+ * For convenience, the function calls 'json_object_put' for 'object'.
  * Thus, in the case where 'object' should remain available after
  * the function returns, the function 'json_object_get' shall be used.
  */
-void afb_daemon_broadcast_event(struct afb_daemon daemon, const char *name, struct json_object *object);
+void afb_daemon_broadcast_event(struct afb_daemon daemon, const char *name, struct json_object *object);

Be aware, as with reply functions object is automatically released using json_object_put when using this function. Call json_object_get before calling afb_daemon_broadcast_event to keep object available after function returns.

@@ -815,7 +834,7 @@ Author: José Bollo

Here, this is an invocation of the binding by an other client that unblock the suspended wait call. Nevertheless in most case this should be a timer, a hardware event, a sync with a concurrent process or thread, ...

Common case of an asynchronous implementation.

Here is the listing of the function wait:

-
static void wait(struct afb_req req)
+
static void wait(struct afb_req req)
 {
     struct board *board;
     struct waiter *waiter;
@@ -830,7 +849,7 @@ Author:  José Bollo
waiter->next = board->waiters; afb_req_addref(req); board->waiters = waiter; -}
+}

After retrieving the board, the function adds a new waiter to waiters list and returns without setting a reply.

Before returning, it increases req request's reference count using afb_req_addref function.

@@ -838,7 +857,7 @@ Author: José Bollo

Later, when a board changes, it calls tic-tac-toe changed function with reason of change in parameter.

Here is the full listing of the function changed:

-
/*
+
/*
  * signals a change of the board
  */
 static void changed(struct board *board, const char *reason)
@@ -860,18 +879,18 @@ Author:  José Bollo
} afb_event_sender_push(afb_daemon_get_event_sender(afbitf->daemon), reason, description); -}
+}

The list of waiters is walked and a reply is sent to each waiter. After sending the reply, the reference count of the request is decremented using afb_req_unref to allow resources to be freed.

The reference count MUST be decremented using afb_req_unref to free resources and avoid memory leaks. This usage count decrement should happen AFTER setting reply or bad things may happen.

How to build a binding

Afb-daemon provides a pkg-config configuration file that can be queried by providing afb-daemon in command line arguments. This configuration file provides data that should be used for bindings compilation. Examples:

-
$ pkg-config --cflags afb-daemon
-$ pkg-config --libs afb-daemon
+
$ pkg-config --cflags afb-daemon
+$ pkg-config --libs afb-daemon

Example for cmake meta build system

This example is the extract for building the binding afm-main using CMAKE.

-
pkg_check_modules(afb afb-daemon)
+
pkg_check_modules(afb afb-daemon)
 if(afb_FOUND)
     message(STATUS "Creation afm-main-binding for AFB-DAEMON")
     add_library(afm-main-binding MODULE afm-main-binding.c)
@@ -885,11 +904,15 @@ $ pkg-config --libs afb-daemon
install(TARGETS afm-main-binding LIBRARY DESTINATION ${binding_dir}) else() message(STATUS "Not creating the binding for AFB-DAEMON") -endif()
+endif()

Let now describe some of these lines.

-
pkg_check_modules(afb afb-daemon)
+
pkg_check_modules(afb afb-daemon)

This first lines searches to the pkg-config configuration file for afb-daemon. Resulting data are stored in the following variables:

- +
++++ @@ -924,20 +947,20 @@ $ pkg-config --libs afb-daemon
Variable

If development files are found, the binding can be added to the set of target to build.

-
add_library(afm-main-binding MODULE afm-main-binding.c)
+
add_library(afm-main-binding MODULE afm-main-binding.c)

This line asks to create a shared library having a single source file named afm-main-binding.c to be compiled. The default name of the created shared object is libafm-main-binding.so.

-
set_target_properties(afm-main-binding PROPERTIES
+
set_target_properties(afm-main-binding PROPERTIES
     PREFIX ""
     LINK_FLAGS "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/afm-main-binding.export-map"
-)
+)

This lines are doing two things:

  1. It renames the built library from libafm-main-binding.so to afm-main-binding.so by removing the implicitly added prefix lib. This step is not mandatory because afb-daemon doesn't check names of files at load time. The only filename convention used by afb-daemon relates to .so termination. *.so pattern is used when afb-daemon automatically discovers binding from a directory hierarchy.

  2. It applies a version script at link time to only export the reserved name afbBindingV1Register for registration entry point. By default, when building a shared library linker exports all the public symbols (C functions that are not static).

Next line are:

-
target_include_directories(afm-main-binding PRIVATE ${afb_INCLUDE_DIRS})
-target_link_libraries(afm-main-binding utils ${afb_LIBRARIES})
+
target_include_directories(afm-main-binding PRIVATE ${afb_INCLUDE_DIRS})
+target_link_libraries(afm-main-binding utils ${afb_LIBRARIES})

As you can see it uses the variables computed by pkg_check_modules(afb afb-daemon) to configure the compiler and the linker.

Exporting the function afbBindingV1Register

The function afbBindingV1Register MUST be exported. This can be achieved using a version script at link time. Here after is a version script used for tic-tac-toe (bindings/samples/export.map).