AGL/Phase 2 - Application Framework Core

AGL/Phase 2 - Application Framework Core

10. HOWTO WRITE a BINDING for AFB-DAEMON

10.1 概要

  Afbデーモンバインダは、HTTPプロトコルを介してファイルを提供し、HTTPまたはWebSocketプロトコルを介してアプリケーションAPIメソッドを公開する機能を開発者に提供します。

Bindingはafb-daemonAPIを追加するために使用される。この章ではbindingの書き方について説明する。

この概要を除いて、このドキュメントは開発者を対象としています。

例をさらに進める前に、ここではbinder bindingの基礎について簡単に説明します

10.1.1 Nature of a binding

A binding is an independent piece of software. A binding is self contain and exposes application logic as sharable library.

Bindingは、アプリケーションに公開するAPIをafb-daemonによって動的に読み込まれます。

Technically, a binder binding does not reference and is not linked with any afb-daemon library.

10.1.2 Class of bindings

2つのbindingをサポートしている。:application bindings と service bindings。
両方ともソースコードは同じです。共有モードとセキュリティコンテキストだけ分かれます。

Application-bindings

Application-bindingsはアプリケーションUIとサービスの接着剤の役割です。
すべてのAGLアプリケーションは、アプリケーションロジックを下位のプラットフォームサービスに接続するための1つまたは複数のbinding起動に対応したbinderを持つ。
アプリケーションがフレームワークによって起動したとき、専用のbinderが起動し、application binding(s) を読み込み起動する。

Application-bindings は一般的に、ユニークなクライアントのためのユニークなコンテキストを操作する。
Application frameworkとして、それぞれのAGLアプリケーション毎に専用のafb_daemonインスタンスを起動してください、
もし、与えられたbindingが多様なアプリケーションで使われるならば、それらのアプリケーションの各々は結局 “共有”bindingの新しくてプライベートなインスタンスを得る。

Service-bindings

Service-bindingsは、applicationコンテキストの呼び出し内ではなく、サービスセキュリティコンテキスト内でAPI呼び出しを可能にする。
Service-bindingsはユニークなインスタンスとして起動する。
Service-bindingsは複数のアプリケーションから共有できる。

Service-bindingsはステートレス(状態を持たない)になれる、またはクライアントコンテキストを管理できる。
コンテキストを管理するとき、各クライアントはプライベートコンテキストを取得できる。
共有は、プラットホームにグローバルになる(GPSサービスなど)か、所定のユーザーを専門とする(ユーザー選択など)。

10.1.3 Live cycle of bindings within afb-daemon

Application-binder、Service-binderは新しいafb-daemonが開始するごとに読み込まれて実行される。

起動時、読み込まれたbindingは自身を初期化する。 1つのbindingの初期化に失敗するとafb-daemon自身が中断される。

逆に、初期化に成功すると、bindingは、ユニークな名前と、それが公開するmethodに付加されたVerb(binderの観点からのmethod名)のリストを登録する必要がある。

初期化がおわると、アプリケーションクライアントからの正常な API/verb への要求に関して、Application-binderやService-binderに紐付けられるafb-daemonによってメソッドが実行される。 実行の最後に、afb-daemonによる特別な操作はされない。 Afb-daemon停止時に特別な操作が必要なときは、開発者はexit関数を登録するために、bindingのインストールシーケンスの間に’atexit/on_exit’を使わなければいけない。

10.1.4 Binding Contend

Bindingは2つのクラス(‘names’と ‘functions’)を登録する。

Bindingは'names'カテゴリーを定義する: - bindingによって公開されるすべてのAPIにアクセスするためのユニークなbinding名。 - このbindingによって提供される methods/verbs を表す1つの名前。

Bindingsは'functions'の2つのカテゴリーを定義する: - 初期化処理のための関数 - 公開されるAPIメソッドを実装する関数

Afb-daemonAPI(binding name)とVERB(実行するメソッド)を抽出するために、URI要求を解析します。 As an example, URI foo/bar translates to binding named foo and method named bar. To serve such a request, afb-daemon looks for an active binding named foo and then within this binding for a method named bar. When find afb-daemon calls corresponding method with attached parameter if any.

Afb-daemonURIを解析するとき、大文字/小文字は無視する。TicTacToe/Boardtictactoe/board と同じ

The name of the binding

The name of a given binding is also known as the name of the API prefix that defines the binding.

Afb-daemonインスタンス内でユニークな名前をつけなければいけない。

For example, when a client of afb-daemon calls a URI named foo/bar. Afb-daemon extracts the prefix foo and the suffix bar. foo must match a binding name and bar a VERB attached to some method.

Names of methods

Each binding exposes a set of methods that can be called by the clients of a given afb-daemon.

VERB名はBinding内でユニークな名前をつけなければいけない。

Bindings static declaration link VERBS to corresponding methods. When clients emit requests on a given API/VERB corresponding method is called by afb-daemon.

Initialisation function

Bindingsの初期化関数はいくつかの目的がある。 Binding's initialisation function serves several purposes.

  1. Afb-daemonが初期化関数名に依存するbindingのバージョンを変更できるようにする。現在サポートされているのは afbBindingV1Register のみ。バージョンは1.0。

  2. binding自身が初期化処理をできるようにする。

  3. 様々な定義(公開されるAPI/VERBの説明、必要条件、機能)の命名ができるようにする。

Functions instantiation of API/VERBs

API/VERBS が呼ばれたとき、afb-daemonはリクエストオブジェクトを生成する。それから、このリクエストオブジェクトは要求されたメソッド対応する実行関数(bindingの関数)に渡される。

実行関数は次の用途で使われるリクエストオブジェクトを受け取ります。: リクエストの引数を得る。返答をする。セッションデータを保存する。

Bindigsはすべてのリクエストに対して返答しなければいけない。

だが、必ずしもAPI/VERBの実行関数から抜ける前に返答しなくてもよい。 これは非同期アクションのために重要なふるまいだ。

関数から抜ける前に返答をセットするAPI/VERB 実行は、同期実行と呼ばれる。 関数から抜ける前に返答をセットしないAPI/VERB 実行は、非同期実行と呼ばれる。

非同期実行は一般的に非同期アクションを開始します。 リクエスト時にいくつかのコンテキストを登録し、非同期アクションが完成したときにだけリクエストの返答をします。

10.2 The Tic-Tac-Toe example

このパートでは、afb-bindingの書き方を説明する。 実践的であるために、○×ゲームをベースにした多くの例を使います。 このソースは bindings/samples/tic-tac-toe.c にあります。

このbinding nameは tictactoe です。

10.3 Dependencies when compiling

Afb-daemonpkg-config用の設定ファイルを提供している。 以下のコマンドを打ってください

pkg-config --cflags afb-daemon

コンパイル時に使用するflagsの表示:

$ pkg-config --cflags afb-daemon
-I/opt/local/include -I/usr/include/json-c

リンクの表示:

$ pkg-config --libs afb-daemon
-ljson-c

Afb-daemon automatically includes dependency to json-c. This is activated through Requires keyword in pkg-config. While almost every binding replies on json-c this is not a must have dependency.

Internally, afb-daemon relies on libsystemd for its event loop, as well as for its binding to D-Bus. Bindings developers are encouraged to leverage libsystemd when possible. Nevertheless there is no hard dependency to libsystemd if ever you rather not use it, feel free to do so.

Afb-daemon binding are fully self contain. They do not enforce dependency on any libraries from the application framework. Afb-daemon dependencies requirer to run AGL bindings are given at runtime through pointers leveraging read-only memory feature.

10.4 Header files to include

Binding tictactoe は以下のヘッダをインクルードしている。

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

afb/afb-binding.h ヘッダーは bindingが持つべき機能を含んでいる。

Outside of includes used to support application logic, common external headers used within bindings are:

  • json-c/json.h: json: オブジェクトを操作する為にインクルードする
  • systemd/sd-event.h: イベントメインループにアクセスする為にインクルードする
  • systemd/sd-bus.h: dbusコネクションのためにインクルードする

The tictactoe binding does not leverage systemd features, also only json.h is used on top of mandatory afb/afb-binding.h.

afb/afb-binding.h をインクルードするとき、マクロ _GNU_SOURCE を定義しなければいけない。

10.5 Choosing names


bindingsの設計者はすべてのAPI(binding)、メソッド(VERBs)を表すユニークな名前を定義しなければいけない。 また、URIで name/value の組み合わせでリクエストされる引数の名前も定義しなければいけない。

While forging names, designers should respect few rules to ensure that created names are valid and easy to use across platforms.

すべての名前と文字列はUTF-8エンコードされる。

10.5.1 Names for API (binding)

Binding API名はチェックされる。 以下を除いたすべての文字は許可される:

  • the control characters (\u0000 .. \u001f)
  • the characters of the set { ' ', '"', '#', '%', '&', '\'', '/', '?', '`', '\x7f' }

In other words the set of forbidden characters is { \u0000..\u0020, \u0022, \u0023, \u0025..\u0027, \u002f, \u003f, \u0060, \u007f }.

Afb-daemon makes no distinction between lower case and upper case when searching for API/VERB.

10.5.2 Names for methods

The names of methods VERBs are totally free and not checked.

However, the validity rules for method's VERB name are the same as for Binding API name except that the dot(.) character is forbidden.

Afb-daemon makes no case distinction when searching for an API by name.

10.5.3 Names for arguments

引数名は制限されておらず、自由にできる。 Argument's name are not restricted and can be everything you wish.

Warning arguments search is case sensitive and "index" and "Index" are not two different arguments.

10.5.4 Forging names widely available

javascriptオブジェクトのキー名はほとんどは配列表記を使うことができる:

object[key] = value

それにもかかわらず、これはjavascriptのドット表記法では当てはまりません:

object.key = value

ドット表記を使用すると、キーは正しいjavascript(識別子とダッシュ(-)およびその他の予約文字は使用できません。)でなければなりません。

このため、開発者はjavascriptとHTML表記の両方と互換性のある名前を選択することをお勧めします.

大文字と小文字の区別に依存しない引数にしておくことは、良い習慣です。 This may reduce headache strength at debug time, especially with interpreted language like javascript that may not warn you that a variable was not defined.

10.6 Writing a synchronous method implementation

tictactoe/board メソッドは同期処理の実装です。

/*
 * get the board
 */
static void board(struct afb_req req)
{
    struct board *board;
    struct json_object *description;

    /* retrieves the context for the session */
    board = board_of_req(req);
    INFO(afbitf, "method 'board' called for boardid %d", board->id);

    /* describe the board */
    description = describe(board);

    /* send the board's description */
    afb_req_success(req, description, NULL);
}

この例は同期メソッドの実装に関する様々な要素を説明している。 要約すると:

  1. board_of_req 関数はbinding用に保存されているコンテキスト(ボード情報)を検索する。

  2. マクロ定義の INFOINFO 種別のメッセージをログシステムへ送信する。グローバル変数afbitf は afb-daemon へのインターフェースです。

  3. The function describe creates a json_object representing the board.

  4. The function afb_req_success sends the reply, attaching to it the object description.

10.6.1 The incoming request

すべてのbindingの実装で、リクエストは構造体 struct afb_req で受け取る。

注意:これは構造体のポインタではない。

The definition of struct afb_req is:

/*
 * Describes the request by bindings from afb-daemon
 */
struct afb_req {
    const struct afb_req_itf *itf;  /* the interfacing functions */
    void *closure;          /* the closure for functions */
};

2つのポインタを含んでいる。: - itf : 内部のリクエストを操作するための関数へのポインタ。 - closure : 関数クロージャーへのポインタ。

The structure must never be used directly. Instead developer should use the intended functions provided by afb-daemon as described here after.

req は以下の目的で使われる。 - リクエストの引数を取得する。 - レスポンスを返す。 - セッションデータを保存する。

このオブジェクトとインターフェースは afb/afb-req-itf.h に定義と記載がある。

borad() 関数の例では、req オブジェクトリクエストを2回使用している。

1回目は、リクエストのセッションに関連付けられているボード情報を検索している。

2回目は、現在のボードの情報を記述したjsonオブジェクトを返答している。

10.6.2 Associating a client context to a session

tic-tac-toe binding がリクエストを受信したとき、セッションに関連付けられたゲームを記述しているボード情報を取得しなければいけない。

Bindingは、セッションへの関連付けされたデータを持つこと一般的です。 このデータはセッションのための”binding context”と呼ばれている。 tic-tac-toe binding のコンテキストはボード情報です。

Requests afb_req offer four functions for storing and retrieving session associated context.

これらの処理を行う関数は以下です:

  • afb_req_context_get: 現在のbinding用に保存されているコンテキストを取り出す。

  • afb_req_context_set: 現在のbindingのコンテキストを保存する。

  • afb_req_context: 現在のbindingのコンテキストデータがあれば取り出す。 まだない場合は新しいコンテキストを作成して保存する。

  • afb_req_context_clear: 保存されているコンテキストを削除する。

tictactoe binding はコンテキスト(ボード情報)を取り出すための便利な関数 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);
}

afb_req_context 関数はリクエストのセッションの為に、コンテキストが存在することを保証する関数だ。 最後の2つの引数は、コンテキストを確保するための関数と、コンテキストを開放する関数です。

注意:コンパイルワーニングを避けるために、関数型キャストに注意してください。

以下が、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
 * the function 'create_context' and stores it with the freeing function
 * 'free_context'.
 */
static inline void *afb_req_context(struct afb_req req, void *(*create_context)(), void (*free_context)(void*))
{
    void *result = afb_req_context_get(req);
    if (result == NULL) {
        result = create_context();
        afb_req_context_set(req, result, free_context);
    }
    return result;
}

2つ目の引数がコンテキストを作成する関数です。 tic-tac-toe binding では get_new_board 関数がそれにあたります。 get_new_board 関数は新しいボード情報を作成し、ボード情報の使用カウントを1に設定します。 使用カウントをチェックし、ボードを使用しているユーザーがいない時に資源を解放します。 ボードは、未使用時にリソースを解放するために使用カウントをチェックしています。

3つ目の引数がコンテキストの資源を解放する関数です。 tic-tac-toe binding では release_board 関数がそれにあたります。 release_board 関数は、引数で渡されたボード情報の使用カウントを1つ減らす。 使用カウントが0になったとき、ボード情報コンテキストは開放される。

コンテキストを扱う他の関数の定義:

/*
 * Gets the pointer stored by the binding for the session of 'req'.
 * When the binding has not yet recorded a pointer, NULL is returned.
 */
void *afb_req_context_get(struct afb_req req);

/*
 * Stores for the binding the pointer 'context' to the session of 'req'.
 * The function 'free_context' will be called when the session is closed
 * or if binding stores an other pointer.
 */
void afb_req_context_set(struct afb_req req, void *context, void (*free_context)(void*));

/*
 * Frees the pointer stored by the binding for the session of 'req'
 * and sets it to NULL.
 *
 * Shortcut for: afb_req_context_set(req, NULL, NULL)
 */
static inline void afb_req_context_clear(struct afb_req req)
{
    afb_req_context_set(req, NULL, NULL);
}

10.6.3 Sending reply to a request

リプライの種類は2つ。Successful と failure です。

1つのリクエストに対するリプライは1つで1回のみです。

"success"をリプライする関数は、afb_req_successafb_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 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(struct afb_req req, struct json_object *obj, const char *info);

/*
 * Same as 'afb_req_success' but the 'info' is a formatting
 * string followed by arguments.
 *
 * 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, ...);

"failure"をリプライする関数は、afb_req_failafb_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.
 *
 * Note that calling afb_req_fail("success", info) is equivalent
 * to call afb_req_success(NULL, info). Thus even if possible it
 * is strongly recommended to NEVER use "success" for status.
 *
 * 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(struct afb_req req, const char *status, const char *info);

/*
 * Same as 'afb_req_fail' but the 'info' is a formatting
 * string followed by arguments.
 *
 * 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, ...);

利便性をよくするために、これらの関数は obj を開放するために自動的に json_object_put を呼ぶ。 これらのリプライ関数を通ったあとの obj はNULLなので、もう使用してはいけません。 もし例外的にリプライ関数を呼んだ後で obj を使いたい場合は、obj の使用カウントを増やすために json_object_getを呼び、 objjson_object_put による影響を無効にすることができます。

10.7. Getting argument of invocation

多くのmethdは引数を必要とする。Afb-daemon bindingは引数を名前指定で取り出す。

引数はHTTPかWebSocketを通して渡される。

例えば、tic-tac-toe binding の join は”ゲームに参加するための boardid を引数として必要としている。

/*
 * Join a board
 */
static void join(struct afb_req req)
{
    struct board *board, *new_board;
    const char *id;

    /* retrieves the context for the session */
    board = board_of_req(req);
    INFO(afbitf, "method 'join' called for boardid %d", board->id);

    /* retrieves the argument */
    id = afb_req_value(req, "boardid");
    if (id == NULL)
        goto bad_request;
    ...

afb_req_value 関数はリクエスreq の中から、2つ目の引数で指定された名前の引数を探す。指定した名前の変数が見つからなかった場合、afb_req_value 関数はNULLを返す。

検索は大文字小文字は区別され、boardidBoardId は同じではない。 にも関わらず、大文字と小文字だけ異なるとる名前をつけるのは良い考えではない。

10.7.1 Basic functions for querying arguments

afb_req_value 関数は以下のように定義されている。:

/*
 * 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.
 *
 * Shortcut for: afb_req_get(req, name).value
 */
static inline const char *afb_req_value(struct afb_req req, const char *name)
{
    return afb_req_get(req, name).value;
}

afb_req_get 関数を呼び出すショートカットとして定義されている。:

/*
 * 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.
 * When the argument of 'name' is found, the fields are filled,
 * in particular, the field 'result.name' is set to 'name'.
 *
 * There is a special name value: the empty string.
 * The argument of name "" is defined only if the request was made using
 * 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);

上の関数は2つのパラメータ、探索するためのリクエストと引数名を取り扱う。struct afb_arg タイプの構造体を返却する。

Context-Typeがapplication/jsonのHTTP/POSTリクエストの場合、特別な名前が定義されている。それは、””(空)文字。空文字を指定した場合、取り出すvalueはPOSTリクエストのbody部分(JSON文字列)となる。

struct afb_arg は以下のように定義されている。

/*
 * Describes an argument (or parameter) of a request
 */
struct afb_arg {
    const char *name;   /* name of the argument or NULL if invalid */
    const char *value;  /* string representation of the value of the argument */
                /* 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 */
};

この構造体はリクエストの引数データを返す。このデータには path フィールドがある。この pathafb_req_path 関数を使ってアクセスできる。以下のように定義している。

/*
 * 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.
 *
 * Shortcut for: afb_req_get(req, name).path
 */
static inline const char *afb_req_path(struct afb_req req, const char *name)
{
    return afb_req_get(req, name).path;
}

このpathはファイルを送信するHTTP/POSTリクエストのためだけに定義されている。

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>
<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>

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);

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

  • For HTTP requests, this json object uses key names mapped on argument name. Values are either string for common arguments or object ie: { "file": "...", "path": "..." }

  • For WebSockets requests, returned directly the object as provided by the client.

In fact, for Websockets requests, the function afb_req_value can be seen as a shortcut to json_object_get_string(json_object_object_get(afb_req_json(req), name))

10.8. Initialisation of the binding and declaration of methods

アクティブにするには、Bindigのmethodsはafb-daemonへ宣言する必要がある。さらに、binding自身を登録しなければいけません。

登録の仕組みは単純です。afb-needが開始したときに、リスト(コマンドラインか、設定ファイルに指定する)に登録されているすべてのbindingが読み込まれる。

bindingの読み込み手順:

  1. Afb-daemondlopen でbindingをロードする。

  2. Afb-daemondlsym を使ってシンボル名 afbBindingV1Register を探す。このシンボル名をエクスポートされたbindingの初期化関数として認識する。

  3. Afb-daemonはbindingに渡すインターフェースオブジェクトを作る。

  4. Afb-daemonafbBindingV1Register 関数を呼び、引数でインターフェースオブジェクトのポインタを渡す。

  5. afbBindingV1Register 関数は、bindingの設定と初期化を行う。

  6. afbBindingV1Register 関数は、bindingの情報(バージョン、名前、methodsリスト)の構造体ポインタを返却する。

  7. Afb-daemonは名前とバージョンに問題ないか確認する。確認できれば、Afb-daemonの初期化完了後すぐにbindingとそのmethodは登録されて使えるようになる。

以下は、tic-tac-toe binding の afbBindingV1Register 関数です。

/*
 * activation function for registering the binding called by afb-daemon
 */
const struct afb_binding *afbBindingV1Register(const struct afb_binding_interface *itf)
{
   afbitf = itf;         // records the interface for accessing afb-daemon
   return &binding_description;  // returns the description of the binding
}

この初期化関数は小さい。なぜなら、 tic-tac-toe bindingはアプリケーション関連の初期化処理を必要としていないから。ここではafb-daemonインターフェースの登録と、binding情報の返却しか行っていない。

afbitf 変数はbinding用のグローバル変数です。ログやイベント通知の為のafb-daemonのインターフェース(ポインタ)を保持しておく。以下のように定義する。

/*
 * the interface to afb-daemon
 */
const struct afb_binding_interface *afbitf;

bindingの説明はこのように定義します。

/*
 * array of the methods exported to afb-daemon
 */
static const struct afb_verb_desc_v1 binding_methods[] = {
   /* VERB'S NAME     SESSION MANAGEMENT          FUNCTION TO CALL  SHORT DESCRIPTION */
   { .name= "new",   .session= AFB_SESSION_NONE, .callback= new,   .info= "Starts a new game" },
   { .name= "play",  .session= AFB_SESSION_NONE, .callback= play,  .info= "Asks the server to play" },
   { .name= "move",  .session= AFB_SESSION_NONE, .callback= move,  .info= "Tells the client move" },
   { .name= "board", .session= AFB_SESSION_NONE, .callback= board, .info= "Get the current board" },
   { .name= "level", .session= AFB_SESSION_NONE, .callback= level, .info= "Set the server level" },
   { .name= "join",  .session= AFB_SESSION_CHECK,.callback= join,  .info= "Join a board" },
   { .name= "undo",  .session= AFB_SESSION_NONE, .callback= undo,  .info= "Undo the last move" },
   { .name= "wait",  .session= AFB_SESSION_NONE, .callback= wait,  .info= "Wait for a change" },
   { .name= NULL } /* marker for end of the array */
};

/*
 * description of the binding for afb-daemon
 */
static const struct afb_binding binding_description =
{
   /* description conforms to VERSION 1 */
   .type= AFB_BINDING_VERSION_1,
   .v1= {               /* fills the v1 field of the union when AFB_BINDING_VERSION_1 */
      .prefix= "tictactoe",     /* the API name (or binding name or prefix) */
      .info= "Sample tac-tac-toe game", /* short description of of the binding */
      .methods = binding_methods        /* the array describing the methods of the API */
   }
};

binding_description 構造体はbindingを説明している。 bindingの種類とバージョン、名前、概要、メソッド一覧を定義しています。

メソッド一覧はメソッドを説明する構造体の配列で、終端はNULLで判断している。

バージョン1のafb-damon bindingでは、4つのフィールドを持っている:

  • メソッド名,

  • セッション管理で仕様するフラグ,

  • メソッドがリクエストされたときに呼ばれる関数,

  • 概要。

メソッドを説明する構造体は、以下のように定義されている。

/*
 * Description of one method of the API provided by the binding
 * This enumeration is valid for bindings of type 1
 */
struct afb_verb_desc_v1
{
       const char *name;                       /* name of the method */
       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:

Constant name Meaning
AFB_SESSION_CREATE Equals to AFB_SESSION_LOA_EQ_0
AFB_SESSION_CLOSE Closes the session after the reply and set the LOA to 0
AFB_SESSION_RENEW Refreshes the token of authentification
AFB_SESSION_CHECK Just requires the token authentification
AFB_SESSION_LOA_LE_0 Requires the current LOA to be lesser then or equal to 0
AFB_SESSION_LOA_LE_1 Requires the current LOA to be lesser then or equal to 1
AFB_SESSION_LOA_LE_2 Requires the current LOA to be lesser then or equal to 2
AFB_SESSION_LOA_LE_3 Requires the current LOA to be lesser then or equal to 3
AFB_SESSION_LOA_GE_0 Requires the current LOA to be greater then or equal to 0
AFB_SESSION_LOA_GE_1 Requires the current LOA to be greater then or equal to 1
AFB_SESSION_LOA_GE_2 Requires the current LOA to be greater then or equal to 2
AFB_SESSION_LOA_GE_3 Requires the current LOA to be greater then or equal to 3
AFB_SESSION_LOA_EQ_0 Requires the current LOA to be equal to 0
AFB_SESSION_LOA_EQ_1 Requires the current LOA to be equal to 1
AFB_SESSION_LOA_EQ_2 Requires the current LOA to be equal to 2
AFB_SESSION_LOA_EQ_3 Requires the current LOA to be equal to 3

If any of this flag is set, afb-daemon requires an authentication token as if AFB_SESSION_CHECK flag was also set.

The special value AFB_SESSION_NONE is zero and can be used to bypass token check.

Note that AFB_SESSION_CREATE and AFB_SESSION_CLOSE might be removed in later versions.

10.9. Sending messages to the log system

Afb-daemonは4つのレベル(verbosity)の詳細と、5つのログメッセージのメソッドがある。

verbosityは管理される。オプションをつけるとafb-daemonのverbosityを変えることができ、bindingのverbosityはbindingによってbindingを設定できる。

ログメッセージのメソッドはマクロで定義されていて、マクロはverbosityレベルを見てメッセージを出力しなければいけないレベルのときにだけ実際のログ関数を呼び出す。メッセージを出力すべきでないならば、フォーマットメッセージの引数の評価は回避します。

10.9.1. Verbs for logging messages

5つのログメソッドは以下です:

Macro Verbosity Meaning syslog level
ERROR 0 Error conditions 3
WARNING 1 Warning conditions 4
NOTICE 1 Normal but significant condition 5
INFO 2 Informational 6
DEBUG 3 Debug-level messages 7

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, ...);

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.

10.9.2. Managing verbosity

Depending on the level of verbosity, the messages are output or not. The following table explains what messages will be output depending ont the verbosity level.

Level of verbosity Outputed macro
0 ERROR
1 ERROR + WARNING + NOTICE
2 ERROR + WARNING + NOTICE + INFO
3 ERROR + WARNING + NOTICE + INFO + DEBUG

10.9.3. Output format and destination

The syslog level is used for forging a prefix to the message. The prefixes are:

syslog level prefix
0 <0> EMERGENCY
1 <1> ALERT
2 <2> CRITICAL
3 <3> ERROR
4 <4> WARNING
5 <5> NOTICE
6 <6> INFO
7 <7> DEBUG

The message is pushed to standard error. The final destination of the message depends on how systemd service was configured through its variable StandardError. It can be journal, syslog or kmsg. (See man sd-daemon).

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)
{
    ...
    struct json_object *description;

    /* get the description */
    description = describe(board);

    ...

    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 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);

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.

Event name received by listeners is prefixed with binding name. So when a change occurs after a move, the reason is move and every clients receive an event tictactoe/move.

Note that nothing is said about case sensitivity of event names. However, the event is always prefixed with the name that the binding declared, with the same case, followed with a slash /. Thus it is safe to compare event using a case sensitive comparison.

Writing an asynchronous method implementation

The tic-tac-toe example allows two clients or more to share the same board. This is implemented by the method join that illustrated partly how to retrieve arguments.

When two or more clients are sharing a same board, one of them can wait until the state of the board changes, but this could also be implemented using events because an even is generated each time the board changes.

In this case, the reply to the wait is sent only when the board changes. See the diagram below:

CLIENT A       CLIENT B         TIC-TAC-TOE
   |              |                  |
   +--------------|----------------->| wait . . . . . . . .
   |              |                  |                     .
   :              :                  :                      .
   :              :                  :                      .
   |              |                  |                      .
   |              +----------------->| move . . .           .
   |              |                  |          V           .
   |              |<-----------------+ success of move      .
   |              |                  |                    .
   |<-------------|------------------+ success of wait  <

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)
{
    struct board *board;
    struct waiter *waiter;

    /* retrieves the context for the session */
    board = board_of_req(req);
    INFO(afbitf, "method 'wait' called for boardid %d", board->id);

    /* creates the waiter and enqueues it */
    waiter = calloc(1, sizeof *waiter);
    waiter->req = req;
    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.

When a method returns without setting a reply, it MUST increment request's reference count using afb_req_addref. If unpredictable behaviour may pop up.

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)
{
    struct waiter *waiter, *next;
    struct json_object *description;

    /* get the description */
    description = describe(board);

    waiter = board->waiters;
    board->waiters = NULL;
    while (waiter != NULL) {
        next = waiter->next;
        afb_req_success(waiter->req, json_object_get(description), reason);
        afb_req_unref(waiter->req);
        free(waiter);
        waiter = next;
    }

    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

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)
if(afb_FOUND)
    message(STATUS "Creation afm-main-binding for AFB-DAEMON")
    add_library(afm-main-binding MODULE afm-main-binding.c)
    target_compile_options(afm-main-binding PRIVATE ${afb_CFLAGS})
    target_include_directories(afm-main-binding PRIVATE ${afb_INCLUDE_DIRS})
    target_link_libraries(afm-main-binding utils ${afb_LIBRARIES})
    set_target_properties(afm-main-binding PROPERTIES
        PREFIX ""
        LINK_FLAGS "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/afm-main-binding.export-map"
    )
    install(TARGETS afm-main-binding LIBRARY DESTINATION ${binding_dir})
else()
    message(STATUS "Not creating the binding for AFB-DAEMON")
endif()

Let now describe some of these lines.

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:

Variable Meaning
afb_FOUND Set to 1 if afb-daemon binding development files exist
afb_LIBRARIES Only the libraries (w/o the '-l') for compiling afb-daemon bindings
afb_LIBRARY_DIRS The paths of the libraries (w/o the '-L') for compiling afb-daemon bindings
afb_LDFLAGS All required linker flags for compiling afb-daemon bindings
afb_INCLUDE_DIRS The '-I' preprocessor flags (w/o the '-I') for compiling afb-daemon bindings
afb_CFLAGS All required cflags for compiling afb-daemon bindings

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)

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
    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})

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).

{ global: afbBindingV1Register; local: *; };

This sample version script exports as global the symbol afbBindingV1Register and hides any other symbols.

This version script is added to the link options using the option --version-script=export.map is given directly to the linker or using the option -Wl,--version-script=export.map when the option is given to the C compiler.

Building within yocto

Adding a dependency to afb-daemon is enough. See below:

DEPENDS += " afb-daemon "