From: Jan-Simon Möller Date: Wed, 26 Jan 2022 11:25:31 +0000 (+0100) Subject: Update to documentation before Marlin X-Git-Tag: 12.92.0^0 X-Git-Url: https://gerrit.automotivelinux.org/gerrit/gitweb?a=commitdiff_plain;h=8160b5cdc8547277f3f31ee1e41524754d5d987d;p=AGL%2Fdocumentation.git Update to documentation before Marlin This is mostly a cleanup before the Magic Marlin Release. We do have the Application Framework chapter rewrite pending. Bug-AGL: SPEC-4236 Signed-off-by: Jan-Simon Möller Change-Id: I7e1f39667b4db417497b1d0c84065c173fa18439 Reviewed-on: https://gerrit.automotivelinux.org/gerrit/c/AGL/documentation/+/27097 --- diff --git a/docs/0_Getting_Started/1_Quickstart/Using_Ready_Made_Images.md b/docs/0_Getting_Started/1_Quickstart/Using_Ready_Made_Images.md index a10becd..eaae38e 100644 --- a/docs/0_Getting_Started/1_Quickstart/Using_Ready_Made_Images.md +++ b/docs/0_Getting_Started/1_Quickstart/Using_Ready_Made_Images.md @@ -44,7 +44,7 @@ AGL provides a number of pre-built ready-made images of various versions. ```sh $ ( sleep 5 && vinagre --vnc-scale localhost ) > /tmp/vinagre.log 2>&1 & - qemu-system-x86_64 -device virtio-net-pci,netdev=net0,mac=52:54:00:12:35:02 -netdev user,id=net0,hostfwd=tcp::2222-:22 \ + $ qemu-system-x86_64 -device virtio-net-pci,netdev=net0,mac=52:54:00:12:35:02 -netdev user,id=net0,hostfwd=tcp::2222-:22 \ -drive file=agl-demo-platform-crosssdk-qemux86-64.ext4,if=virtio,format=raw -show-cursor -usb -usbdevice tablet -device virtio-rng-pci \ -snapshot -vga virtio \ -vnc :0 -soundhw hda -machine q35 -cpu kvm64 -cpu qemu64,+ssse3,+sse4.1,+sse4.2,+popcnt -enable-kvm \ diff --git a/docs/0_Getting_Started/2_Building_AGL_Image/3_Initializing_Your_Build_Environment.md b/docs/0_Getting_Started/2_Building_AGL_Image/3_Initializing_Your_Build_Environment.md index 15ad5ed..efe7001 100644 --- a/docs/0_Getting_Started/2_Building_AGL_Image/3_Initializing_Your_Build_Environment.md +++ b/docs/0_Getting_Started/2_Building_AGL_Image/3_Initializing_Your_Build_Environment.md @@ -36,8 +36,6 @@ Available machines: bbe # BeagleBoneEnhanced beaglebone # BeagleBone cubox-i # multiple i.MX6 boards - cyclone5 # CycloneV - dra7xx-evm # TI DRA7xx-EVM 'vayu' dragonboard-410c # Qualcomm Dragonboard 410c dragonboard-820c # Qualcomm Dragonboard 820c ebisu # Renesas RCar Ebisu @@ -50,6 +48,7 @@ Available machines: imx8mqevk # i.MX8 w etnaviv imx8mqevk-viv # i.MX8 w vivante intel-corei7-64 # x86-64 (Intel flavour) + j7-evm # TI Jacinto 7 EVM m3-salvator-x # Renesas RCar Salvator/M3 m3ulcb # Renesas RCar M3 m3ulcb-kf # Renesas RCar M3 w Kingfisher Board @@ -59,6 +58,8 @@ Available machines: qemuarm64 # Qemu AArch 64 (ARM 64bit) * qemux86-64 # Qemu x86-64 raspberrypi4 # Raspberry Pi 4 + virtio-aarch64 # Virtio Guest + ``` ## AGL Features @@ -72,54 +73,50 @@ Following is a list of the available features: ```sh Available features: - [meta-agl] - agl-all-features :( agl-demo agl-appfw-smack agl-hmi-framework agl-profile-graphical-qt5 agl-profile-graphical agl-pipewire agl-speech-framework agl-netboot ) - agl-appfw-smack - agl-archiver - agl-buildstats - agl-ci - agl-ci-change-features :( agl-demo agl-appfw-smack agl-hmi-framework agl-profile-graphical-qt5 agl-profile-graphical agl-pipewire agl-speech-framework agl-devel agl-netboot agl-pipewire agl-cloudproxy agl-buildstats agl-ptest ) - agl-ci-change-features-nogfx :( agl-demo agl-appfw-smack agl-hmi-framework agl-profile-graphical-qt5 agl-profile-graphical agl-pipewire agl-speech-framework agl-devel agl-netboot agl-pipewire agl-cloudproxy agl-buildstats agl-ptest ) - agl-ci-snapshot-features :( agl-demo agl-appfw-smack agl-hmi-framework agl-profile-graphical-qt5 agl-profile-graphical agl-pipewire agl-speech-framework agl-devel agl-netboot agl-archiver agl-pipewire agl-buildstats agl-ptest ) - agl-ci-snapshot-features-nogfx :( agl-demo agl-appfw-smack agl-hmi-framework agl-profile-graphical-qt5 agl-profile-graphical agl-pipewire agl-speech-framework agl-devel agl-netboot agl-archiver agl-pipewire agl-buildstats agl-ptest ) - agl-devel - agl-fossdriver - agl-gplv2 - agl-hmi-framework - agl-netboot - agl-pipewire - agl-profile-cluster :( agl-profile-graphical ) - agl-profile-cluster-qt5 :( agl-profile-graphical-qt5 agl-profile-graphical ) - agl-profile-graphical - agl-profile-graphical-html5 :( agl-profile-graphical ) - agl-profile-graphical-qt5 :( agl-profile-graphical ) - agl-profile-hud - agl-profile-telematics - agl-ptest - agl-sign-wgts - agl-sota - agl-virt - agl-virt-guest-xen - agl-virt-xen :( agl-virt ) - agl-weston-remoting :( agl-profile-graphical ) - [meta-agl-cluster-demo] - agl-cluster-demo :( agl-profile-cluster-qt5 agl-profile-graphical-qt5 agl-profile-graphical agl-hmi-framework ) - agl-cluster-demo-preload - [meta-agl-demo] - agl-cloudproxy - agl-cluster-demo-support :( agl-weston-remoting agl-profile-graphical ) - agl-demo :( agl-appfw-smack agl-hmi-framework agl-profile-graphical-qt5 agl-profile-graphical agl-pipewire agl-speech-framework ) - agl-demo-preload - agl-demo-soundmanager :( agl-appfw-smack agl-hmi-framework agl-profile-graphical-qt5 agl-profile-graphical agl-audio-soundmanager-framework ) - [meta-agl-devel] - agl-jailhouse - agl-speech-framework - agl-voiceagent-alexa :( agl-speech-framework ) - agl-voiceagent-alexa-wakeword :( agl-voiceagent-alexa agl-speech-framework ) - [meta-agl-extra] - agl-localdev - [meta-agl-telematics-demo] - agl-telematics-demo :( agl-profile-telematics ) + + [meta-agl] # CORE layer + agl-all-features :( agl-demo agl-pipewire agl-app-framework agl-netboot ) + # For the usual demo image + agl-app-framework # Application Framework + agl-archiver # Source Archiver + agl-buildstats # Build Statistics + agl-devel :( agl-package-management ) # Developer Env (root login) + agl-fossdriver # Fossology integration + agl-gplv2 # GPLv2-only packages + agl-localdev # inclusion of local development folder + agl-netboot # network boot (e.g. CI) + agl-package-management # include package management (e.g. rpm) + agl-pipewire # include pipewire + agl-ptest # enable ptest pckages + agl-refhw-h3 # enable reference hardware + agl-virt # EG-Virt features + agl-virt-guest-xen # EG-Virt features + agl-virt-xen :( agl-virt ) # EG-Virt features + agl-weston-remoting :( agl-demo agl-pipewire agl-app-framework ) + agl-weston-waltham-remoting :( agl-demo agl-pipewire agl-app-framework ) + + [meta-agl-demo] # DEMO layer + agl-cluster-demo-support :( agl-weston-remoting agl-demo agl-pipewire agl-app-framework ) + # sample IVI demo + agl-demo :( agl-pipewire agl-app-framework ) # default IVI demo + agl-demo-preload # Add Tokens and sample files + + [meta-agl-devel] # Development layer + agl-basesystem # Toyota basesystem + agl-drm-lease # DRM lease support + agl-egvirt # EG-Virt feature + agl-flutter # Flutter support + agl-jailhouse # GSoC: jailhouse enablement + agl-lxc :( agl-drm-lease agl-pipewire ) # IC-EG container support + agl-ros2 # GSoC: ros2 enablement + +Specialized features (e.g. CI): + agl-ci # Tweaks for CI + agl-ci-change-features :( agl-demo agl-pipewire agl-app-framework agl-devel agl-package-management agl-netboot agl-pipewire agl-buildstats agl-ptest ) + agl-ci-change-features-nogfx :( agl-demo agl-pipewire agl-app-framework agl-devel agl-package-management agl-netboot agl-pipewire agl-buildstats agl-ptest ) + agl-ci-snapshot-features :( agl-demo agl-pipewire agl-app-framework agl-devel agl-package-management agl-netboot agl-archiver agl-pipewire agl-buildstats agl-ptest ) + agl-ci-snapshot-features-nogfx :( agl-demo agl-pipewire agl-app-framework agl-devel agl-package-management agl-netboot agl-archiver agl-pipewire agl-buildstats agl-ptest ) + ``` To find out exactly what a feature provides, check out the respective layer and its README. @@ -136,8 +133,7 @@ Following are brief descriptions of the AGL features you can specify on the * **agl-all-features**: A set of AGL default features. Do not think of this set of features as all the AGL features. -* **agl-appfw-smack**: Enables IoT.bzh Application Framework plus SMACK and - Cynara. +* **agl-app-framework**: Application Framework * **agl-archiver**: Enables the archiver class for releases. @@ -163,45 +159,15 @@ Following are brief descriptions of the AGL features you can specify on the Netboot is needed for CI and useful for development to avoid writing sdcards. Needs additional setup. - - * **agl-ptest**: Enables [Ptest](https://yoctoproject.org/docs/3.1.4/dev-manual/dev-manual.html#testing-packages-with-ptest) as part of the build. -* **agl-sota**: Enables Software Over-the-Air (SOTA) components and dependencies. - Includes meta-updater, meta-updater-qemux86-64, meta-filesystems, and meta-python. - * **agl-demo**: Enables the layers meta-agl-demo and meta-qt5. You need agl-demo if you are going to build the agl-demo-platform. -* **agl-sdl**: Enables or adds SDL to the build. - * **agl-pipewire**: Enables AGLs pipewire support. -* **agl-audio-soundmanager-framework**: Enables Soundmanager framework, which is an exclusive switch for audio framework. - * **agl-localdev**: Adds a local layer named "meta-localdev" in the meta directory and a local.dev.inc configuration file when that file is present. diff --git a/docs/0_Getting_Started/2_Building_AGL_Image/5_1_x86_Emulation_and_Hardware.md b/docs/0_Getting_Started/2_Building_AGL_Image/5_1_x86_Emulation_and_Hardware.md index 0f2121c..7282f66 100644 --- a/docs/0_Getting_Started/2_Building_AGL_Image/5_1_x86_Emulation_and_Hardware.md +++ b/docs/0_Getting_Started/2_Building_AGL_Image/5_1_x86_Emulation_and_Hardware.md @@ -18,7 +18,7 @@ using the `aglsetup.sh` script. If you are building the AGL demo image for emulation, you need to specify some specific options when you run the script: -**Qt based IVI demo :** +**Sample Qt based IVI demo :** ```sh $ source meta-agl/scripts/aglsetup.sh -f -m qemux86-64 -b qemux86-64 agl-demo agl-devel @@ -28,7 +28,7 @@ $ echo 'SSTATE_DIR = "$AGL_TOP/sstate-cache/"' >> $AGL_TOP/site.conf $ ln -sf $AGL_TOP/site.conf conf/ ``` -**HTML5 based IVI demo :** +**Sample HTML5 based IVI demo :** ```sh $ source meta-agl/scripts/aglsetup.sh -f -m qemux86-64 -b qemux86-64 agl-demo agl-devel agl-profile-graphical-html5 @@ -38,6 +38,26 @@ $ echo 'SSTATE_DIR = "$AGL_TOP/sstate-cache/"' >> $AGL_TOP/site.conf $ ln -sf $AGL_TOP/site.conf conf/ ``` +**IVI-EG Flutter based demo :** + +```sh +$ source meta-agl/scripts/aglsetup.sh -f -m qemux86-64 -b qemux86-64 agl-flutter agl-devel +$ echo '# reuse download directories' >> $AGL_TOP/site.conf +$ echo 'DL_DIR = "$HOME/downloads/"' >> $AGL_TOP/site.conf +$ echo 'SSTATE_DIR = "$AGL_TOP/sstate-cache/"' >> $AGL_TOP/site.conf +$ ln -sf $AGL_TOP/site.conf conf/ +``` + +**IC-EG container image :** +```sh +### TBD +``` + +**Virt-EG demo image :** +```sh +### TBD +``` + The "-m" option specifies the "qemux86-64" machine. The list of AGL features used with script are appropriate for development of the AGL demo image suited for either QEMU or VirtualBox. @@ -50,7 +70,7 @@ Start the build using the `bitbake` command. CPU and and Internet connection speeds. The build also takes approximately 100G-bytes of free disk space. -**Qt based IVI demo :** +**Sample Qt based IVI demo :** The target is `agl-demo-platform`. ```sh @@ -65,7 +85,7 @@ By default, the build process puts the resulting image in the Build Directory an $ export IMAGE_NAME=agl-demo-platform-qemux86-64.vmdk.xz ``` -**HTML5 based IVI demo :** +**Sample HTML5 based IVI demo :** The target is `agl-demo-platform-html5`. ```sh @@ -80,10 +100,29 @@ By default, the build process puts the resulting image in the Build Directory an $ export IMAGE_NAME=agl-demo-platform-html5-qemux86-64.vmdk.xz ``` +**IVI-EG Flutter based demo :** +The target is `agl-image-flutter`. + +```sh +$ time bitbake agl-image-flutter +``` + +**IC-EG container image :** +```sh +# TBD +``` + +**Virt-EG demo image :** +```sh +# TBD +``` + ## 3. Deploying the AGL Demo Image Deploying the image consists of decompressing the image and then booting it using either QEMU, VirtualBox or physical system. +The examples below are usually for the 'agl-demo-platform' target. +Please adapt accordingly to your target image. **3.1 QEMU** diff --git a/docs/3_Developer_Guides/0_FIXME.md b/docs/3_Developer_Guides/0_FIXME.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/3_Developer_Guides/1_Application_Framework/0_Introduction.md b/docs/3_Developer_Guides/1_Application_Framework/0_Introduction.md deleted file mode 100644 index efc31ee..0000000 --- a/docs/3_Developer_Guides/1_Application_Framework/0_Introduction.md +++ /dev/null @@ -1,261 +0,0 @@ ---- -title: Introduction ---- - -## Foreword - -This document describes what we intend to do. -It may happen that our current implementation and the content of this document differ. - -In case of differences, it is assumed that this document is right and the implementation is wrong. - -## Introduction - -During the first works in having the security model of Tizen integrated in AGL -(Automotive Grade Linux) distribution, it became quickly obvious that the count -of components specific to Tizen to integrate was huge. - -Here is a minimal list of what was needed: - -- platform/appfw/app-installers -- platform/core/security/cert-svc -- platform/core/appfw/ail -- platform/core/appfw/aul-1 -- platform/core/appfw/libslp-db-util -- platform/core/appfw/pkgmgr-info -- platform/core/appfw/slp-pkgmgr - -But this list isn't complete because many dependencies are hidden. -Those hidden dependencies are including some common libraries but also many -tizen specific sub-components: - -- iniparser -- bundle -- dlog, -- libtzplatform-config -- db-util -- vconf-buxton -- ... - -This is an issue because AGL is not expected to be Tizen. -Taking it would either need to patch it for removing unwanted components or to take all of them. - -However, a careful study of the core components of the security framework -of Tizen showed that their dependencies to Tizen are light (and since some -of our work, there is no more dependency to tizen). -Those components are : - -- **cynara** -- **security-manager** -- **D-Bus aware of cynara** - -Luckily, these core security components of Tizen are provided -by [meta-intel-iot-security][meta-intel], a set of yocto layers. -These layers were created by Intel to isolate Tizen specific security -components from the initial port of Tizen to Yocto. -The 3 layers are providing components for: - -- Implementing Smack LSM -- Implementing Integrity Measurement Architecture -- Implementing Tizen Security Framework - -The figure below shows the history of these layers. - -![Security_model_history](./images/Security_model_history.svg) - -We took the decision to use these security layers that provide the -basis of the Tizen security, the security framework. - -For the components of the application framework, built top of -the security framework, instead of pulling the huge set of packages -from Tizen, we decided to refit it by developing a tiny set of -components that would implement the same behaviour but without all -the dependencies and with minor architectural improvements for AGL. - -These components are : - -- **afm-system-daemon** -- **afm-user-daemon** - -They provides infrastructure for installing, uninstalling, -launching, terminating, pausing and resuming applications in -a multi user secure environment. - -A third component exists in the framework, the binder **afb-daemon**. -The binder provides the easiest way to provide secured API for -any tier. -Currently, the use of the binder is not absolutely mandatory. - -This documentation explains the framework created by IoT.bzh -by rewriting the Tizen Application Framework. -Be aware of the previous foreword. - -## Overview - -The figure below shows the major components of the framework -and their interactions going through the following scenario: - -- APPLICATION installs an other application and then launch it. - ![AppFW-APP_install_sequences](./images/AppFW-APP_install_sequences.svg) - -Let follow the sequence of calls: - -1. APPLICATION calls its **binder** to install the OTHER application. - -1. The binding **afm-main-binding** of the **binder** calls, through - **D-Bus** system, the system daemon to install the OTHER application. - -1. The system **D-Bus** checks wether APPLICATION has the permission - or not to install applications by calling **CYNARA**. - -1. The system **D-Bus** transmits the request to **afm-system-daemon**. - - **afm-system-daemon** checks the application to install, its - signatures and rights and install it. - -1. **afm-system-daemon** calls **SECURITY-MANAGER** for fulfilling - security context of the installed application. - -1. **SECURITY-MANAGER** calls **CYNARA** to install initial permissions - for the application. - -1. APPLICATION call its binder to start the nearly installed OTHER application. - -1. The binding **afm-main-binding** of the **binder** calls, through - **D-Bus** session, the user daemon to launch the OTHER application. - -1. The session **D-Bus** checks wether APPLICATION has the permission - or not to start an application by calling **CYNARA**. - -1. The session **D-Bus** transmits the request to **afm-user-daemon**. - -1. **afm-user-daemon** checks wether APPLICATION has the permission - or not to start the OTHER application **CYNARA**. - -1. **afm-user-daemon** uses **SECURITY-MANAGER** features to set - the security context for the OTHER application. - -1. **afm-user-daemon** launches the OTHER application. - -This scenario does not cover all the features of the frameworks. -Shortly because details will be revealed in the next chapters, -the components are: - -- ***SECURITY-MANAGER***: in charge of setting Smack contexts and rules, - of setting groups, and, of creating initial content of *CYNARA* rules - for applications. - -- ***CYNARA***: in charge of handling API access permissions by users and by - applications. - -- ***D-Bus***: in charge of checking security of messaging. The usual D-Bus - security rules are enhanced by *CYNARA* checking rules. - -- ***afm-system-daemon***: in charge of installing and uninstalling applications. - -- ***afm-user-daemon***: in charge of listing applications, querying application details, - starting, terminating, pausing, resuming applications and their instances - for a given user context. - -- ***afb-binder***: in charge of serving resources and features through an - HTTP interface. - -- ***afm-main-binding***: This binding allows applications to use the API - of the AGL framework. - -## Links between the "Security framework" and the "Application framework" - -The security framework refers to the security model used to ensure -security and to the tools that are provided for implementing that model. - -The security model refers to how DAC (Discretionary Access Control), -MAC (Mandatory Access Control) and Capabilities are used by the system -to ensure security and privacy. -It also includes features of reporting using audit features and by managing -logs and alerts. - -The application framework manages the applications: - -- installing -- uninstalling -- starting -- pausing -- listing -- ... - -The application framework uses the security model/framework -to ensure the security and the privacy of the applications that -it manages. - -The application framework must be compliant with the underlying -security model/framework. -But it should hide it to the applications. - -## The security framework - -The implemented security model is the security model of Tizen 3. -This model is described [here][tizen-secu-3]. - -The security framework then comes from Tizen 3 but through -the [meta-intel]. -It includes: - -- **Security-Manager** -- **Cynara** -- **D-Bus** compliant to Cynara. - -Two patches are applied to the security-manager. -The goal of these patches is to remove specific dependencies with Tizen packages that are not needed by AGL. -None of these patches adds or removes any behaviour. - -**In theory, the security framework/model is an implementation details -that should not impact the layers above the application framework**. - -The security framework of Tizen provides "nice lad" a valuable component to -scan log files and analyse auditing. -This component is still in development. - -## The application framework - -The application framework on top of the security framework -provides the components to install and uninstall applications -and to run it in a secured environment. - -The goal is to manage applications and to hide the details of -the security framework to the applications. - -For the reasons explained in introduction, we did not used the -application framework of Tizen as is but used an adaptation of it. - -The basis is kept identical: - -- The applications are distributed in a digitally signed container that must - match the specifications of widgets (web applications). - -This is described by the technical recommendations [widgets] and -[widgets-digsig] of the W3 consortium. - -This model allows: - -- The distribution of HTML, QML and binary applications. -- The management of signatures of the widget packages. - -This basis is not meant as being rigid and it can be extended in the -future to include for example incremental delivery. - -[meta-intel]: https://github.com/01org/meta-intel-iot-security "A collection of layers providing security technologies" -[widgets]: http://www.w3.org/TR/widgets "Packaged Web Apps" -[widgets-digsig]: http://www.w3.org/TR/widgets-digsig "XML Digital Signatures for Widgets" -[libxml2]: http://xmlsoft.org/html/index.html "libxml2" -[openssl]: https://www.openssl.org "OpenSSL" -[xmlsec]: https://www.aleksey.com/xmlsec "XMLSec" -[json-c]: https://github.com/json-c/json-c "JSON-c" -[d-bus]: http://www.freedesktop.org/wiki/Software/dbus "D-Bus" -[libzip]: http://www.nih.at/libzip "libzip" -[cmake]: https://cmake.org "CMake" -[security-manager]: https://wiki.tizen.org/wiki/Security/Tizen_3.X_Security_Manager "Security-Manager" -[app-manifest]: http://www.w3.org/TR/appmanifest "Web App Manifest" -[tizen-security]: https://wiki.tizen.org/wiki/Security "Tizen security home page" -[tizen-secu-3]: https://wiki.tizen.org/wiki/Security/Tizen_3.X_Overview "Tizen 3 security overview" -[AppFW-APP_install_sequences]: images/AppFW-APP_install_sequences.svg -[Security_model_history]: images/Security_model_history.svg \ No newline at end of file diff --git a/docs/3_Developer_Guides/1_Application_Framework/1_afm-daemons.md b/docs/3_Developer_Guides/1_Application_Framework/1_afm-daemons.md deleted file mode 100644 index b8eb21b..0000000 --- a/docs/3_Developer_Guides/1_Application_Framework/1_afm-daemons.md +++ /dev/null @@ -1,649 +0,0 @@ ---- -title: The afm daemons ---- - -## Foreword - -This document describes application framework daemons -FCS (Fully Conform to Specification) implementation is still under development. -It may happen that current implementation somehow diverges with specifications. - -## Introduction - -Daemons ***afm-user-daemon*** and ***afm-system-daemon*** handle applications -life. -Understand that they will manage operations like: - -- ***installation*** -- ***uninstallation*** -- ***running*** -- ***suspend*** -- ***inventory*** -- ... - -In addition, they ensure that operations use the security framework as needed -and that applications are executed in the correct context. - -***D-Bus*** is in charge of transmitting orders to the appropriate daemon -depending upon ***D-Bus*** destination. - -The figure below summarizes the situation of both **afm-system-daemon** and -**afm-user-daemon** in the system. - -![afm-daemons][afm-daemons] - -## The D-Bus interface - -### Overview of the dbus interface - -The ***afm daemons*** takes theirs orders from the session instance -of D-Bus. -The use of D-Bus is great because it allows to implement -discovery and signaling. - -The dbus session is by default addressed by environment -variable *DBUS_SESSION_BUS_ADDRESS*. Using **systemd** -variable *DBUS_SESSION_BUS_ADDRESS* is automatically set for -user sessions. - -They are listening with the destination name ***org.AGL.afm.[user|system]*** -at the object of path ***/org/AGL/afm/[user|system]*** on the interface -***org.AGL.afm.[user|system]*** for the below detailed members for the -***afm-system-daemon***: - -- ***install*** -- ***uninstall*** - -And for ***afm-user-daemon***: - -- ***runnables*** -- ***detail*** -- ***start*** -- ***once*** -- ***terminate*** -- ***pause*** -- ***resume*** -- ***runners*** -- ***state*** -- ***install*** -- ***uninstall*** - -D-Bus is mainly used for signaling and discovery. -Its optimized typed protocol is not used except for transmitting - only one string in both directions. - -The client and the service are using JSON serialization to -exchange data. -Signature of any member of the D-Bus interface is -***string -> string*** for ***JSON -> JSON***. -This is the normal case, if there is an error, current implementation -returns a dbus error that is a string. - -Here are examples using *dbus-send*, here to install an application from a -widget file: - -```bash -dbus-send --session --print-reply \ - --dest=org.AGL.afm.system \ - /org/AGL/afm/system \ - org.AGL.afm.system.install 'string:"/tmp/appli.wgt" -``` - -And here, to query data on installed applications that can be run: - -```bash -dbus-send --session --print-reply \ - --dest=org.AGL.afm.user \ - /org/AGL/afm/user \ - org.AGL.afm.user.runnables string:true -``` - -### The protocol over D-Bus - -On all following sub-chapters we assume that we talk about either -***afm-system-daemon*** or ***afm-user-daemon***. Method and D-Bus parameters -are considered as self-explanatory. - -The D-Bus interface is defined by: - -- **DESTINATION**: org.AGL.afm.[user|system] -- **PATH**: /org/AGL/afm/[user|system] -- **INTERFACE**: org.AGL.afm.[user|system] - -#### Method org.AGL.afm.system.install - -**Description**: Install an application from a widget file. - -When an application with the same *id* and *version* already exists. Outside of -using *force=true* the application is not reinstalled. - -Applications are installed the subdirectories of applications common directory. -If *root* is specified, the application is installed under the -sub-directories of the *root* defined. - -Note that this methods is a simple accessor method of -***org.AGL.afm.system.install*** from ***afm-system-daemon***. - -After the installation and before returning to the sender, -***afm-system-daemon*** sends a signal ***org.AGL.afm.system.changed***. - -**Input**: The *path* of the widget file to install and, optionally, -a flag to *force* reinstallation, and, optionally, a *root* directory. - -Either just a string being the absolute path of the widget file: - -```bash -"/a/path/driving/to/the/widget" -``` - -Or an object: - -```json -{ - "wgt": "/a/path/to/the/widget", - "force": false, - "root": "/a/path/to/the/root" -} -``` - -"wgt" and "root" must be absolute paths. - -**output**: An object with the field "added" being the string for -the id of the added application. - -```json -{"added":"appli@x.y"} -``` - - - -#### Method org.AGL.afm.system.uninstall - -**Description**: Uninstall an application from its id. - -Note that this methods is a simple method accessor of -***org.AGL.afm.system.uninstall*** from ***afm-system-daemon***. - -After the uninstallation and before returning to the sender, -***afm-system-daemon*** sends a signal ***org.AGL.afm.system.changed***. - -**Input**: the *id* of the application and optionally the application *root* path. - -Either a string: - -```bash -"appli@x.y" -``` - -Or an object: - -```json -{ - "id": "appli@x.y", - "root": "/a/path/to/the/root" -} -``` - -**output**: the value 'true'. - - - -#### Method org.AGL.afm.user.detail - -**Description**: Get details about an application from its id. - -**Input**: the id of the application as below. - -Either just a string: - -```bash -"appli@x.y" -``` - -Or an object having the field "id" of type string: - -```json -{"id":"appli@x.y"} -``` - -**Output**: A JSON object describing the application containing -the fields described below. - -```json -{ - "id": string, the application id (id@version) - "version": string, the version of the application - "width": integer, requested width of the application - "height": integer, requested height of the application - "name": string, the name of the application - "description": string, the description of the application - "shortname": string, the short name of the application - "author": string, the author of the application -} -``` - - - -#### Method org.AGL.afm.user.runnables - -**Description**: Get the list of applications that can be run. - -**Input**: any valid json entry, can be anything except null. - -**output**: An array of description of the runnable applications. -Each item of the array contains an object containing the detail of -an application as described above for the method -*org.AGL.afm.user.detail*. - - - -#### Method org.AGL.afm.user.install - -**Description**: Install an application from its widget file. - -If an application of the same *id* and *version* exists, it is not -reinstalled except when *force=true*. - -Applications are installed in the subdirectories of the common directory -reserved for applications. -If *root* is specified, the application is installed under -sub-directories of defined *root*. - -Note that this methods is a simple accessor to the method -***org.AGL.afm.system.install*** of ***afm-system-daemon***. - -After the installation and before returning to the sender, -***afm-user-daemon*** sends the signal ***org.AGL.afm.user.changed***. - -**Input**: The *path* of widget file to be installed. Optionally, -a flag to *force* reinstallation and/or a *root* directory. - -Simple form a simple string containing the absolute widget path: - -```bash -"/a/path/driving/to/the/widget" -``` - -Or an object: - -```json -{ - "wgt": "/a/path/to/the/widget", - "force": false, - "root": "/a/path/to/the/root" -} -``` - -***wgt*** and ***root*** MUST be absolute paths. - -**output**: An object containing field "added" to use as application ID. - -```json -{"added":"appli@x.y"} -``` - - - -#### Method org.AGL.afm.user.uninstall - -**Description**: Uninstall an application from its id. - -Note that this methods is a simple accessor to -***org.AGL.afm.system.uninstall*** method from ***afm-system-daemon***. - -After the uninstallation and before returning to the sender, -***afm-user-daemon*** sends the signal ***org.AGL.afm.user.changed***. - -**Input**: the *id* of the application and, optionally, the path to -application *root*. - -Either a string: - -```bash -"appli@x.y" -``` - -Or an object: - -```json -{ - "id": "appli@x.y", - "root": "/a/path/to/the/root" -} -``` - -**output**: the value 'true'. - - - -#### Method org.AGL.afm.user.start - -**Description**: - -**Input**: the *id* of the application and, optionally, the -start *mode* as below. - -Either just a string: - -```bash -"appli@x.y" -``` - -Or an object containing field "id" of type string and -optionally a field mode: - -```json -{"id":"appli@x.y","mode":"local"} -``` - -The field "mode" is a string equal to either "local" or "remote". - -[Currently the mode is not available in the systemd version] - -**output**: The *runid* of the application launched. *runid* is an integer. - - - -#### Method org.AGL.afm.user.once - -**Description**: - -**Input**: the *id* of the application - -Either just a string: - -```bash -"appli@x.y" -``` - -Or an object containing field "id" of type string. - -```json -{"id":"appli@x.y"} -``` - -**output**: The *state* of the application retrieved or launched. -See *org.AGL.afm.user.state* to get a description of the returned -object. - - - -#### Method org.AGL.afm.user.terminate - -**Description**: Terminates the application attached to *runid*. - -**Input**: The *runid* (an integer) of running instance to terminate. - -**output**: the value 'true'. - - - -#### Method org.AGL.afm.user.stop - -Obsolete since 8th November 2016 (2016/11/08). -Kept for compatibility. - -Use **org.AGL.afm.user.pause** instead. - - - -#### Method org.AGL.afm.user.continue - -Obsolete since 8th November 2016 (2016/11/08). -Kept for compatibility. - -Use **org.AGL.afm.user.resume** instead. - - - -#### Method org.AGL.afm.user.pause - -[Currently not available in the systemd version] - -**Description**: Pauses the application attached to *runid* until terminate or resume. - -**Input**: The *runid* (integer) of the running instance to pause. - -**output**: the value 'true'. - - - -#### Method org.AGL.afm.user.resume - -[Currently not available in the systemd version] - -**Description**: Resumes the application attached to *runid* previously paused. - -**Input**: The *runid* (integer) of the running instance to resume. - -**output**: the value 'true'. - - - -#### Method org.AGL.afm.user.state - -**Description**: Get information about a running instance of *runid*. - -**Input**: The *runid* (integer) of the running instance inspected. - -**output**: An object describing instance state. -It contains: - -- the runid (integer) -- the pids of the processes as an array starting -- with the group leader -- the id of the running application (string) -- the state of the application (string either: "starting", "running", "paused"). - -Example of returned state: - -```json - { - "runid": 2, - "pids": [ 435, 436 ], - "state": "running", - "id": "appli@x.y" - } -``` - - - -#### Method org.AGL.afm.user.runners - -**Description**: Get the list of currently running instances. - -**Input**: anything. - -**output**: An array of states, one per running instance, as returned by -the method ***org.AGL.afm.user.state***. - -## Starting **afm daemons** - -***afm-system-daemon*** and ***afm-user-daemon*** are launched as systemd -services attached to system and user respectively. -Normally, service files are locatedat */lib/systemd/system/afm-system-daemon.service* and -*/usr/lib/systemd/user/afm-user-daemon.service*. - -### ***afm-system-daemon*** options - -The options for launching **afm-system-daemon** are: - -```bash - -r - --root directory - - Set the root application directory. - - Note that the default root directory is defined - to be /usr/share/afm/applications (may change). - - -d - --daemon - - Daemonizes the process. It is not needed by systemd. - - -q - --quiet - - Reduces the verbosity (can be repeated). - - -v - --verbose - - Increases the verbosity (can be repeated). - - -h - --help - - Prints a short help. -``` - -### ***afm-user-daemon*** options - -The options for launching **afm-user-daemon** are: - -```bash - -a - --application directory - - [Currently not available in the systemd version] - - Includes the given application directory to - the database base of applications. - - Can be repeated. - - -r - --root directory - - [Currently not available in the systemd version] - - Includes root application directory or directories when - passing multiple rootdir to - applications database. - - Note that default root directory for - applications is always added. In current version - /usr/share/afm/applications is used as default. - - -m - --mode (local|remote) - - [Currently not available in the systemd version] - - Set the default launch mode. - The default value is 'local' - - -d - --daemon - - Daemonizes the process. It is not needed by systemd. - - -q - --quiet - - Reduces the verbosity (can be repeated). - - -v - --verbose - - Increases the verbosity (can be repeated). - - -h - --help - - Prints a short help. -``` - -## Tasks of **afm-user-daemon** - -### Maintaining list of applications - -At start **afm-user-daemon** scans the directories containing -applications and load in memory a list of available applications -accessible by current user. - -When **afm-system-daemon** installs or removes an application. -On success it sends the signal *org.AGL.afm.system.changed*. -When receiving such a signal, **afm-user-daemon** rebuilds its -applications list. - -**afm-user-daemon** provides the data it collects about -applications to its clients. -Clients may either request the full list -of available applications or a more specific information about a -given application. - -### Launching application - -**afm-user-daemon** launches application by using systemd. -Systemd builds a secure environment for the application -before starting it. - -Once launched, running instances of application receive -a runid that identify them. -To make interface with systemd evident, the pid is the runid. - -### Managing instances of running applications - -**afm-user-daemon** manages the list of applications -that it launched. - -When owning the right permissions, a client can get the list -of running instances and details about a specific -running instance. -It can also terminate a given application. - -### Installing and uninstalling applications - -If the client own the right permissions, -**afm-user-daemon** delegates that task -to **afm-system-daemon**. - -## Using ***afm-util*** - -The command line tool ***afm-util*** uses dbus-send to send -orders to **afm-user-daemon**. -This small scripts allows to send command to ***afm-user-daemon*** either -interactively at shell prompt or scriptically. - -The syntax is simple: - -- it accept a command and when requires attached arguments. - -Here is the summary of ***afm-util***: - -- **afm-util runnables **: - list the runnable widgets installed - -- **afm-util install wgt **: - install the wgt file - -- **afm-util uninstall id **: - remove the installed widget of id - -- **afm-util detail id **: - print detail about the installed widget of id - -- **afm-util runners **: - list the running instance - -- **afm-util start id **: - start an instance of the widget of id - -- **afm-util once id **: - run once an instance of the widget of id - -- **afm-util terminate rid **: - terminate the running instance rid - -- **afm-util state rid **: - get status of the running instance rid - -Here is how to list applications using ***afm-util***: - -```bash - afm-util runnables -``` - -[afm-daemons]: images/afm-daemons.svg diff --git a/docs/3_Developer_Guides/1_Application_Framework/2_widgets.md b/docs/3_Developer_Guides/1_Application_Framework/2_widgets.md deleted file mode 100644 index 07edc52..0000000 --- a/docs/3_Developer_Guides/1_Application_Framework/2_widgets.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -title: Widgets ---- - -# The widgets - -The widgets are described by the W3C's technical recommendations -[Packaged Web Apps (Widgets)](http://www.w3.org/TR/widgets) and [XML Digital Signatures for Widgets](http://www.w3.org/TR/widgets-digsig) - -In summary, **widgets are ZIP files that can be signed and -whose content is described by the file **. \ No newline at end of file diff --git a/docs/3_Developer_Guides/1_Application_Framework/3_widgets_overview.md b/docs/3_Developer_Guides/1_Application_Framework/3_widgets_overview.md deleted file mode 100644 index 28dbc60..0000000 --- a/docs/3_Developer_Guides/1_Application_Framework/3_widgets_overview.md +++ /dev/null @@ -1,158 +0,0 @@ ---- -title: Overview of widgets ---- - - -# Tools for managing widgets - -This project includes tools for managing widgets. -These tools are: - -- ***wgtpkg-info***: command line tool to display - informations about a widget file. - -- ***wgtpkg-install***: command line tool to - install a widget file. - -- ***wgtpkg-pack***: command line tool to create - a widget file from a widget directory. - -- ***wgtpkg-sign***: command line tool to add a signature - to a widget directory. - -For all these commands, a tiny help is available with -options **-h** or **--help**. - -There is no tool for unpacking a widget. -For doing such operation, you can use the command **unzip**. - -To list the files of a widget: - -```bash -unzip -l WIDGET -``` - -To extract a widget in some directory: - -```bash -unzip WIDGET -d DIRECTORY -``` - -*Note: that DIRECTORY will be created if needed*. - -## Getting data about a widget file - -The command **wgtpkg-info** opens a widget file, reads its **config.xml** -file and displays its content in a human readable way. - -## Signing and packing widget - -### Signing - -To sign a widget, you need a private key and its certificate. - -The tool **wgtpkg-sign** creates or replace a signature file in -the directory of the widget BEFORE its packaging. - -There are two types of signature files: author and distributor. - -Example 1: add an author signature - -```bash -wgtpkg-sign -a -k me.key.pem -c me.cert.pem DIRECTORY -``` - -Example 2: add a distributor signature - -```bash -wgtpkg-sign -k authority.key.pem -c authority.cert.pem DIRECTORY -``` - -### Packing - -This operation can be done using the command **zip** but -we provide the tool **wgtpkg-pack** that may add checking. - -Example: - -```bash -wgtpkg-pack DIRECTORY -o file.wgt -``` - -## Writing a widget - -### App directory organization - -There are few directories that are by default used in the binder. At the root -directory of the widget folder, here are the directories that could be used: - -- *lib* : default directory where lies external libraries needed for - the binding. Binding could be stored here too or in another directory of your - choice. -- *htdocs* : root HTTP directory if binding has web UI. - -### The steps for writing a widget - -1. make your application -2. create its configuration file **config.xml** -3. sign it -4. pack it - -Fairly easy, no? - -## Organization of directory of applications - -### Directory where are stored applications - -Applications can be installed in different places: - -- the system itself, extension device. - -On a phone application are typically installed on the sd card. - -This translates to: - -- /var/local/lib/afm/applications - -From here this path is referenced as: "APPDIR". - -The main path for applications is: APPDIR/PKGID/VER. - -Where: - -- APPDIR is as defined above -- PKGID is a directory whose name is the package identifier -- VER is the version of the package MAJOR.MINOR - -This organization has the advantage to allow several versions -to leave together. -This is needed for some good reasons (rolling back) and also for less good reasons (user habits). - -### Identity of installed files - -All files are installed as user "afm" and group "afm". -All files have rw(x) for user and r-(x) for group and others. - -This allows every user to read every file. - -### Labeling the directories of applications - -The data of a user are in its directory and are labelled by the security-manager using the application labels. - -[widgets]: http://www.w3.org/TR/widgets "Packaged Web Apps" -[widgets-digsig]: http://www.w3.org/TR/widgets-digsig "XML Digital Signatures for Widgets" -[app-manifest]: http://www.w3.org/TR/appmanifest "Web App Manifest" -[meta-intel]: https://github.com/01org/meta-intel-iot-security "A collection of layers providing security technologies" -[widgets]: http://www.w3.org/TR/widgets "Packaged Web Apps" -[widgets-digsig]: http://www.w3.org/TR/widgets-digsig "XML Digital Signatures for Widgets" -[libxml2]: http://xmlsoft.org/html/index.html "libxml2" -[openssl]: https://www.openssl.org "OpenSSL" -[xmlsec]: https://www.aleksey.com/xmlsec "XMLSec" -[json-c]: https://github.com/json-c/json-c "JSON-c" -[d-bus]: http://www.freedesktop.org/wiki/Software/dbus "D-Bus" -[libzip]: http://www.nih.at/libzip "libzip" -[cmake]: https://cmake.org "CMake" -[security-manager]: https://wiki.tizen.org/wiki/Security/Tizen_3.X_Security_Manager "Security-Manager" -[app-manifest]: http://www.w3.org/TR/appmanifest "Web App Manifest" -[tizen-security]: https://wiki.tizen.org/wiki/Security "Tizen security home page" -[tizen-secu-3]: https://wiki.tizen.org/wiki/Security/Tizen_3.X_Overview "Tizen 3 security overview" diff --git a/docs/3_Developer_Guides/1_Application_Framework/4_Widget_configuration_file.md b/docs/3_Developer_Guides/1_Application_Framework/4_Widget_configuration_file.md deleted file mode 100644 index f7acb23..0000000 --- a/docs/3_Developer_Guides/1_Application_Framework/4_Widget_configuration_file.md +++ /dev/null @@ -1,589 +0,0 @@ ---- -title: Widget configuration file ---- - -# Configuration file - config.xml - -The widgets are described by the W3C's technical recommendations -[Packaged Web Apps (Widgets)][widgets] and [XML Digital Signatures for -Widgets][widgets-digsig] -that specifies the configuration file **config.xml**. - -## Overview - -The file **config.xml** describes important data of the application -to the framework: - -- the unique identifier of the application -- the name of the application -- the type of the application -- the icon of the application -- the permissions linked to the application -- the services and dependencies of the application - -The file MUST be at the root of the widget and MUST be case sensitively name -***config.xml***. - -The file **config.xml** is a XML file described by the document -[widgets]. - -Here is the example of the config file for the QML application SmartHome. - -```xml - - - SmartHome - - - This is the Smarthome QML demo application. It shows some user interfaces for controlling an -automated house. The user interface is completely done with QML. - Qt team - GPL - -``` - -The most important items are: - -- ****: gives the id of the widget. It must be unique. - -- ****: gives the version of the widget - -- ****: gives a path to the icon of the application - (can be repeated with different sizes) - -- ****: this indicates the entry point and its type. - -## Standard elements of "config.xml" - -### The element widget - -#### the attribute id of widget - -The attribute *id* is mandatory (for version 2.x, blowfish) and must be unique. - -Values for *id* are any non empty string containing only latin letters, -arabic digits, and the three characters '.' (dot), '-' (dash) and -'\_' (underscore). - -Authors can use a mnemonic id or can pick a unique id using -command **uuid** or **uuidgen**. - -### the attribute version of widget - -The attribute *version* is mandatory (for version 2.x, blowfish). - -Values for *version* are any non empty string containing only latin letters, -arabic digits, and the three characters '.' (dot), '-' (dash) and -'\_' (underscore). - -Version values are dot separated fields MAJOR.MINOR.REVISION. -Such version would preferably follow guidelines of -[semantic versioning][semantic-version]. - -### The element content - -The element *content* is mandatory (for version 2.x, blowfish) and must designate a file -(subject to localization) with its attribute *src*. - -The content designed depends on its type. See below for the known types. - -### The element icon - -The element *icon* is mandatory (for version 2.x, blowfish) and must -be unique. It must designate an image file with its attribute *src*. - -## AGL features - -The AGL framework uses the feature tag for specifying security and binding -requirement of the widget. - -Since the migration of the framework to leverage systemd power, -the features are of important use to: - -- declare more than just an application -- declare the expected dependencies -- declare the expected permissions -- declare the exported apis - -The specification of [widgets][widgets] is intended to describe -only one application. -In the present case, we expect to describe more than just an application. -For example, a publisher could provide a widget containing a service, -an application for tuning that service, an application that -leverage the service. -Here, the term of service means a background application that -runs without IHM and whose public api can be accessed by other -applications. - -So the features are used to describe each of the possible -units of widgets. -The "standard" unit in the meaning of [widgets][widgets] -is called the "main" unit. - -### required-api: feature name="urn:AGL:widget:required-api" - -List of the api required by the widget. - -Each required api must be explicit using a `` entry. - -Example: - -```xml - - - - - -``` - -This will be *virtually* translated for mustaches to the JSON - -```json -"required-api": [ - { "name": "gps", "value": "auto" }, - { "name": "afm-main", "value": "link" } - ] -``` - -#### required-api: param name="#target" - -OPTIONAL - -Declares the name of the unit requiring the listed apis. -Only one instance of the param "#target" is allowed. -When there is not instance of this param, it behave as if -the target main was specified. - -#### required-api: param name=[required api name] - -The name is the name of the required API. - -The value describes how to connect to the required api. -It is either: - -- local: OBSOLETE SINCE FF (AGL6), PROVIDED FOR COMPATIBILITY - Use the feature **urn:AGL:widget:required-binding** instead. - The binding is a local shared object. - In that case, the name is the relative path of the - shared object to be loaded. - -- auto: - The framework set automatically the kind of - the connection to the API - -- ws: - The framework connect using internal websockets - -- dbus: [OBSOLETE, shouldn't be used currently] - The framework connect using internal dbus - -- tcp: - In that case, the name is the URI to access the service. - The framework connect using a URI of type - HOST:PORT/API - API gives the name of the imported api. - -- cloud: [PROPOSAL - NOT IMPLEMENTED] - The framework connect externally using websock. - In that case, the name includes data to access the service. - Example: `` - -### required-binding: feature name="urn:AGL:widget:required-binding" - -List of the bindings required by the widget. - -Note: Since AGL 6 (FF - Funky Flounder), -the binder implements bindings version 3 that allow the declaration -of 0, 1 or more APIs by one binding. In other words, the equivalency -one binding = one API is lost. At the same time the framework added -the ability to use bindings exported by other widgets. - -Each required binding must be explicit using a `` entry. - -Example: - -```xml - - - - -``` - -This will be *virtually* translated for mustaches to the JSON - -```json -"required-binding": [ - { "name": "libexec/binding-gps.so", "value": "local" }, - { "name": "extra", "value": "extern" } - ] -``` - -#### required-binding: param name=[name or path] - -The name or the path of the required BINDING. - -The value describes how to connect to the required binding. -It is either: - -- local: - The binding is a local shared object. - In that case, the name is the relative path of the - shared object to be loaded. - -- extern: - The binding is external. The name is the exported binding name. - See provided-binding. - -### provided-binding: feature name="urn:AGL:widget:provided-binding" - -This feature allows to export a binding to other binders. -The bindings whose relative name is given as value is exported to -other binders under the given name. - -Each provided binding must be explicit using a `` entry. - -Example: - -```xml - - - -``` - -This will be *virtually* translated for mustaches to the JSON - -```json -"provided-binding": [ - { "name": "extra", "value": "export/binding-gps.so" } - ] -``` - -#### provided-binding: param name=[exported name] - -Exports a local binding to other applications. - -The value must contain the path to the exported binding. - -### required-permission: feature name="urn:AGL:widget:required-permission" - -List of the permissions required by the unit. - -Each required permission must be explicit using a `` entry. - -Example: - -```xml - - - - - -``` - -This will be *virtually* translated for mustaches to the JSON - -```json -"required-permission":{ - "urn:AGL:permission:real-time":{ - "name":"urn:AGL:permission:real-time", - "value":"required" - }, - "urn:AGL:permission:syscall:*":{ - "name":"urn:AGL:permission:syscall:*", - "value":"required" - } -} -``` - -#### required-permission: param name="#target" - -OPTIONAL - -Declares the name of the unit requiring the listed permissions. -Only one instance of the param "#target" is allowed. -When there is not instance of this param, it behave as if -the target main was specified. - -#### required-permission: param name=[required permission name] - -The value is either: - -- required: the permission is mandatorily needed except if the feature - isn't required (required="false") and in that case it is optional. -- optional: the permission is optional - -### provided-unit: feature name="urn:AGL:widget:provided-unit" - -This feature is made for declaring new units -for the widget. -Using this feature, a software publisher -can provide more than one application in the same widget. - -Example: - -```xml - - - - - - -``` - -This will be *virtually* translated for mustaches to the JSON - -```json - { - "#target":"geoloc", - "description":"binding of name geoloc", - "content":{ - "src":"index.html", - "type":"application\/vnd.agl.service" - }, - ... - } -``` - -#### provided-unit: param name="#target" - -REQUIRED - -Declares the name of the unit. The default unit, the unit -of the main of the widget, has the name "main". -The value given here must be unique within the widget file. -It will be used in other places of the widget config.xml file to -designate the unit. - -Only one instance of the param "#target" is allowed. -The value can't be "main". - -#### provided-unit: param name="content.type" - -REQUIRED - -The mimetype of the provided unit. - -#### provided-unit: param name="content.src" - -A path to the source - -#### other parameters - -The items that can be set for the main unit -can also be set using the params if needed. - -- description -- name.content -- name.short -- ... - -### provided-api: feature name="urn:AGL:widget:provided-api" - -Use this feature for exporting one or more API of a unit -to other widgets of the platform. - -This feature is an important feature of the framework. - -Example: - -```xml - - - - - -``` - -This will be *virtually* translated for mustaches to the JSON - -```json - "provided-api":[ - { - "name":"geoloc", - "value":"auto" - }, - { - "name":"moonloc", - "value":"auto" - } - ], -``` - -#### provided-api: param name="#target" - -OPTIONAL - -Declares the name of the unit exporting the listed apis. -Only one instance of the param "#target" is allowed. -When there is not instance of this param, it behave as if -the target main was specified. - -#### provided-api: param name=[name of exported api] - -The name give the name of the api that is exported. - -The value is one of the following values: - -- ws: - export the api using UNIX websocket - -- dbus: [OBSOLETE, shouldn't be used currently] - export the API using dbus - -- auto: - export the api using the default method(s). - -- tcp: - In that case, the name is the URI used for exposing the service. - The URI is of type - HOST:PORT/API - API gives the name of the exported api. - -### file-properties: feature name="urn:AGL:widget:file-properties" - -Use this feature for setting properties to files of the widget. -At this time, this feature only allows to set executable flag -for making companion program executable explicitly. - -Example: - -```xml - - - - -``` - -#### file-properties: param name="path" - -The name is the relative path of the file whose property -must be set. - -The value must be "executable" to make the file executable. - -## Known content types - -The configuration file ***/etc/afm/afm-unit.conf*** defines -how to create systemd units for widgets. - -Known types for the type of content are: - -- ***text/html***: - HTML application, - content.src designates the home page of the application - -- ***application/vnd.agl.native*** - AGL compatible native, - content.src designates the relative path of the binary. - -- ***application/vnd.agl.service***: - AGL service, content.src is not used. - -- ***application/x-executable***: - Native application, - content.src designates the relative path of the binary. - For such application, only security setup is made. - -Adding more types is easy, it just need to edit the configuration -file ***afm-unit.conf***. - -### Older content type currently not supported at the moment - -This types were defined previously when the framework was not -leveraging systemd. -The transition to systemd let these types out at the moment. - -- ***application/vnd.agl.url*** -- ***text/vnd.qt.qml***, ***application/vnd.agl.qml*** -- ***application/vnd.agl.qml.hybrid*** -- ***application/vnd.agl.html.hybrid*** - -## The configuration file afm-unit.conf - -The integration of the framework with systemd -mainly consists of creating the systemd unit -files corresponding to the need and requirements -of the installed widgets. - -This configuration file named `afm-unit.conf` installed -on the system with the path `/etc/afm/afm-unit.conf` -describes how to generate all units from the *config.xml* -configuration files of widgets. -The description uses an extended version of the templating -formalism of [mustache][] to describes all the units. - -Let present how it works using the following diagram that -describes graphically the workflow of creating the unit -files for systemd `afm-unit.conf` from the configuration -file of the widget `config.xml`: - -![make-units](pictures/make-units.svg) - -In a first step, and because [mustache][] is intended -to work on JSON representations, the configuration file is -translated to an internal JSON representation. -This representation is shown along the examples of the documentation -of the config files of widgets. - -In a second step, the mustache template `afm-unit.conf` -is instantiated using the C library [mustach][] that follows -the rules of [mustache][mustache] and with all its available -extensions: - -- use of colon (:) for explicit substitution -- test of values with = or =! - -In a third step, the result of instantiating `afm-unit.conf` -for the widget is split in units. -To achieve that goal, the lines containing specific directives are searched. -Any directive occupy one full line. -The directives are: - -- %nl - Produce an empty line at the end -- %begin systemd-unit -- %end systemd-unit - Delimit the produced unit, its begin and its end -- %systemd-unit user -- %systemd-unit system - Tells the kind of unit (user/system) -- %systemd-unit service NAME -- %systemd-unit socket NAME - Gives the name and type (service or socket) of the unit. - The extension is automatically computed from the type - and must not be set in the name. -- %systemd-unit wanted-by NAME - Tells to install a link to the unit in the wants of NAME - -Then the computed units are then written to the filesystem -and inserted in systemd. - -The generated unit files will contain variables for internal -use of the framework. -These variables are starting with `X-AFM-`. -The variables starting with `X-AFM-` but not with `X-AFM--` are -the public variables. -These variables will be returned by the -framework as the details of an application (see **afm-util detail ...**). - -Variables starting with `X-AFM--` are private to the framework. -By example, the variable `X-AFM--http-port` is used to -record the allocated port for applications. - -[mustach]: https://gitlab.com/jobol/mustach "basic C implementation of mustache" -[mustache]: http://mustache.github.io/mustache.5.html "mustache - Logic-less templates" -[widgets]: http://www.w3.org/TR/widgets "Packaged Web Apps" -[widgets-digsig]: http://www.w3.org/TR/widgets-digsig "XML Digital Signatures for Widgets" -[libxml2]: http://xmlsoft.org/html/index.html "libxml2" -[app-manifest]: http://www.w3.org/TR/appmanifest "Web App Manifest" -[meta-intel]: https://github.com/01org/meta-intel-iot-security "A collection of layers providing security technologies" -[openssl]: https://www.openssl.org "OpenSSL" -[xmlsec]: https://www.aleksey.com/xmlsec "XMLSec" -[json-c]: https://github.com/json-c/json-c "JSON-c" -[d-bus]: http://www.freedesktop.org/wiki/Software/dbus "D-Bus" -[libzip]: http://www.nih.at/libzip "libzip" -[cmake]: https://cmake.org "CMake" -[security-manager]: https://wiki.tizen.org/wiki/Security/Tizen_3.X_Security_Manager "Security-Manager" -[tizen-security]: https://wiki.tizen.org/wiki/Security "Tizen security home page" -[tizen-secu-3]: https://wiki.tizen.org/wiki/Security/Tizen_3.X_Overview "Tizen 3 security overview" -[semantic-version]: http://semver.org/ "Semantic versioning" diff --git a/docs/3_Developer_Guides/1_Application_Framework/5_Permissions.md b/docs/3_Developer_Guides/1_Application_Framework/5_Permissions.md deleted file mode 100644 index 8b149c0..0000000 --- a/docs/3_Developer_Guides/1_Application_Framework/5_Permissions.md +++ /dev/null @@ -1,131 +0,0 @@ ---- -title: Permissions ---- - -## Permission's names - -The proposal here is to specify a naming scheme for permissions -that allows the system to be as stateless as possible. -The current specification includes in the naming of permissions either -the name of the bound binding when existing and the level of the -permission itself. -Doing this, there is no real need for the -framework to keep installed permissions in a database. - -The permission names are [URN][URN] of the form: - -```bash - urn:AGL:permission::: -``` - -where "AGL" is the NID (the namespace identifier) dedicated to AGL. -(note: a RFC should be produced to standardize this name space) - -The permission names are made of NSS (the namespace specific string) -starting with "permission:" and followed by colon separated -fields. -The 2 first fields are `` and `` and the remaining -fields are grouped to form the ``. - -```bash - ::= [ ] - - ::= 1* - - ::= | | | - - ::= "-" | "." | "_" | "@" -``` - -The field `` can be made of any valid character for NSS except -the characters colon and star (:*). -This field designates the api providing the permission. -This scheme is used to deduce binding requirements -from permission requirements. -The field `` can be the empty string when the permission -is defined by the AGL system itself. - -[PROPOSAL 1] The field `` if starting with the character "@" represents -a transversal/cross permission not bound to any binding. - -[PROPOSAL 2]The field `` if starting with the 2 characters "@@" -in addition to a permission not bound to any binding, represents a -permission that must be set at installation and that can not be -revoked later. - - ::= 1* - -The field `` is made only of letters in lower case. -The field `` can only take some predefined values: - -- system -- platform -- partner -- tiers -- owner -- public - -The field `` is made of `` separated -by colons. - - ::= 0*(":" ) - -The names at left are hierarchically grouping the -names at right. -This hierarchical behaviour is intended to -be used to request permissions using hierarchical grouping. - -## Permission value - -In some case, it could be worth to add a value to a permission. - -Currently, the framework allows it for permissions linked to -systemd. -But this not currently used. - -Conversely, permissions linked to cynara can't carry data -except in their name. - -Thus to have a simple and cleaner model, it is better to forbid -attachment of value to permission. - -## Example of permissions - -Here is a list of some possible permissions. -These permissions are available the 21th of May 2019. - -- urn:AGL:permission::platform:no-oom - Set OOMScoreAdjust=-500 to keep the out-of-memory - killer away. -- urn:AGL:permission::partner:real-time - Set IOSchedulingClass=realtime to give to the process - realtime scheduling. - Conversely, not having this permission set RestrictRealtime=on - to forbid realtime features. -- urn:AGL:permission::public:display - Adds the group "display" to the list of supplementary groups - of the process. -- urn:AGL:permission::public:syscall:clock - Without this permission SystemCallFilter=~@clock is set to - forfid call to clock. -- urn:AGL:permission::public:no-htdocs - The http directory served is not "htdocs" but "." -- urn:AGL:permission::public:applications:read - Allows to read data of installed applications (and to - access icons). -- urn:AGL:permission::partner:service:no-ws - Forbids services to provide its API through websocket. -- urn:AGL:permission::partner:service:no-dbus - Forbids services to provide its API through D-Bus. -- urn:AGL:permission::system:run-by-default - Starts automatically the application. Example: home-screen. -- urn:AGL:permission::partner:scope-platform - Install the service at the scope of the platform. -- urn:AGL:permission::system:capability:keep-all - Keep all capabilities for the service. Note that implementing - that permission is not mandatory or can be adapted for the given - system. -- - Permission to use D-Bus. - -[URN]: https://tools.ietf.org/rfc/rfc2141.txt "RFC 2141: URN Syntax" diff --git a/docs/3_Developer_Guides/1_Application_Framework/6_Quick-Tutorial.md b/docs/3_Developer_Guides/1_Application_Framework/6_Quick-Tutorial.md deleted file mode 100644 index f031235..0000000 --- a/docs/3_Developer_Guides/1_Application_Framework/6_Quick-Tutorial.md +++ /dev/null @@ -1,267 +0,0 @@ ---- -title: Quick Tutorial ---- - -## Introduction - -This document proposes a quick tutorial to demonstrate the major -functionalities of the AGL Application Framework. -For more complete information, please refer to the inline documentation -available in the main git repository: - - - [https://gerrit.automotivelinux.org/gerrit/#/admin/projects/src/app-framework-main] - - [https://gerrit.automotivelinux.org/gerrit/#/admin/projects/src/app-framework-binder] - -For more information on AGL, please visit: -[https://www.automotivelinux.org/] - -## Sample applications - -4 sample applications (.wgt files) are prebuilt and available at the following address: -[https://github.com/iotbzh/afm-widget-examples] - -You can get them by cloning this git repository on your desktop (will be useful later in this tutorial): - -```bash -git clone https://github.com/iotbzh/afm-widget-examples -``` - -## Using the CLI tool - -### Setup Environment - -Connect your AGL target board to the network and copy some sample widgets on it through SSH (set BOARDIP with your board IP address) : - -```bash -cd afm-widget-examples -BOARDIP=1.2.3.4 -scp *.wgt root@$BOARDIP:~/ -``` - -Connect through SSH on the target board and check for Application Framework daemons: - -```bash -$ ssh root@$BOARDIP -root@porter:~# ps -ef|grep bin/afm -afm 409 1 0 13:00 ? 00:00:00 /usr/bin/afm-system-daemon -root 505 499 0 13:01 ? 00:00:00 /usr/bin/afm-user-daemon -root 596 550 0 13:22 pts/0 00:00:00 grep afm -``` - -We can see that there are two daemons running: - -* **afm-system-daemon** runs with a system user 'afm' and is responsible for - installing/uninstalling packages -* **afm-user-daemon** runs as a user daemon (currently as root because it's the - only real user on the target board) and is responsible for the whole life - cycle of the applications running inside the user session. - -The application framework has a tool running on the -Command Line Interface (CLI). -Using the **afm-util** command, you can install, uninstall, list, run, pause ... applications. - -To begin, run '**afm-util help**' to get a quick help on commands: - -```bash -root@porter:~# afm-util help -usage: afm-util command [arg] -``` - -The commands are: - -```bash -list -runnables list the runnable widgets installed - -add wgt -install wgt install the wgt file - -remove id -uninstall id remove the installed widget of id - -info id -detail id print detail about the installed widget of id - -ps -runners list the running instance - -run id -start id start an instance of the widget of id - -kill rid -terminate rid terminate the running instance rid - -status rid -state rid get status of the running instance rid -``` - -### Install an application - -You can then install your first application: - -```bash -root@porter:~# afm-util install /home/root/annex.wgt -{ "added": "webapps-annex@0.0" } -``` - -Let's install a second application: - -```bash -root@porter:~# afm-util install /home/root/memory-match.wgt -{ "added": "webapps-memory-match@1.1" } -``` - -Note that usually, **afm-util** will return a **JSON result**, which is the common format for messages returned by the Application Framework daemons. - -### List installed applications - -You can then list all installed applications: - -```bash -root@porter:~# afm-util list -[ { "id": "webapps-annex@0.0", "version": "0.0.10", "width": 0, "height": 0, "name": "Annex", "description": "Reversi\/Othello", "shortname": "", "author": "Todd Brandt " }, -{ "id": "webapps-memory-match@1.1", "version": "1.1.7", "width": 0, "height": 0, "name": "MemoryMatch", "description": "Memory match", "shortname": "", "author": "Todd Brandt " } ] -``` - -Here, we can see the two previously installed applications. - -### Get information about an application - -Let's get some details about the first application: - -```bash -root@porter:~# afm-util info webapps-annex@0.0 -{ "id": "webapps-annex@0.0", "version": "0.0.10", "width": 0, "height": 0, "name": "Annex", "description": "Reversi\/Othello", "shortname": "", "author": "Todd Brandt " } -``` - -Note: that AGL applications are mostly handled by afm-util through their IDs. -In our example, the application ID is 'webapps-annex@0.0'. - -### Start application - -Let's start the first application Annex: - -```bash -root@porter:~# afm-util start webapps-annex@0.0 -1 -``` - -As the application is a HTML5 game, you should then get a webview running with QML on the board display. - -### Security Context - -The application has been started in the user session, with a dedicated security context, enforced by SMACK. -To illustrate this, we can take a look at the running processes and their respective SMACK labels: - -```bash -root@porter:~# ps -efZ |grep webapps-annex | grep -v grep -User::App::webapps-annex root 716 491 0 13:19 ? 00:00:00 /usr/bin/afb-daemon --mode=local --readyfd=8 --alias=/icons /usr/share/afm/icons --port=12348 --rootdir=/usr/share/afm/applications/webapps-annex/0.0 --token=7D6D2F16 --sessiondir=/home/root/app-data/webapps-annex/.afb-daemon -User::App::webapps-annex root 717 491 0 13:19 ? 00:00:00 /usr/bin/qt5/qmlscene http://localhost:12348/index.html?token=7D6D2F16 /usr/bin/web-runtime-webkit.qml -``` - -In the previous result, we see that the application is composed of two processes: - -* the application binder (afb-daemon) -* the application UI (qmlscene ...) - -While most system processes run with the label 'System', we see that the -application runs with a specific SMACK label 'User::App::webapps-annex': this -label is used to force the application to follow -a Mandatory Access Control (MAC) scheme. -This means that those processes run in their own security context, -isolated from the rest of the system (and other applications). -Global security rules can then be applied to restrict access -to all other user or system resources. - -### Check running applications - -To check for running applications, just run: - -```bash -root@porter:~# afm-util ps -[ { "runid": 1, "state": "running", "id": "webapps-annex@0.0" } ] -``` - -The 'runid' is the application instance ID and is used as an argument for the -subcommands controlling the application runtime state (kill/pause/resume/status) - -### Uninstall application - -To uninstall an application, simply use its ID: - -```bash -root@porter:~# afm-util uninstall webapps-annex@0.0 -true -``` - -Then list the installed apps to confirm the removal: - -```bash -root@porter:~# afm-util list -[ { "id": "webapps-memory-match@1.1", "version": "1.1.7", "width": 0, "height": 0, "name": "MemoryMatch", "description": "Memory match", "shortname": "", "author": "Todd Brandt " } ] -``` - -## afm-client: a sample HTML5 'Homescreen' - -**afm-client** is a HTML5 UI that allows to install/uninstall applications as well as starting/pausing them as already demonstrated with afm-util. - -The HTML5 UI is accessible remotely through this URL: - - -### Installing an application - -By clicking on the '**Upload**' button on the right, -you can send an application package (WGT file) and install it. -Select for example the file '**rabbit.wgt**' that was cloned initially - from the git repository afm-widget-examples. - -Then a popup requester ask for a confirmation: -'Upload Application rabbit.wgt ?'. Click on the '**Install**' button. - -You should then see some changes in the toolbar: -a new icon appeared, representing the freshly installed application. - -### Running an application - -In the toolbar, click on the button representing the Rabbit application. -You'll get a popup asking to: - -* start the application -* or get some info about it -* or uninstall it - -Click on the 'start' item: the application starts and should be visible - as a webview on the target board display. -Note that at this point, we could also run the application remotely, -that is in the same browser as the Homescreen app. -By default, the application framework is configured -to run applications 'locally' on the board display. - -### Uninstalling an application - -From the same popup menu, you can select 'uninstall' -to remove the application from the system. -As a consequence, the application icon should disappear from the toolbar. - -## afb-client: a template for Angular Applications - -Another package '**afb-client**' is also available for testing. -This is a sample HTML5 application demonstrating various basic -capabilities of the Binder daemon. -It can be used by developers as a template to start writing real AGL Applications. - -This application is not available as WGT file yet and it should be started manually without any specific security context: - -```bash -root@porter:~# /usr/bin/afb-daemon --port=1235 --token='' --sessiondir=/home/root/.afm-daemon --rootdir=/usr/share/agl/afb-client --alias=/icons:/usr/share/afm/icons -``` - -Then you can access it from a browser: - - -afb-client is a simple application to demonstrate the built-in capabilities of the binder daemon (handling sessions and security tokens, testing POSTs uploads...) and was used during the application framework development to validate the proposed features. - -[https://github.com/iotbzh/afm-widget-examples]: https://github.com/iotbzh/afm-widget-examples -[https://www.automotivelinux.org/]: https://www.automotivelinux.org/ -[https://gerrit.automotivelinux.org/gerrit/#/admin/projects/src/app-framework-binder]: https://gerrit.automotivelinux.org/gerrit/#/admin/projects/src/app-framework-binder -[https://gerrit.automotivelinux.org/gerrit/#/admin/projects/src/app-framework-main]: https://gerrit.automotivelinux.org/gerrit/#/admin/projects/src/app-framework-main diff --git a/docs/3_Developer_Guides/1_Application_Framework/images/AppFW-APP_install_sequences.svg b/docs/3_Developer_Guides/1_Application_Framework/images/AppFW-APP_install_sequences.svg deleted file mode 100644 index fab8399..0000000 --- a/docs/3_Developer_Guides/1_Application_Framework/images/AppFW-APP_install_sequences.svg +++ /dev/null @@ -1,408 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - System - - - - - - - - - - - - - - - User - - - - - - - - - - - D-Bus session - - - - - - - - - - SMACK isolatedother application - - - - - - - - - - SECURITY MANAGER - - - - - - - - - - afm-system-daemon - - - - - - - - - - CYNARA - - - - - - - - - - D-Bus system - - - - - - - - - - afm-user-daemon - - - - - - - - - - SMACK isolated Application - - - - - - - - - - - - - - - - - Application UI - - - - - - - - - - - binder afb-daemon - - - - - - - - - - afm-main-binding - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - (1), (7) - - - - - - (2) - - - - - - (3) - - - - - - (4) - - - - - - (5) - - - - - - (6) - - - - - - (9) - - - - - - (11) - - - - - - (12) - - - - - - (10) - - - - - - (13) - - - - - - (8) - - - - - - - diff --git a/docs/3_Developer_Guides/1_Application_Framework/images/Security_model_history.svg b/docs/3_Developer_Guides/1_Application_Framework/images/Security_model_history.svg deleted file mode 100644 index 7935437..0000000 --- a/docs/3_Developer_Guides/1_Application_Framework/images/Security_model_history.svg +++ /dev/null @@ -1,149 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Tizen OBS - - - - - - Tizen Yocto - - - - - - meta-intel-iot-security - - - - - - 2014 - - - - - - 2015 - - - - - - - \ No newline at end of file diff --git a/docs/3_Developer_Guides/1_Application_Framework/images/afm-daemons.svg b/docs/3_Developer_Guides/1_Application_Framework/images/afm-daemons.svg deleted file mode 100644 index 02b2c92..0000000 --- a/docs/3_Developer_Guides/1_Application_Framework/images/afm-daemons.svg +++ /dev/null @@ -1,237 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - System - - - - - - - - - - - - - - - User - - - - - - - - - - - D-Bus session - - - - - - - - - - SMACK isolatedApplication - - - - - - - - - - SECURITY MANAGER - - - - - - - - - - afm-system-daemon - - - - - - - - - - CYNARA - - - - - - - - - - D-Bus system - - - - - - - - - - afm-user-daemon - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/docs/3_Developer_Guides/1_Application_Framework/images/make-units.svg b/docs/3_Developer_Guides/1_Application_Framework/images/make-units.svg deleted file mode 100644 index d52a8c7..0000000 --- a/docs/3_Developer_Guides/1_Application_Framework/images/make-units.svg +++ /dev/null @@ -1,436 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - <number> - - - - - - - - - - - - - - config.xml - - - - - - - /etc/afm/afm-unit.conf - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - json description - - - - - - - - - Mustache engine - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - units description - - - - - - - *.service - - - - - - - *.socket - - - - - - virtualdata - - - - - - - - - - - - - - - - - - - - - - - Unit installer - - - - - - - - - Config engine - - - - - - - ... - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - configurationfile - - - - - - systemdunits - - - - - - - \ No newline at end of file diff --git a/docs/3_Developer_Guides/1_Setting_Up_AGL_SDK.md b/docs/3_Developer_Guides/1_Setting_Up_AGL_SDK.md index c4ea431..8cdbe3e 100644 --- a/docs/3_Developer_Guides/1_Setting_Up_AGL_SDK.md +++ b/docs/3_Developer_Guides/1_Setting_Up_AGL_SDK.md @@ -14,7 +14,7 @@ quickstart the service and application development process. - **AARCH64 - ARM 64bit** : [qemuarm64](https://download.automotivelinux.org/AGL/snapshots/master/latest/qemuarm64/deploy/sdk/poky-agl-glibc-x86_64-agl-demo-platform-crosssdk-aarch64-qemuarm64-toolchain-10.90.0+snapshot.sh) *Henceforth,* **qemux86-64** *is used in these guides, unless specified - otherwise.* + otherwise. We also use the 'agl-demo-platform-crosssdk' as example.* 2. Create application developmment directory and copy SDK into them : diff --git a/docs/3_Developer_Guides/2_Application_Framework_Binder/0_Overview.md b/docs/3_Developer_Guides/2_Application_Framework_Binder/0_Overview.md deleted file mode 100644 index 22a88ba..0000000 --- a/docs/3_Developer_Guides/2_Application_Framework_Binder/0_Overview.md +++ /dev/null @@ -1,91 +0,0 @@ ---- -title: Overview ---- - -The ***binder*** provides the way to connect applications to -the services that it needs. - -It provides a fast way to securely offer APIs to applications -written in any language and running almost anywhere. - -- The ***binder*** is developed for AGL (Automotive Grade Linux) but it is not bound to AGL. -- The ***binder*** is the usual name. -- The binary is named **afb-daemon**. -- The name **afb-daemon** stands for ***Application Framework Binder Daemon***. - -The word *daemon*, here, denote the fact that the ***binder*** makes witchcraft to -connect applications to their expected services. (note: that usually the term of -daemon denotes background process but not here). - -Each ***binder*** **afb-daemon** is in charge to bind one instance of -an application or service to the rest of the system, applications and services. -Within AGL, the connection between services and/or applications -is tuned by the AGL framework and the AGL system. - -## The basis of the binder - -The following figure shows main concepts linked to the ***binder***. - -![Figure: binder basis](images/basis.svg) - -The shown elements are: - -- The SECURITY CONTEXT - - The primary intention of any ***binder*** is to provide - a secured environment for any application. - On AGL, the **security context** is ensured by [Smack] - , the security context of the application or service. - -- The BINDER - - This is the central element. - It makes possible to run HTML5 applications and provides - the unified access to APIs provided by the ***bindings***. - - Running a pure HTML5 application doesn't require any ***binding***. - In that case , the ***binder*** acts as a simple HTTP server for - the web runtime. - -- The BINDINGs - - A ***binding*** adds one **API** to the ***binder***. - - An **API** is a set of **verbs** that can be called - using either REST over HTTP or a kind of JSON RPC. - - ***bindings*** are either: - - - dynamically loaded libraries in the ***binder*** process - - remote service running on the same host - - remote service running on other hosts - - When acting as an HTTP server, the binder treats the language - settings of the HTTP requests to provide internationalized - content as specified by - [widget - specifications](https://www.w3.org/TR/widgets/#internationalization-and-localization). - -- The APPLICATION - - An ***application*** connects to the binder to get access to - the **API** that it provides or to get its HTTP services to access - resources. - -## Interconnection of binders - -The AGL framework interprets the **widget/application** manifests -to setup the ***bindings*** configuration of the ***binders***. - -The figure below shows that ***binders*** are interconnected. - -![Figure: binder interconnection](images/interconnection.svg) - -The figure shows 4 several **application/service**: **A**, **B**, -**C** and **D**. - -The application **A** might use an **API** that is shown as a -local ***binding*** but that in reality runs within the context -of **D**. - -The framework AGL takes care of making the plumbing working. \ No newline at end of file diff --git a/docs/3_Developer_Guides/2_Application_Framework_Binder/1_Binder_daemon_vocabulary.md b/docs/3_Developer_Guides/2_Application_Framework_Binder/1_Binder_daemon_vocabulary.md deleted file mode 100644 index 9839e65..0000000 --- a/docs/3_Developer_Guides/2_Application_Framework_Binder/1_Binder_daemon_vocabulary.md +++ /dev/null @@ -1,104 +0,0 @@ ---- -title: Binder daemon vocabulary ---- - -## Binding - -A shared library object intended to add a functionality to an afb-daemon -instance. -It implements an API and may provide a service. - -Binding made for services can have specific entry points called after -initialization and before serving. - -## Event - -Messages with data propagated from the services to the client and not expecting -any reply. - -The current implementation allows to widely broadcast events to all clients. - -## Level of assurance (LOA) - -This level that can be from 0 to 3 represent the level of -assurance that the services can expect from the session. - -The exact definition of the meaning of these levels and how to use it remains to -be achieved. - -## Request - -A request is an invocation by a client to a binding method using a message -transferred through some protocol: - -- HTTP -- WebSocket -- ... - -and served by ***afb-daemon*** - -## Reply/Response - -This is a message sent to client as the result of the request. - -## Service - -Service are made of bindings running on a binder -The binder is in charge of connecting services and applications. -A service can serve many clients. - -The framework establishes connection between the services and the clients. -Using sockets currently but other protocols are considered. - -The term of service is tightly bound to the notion of API. - -## Session - -A session is meant to be the unique instance context of a client, -which identify that instance across requests. - -Each session has an identifier. -Session identifier generated by afb-daemon are UUIDs. -A client can present its own session id. - -Internally, afb-daemon offers a mechanism to attach data to sessions. -When a session is closed or disappears, data attached to that session -are freed. - -## Token - -The token is an identifier that the client must give to be authenticated. - -At start, afb-daemon get an initial token. -This initial token must be presented by incoming client to be authenticated. - -A token is valid only for a period. - -The token must be renewed periodically. -When the token is renewed, afb-daemon sends the new token to the client. - -Tokens generated by afb-daemon are UUIDs. - -## UUID - -It stand for Universal Unique IDentifier. - -It is designed to create identifier in a way that avoid has much as possible -conflicts. -It means that if two different instances create an UUID, the -probability that they create the same UUID is very low, near to zero. - -## x-afb-reqid - -Argument name that can be used with HTTP request. -When this argument is given, it is automatically added to the "request" object of the answer. - -## x-afb-token - -Argument name meant to give the token without ambiguity. -You can also use the name **token** but it may conflicts with others arguments. - -## x-afb-uuid - -Argument name for giving explicitly the session identifier without ambiguity. -You can also use the name **uuid** but it may conflicts with others arguments. diff --git a/docs/3_Developer_Guides/2_Application_Framework_Binder/2_How_to_write_a_binding.md b/docs/3_Developer_Guides/2_Application_Framework_Binder/2_How_to_write_a_binding.md deleted file mode 100644 index d739167..0000000 --- a/docs/3_Developer_Guides/2_Application_Framework_Binder/2_How_to_write_a_binding.md +++ /dev/null @@ -1,444 +0,0 @@ ---- -title: How to write a binding? ---- - -# Overview of the bindings - -The ***binder*** serves files through HTTP protocol and offers developers the capability to offer application API methods through HTTP or -WebSocket protocol. - -The ***bindings*** are used to add **API** to ***binders***. -This part describes how to write a ***binding*** for ***binder*** -or in other words how to add a new **API** to the system. - -This section target developers. - -This section shortly explain how to write a binding -using the C programming language. - -It is convenient to install the ***binder*** on the -desktop used for writing the binding. -It allows for easy debug and test. - -## Nature of a binding - -A ***binding*** is an independent piece of software compiled as a shared -library and dynamically loaded by a ***binder***. -It is intended to provide one **API** (**A**pplication **P**rogramming -**I**nterface). - -The **API** is designated and accessed through its name. -It contains several **verbs** that implement the ***binding*** -functionalities. -Each of these **verbs** is a **method** that -processes requests of applications and sends results. - -The ***binding***'s methods are invoked by HTTP or websocket -requests. - -The **methods** of the ***bindings*** are noted **api/verb** -where **api** is the **API** name of the binding and **verb** is -the **method**'s name within the **API**. -This notation comes from HTTP invocations that rely on URL path terminated -with **api/verb**. - -The name of an **API** can be made of any characters except: - -- the control characters (\u0000 .. \u001f) -- the characters of the set { ' ', '"', '#', '%', '&', - '\'', '/', '?', '`', '\x7f' } - -The names of the **verbs** can be any character. - -The binder makes no distinctions between upper case and lower case -latin letters. -So **API/VERB** matches **Api/Verb** or **api/verb**. - -## Versions of the bindings - -Since introduction of the binder, the way how bindings are written -evolved a little. While changing, attention was made to ensure binary -compatibility between the different versions. - -Actually it exists 3 ways of writing ***bindings***. -You can either write: - -- a binding version 1 (not more supported); -- a binding version 2 (not recommended); -- a binding version 3 (RECOMMENDED). - -A ***binder*** loads and runs any of these version in any combination. -This document explain how to write bindings version 3. - -## Sample binding: tuto-1 - -This is the code of the binding **tuto-1.c**: - -```C - 1 #define AFB_BINDING_VERSION 3 - 2 #include - 3 - 4 void hello(afb_req_t req) - 5 { - 6 AFB_REQ_DEBUG(req, "hello world"); - 7 afb_req_reply(req, NULL, NULL, "hello world"); - 8 } - 9 - 10 const afb_verb_t verbs[] = { - 11 { .verb="hello", .callback=hello }, - 12 { .verb=NULL } - 13 }; - 14 - 15 const afb_binding_t afbBindingExport = { - 16 .api = "tuto-1", - 17 .verbs = verbs - 18 }; -``` - -Compiling: - -```bash -gcc -fPIC -shared tuto-1.c -o tuto-1.so $(pkg-config --cflags-only-I afb-daemon) -``` - -> Note: the variable environment variable PKG_CONFIG_PATH might be necessary -> tuned to get **pkg-config** working properly - -Running: - -```bash -afb-daemon --binding ./tuto-1.so --port 3333 --token '' -``` - -At this point, afb-daemon has started, it loaded the binding tuto-1.so and now -listen at localhost on the port 3333. - -Testing using **curl**: - -```bash -$ curl http://localhost:3333/api/tuto-1/hello -{"jtype":"afb-reply","request":{"status":"success","info":"hello world","uuid":"1e587b54-900b-49ab-9940-46141bc2e1d6"}} -``` - -Testing using **afb-client-demo** (with option -H for -getting a human readable output): - -```bash -$ afb-client-demo -H ws://localhost:3333/api?token=x tuto-1 hello -ON-REPLY 1:tuto-1/hello: OK -{ - "jtype":"afb-reply", - "request":{ - "status":"success", - "info":"hello world", - "uuid":"03a84ad1-458a-4ace-af74-b1da917391b9" - } -} -``` - -This shows basic things: - -- The include to get for creating a binding -- How to declare the API offered by the binding -- How to handle requests made to the binding - -### Getting declarations for the binding - -The lines 1 and 2 show how to get the include file **afb-binding.h**. - -```C - 1 #define AFB_BINDING_VERSION 3 - 2 #include -``` - -You must define the version of ***binding*** that you are using. -This is done line 1 where we define that this is the version 3 (earlier -versions 1 and 2 are deprecated). - -If you don't define it, an error is reported and the compilation aborts. - -To include **afb-binding.h** successfully, the include search path -should be set correctly if needed (not needed only if installed in -/usr/include/afb directory that is the default). - -Setting the include path is easy using **pkg-config**: - -```bash -pkg-config --cflags-only-I afb-daemon -``` - -> Note for **C++** developers: -> -> The ***binder*** currently expose a draft version of **C++** api. -> To get it include the file <**afb/afb-binding**> (without **.h**). - - -### Declaring the API of the binding - -Lines 10 to 18 show the declaration of the ***binding***. - -The ***binder*** knows that this is a ***binding*** because -it finds the exported symbol **afbBindingExport** that is expected to be -a structure of type **afb_binding_t**. - -```C - 10 const afb_verb_t verbs[] = { - 11 { .verb="hello", .callback=hello }, - 12 { .verb=NULL } - 13 }; - 14 - 15 const afb_binding_t afbBindingExport = { - 16 .api = "tuto-1", - 17 .verbs = verbs - 18 }; -``` - -The structure **afbBindingExport** actually tells that: - -- the exported **API** name is **tuto-1** (line 16) -- the array of verbs is the above defined one - -The exported list of verb is specified by an array of structures of -type **afb_verb_t**, each describing a verb, ended with a verb NULL (line 12). - -The only defined verb here (line 11) is named **hello** (field **.verb**) -and the function that handle the related request is **hello** -(field **.callback**). - -### Handling binder's requests - -As shown above this is by default the common include directory where -the AGL stuff is installed. - -```C - 4 void hello(afb_req_t req) - 5 { - 6 AFB_REQ_DEBUG(req, "hello world"); - 7 afb_req_reply(req, NULL, NULL, "hello world"); - 8 } -``` - -When the ***binder*** receives a request for the verb **hello** of -of the api **tuto-1**, it invoke the callback **hello** of the **binding** -with the argument **req** that handles the client request. - -The callback has to treat synchronously or asynchronously the request and -should at the end emit a reply for the request. - -At the line 7, the callback for **tuto-1/hello** replies to the request **req**. -Parameters of the reply are: - - 1. The first parameter is the replied request - 2. The second parameter is a json object (here NULL) - 3. The third parameter is the error string indication (here NULL: no error) - 4. The fourth parameter is an informative string (that can be NULL) that can be used to provide meta data. - -The 3 last parameters are sent back to the client as the reply content. - - - -## Sample binding: tuto-2 - -The second tutorial shows many important feature that can -commonly be used when writing a ***binding***: - -- initialization, getting arguments, sending replies, pushing events. - -This is the code of the binding **tuto-2.c**: - -```C - 1 #include - 2 #include - 3 - 4 #define AFB_BINDING_VERSION 3 - 5 #include - 6 - 7 afb_event_t event_login, event_logout; - 8 - 9 void login(afb_req_t req) - 10 { - 11 json_object *args, *user, *passwd; - 12 char *usr; - 13 - 14 args = afb_req_json(req); - 15 if (!json_object_object_get_ex(args, "user", &user) - 16 || !json_object_object_get_ex(args, "password", &passwd)) { - 17 AFB_REQ_ERROR(req, "login, bad request: %s", json_object_get_string(args)); - 18 afb_req_reply(req, NULL, "bad-request", NULL); - 19 } else if (afb_req_context_get(req)) { - 20 AFB_REQ_ERROR(req, "login, bad state, logout first"); - 21 afb_req_reply(req, NULL, "bad-state", NULL); - 22 } else if (strcmp(json_object_get_string(passwd), "please")) { - 23 AFB_REQ_ERROR(req, "login, unauthorized: %s", json_object_get_string(args)); - 24 afb_req_reply(req, NULL, "unauthorized", NULL); - 25 } else { - 26 usr = strdup(json_object_get_string(user)); - 27 AFB_REQ_NOTICE(req, "login user: %s", usr); - 28 afb_req_session_set_LOA(req, 1); - 29 afb_req_context_set(req, usr, free); - 30 afb_req_reply(req, NULL, NULL, NULL); - 31 afb_event_push(event_login, json_object_new_string(usr)); - 32 } - 33 } - 34 - 35 void action(afb_req_t req) - 36 { - 37 json_object *args, *val; - 38 char *usr; - 39 - 40 args = afb_req_json(req); - 41 usr = afb_req_context_get(req); - 42 AFB_REQ_NOTICE(req, "action for user %s: %s", usr, json_object_get_string(args)); - 43 if (json_object_object_get_ex(args, "subscribe", &val)) { - 44 if (json_object_get_boolean(val)) { - 45 AFB_REQ_NOTICE(req, "user %s subscribes to events", usr); - 46 afb_req_subscribe(req, event_login); - 47 afb_req_subscribe(req, event_logout); - 48 } else { - 49 AFB_REQ_NOTICE(req, "user %s unsubscribes to events", usr); - 50 afb_req_unsubscribe(req, event_login); - 51 afb_req_unsubscribe(req, event_logout); - 52 } - 53 } - 54 afb_req_reply(req, json_object_get(args), NULL, NULL); - 55 } - 56 - 57 void logout(afb_req_t req) - 58 { - 59 char *usr; - 60 - 61 usr = afb_req_context_get(req); - 62 AFB_REQ_NOTICE(req, "login user %s out", usr); - 63 afb_event_push(event_logout, json_object_new_string(usr)); - 64 afb_req_session_set_LOA(req, 0); - 65 afb_req_context_clear(req); - 66 afb_req_reply(req, NULL, NULL, NULL); - 67 } - 68 - 69 int preinit(afb_api_t api) - 70 { - 71 AFB_API_NOTICE(api, "preinit"); - 72 return 0; - 73 } - 74 - 75 int init(afb_api_t api) - 76 { - 77 AFB_API_NOTICE(api, "init"); - 78 event_login = afb_api_make_event(api, "login"); - 79 event_logout = afb_api_make_event(api, "logout"); - 80 if (afb_event_is_valid(event_login) && afb_event_is_valid(event_logout)) - 81 return 0; - 82 AFB_API_ERROR(api, "Can't create events"); - 83 return -1; - 84 } - 85 - 86 const afb_verb_t verbs[] = { - 87 { .verb="login", .callback=login }, - 88 { .verb="action", .callback=action, .session=AFB_SESSION_LOA_1 }, - 89 { .verb="logout", .callback=logout, .session=AFB_SESSION_LOA_1 }, - 90 { .verb=NULL } - 91 }; - 92 - 93 const afb_binding_t afbBindingExport = { - 94 .api = "tuto-2", - 95 .specification = NULL, - 96 .verbs = verbs, - 97 .preinit = preinit, - 98 .init = init, - 99 .noconcurrency = 0 - 100 }; -``` - -Compiling: - -```bash -gcc -fPIC -shared tuto-2.c -o tuto-2.so $(pkg-config --cflags --libs afb-daemon) -``` - -Running: - -```bash -afb-daemon --binding ./tuto-2.so --port 3333 --token '' -``` - -Testing: - -```bash -$ afb-client-demo -H localhost:3333/api?token=toto -tuto-2 login {"help":true} -ON-REPLY 1:tuto-2/login: ERROR -{ - "jtype":"afb-reply", - "request":{ - "status":"bad-request", - "uuid":"e2b24a13-fc43-487e-a5f4-9266dd1e60a9" - } -} -tuto-2 login {"user":"jose","password":"please"} -ON-REPLY 2:tuto-2/login: OK -{ - "jtype":"afb-reply", - "request":{ - "status":"success" - } -} -tuto-2 login {"user":"jobol","password":"please"} -ON-REPLY 3:tuto-2/login: ERROR -{ - "jtype":"afb-reply", - "request":{ - "status":"bad-state" - } -} -tuto-2 action {"subscribe":true} -ON-REPLY 4:tuto-2/action: OK -{ - "response":{ - "subscribe":true - }, - "jtype":"afb-reply", - "request":{ - "status":"success" - } -} -``` - -In another terminal: - -```bash -$ afb-client-demo -H localhost:3333/api?token=toto -tuto-2 login {"user":"jobol","password":"please"} -ON-REPLY 1:tuto-2/login: OK -{ - "jtype":"afb-reply", - "request":{ - "status":"success", - "uuid":"a09f55ff-0e89-4f4e-8415-c6e0e7f439be" - } -} -tuto-2 logout true -ON-REPLY 2:tuto-2/logout: OK -{ - "jtype":"afb-reply", - "request":{ - "status":"success" - } -} -``` - -It produced in the first terminal: - -```bash -ON-EVENT tuto-2/login: -{ - "event":"tuto-2\/login", - "data":"jobol", - "jtype":"afb-event" -} -ON-EVENT tuto-2/logout: -{ - "event":"tuto-2\/logout", - "data":"jobol", - "jtype":"afb-event" -} -``` diff --git a/docs/3_Developer_Guides/2_Application_Framework_Binder/3_Binder_References.md b/docs/3_Developer_Guides/2_Application_Framework_Binder/3_Binder_References.md deleted file mode 100644 index fab571b..0000000 --- a/docs/3_Developer_Guides/2_Application_Framework_Binder/3_Binder_References.md +++ /dev/null @@ -1,2524 +0,0 @@ ---- -title: Binder References ---- - -i. TYPES AND GLOBALS -====================== - -## The global afbBindingRoot - -The global **afbBindingRoot** of type **afb_api_t** is always implicitly -defined for bindings of version 3 or upper. It records the root api of -the binding. - -When the binding has a defined **afbBindingExport**, the root api -**afbBindingRoot** is the **afb_pi_t** relative to the api created for -this static description. - -When the binding has no defined **afbBindingExport**, the root api is -a virtual api representing the shared object of the binding. In that case -the name of the api is the path of the shared object. Its use is restricted -but allows log messages. - -## The global afbBindingExport - -The global **afbBindingExport** is not mandatory. - -If **afbBindingExport** is defined and exported, it must be of the type -**const afb_binding_t** and must describe the *root* api of the binding. - -## The type afb_api_t - -Bindings now can declare more than one api. The counter part is that -a new handle is needed to manage apis. These handles are of the type -**afb_api_t**. - -It is defined as below. - -```C -typedef struct afb_api_x3 afb_api_t; -``` - -## The type afb_binding_t - -The main structure, of type **afb_binding_t**, for describing the binding -must be exported under the name **afbBindingExport**. - -This structure is defined as below. - -```C -typedef struct afb_binding_v3 afb_binding_t; -``` - -Where: - -```C -/** - * Description of the bindings of type version 3 - */ -struct afb_binding_v3 -{ - /** api name for the binding, can't be NULL */ - const char *api; - - /** textual specification of the binding, can be NULL */ - const char *specification; - - /** some info about the api, can be NULL */ - const char *info; - - /** array of descriptions of verbs terminated by a NULL name, can be NULL */ - const struct afb_verb_v3 *verbs; - - /** callback at load of the binding */ - int (*preinit)(struct afb_api_x3 *api); - - /** callback for starting the service */ - int (*init)(struct afb_api_x3 *api); - - /** callback for handling events */ - void (*onevent)(struct afb_api_x3 *api, const char *event, struct json_object *object); - - /** userdata for afb_api_x3 */ - void *userdata; - - /** space separated list of provided class(es) */ - const char *provide_class; - - /** space separated list of required class(es) */ - const char *require_class; - - /** space separated list of required API(es) */ - const char *require_api; - - /** avoids concurrent requests to verbs */ - unsigned noconcurrency: 1; -}; -``` - -## The type afb_verb_t - -Each verb is described with a structure of type **afb_verb_t** -defined below: - -```C -typedef struct afb_verb_v3 afb_verb_t; -``` - -```C -/** - * Description of one verb as provided for binding API version 3 - */ -struct afb_verb_v3 -{ - /** name of the verb, NULL only at end of the array */ - const char *verb; - - /** callback function implementing the verb */ - void (*callback)(afb_req_t_x2 *req); - - /** required authorization, can be NULL */ - const struct afb_auth *auth; - - /** some info about the verb, can be NULL */ - const char *info; - - /**< data for the verb callback */ - void *vcbdata; - - /** authorization and session requirements of the verb */ - uint16_t session; - - /** is the verb glob name */ - uint16_t glob: 1; -}; -``` - -The **session** flags is one of the constant defined below: - -| Name | Description -|:----------------------:|------------------------------------------------------ -| AFB_SESSION_NONE | no flag, synonym to 0 -| AFB_SESSION_LOA_0 | Requires the LOA to be 0 or more, synonym to 0 or AFB_SESSION_NONE -| AFB_SESSION_LOA_1 | Requires the LOA to be 1 or more -| AFB_SESSION_LOA_2 | Requires the LOA to be 2 or more -| AFB_SESSION_LOA_3 | Requires the LOA to be 3 or more -| AFB_SESSION_CHECK | Requires the token to be set and valid -| AFB_SESSION_REFRESH | Implies a token refresh -| AFB_SESSION_CLOSE | Implies closing the session after request processed - -The LOA (Level Of Assurance) is set, by binding api, using the function **afb_req_session_set_LOA**. - -The session can be closed, by binding api, using the function **afb_req_session_close**. - -## The types afb_auth_t and afb_auth_type_t - -The structure **afb_auth_t** is used within verb description to -set security requirements. -The interpretation of the structure depends on the value of the field **type**. - -```C -typedef struct afb_auth afb_auth_t; - -/** - * Definition of an authorization entry - */ -struct afb_auth -{ - /** type of entry @see afb_auth_type */ - enum afb_auth_type type; - - union { - /** text when @ref type == @ref afb_auth_Permission */ - const char *text; - - /** level of assurancy when @ref type == @ref afb_auth_LOA */ - unsigned loa; - - /** first child when @ref type in { @ref afb_auth_Or, @ref afb_auth_And, @ref afb_auth_Not } */ - const struct afb_auth *first; - }; - - /** second child when @ref type in { @ref afb_auth_Or, @ref afb_auth_And } */ - const struct afb_auth *next; -}; - -``` - -The possible values for **type** is defined here: - -```C -typedef enum afb_auth_type afb_auth_type_t; - -/** - * Enumeration for authority (Session/Token/Assurance) definitions. - * - * @see afb_auth - */ -enum afb_auth_type -{ - /** never authorized, no data */ - afb_auth_No = 0, - - /** authorized if token valid, no data */ - afb_auth_Token, - - /** authorized if LOA greater than or equal to data 'loa' */ - afb_auth_LOA, - - /** authorized if permission 'text' is granted */ - afb_auth_Permission, - - /** authorized if 'first' or 'next' is authorized */ - afb_auth_Or, - - /** authorized if 'first' and 'next' are authorized */ - afb_auth_And, - - /** authorized if 'first' is not authorized */ - afb_auth_Not, - - /** always authorized, no data */ - afb_auth_Yes -}; -``` - -Example: - -```C -static const afb_auth_t myauth[] = { - { .type = afb_auth_Permission, .text = "urn:AGL:permission:me:public:set" }, - { .type = afb_auth_Permission, .text = "urn:AGL:permission:me:public:get" }, - { .type = afb_auth_Or, .first = &myauth[1], .next = &myauth[0] } -}; -``` - - -## The type afb_req_subcall_flags_t - -This is an enumeration that defines bit's positions for setting behaviour -of subcalls. - -| flag | value | description -|----------------------------|-------|-------------- -| afb_req_subcall_catch_events | 1 | the calling API wants to receive the events from subscription -| afb_req_subcall_pass_events | 2 | the original request will receive the events from subscription -| afb_req_subcall_on_behalf | 4 | the calling API wants to use the credentials of the original request -| afb_req_subcall_api_session | 8 | the calling API wants to use its session instead of the one of the original request - -ii. MACROS FOR LOGGING -================= - -The final behaviour of macros can be tuned using 2 defines that must be defined -before including ****. - -| define | action -|---------------------------------------|-------------------- -| AFB_BINDING_PRAGMA_NO_VERBOSE_DATA | show file and line, remove function and text message -| AFB_BINDING_PRAGMA_NO_VERBOSE_DETAILS | show text, remove function, line and file - -## Logging for an api - -The following macros must be used for logging for an **api** of type -**afb_api_t**. - -```C -AFB_API_ERROR(api,fmt,...) -AFB_API_WARNING(api,fmt,...) -AFB_API_NOTICE(api,fmt,...) -AFB_API_INFO(api,fmt,...) -AFB_API_DEBUG(api,fmt,...) -``` - -## Logging for a request - - -The following macros can be used for logging in the context -of a request **req** of type **afb_req_t**: - -```C -AFB_REQ_ERROR(req,fmt,...) -AFB_REQ_WARNING(req,fmt,...) -AFB_REQ_NOTICE(req,fmt,...) -AFB_REQ_INFO(req,fmt,...) -AFB_REQ_DEBUG(req,fmt,...) -``` - -By default, the logging macros add file, line and function -indication. - -## Logging legacy - -The following macros are provided for legacy. - -```C -AFB_ERROR(fmt,...) -AFB_WARNING(fmt,...) -AFB_NOTICE(fmt,...) -AFB_INFO(fmt,...) -AFB_DEBUG(fmt,...) -``` - -iii. FUNCTIONS OF CLASS **afb_api** -============================ - -## General functions - -### afb_api_name - -```C -/** - * Get the name of the 'api'. - * - * @param api the api whose name is to be returned - * - * @return the name of the api. - * - * The returned value must not be changed nor freed. - */ -const char *afb_api_name( - afb_api_t api); -``` - -### afb_api_get_userdata - -```C -/** - * Get the "userdata" pointer of the 'api' - * - * @param api the api whose user's data is to be returned - * - * @return the user's data pointer of the api. - * - * @see afb_api_set_userdata - */ -void *afb_api_get_userdata( - afb_api_t api); -``` - -### afb_api_set_userdata - -```C -/** - * Set the "userdata" pointer of the 'api' to 'value' - * - * @param api the api whose user's data is to be set - * @param value the data to set - * - * @see afb_api_get_userdata - */ -void afb_api_set_userdata( - afb_api_t api, - void *value); -``` - -### afb_api_require_api - -```C -/** - * Check that it requires the API of 'name'. - * If 'initialized' is not zero it requests the API to be - * initialized, implying its initialization if needed. - * - * Calling this function is only allowed within init. - * - * A single request allows to require multiple apis. - * - * @param api the api that requires the other api by its name - * @param name a space separated list of required api names - * @param initialized if zero, the api is just required to exist. If not zero, - * the api is required to exist and to be initialized at return of the call - * (initializing it if needed and possible as a side effect of the call). - * - * @return 0 in case of success or -1 in case of error with errno set appropriately. - */ -int afb_api_require_api( - afb_api_t api, - const char *name, - int initialized); -``` - - -## Verbosity functions - -### afb_api_wants_log_level - -```C -/** - * Is the log message of 'level (as defined for syslog) required for the api? - * - * @param api the api to check - * @param level the level to check as defined for syslog: - * - * EMERGENCY 0 System is unusable - * ALERT 1 Action must be taken immediately - * CRITICAL 2 Critical conditions - * ERROR 3 Error conditions - * WARNING 4 Warning conditions - * NOTICE 5 Normal but significant condition - * INFO 6 Informational - * DEBUG 7 Debug-level messages - * - * @return 0 if not required or a value not null if required - * - * @see syslog - */ -int afb_api_wants_log_level( - afb_api_t api, - int level); -``` - -### afb_api_vverbose - -```C -/** - * Send to the journal with the logging 'level' a message described - * by 'fmt' applied to the va-list 'args'. - * - * 'file', 'line' and 'func' are indicators of code position in source files - * (see macros __FILE__, __LINE__ and __func__). - * - * 'level' is defined by syslog standard: - * - * EMERGENCY 0 System is unusable - * ALERT 1 Action must be taken immediately - * CRITICAL 2 Critical conditions - * ERROR 3 Error conditions - * WARNING 4 Warning conditions - * NOTICE 5 Normal but significant condition - * INFO 6 Informational - * DEBUG 7 Debug-level messages - * - * @param api the api that collects the logging message - * @param level the level of the message - * @param file the source file that logs the messages or NULL - * @param line the line in the source file that logs the message - * @param func the name of the function in the source file that logs - * @param fmt the format of the message as in printf - * @param args the arguments to the format string of the message as a va_list - * - * @see syslog - * @see printf - */ -void afb_api_vverbose( - afb_api_t api, - int level, - const char *file, - int line, - const char *func, - const char *fmt, - va_list args); -``` - -### afb_api_verbose - -```C -/** - * Send to the journal with the log 'level' a message described - * by 'fmt' and following parameters. - * - * 'file', 'line' and 'func' are indicators of position of the code in source files - * (see macros __FILE__, __LINE__ and __func__). - * - * 'level' is defined by syslog standard: - * EMERGENCY 0 System is unusable - * ALERT 1 Action must be taken immediately - * CRITICAL 2 Critical conditions - * ERROR 3 Error conditions - * WARNING 4 Warning conditions - * NOTICE 5 Normal but significant condition - * INFO 6 Informational - * DEBUG 7 Debug-level messages - * - * @param api the api that collects the logging message - * @param level the level of the message - * @param file the source file that logs the messages or NULL - * @param line the line in the source file that logs the message - * @param func the name of the function in the source file that logs - * @param fmt the format of the message as in printf - * @param ... the arguments to the format string of the message - * - * @see syslog - * @see printf - */ -void afb_api_verbose( - afb_api_t api, - int level, - const char *file, - int line, - const char *func, - const char *fmt, - ...); -``` - -## Data retrieval functions - -### afb_api_rootdir_get_fd - -```C -/** - * Get the root directory file descriptor. This file descriptor can - * be used with functions 'openat', 'fstatat', ... - * - * CAUTION, manipulate this descriptor with care, in particular, don't close - * it. - * - * This can be used to get the path of the root directory using: - * - * char buffer[MAX_PATH], proc[100]; - * int dirfd = afb_api_rootdir_get_fd(api); - * snprintf(proc, sizeof proc, "/proc/self/fd/%d", dirfd); - * readlink(proc, buffer, sizeof buffer); - * - * But note that within AGL this is the value given by the environment variable - * AFM_APP_INSTALL_DIR. - * - * @param api the api that uses the directory file descriptor - * - * @return the file descriptor of the root directory. - * - * @see afb_api_rootdir_open_locale - */ -int afb_api_rootdir_get_fd( - afb_api_t api); -``` - -### afb_api_rootdir_open_locale - -```C -/** - * Opens 'filename' within the root directory with 'flags' (see function openat) - * using the 'locale' definition (example: "jp,en-US") that can be NULL. - * - * The filename must be relative to the root of the bindings. - * - * The opening mode must be for read or write but not for O_CREAT. - * - * The definition of locales and of how files are searched can be checked - * here: https://www.w3.org/TR/widgets/#folder-based-localization - * and https://tools.ietf.org/html/rfc7231#section-5.3.5 - * - * @param api the api that queries the file - * @param filename the relative path to the file to open - * @param flags the flags for opening as for C function 'open' - * @param locale string indicating how to search content, can be NULL - * - * @return the file descriptor or -1 in case of error and errno is set with the - * error indication. - * - * @see open - * @see afb_api_rootdir_get_fd - */ -int afb_api_rootdir_open_locale( - afb_api_t api, - const char *filename, - int flags, - const char *locale); -``` - -### afb_api_settings - -```C -/** - * Settings of the api. - * - * Get the settings of the API. The settings are recorded - * as a JSON object. The returned object should not be modified. - * It MUST NOT be released using json_object_put. - * - * @param api the api whose settings are required - * - * @returns The setting object. - */ -struct json_object *afb_api_settings( - struct afb_api_x3 *api); -``` - -## Calls and job functions - -### afb_api_call - -```C -/** - * Calls the 'verb' of the 'apiname' with the arguments 'args' and 'verb' in the name of the binding 'api'. - * The result of the call is delivered to the 'callback' function with the 'callback_closure'. - * - * For convenience, the function calls 'json_object_put' for 'args'. - * Thus, in the case where 'args' should remain available after - * the function returns, the function 'json_object_get' shall be used. - * - * The 'callback' receives 5 arguments: - * 1. 'closure' the user defined closure pointer 'closure', - * 2. 'object' a JSON object returned (can be NULL) - * 3. 'error' a string not NULL in case of error but NULL on success - * 4. 'info' a string handling some info (can be NULL) - * 5. 'api' the api - * - * NOTE: For convenience, *json_object_put* is called on 'object' after the - * callback returns. So, it is wrong to call *json_object_put* in the callback. - * - * @param api The api that makes the call - * @param apiname The api name of the method to call - * @param verb The verb name of the method to call - * @param args The arguments to pass to the method - * @param callback The to call on completion - * @param closure The closure to pass to the callback - * - * - * @see afb_req_subcall - * @see afb_req_subcall_sync - * @see afb_api_call_sync - */ -void afb_api_call( - afb_api_t api, - const char *apiname, - const char *verb, - struct json_object *args, - void (*callback)( - void *closure, - struct json_object *object, - const char *error, - const char * info, - afb_api_t api), - void *closure); -``` - -### afb_api_call_sync - -```C -/** - * Calls the 'verb' of the 'apiname' with the arguments 'args' and 'verb' in the name of the binding 'api'. - * 'result' will receive the response. - * - * For convenience, the function calls 'json_object_put' for 'args'. - * Thus, in the case where 'args' should remain available after - * the function returns, the function 'json_object_get' shall be used. - * - * @param api The api that makes the call - * @param apiname The api name of the method to call - * @param verb The verb name of the method to call - * @param args The arguments to pass to the method - * @param object Where to store the returned object - should call json_object_put on it - can be NULL - * @param error Where to store the copied returned error - should call free on it - can be NULL - * @param info Where to store the copied returned info - should call free on it - can be NULL - * - * @returns 0 in case of success or a negative value in case of error. - * - * @see afb_req_subcall - * @see afb_req_subcall_sync - * @see afb_api_call - */ -int afb_api_call_sync( - afb_api_t api, - const char *apiname, - const char *verb, - struct json_object *args, - struct json_object **object, - char **error, - char **info); -``` - -### afb_api_queue_job - -```C -/** - * Queue the job defined by 'callback' and 'argument' for being executed asynchronously - * in this thread (later) or in an other thread. - * - * If 'group' is not NULL, the jobs queued with a same value (as the pointer value 'group') - * are executed in sequence in the order of there submission. - * - * If 'timeout' is not 0, it represent the maximum execution time for the job in seconds. - * At first, the job is called with 0 as signum and the given argument. - * - * The job is executed with the monitoring of its time and some signals like SIGSEGV and - * SIGFPE. When a such signal is catched, the job is terminated and reexecuted but with - * signum being the signal number (SIGALRM when timeout expired). - * - * When executed, the callback function receives 2 arguments: - * - * - int signum: the signal catched if any or zero at the beginning - * - void *arg: the parameter 'argument' - * - * A typical implementation of the job callback is: - * - * void my_job_cb(int signum, void *arg) - * { - * struct myarg_t *myarg = arg; - * if (signum) - * AFB_API_ERROR(myarg->api, "job interrupted with signal %s", strsignal(signum)); - * else - * really_do_my_job(myarg); - * } - * - * @param api the api that queue the job - * @param callback the job as a callback function - * @param argument the argument to pass to the queued job - * @param group the group of the job, NULL if no group - * @param timeout the timeout of execution of the job - * - * @return 0 in case of success or -1 in case of error with errno set appropriately. - */ -int afb_api_queue_job( - afb_api_t api, - void (*callback)(int signum, void *arg), - void *argument, - void *group, - int timeout); -``` - -## Event functions - -### afb_api_broadcast_event - -```C -/** - * Broadcasts widely the event of 'name' with the data 'object'. - * 'object' can be NULL. - * - * 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. - * - * Calling this function is only forbidden during preinit. - * - * The event sent as the name API/name where API is the name of the - * api. - * - * @param api the api that broadcast the event - * @param name the event name suffix - * @param object the object that comes with the event - * - * @return 0 in case of success or -1 in case of error - */ -int afb_api_broadcast_event( - afb_api_t api, - const char *name, - struct json_object *object); -``` - -### afb_api_make_event - -```C -/** - * Creates an event of 'name' and returns it. - * - * Calling this function is only forbidden during preinit. - * - * See afb_event_is_valid to check if there is an error. - * - * The event created as the name API/name where API is the name of the - * api. - * - * @param api the api that creates the event - * @param name the event name suffix - * - * @return the created event. Use the function afb_event_is_valid to check - * whether the event is valid (created) or not (error as reported by errno). - * - * @see afb_event_is_valid - */ -afb_event_t afb_api_make_event( - afb_api_t api, - const char *name); -``` - -### afb_api_event_handler_add - -```C -/** - * Add a specific event handler for the api - * - * The handler callback is called when an event matching the given pattern - * is received (it is received if broadcasted or after subscription through - * a call or a subcall). - * - * The handler callback receive 4 arguments: - * - * - the closure given here - * - the event full name - * - the companion JSON object of the event - * - the api that subscribed the event - * - * @param api the api that creates the handler - * @param pattern the global pattern of the event to handle - * @param callback the handler callback function - * @param closure the closure of the handler - * - * @return 0 in case of success or -1 on failure with errno set - * - * @see afb_api_on_event - * @see afb_api_event_handler_del - */ -int afb_api_event_handler_add( - afb_api_t api, - const char *pattern, - void (*callback)( - void *, - const char*, - struct json_object*, - afb_api_t), - void *closure); -``` - -### afb_api_event_handler_del - -```C -/** - * Delete a specific event handler for the api - * - * @param api the api that the handler belongs to - * @param pattern the global pattern of the handler to remove - * @param closure if not NULL it will receive the closure set to the handler - * - * @return 0 in case of success or -1 on failure with errno set - * - * @see afb_api_on_event - * @see afb_api_event_handler_add - */ -int afb_api_event_handler_del( - afb_api_t api, - const char *pattern, - void **closure); - -``` - -## Systemd functions - -### afb_api_get_event_loop - -```C -/** - * Retrieves the common systemd's event loop of AFB - * - * @param api the api that uses the event loop - * - * @return the systemd event loop if active, NULL otherwise - * - * @see afb_api_get_user_bus - * @see afb_api_get_system_bus - */ -struct sd_event *afb_api_get_event_loop( - afb_api_t api); -``` - -### afb_api_get_user_bus - -```C -/** - * Retrieves the common systemd's user/session d-bus of AFB - * - * @param api the api that uses the user dbus - * - * @return the systemd user connection to dbus if active, NULL otherwise - * - * @see afb_api_get_event_loop - * @see afb_api_get_system_bus - */ -struct sd_bus *afb_api_get_user_bus( - afb_api_t api); -``` - -### afb_api_get_system_bus - -```C -/** - * Retrieves the common systemd's system d-bus of AFB - * - * @param api the api that uses the system dbus - * - * @return the systemd system connection to dbus if active, NULL otherwise - * - * @see afb_api_get_event_loop - * @see afb_api_get_user_bus - */ -struct sd_bus *afb_api_get_system_bus( - afb_api_t api); -``` - - -## Dynamic api functions - -### afb_api_new_api - -```C -/** - * Creates a new api of name 'apiname' briefly described by 'info' (that can - * be NULL). - * - * When the pre-initialization function is given, it is a function that - * receives 2 parameters: - * - * - the closure as given in the call - * - the created api that can be initialised - * - * This pre-initialization function must return a negative value to abort - * the creation of the api. Otherwise, it returns a non-negative value to - * continue. - * - * @param api the api that creates the other one - * @param apiname the name of the new api - * @param info the brief description of the new api (can be NULL) - * @param noconcurrency zero or not zero whether the new api is reentrant or not - * @param preinit the pre-initialization function if any (can be NULL) - * @param closure the closure for the pre-initialization preinit - * - * @return the created api in case of success or NULL on error - * - * @see afb_api_delete_api - */ -afb_api_t afb_api_new_api( - afb_api_t api, - const char *apiname, - const char *info, - int noconcurrency, - int (*preinit)(void*, afb_api_t ), - void *closure); -``` - -### afb_api_set_verbs_v2 - -```C -/** - * @deprecated use @ref afb_api_set_verbs_v3 instead - * - * Set the verbs of the 'api' using description of verbs of the api v2 - * - * @param api the api that will get the verbs - * @param verbs the array of verbs to add terminated with an item with name=NULL - * - * @return 0 in case of success or -1 on failure with errno set - * - * @see afb_verb_v2 - * @see afb_api_add_verb - * @see afb_api_set_verbs_v3 - */ -int afb_api_set_verbs_v2( - afb_api_t api, - const struct afb_verb_v2 *verbs); -``` - -### afb_api_set_verbs_v3 - -```C -/** - * Set the verbs of the 'api' using description of verbs of the api v2 - * - * @param api the api that will get the verbs - * @param verbs the array of verbs to add terminated with an item with name=NULL - * - * @return 0 in case of success or -1 on failure with errno set - * - * @see afb_verb_v3 - * @see afb_api_add_verb - * @see afb_api_del_verb - */ -int afb_api_set_verbs_v3( - afb_api_t api, - const struct afb_verb_v3 *verbs); -``` - -### afb_api_add_verb - -```C -/** - * Add one verb to the dynamic set of the api - * - * @param api the api to change - * @param verb name of the verb - * @param info brief description of the verb, can be NULL - * @param callback callback function implementing the verb - * @param vcbdata data for the verb callback, available through req - * @param auth required authorization, can be NULL - * @param session authorization and session requirements of the verb - * @param glob is the verb glob name - * - * @return 0 in case of success or -1 on failure with errno set - * - * @see afb_verb_v3 - * @see afb_api_del_verb - * @see afb_api_set_verbs_v3 - * @see fnmatch for matching names using glob - */ -int afb_api_add_verb( - afb_api_t api, - const char *verb, - const char *info, - void (*callback)(struct afb_req_x2 *req), - void *vcbdata, - const struct afb_auth *auth, - uint32_t session, - int glob); -``` - -### afb_api_del_verb - -```C -/** - * Delete one verb from the dynamic set of the api - * - * @param api the api to change - * @param verb name of the verb to delete - * @param vcbdata if not NULL will receive the vcbdata of the deleted verb - * - * @return 0 in case of success or -1 on failure with errno set - * - * @see afb_api_add_verb - */ -int afb_api_del_verb( - afb_api_t api, - const char *verb, - void **vcbdata); -``` - -### afb_api_on_event - -```C -/** - * Set the callback 'onevent' to process events in the name of the 'api'. - * - * This setting can be done statically using the global variable - * @ref afbBindingV3. - * - * This function replace any previously global event callback set. - * - * When an event is received, the callback 'onevent' is called with 3 parameters - * - * - the api that recorded the event handler - * - the full name of the event - * - the companion JSON object of the event - * - * @param api the api that wants to process events - * @param onevent the callback function that will process events (can be NULL - * to remove event callback) - * - * @return 0 in case of success or -1 on failure with errno set - * - * @see afbBindingV3 - * @see afb_binding_v3 - * @see afb_api_event_handler_add - * @see afb_api_event_handler_del - */ -int afb_api_on_event( - afb_api_t api, - void (*onevent)( - afb_api_t api, - const char *event, - struct json_object *object)); -``` - -### afb_api_on_init - -```C -/** - * Set the callback 'oninit' to process initialization of the 'api'. - * - * This setting can be done statically using the global variable - * @ref afbBindingV3 - * - * This function replace any previously initialization callback set. - * - * This function is only valid during the pre-initialization stage. - * - * The callback initialization function will receive one argument: the api - * to initialize. - * - * @param api the api that wants to process events - * @param oninit the callback function that initialize the api - * - * @return 0 in case of success or -1 on failure with errno set - * - * @see afbBindingV3 - * @see afb_binding_v3 - */ -int afb_api_on_init( - afb_api_t api, - int (*oninit)(afb_api_t api)); -``` - -### afb_api_provide_class - -```C -/** - * Tells that the api provides a class of features. Classes are intended to - * allow ordering of initializations: apis that provides a given class are - * initialized before apis requiring it. - * - * This function is only valid during the pre-initialization stage. - * - * @param api the api that provides the classes - * @param name a space separated list of the names of the provided classes - * - * @returns 0 in case of success or a negative value in case of error. - * - * @see afb_api_require_class - */ -int afb_api_provide_class( - afb_api_t api, - const char *name); -``` - -### afb_api_require_class - -```C -/** - * Tells that the api requires a set of class features. Classes are intended to - * allow ordering of initializations: apis that provides a given class are - * initialized before apis requiring it. - * - * This function is only valid during the pre-initialization stage. - * - * @param api the api that requires the classes - * @param name a space separated list of the names of the required classes - * - * @returns 0 in case of success or a negative value in case of error. - * - * @see afb_api_provide_class - */ -int afb_api_require_class( - afb_api_t api, - const char *name); -``` - -### afb_api_seal - -```C -/** - * Seal the api. After a call to this function the api can not be modified - * anymore. - * - * @param api the api to be sealed - */ -void afb_api_seal( - afb_api_t api); -``` - -### afb_api_delete_api - -```C -/** - * Delete the given api. - * - * It is of the responsibility of the caller to don't used the deleted api - * anymore after this function returned. - * - * @param api the api to delete - * - * @returns 0 in case of success or a negative value in case of error. - * - * @see afb_api_new_api - */ -int afb_api_delete_api( - afb_api_t api); -``` - -### afb_api_add_alias - -```C -/** - * Create an aliased name 'as_name' for the api 'name'. - * Calling this function is only allowed within preinit. - * - * @param api the api that requires the aliasing - * @param name the api to alias - * @param as_name the aliased name of the aliased api - * - * @return 0 in case of success or -1 in case of error with errno set appropriately. - */ -int afb_api_add_alias( - afb_api_t api, - const char *name, - const char *as_name); -``` - - -## Legacy functions - -The function for legacy calls are still provided for some time because -adaptation of existing code to the new call functions require a small amount -of work. - -### afb_api_call_legacy - -```C -/** - * @deprecated try to use @ref afb_api_call instead - * - * Calls the 'verb' of the 'apiname' with the arguments 'args' and 'verb' - * in the name of the binding. - * The result of the call is delivered to the 'callback' function - * with the 'callback_closure'. - * - * For convenience, the function calls 'json_object_put' for 'args'. - * Thus, in the case where 'args' should remain available after - * the function returns, the function 'json_object_get' shall be used. - * - * The 'callback' receives 3 arguments: - * 1. 'closure' the user defined closure pointer 'closure', - * 2. 'status' a status being 0 on success or negative when an error occurred, - * 2. 'result' the resulting data as a JSON object. - * - * @param api The api - * @param apiname The api name of the method to call - * @param verb The verb name of the method to call - * @param args The arguments to pass to the method - * @param callback The to call on completion - * @param closure The closure to pass to the callback - * - * @see also 'afb_api_call' - * @see also 'afb_api_call_sync' - * @see also 'afb_api_call_sync_legacy' - * @see also 'afb_req_subcall' - * @see also 'afb_req_subcall_sync' - */ -void afb_api_call_legacy( - afb_api_t api, - const char *apiname, - const char *verb, - struct json_object *args, - void (*callback)( - void *closure, - int status, - struct json_object *result, - afb_api_t api), - void *closure); -``` - -### afb_api_call_sync_legacy - -```C -/** - * @deprecated try to use @ref afb_api_call_sync instead - * - * Calls the 'verb' of the 'apiname' with the arguments 'args' and 'verb' - * in the name of the binding. - * 'result' will receive the response. - * - * For convenience, the function calls 'json_object_put' for 'args'. - * Thus, in the case where 'args' should remain available after - * the function returns, the function 'json_object_get' shall be used. - * - * @param api The api - * @param apiname The api name of the method to call - * @param verb The verb name of the method to call - * @param args The arguments to pass to the method - * @param result Where to store the result - should call json_object_put on it - - * - * @returns 0 in case of success or a negative value in case of error. - * - * @see also 'afb_api_call' - * @see also 'afb_api_call_sync' - * @see also 'afb_api_call_legacy' - * @see also 'afb_req_subcall' - * @see also 'afb_req_subcall_sync' - */ -int afb_api_call_sync_legacy( - afb_api_t api, - const char *apiname, - const char *verb, - struct json_object *args, - struct json_object **result); -``` - -iv. FUNCTIONS OF CLASS **afb_req** -============================ - -## General function - -### afb_req_is_valid - -```C -/** - * Checks whether the request 'req' is valid or not. - * - * @param req the request to check - * - * @return 0 if not valid or 1 if valid. - */ -int afb_req_is_valid( - afb_req_t req); -``` - -### afb_req_get_api - -```C -/** - * Retrieves the api that serves the request - * - * @param req the request whose serving api is queried - * - * @return the api serving the request - */ -afb_api_t afb_req_get_api( - afb_req_t req); -``` - -### afb_req_get_vcbdata - -```C -/** - * Retrieves the callback data of the verb. This callback data is set - * when the verb is created. - * - * @param req whose verb vcbdata is queried - * - * @return the callback data attached to the verb description - */ -void *afb_req_get_vcbdata( - afb_req_t req); -``` - -### afb_req_get_called_api - -```C -/** - * Retrieve the name of the called api. - * - * @param req the request - * - * @return the name of the called api - * - * @see afb_api_new_api - * @see afb_api_add_alias - */ -const char *afb_req_get_called_api( - afb_req_t req); -``` - -### afb_req_get_called_verb - -```C -/** - * Retrieve the name of the called verb - * - * @param req the request - * - * @return the name of the called verb - */ -const char *afb_req_get_called_verb( - afb_req_t req); -``` - -### afb_req_addref - -```C -/** - * Increments the count of references of 'req'. - * - * @param req the request - * - * @return returns the request req - */ -afb_req_t *afb_req_addref( - afb_req_t req); -``` - -### afb_req_unref - -```C -/** - * Decrement the count of references of 'req'. - * - * @param req the request - */ -void afb_req_unref( - afb_req_t req); -``` - - -## Logging functions - -### afb_req_wants_log_level - -```C -/** - * Is the log message of 'level (as defined for syslog) required for the - * request 'req'? - * - * @param req the request - * @param level the level to check as defined for syslog: - * - * EMERGENCY 0 System is unusable - * ALERT 1 Action must be taken immediately - * CRITICAL 2 Critical conditions - * ERROR 3 Error conditions - * WARNING 4 Warning conditions - * NOTICE 5 Normal but significant condition - * INFO 6 Informational - * DEBUG 7 Debug-level messages - * - * @return 0 if not required or a value not null if required - * - * @see syslog - */ -int afb_req_wants_log_level( - afb_req_t req, - int level); -``` - -### afb_req_vverbose - -```C -/** - * Send associated to 'req' a message described by 'fmt' and its 'args' - * to the journal for the verbosity 'level'. - * - * 'file', 'line' and 'func' are indicators of position of the code in source files - * (see macros __FILE__, __LINE__ and __func__). - * - * 'level' is defined by syslog standard: - * EMERGENCY 0 System is unusable - * ALERT 1 Action must be taken immediately - * CRITICAL 2 Critical conditions - * ERROR 3 Error conditions - * WARNING 4 Warning conditions - * NOTICE 5 Normal but significant condition - * INFO 6 Informational - * DEBUG 7 Debug-level messages - * - * @param req the request - * @param level the level of the message - * @param file the source filename that emits the message or NULL - * @param line the line number in the source filename that emits the message - * @param func the name of the function that emits the message or NULL - * @param fmt the message format as for printf - * @param args the arguments to the format - * - * @see printf - * @see afb_req_verbose - */ -void afb_req_vverbose( - afb_req_t req, - int level, const char *file, - int line, - const char * func, - const char *fmt, - va_list args); -``` - -### afb_req_verbose - -```C -/** - * Send associated to 'req' a message described by 'fmt' and following parameters - * to the journal for the verbosity 'level'. - * - * 'file', 'line' and 'func' are indicators of position of the code in source files - * (see macros __FILE__, __LINE__ and __func__). - * - * 'level' is defined by syslog standard: - * EMERGENCY 0 System is unusable - * ALERT 1 Action must be taken immediately - * CRITICAL 2 Critical conditions - * ERROR 3 Error conditions - * WARNING 4 Warning conditions - * NOTICE 5 Normal but significant condition - * INFO 6 Informational - * DEBUG 7 Debug-level messages - * - * @param req the request - * @param level the level of the message - * @param file the source filename that emits the message or NULL - * @param line the line number in the source filename that emits the message - * @param func the name of the function that emits the message or NULL - * @param fmt the message format as for printf - * @param ... the arguments of the format 'fmt' - * - * @see printf - */ -void afb_req_verbose( - afb_req_t req, - int level, const char *file, - int line, - const char * func, - const char *fmt, - ...); -``` - -## Arguments/parameters function - -### afb_req_get - -```C -/** - * 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. - * - * @param req the request - * @param name the name of the argument to get - * - * @return a structure describing the retrieved argument for the request - * - * @see afb_req_value - * @see afb_req_path - */ -struct afb_arg afb_req_get( - afb_req_t req, - const char *name); -``` - -### afb_req_value - -```C -/** - * 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 - * - * @param req the request - * @param name the name of the argument's value to get - * - * @return the value as a string or NULL - * - * @see afb_req_get - * @see afb_req_path - */ -const char *afb_req_value( - afb_req_t req, - const char *name); -``` - -### afb_req_path - -```C -/** - * 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 - * - * @param req the request - * @param name the name of the argument's path to get - * - * @return the path if any or NULL - * - * @see afb_req_get - * @see afb_req_value - */ -const char *afb_req_path( - afb_req_t req, - const char *name); -``` - -### afb_req_json - -```C -/** - * Gets from the request 'req' the json object hashing the arguments. - * - * The returned object must not be released using 'json_object_put'. - * - * @param req the request - * - * @return the JSON object of the query - * - * @see afb_req_get - * @see afb_req_value - * @see afb_req_path - */ -struct json_object *afb_req_json( - afb_req_t req); -``` - -## Reply functions - -The functions **success** and **fail** are still supported. -These functions are now implemented as the following macros: - -```C -#define afb_req_success(r,o,i) afb_req_reply(r,o,NULL,i) -#define afb_req_success_f(r,o,...) afb_req_reply_f(r,o,NULL,__VA_ARGS__) -#define afb_req_success_v(r,o,f,v) afb_req_reply_v(r,o,NULL,f,v) -#define afb_req_fail(r,e,i) afb_req_reply(r,NULL,e,i) -#define afb_req_fail_f(r,e,...) afb_req_reply_f(r,NULL,e,__VA_ARGS__) -#define afb_req_fail_v(r,e,f,v) afb_req_reply_v(r,NULL,e,f,v) -``` - - -### afb_req_reply - -```C -/** - * Sends a reply to the request 'req'. - * - * The status of the reply is set to 'error' (that must be NULL on success). - * Its send the object 'obj' (can be NULL) with an - * informational 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. - * - * @param req the request - * @param obj the replied object or NULL - * @param error the error message if it is a reply error or NULL - * @param info an informative text or NULL - * - * @see afb_req_reply_v - * @see afb_req_reply_f - */ -void afb_req_reply( - afb_req_t req, - struct json_object *obj, - const char *error, - const char *info); -``` - -### afb_req_reply_v - -```C -/** - * Same as 'afb_req_reply_f' but the arguments to the format 'info' - * are given as a variable argument list instance. - * - * 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. - * - * @param req the request - * @param obj the replied object or NULL - * @param error the error message if it is a reply error or NULL - * @param info an informative text containing a format as for vprintf - * @param args the va_list of arguments to the format as for vprintf - * - * @see afb_req_reply - * @see afb_req_reply_f - * @see vprintf - */ -void afb_req_reply_v( - afb_req_t req, - struct json_object *obj, - const char *error, - const char *info, - va_list args); -``` - -### afb_req_reply_f - -```C -/** - * Same as 'afb_req_reply' 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. - * - * @param req the request - * @param obj the replied object or NULL - * @param error the error message if it is a reply error or NULL - * @param info an informative text containing a format as for printf - * @param ... the arguments to the format as for printf - * - * @see afb_req_reply - * @see afb_req_reply_v - * @see printf - */ -void afb_req_reply_f( - afb_req_t req, - struct json_object *obj, - const char *error, - const char *info, - ...); -``` - -## Subcall functions - - - -### afb_req_subcall - -```C -/** - * Calls the 'verb' of the 'api' with the arguments 'args' and 'verb' in the name of the binding. - * The result of the call is delivered to the 'callback' function with the 'callback_closure'. - * - * For convenience, the function calls 'json_object_put' for 'args'. - * Thus, in the case where 'args' should remain available after - * the function returns, the function 'json_object_get' shall be used. - * - * The 'callback' receives 5 arguments: - * 1. 'closure' the user defined closure pointer 'closure', - * 2. 'object' a JSON object returned (can be NULL) - * 3. 'error' a string not NULL in case of error - * 4. 'info' a string handling some info (can be NULL) - * 5. 'req' the req - * - * NOTE: For convenience, *json_object_put* is called on 'object' after the - * callback returns. So, it is wrong to call *json_object_put* in the callback. - * - * @param req The request - * @param api The api name of the method to call - * @param verb The verb name of the method to call - * @param args The arguments to pass to the method - * @param flags The bit field of flags for the subcall as defined by @ref afb_req_subcall_flags_t - * @param callback The to call on completion - * @param closure The closure to pass to the callback - * - * The flags are any combination of the following values: - * - * - afb_req_x2_subcall_catch_events = 1 - * - * the calling API wants to receive the events from subscription - * - * - afb_req_x2_subcall_pass_events = 2 - * - * the original request will receive the events from subscription - * - * - afb_req_x2_subcall_on_behalf = 4 - * - * the calling API wants to use the credentials of the original request - * - * - afb_req_x2_subcall_api_session = 8 - * - * the calling API wants to use its session instead of the one of the - * original request - * - * @see also 'afb_req_subcall_sync' - */ -void afb_req_subcall( - afb_req_t req, - const char *api, - const char *verb, - struct json_object *args, - int flags, - void (*callback)( - void *closure, - struct json_object *object, - const char *error, - const char * info, - afb_req_t req), - void *closure); -``` - -### afb_req_subcall_sync - -```C -/** - * Makes a call to the method of name 'api' / 'verb' with the object 'args'. - * This call is made in the context of the request 'req'. - * This call is synchronous, it waits untill completion of the request. - * It returns 0 on success or a negative value on error answer. - * - * For convenience, the function calls 'json_object_put' for 'args'. - * Thus, in the case where 'args' should remain available after - * the function returns, the function 'json_object_get' shall be used. - * - * See also: - * - 'afb_req_subcall_req' that is convenient to keep request alive automatically. - * - 'afb_req_subcall' that doesn't keep request alive automatically. - * - * @param req The request - * @param api The api name of the method to call - * @param verb The verb name of the method to call - * @param args The arguments to pass to the method - * @param flags The bit field of flags for the subcall as defined by @ref afb_req_subcall_flags - * @param object a pointer where the replied JSON object is stored must be freed using @ref json_object_put (can be NULL) - * @param error a pointer where a copy of the replied error is stored must be freed using @ref free (can be NULL) - * @param info a pointer where a copy of the replied info is stored must be freed using @ref free (can be NULL) - * - * @return 0 in case of success or -1 in case of error - */ -int afb_req_subcall_sync( - afb_req_t req, - const char *api, - const char *verb, - struct json_object *args, - int flags, - struct json_object **object, - char **error, - char **info); -``` - -## Event functions - -### afb_req_subscribe - -```C -/** - * Establishes for the client link identified by 'req' a subscription - * to the 'event'. - * - * Establishing subscription MUST be called BEFORE replying to the request. - * - * @param req the request - * @param event the event to subscribe - * - * @return 0 in case of successful subscription or -1 in case of error. - */ -int afb_req_subscribe( - afb_req_t req, - afb_event_t event); -``` - -### afb_req_unsubscribe - -```C -/** - * Revokes the subscription established to the 'event' for the client - * link identified by 'req'. - * Returns 0 in case of successful subscription or -1 in case of error. - * - * Revoking subscription MUST be called BEFORE replying to the request. - * - * @param req the request - * @param event the event to revoke - * - * @return 0 in case of successful subscription or -1 in case of error. - */ -int afb_req_unsubscribe( - afb_req_t req, - afb_event_t event); -``` - -## Session functions - -### afb_req_context - -```C -/** - * Manage the pointer stored by the binding for the client session of 'req'. - * - * If no previous pointer is stored or if 'replace' is not zero, a new value - * is generated using the function 'create_context' called with the 'closure'. - * If 'create_context' is NULL the generated value is 'closure'. - * - * When a value is created, the function 'free_context' is recorded and will - * be called (with the created value as argument) to free the created value when - * it is not more used. - * - * This function is atomic: it ensures that 2 threads will not race together. - * - * @param req the request - * @param replace if not zero an existing value is replaced - * @param create_context the creation function or NULL - * @param free_context the destroying function or NULL - * @param closure the closure to the creation function - * - * @return the stored value - */ -void *afb_req_context( - afb_req_t req, - int replace, - void *(*create_context)(void *closure), - void (*free_context)(void*), - void *closure); -``` - -### afb_req_context_get - -```C -/** - * Gets the pointer stored by the binding for the session of 'req'. - * When the binding has not yet recorded a pointer, NULL is returned. - * - * Shortcut for: afb_req_context(req, 0, NULL, NULL, NULL) - * - * @param req the request - * - * @return the previously stored value - */ -void *afb_req_context_get( - afb_req_t req); -``` - -### afb_req_context_set - -```C -/** - * 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. - * - * Shortcut for: afb_req_context(req, 1, NULL, free_context, context) - * - * - * @param req the request - * @param context the context value to store - * @param free_context the cleaning function for the stored context (can be NULL) - */ -void afb_req_context_set( - afb_req_t req, - void *context, - void (*free_context)(void*)); -``` - -### afb_req_context_clear - -```C -/** - * 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) - * - * @param req the request - */ -void afb_req_context_clear( - afb_req_t req); -``` - -### afb_req_session_close - -```C -/** - * Closes the session associated with 'req' - * and delete all associated contexts. - * - * @param req the request - */ -void afb_req_session_close( - afb_req_t req); -``` - -### afb_req_session_set_LOA - -```C -/** - * Sets the level of assurance of the session of 'req' - * to 'level'. The effect of this function is subject of - * security policies. - * - * @param req the request - * @param level of assurance from 0 to 7 - * - * @return 0 on success or -1 if failed. - */ -int afb_req_session_set_LOA( - afb_req_t req, - unsigned level); -``` - -## Credential/client functions - -### afb_req_has_permission - -```C -/** - * Check whether the 'permission' is granted or not to the client - * identified by 'req'. - * - * @param req the request - * @param permission string to check - * - * @return 1 if the permission is granted or 0 otherwise. - */ -int afb_req_has_permission( - afb_req_t req, - const char *permission); -``` - -### afb_req_get_application_id - -```C -/** - * Get the application identifier of the client application for the - * request 'req'. - * - * Returns the application identifier or NULL when the application - * can not be identified. - * - * The returned value if not NULL must be freed by the caller - * - * @param req the request - * - * @return the string for the application id of the client MUST BE FREED - */ -char *afb_req_get_application_id( - afb_req_t req); -``` - -### afb_req_get_uid - -```C -/** - * Get the user identifier (UID) of the client for the - * request 'req'. - * - * @param req the request - * - * @return -1 when the application can not be identified or the unix uid. - * - */ -int afb_req_get_uid( - afb_req_t req); -``` - -### afb_req_get_client_info - -```C -/** - * Get informations about the client of the - * request 'req'. - * - * Returns an object with client informations: - * { - * "pid": int, "uid": int, "gid": int, - * "label": string, "id": string, "user": string, - * "uuid": string, "LOA": int - * } - * - * If some of this information can't be computed, the field of the return - * object will not be set at all. - * - * @param req the request - * - * @return a JSON object that must be freed using @ref json_object_put - */ -struct json_object *afb_req_get_client_info( - afb_req_t req); -``` - -## Legacy functions - -### afb_req_subcall_legacy - -```C -/** - * @deprecated use @ref afb_req_subcall - * - * Makes a call to the method of name 'api' / 'verb' with the object 'args'. - * This call is made in the context of the request 'req'. - * On completion, the function 'callback' is invoked with the - * 'closure' given at call and two other parameters: 'iserror' and 'result'. - * 'status' is 0 on success or negative when on an error reply. - * 'result' is the json object of the reply, you must not call json_object_put - * on the result. - * - * For convenience, the function calls 'json_object_put' for 'args'. - * Thus, in the case where 'args' should remain available after - * the function returns, the function 'json_object_get' shall be used. - * - * @param req the request - * @param api the name of the api to call - * @param verb the name of the verb to call - * @param args the arguments of the call as a JSON object - * @param callback the call back that will receive the reply - * @param closure the closure passed back to the callback - * - * @see afb_req_subcall - * @see afb_req_subcall_sync - */ -void afb_req_subcall_legacy( - afb_req_t req, - const char *api, - const char *verb, - struct json_object *args, - void (*callback)( - void *closure, - int iserror, - struct json_object *result, - afb_req_t req), - void *closure); -``` - -### afb_req_subcall_sync_legacy - -```C -/** - * @deprecated use @ref afb_req_subcall_sync - * - * Makes a call to the method of name 'api' / 'verb' with the object 'args'. - * This call is made in the context of the request 'req'. - * This call is synchronous, it waits until completion of the request. - * It returns 0 on success or a negative value on error answer. - * The object pointed by 'result' is filled and must be released by the caller - * after its use by calling 'json_object_put'. - * - * For convenience, the function calls 'json_object_put' for 'args'. - * Thus, in the case where 'args' should remain available after - * the function returns, the function 'json_object_get' shall be used. - * - * @param req the request - * @param api the name of the api to call - * @param verb the name of the verb to call - * @param args the arguments of the call as a JSON object - * @param result the pointer to the JSON object pointer that will receive the result - * - * @return 0 on success or a negative value on error answer. - * - * @see afb_req_subcall - * @see afb_req_subcall_sync - */ -int afb_req_subcall_sync_legacy( - afb_req_t req, - const char *api, - const char *verb, - struct json_object *args, - struct json_object **result); -``` - -v. FUNCTIONS OF CLASS **afb_event** -============================== - -## General functions - -### afb_event_is_valid - -```C -/** - * Checks whether the 'event' is valid or not. - * - * @param event the event to check - * - * @return 0 if not valid or 1 if valid. - */ -int afb_event_is_valid( - afb_event_t event); -``` - -### afb_event_name - -```C -/** - * Gets the name associated to 'event'. - * - * @param event the event whose name is requested - * - * @return the name of the event - * - * The returned name can be used until call to 'afb_event_unref'. - * It shouldn't be freed. - */ -const char *afb_event_name( - afb_event_t event); -``` - -### afb_event_unref - -```C -/** - * Decrease the count of references to 'event'. - * Call this function when the evenid is no more used. - * It destroys the event_x2 when the reference count falls to zero. - * - * @param event the event - */ -void afb_event_unref( - afb_event_t event); -``` - -### afb_event_addref - -```C -/** - * Increases the count of references to 'event' - * - * @param event the event - * - * @return the event - */ -afb_event_t *afb_event_addref( - afb_event_t event); -``` - -## Pushing functions - -### afb_event_broadcast - -```C -/** - * Broadcasts widely an event of 'event' with the data 'object'. - * 'object' can be NULL. - * - * 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. - * - * @param event the event to broadcast - * @param object the companion object to associate to the broadcasted event (can be NULL) - * - * @return 0 in case of success or -1 in case of error - */ -int afb_event_broadcast( - afb_event_t event, - struct json_object *object); -``` - -### afb_event_push - -```C -/** - * Pushes an event of 'event' with the data 'object' to its observers. - * 'object' can be NULL. - * - * 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. - * - * @param event the event to push - * @param object the companion object to associate to the pushed event (can be NULL) - * - * @Return - * * 1 if at least one client listen for the event - * * 0 if no more client listen for the event - * * -1 in case of error (the event can't be delivered) - */ -int afb_event_push( - afb_event_t event, - struct json_object *object); -``` - -vi. FUNCTIONS OF CLASS **afb_daemon** -============================ - -All the functions of the class **afb_daemon** use the default api. -This are internally aliased to the corresponding function of class afb_api_t. - -```C -/** - * Retrieves the common systemd's event loop of AFB - */ -struct sd_event *afb_daemon_get_event_loop(); - -/** - * Retrieves the common systemd's user/session d-bus of AFB - */ -struct sd_bus *afb_daemon_get_user_bus(); - -/** - * Retrieves the common systemd's system d-bus of AFB - */ -struct sd_bus *afb_daemon_get_system_bus(); - -/** - * Broadcasts widely the event of 'name' with the data 'object'. - * 'object' can be NULL. - * - * 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. - * - * Calling this function is only forbidden during preinit. - * - * Returns the count of clients that received the event. - */ -int afb_daemon_broadcast_event( - const char *name, - struct json_object *object); - -/** - * Creates an event of 'name' and returns it. - * - * Calling this function is only forbidden during preinit. - * - * See afb_event_is_valid to check if there is an error. - */ -afb_event_t afb_daemon_make_event( - const char *name); - -/** - * @deprecated use bindings version 3 - * - * Send a message described by 'fmt' and following parameters - * to the journal for the verbosity 'level'. - * - * 'file', 'line' and 'func' are indicators of position of the code in source files - * (see macros __FILE__, __LINE__ and __func__). - * - * 'level' is defined by syslog standard: - * EMERGENCY 0 System is unusable - * ALERT 1 Action must be taken immediately - * CRITICAL 2 Critical conditions - * ERROR 3 Error conditions - * WARNING 4 Warning conditions - * NOTICE 5 Normal but significant condition - * INFO 6 Informational - * DEBUG 7 Debug-level messages - */ -void afb_daemon_verbose( - int level, - const char *file, - int line, - const char * func, - const char *fmt, - ...); - -/** - * @deprecated use bindings version 3 - * - * Get the root directory file descriptor. This file descriptor can - * be used with functions 'openat', 'fstatat', ... - * - * Returns the file descriptor or -1 in case of error. - */ -int afb_daemon_rootdir_get_fd(); - -/** - * Opens 'filename' within the root directory with 'flags' (see function openat) - * using the 'locale' definition (example: "jp,en-US") that can be NULL. - * - * Returns the file descriptor or -1 in case of error. - */ -int afb_daemon_rootdir_open_locale( - const char *filename, - int flags, - const char *locale); - -/** - * Queue the job defined by 'callback' and 'argument' for being executed asynchronously - * in this thread (later) or in an other thread. - * If 'group' is not NUL, the jobs queued with a same value (as the pointer value 'group') - * are executed in sequence in the order of there submission. - * If 'timeout' is not 0, it represent the maximum execution time for the job in seconds. - * At first, the job is called with 0 as signum and the given argument. - * The job is executed with the monitoring of its time and some signals like SIGSEGV and - * SIGFPE. When a such signal is catched, the job is terminated and reexecuted but with - * signum being the signal number (SIGALRM when timeout expired). - * - * Returns 0 in case of success or -1 in case of error. - */ -int afb_daemon_queue_job( - void (*callback)(int signum, void *arg), - void *argument, - void *group, - int timeout); - -/** - * Tells that it requires the API of "name" to exist - * and if 'initialized' is not null to be initialized. - * Calling this function is only allowed within init. - * - * Returns 0 in case of success or -1 in case of error. - */ -int afb_daemon_require_api( - const char *name, - int initialized); - -/** - * Create an aliased name 'as_name' for the api 'name'. - * Calling this function is only allowed within preinit. - * - * Returns 0 in case of success or -1 in case of error. - */ -int afb_daemon_add_alias(const char *name, const char *as_name); - -/** - * Creates a new api of name 'api' with brief 'info'. - * - * Returns 0 in case of success or -1 in case of error. - */ -int afb_daemon_new_api( - const char *api, - const char *info, - int noconcurrency, - int (*preinit)(void*, struct afb_api_x3 *), - void *closure); -``` - -vii. FUNCTIONS OF CLASS **afb_service** -============================== - -All the functions of the class **afb_service** use the default api. - -All these function are deprecated, try to use functions of class **afb_api** instead. - -## afb_service_call - -```C -/** - * @deprecated try to use @ref afb_api_call instead - * - * Calls the 'verb' of the 'api' with the arguments 'args' and 'verb' in the name of the binding. - * The result of the call is delivered to the 'callback' function with the 'callback_closure'. - * - * For convenience, the function calls 'json_object_put' for 'args'. - * Thus, in the case where 'args' should remain available after - * the function returns, the function 'json_object_get' shall be used. - * - * The 'callback' receives 5 arguments: - * 1. 'closure' the user defined closure pointer 'closure', - * 2. 'object' a JSON object returned (can be NULL) - * 3. 'error' a string not NULL in case of error but NULL on success - * 4. 'info' a string handling some info (can be NULL) - * 5. 'api' the api - * - * @param api The api name of the method to call - * @param verb The verb name of the method to call - * @param args The arguments to pass to the method - * @param callback The to call on completion - * @param closure The closure to pass to the callback - * - * - * @see afb_req_subcall - * @see afb_req_subcall_sync - * @see afb_api_call_sync - */ -void afb_service_call( - const char *api, - const char *verb, - struct json_object *args, - void (*callback)( - void *closure, - struct json_object *object, - const char *error, - const char * info, - afb_api_t api), - void *closure); -``` - -## afb_service_call_sync - -```C -/** - * @deprecated try to use @ref afb_api_call_sync instead - * - * Calls the 'verb' of the 'api' with the arguments 'args' and 'verb' in the name of the binding. - * 'result' will receive the response. - * - * For convenience, the function calls 'json_object_put' for 'args'. - * Thus, in the case where 'args' should remain available after - * the function returns, the function 'json_object_get' shall be used. - * - * @param api The api name of the method to call - * @param verb The verb name of the method to call - * @param args The arguments to pass to the method - * @param object Where to store the returned object - should call json_object_put on it - can be NULL - * @param error Where to store the copied returned error - should call free on it - can be NULL - * @param info Where to store the copied returned info - should call free on it - can be NULL - * - * @returns 0 in case of success or a negative value in case of error. - * - * @see afb_req_subcall - * @see afb_req_subcall_sync - * @see afb_api_call - */ -int afb_service_call_sync( - const char *api, - const char *verb, - struct json_object *args, - struct json_object **object, - char **error, - char **info); -``` - -## afb_service_call_legacy - -```C -/** - * @deprecated try to use @ref afb_api_call instead - * - * Calls the 'verb' of the 'api' with the arguments 'args' and 'verb' - * in the name of the binding. - * The result of the call is delivered to the 'callback' function with - * the 'callback_closure'. - * - * For convenience, the function calls 'json_object_put' for 'args'. - * Thus, in the case where 'args' should remain available after - * the function returns, the function 'json_object_get' shall be used. - * - * The 'callback' receives 3 arguments: - * 1. 'closure' the user defined closure pointer 'closure', - * 2. 'status' a status being 0 on success or negative when an error occurred, - * 2. 'result' the resulting data as a JSON object. - * - * @param api The api name of the method to call - * @param verb The verb name of the method to call - * @param args The arguments to pass to the method - * @param callback The to call on completion - * @param closure The closure to pass to the callback - * - * @see also 'afb_api_call' - * @see also 'afb_api_call_sync' - * @see also 'afb_api_call_sync_legacy' - * @see also 'afb_req_subcall' - * @see also 'afb_req_subcall_sync' - */ -void afb_service_call_legacy( - const char *api, - const char *verb, - struct json_object *args, - void (*callback)( - void *closure, - int status, - struct json_object *result, - afb_api_t api), - void *closure); -``` - -## afb_service_call_sync_legacy - -```C -/** - * @deprecated try to use @ref afb_api_call_sync instead - * - * Calls the 'verb' of the 'api' with the arguments 'args' and 'verb' in the - * name of the binding. 'result' will receive the response. - * - * For convenience, the function calls 'json_object_put' for 'args'. - * Thus, in the case where 'args' should remain available after - * the function returns, the function 'json_object_get' shall be used. - * - * @param api The api name of the method to call - * @param verb The verb name of the method to call - * @param args The arguments to pass to the method - * @param result Where to store the result - should call json_object_put on it - - * - * @returns 0 in case of success or a negative value in case of error. - * - * @see also 'afb_api_call' - * @see also 'afb_api_call_sync' - * @see also 'afb_api_call_legacy' - * @see also 'afb_req_subcall' - * @see also 'afb_req_subcall_sync' - */ -int afb_service_call_sync_legacy( - const char *api, - const char *verb, - struct json_object *args, - struct json_object **result); -``` \ No newline at end of file diff --git a/docs/3_Developer_Guides/2_Application_Framework_Binder/4_Binder_events_guide.md b/docs/3_Developer_Guides/2_Application_Framework_Binder/4_Binder_events_guide.md deleted file mode 100644 index 57175a6..0000000 --- a/docs/3_Developer_Guides/2_Application_Framework_Binder/4_Binder_events_guide.md +++ /dev/null @@ -1,291 +0,0 @@ ---- -title: Binder events guide ---- - -Signaling agents are services that send events to any clients that -are subscribed to receive it. -The sent events carry any data. - -To have a good understanding of how to: - -- write a signaling agent. -- actions of subscribing. -- actions of unsubscribing. -- actions of producing. -- actions of sending and receiving. - -Events must be described and explained. - -## Overview of events - -The basis of a signaling agent is shown in the following figure: - -![scenario of using events](images/signaling-basis.svg) - -This figure shows the main role of the signaling framework for the events -propagation. - -For people not familiar with the framework, a signaling agent and -a “binding” are similar. - -### Subscribing and unsubscribing - -- Subscribing is the action that makes a client able to receive - data from a signaling agent. - -Subscription must : - -1. Create resources for generating the data. -2. Deliver the data to the client. - -These two aspects are not handled by the same piece of software. - -1. Generating the data is the responsibility of the developer of the signaling agent -2. Delivering the data is handled by the framework. - -When a client subscribes for data, the agent must: - -1. Check that the subscription request is correct. -2. Establish the computation chain of the required data (if not already done). -3. Create a named event for the computed data (if not already done). -4. Ask the framework to establish the subscription to the event for the request. -5. Optionally give indications about the event in the reply to the client. - -The first two steps do not involve the framework. -They are linked to the business logic of the binding. -The request can be any description of the requested data -and the computing stream can be of any nature, -this is specific to the binding. - -As said before, the framework uses and integrates **libsystemd** and its event -loop. -Within the framework, **libsystemd** is the standard API/library for -bindings expecting to setup and handle I/O, timer or signal events. - -Steps 3 and 4 are bound to the framework. - -The agent must create an object for handling the propagation of produced -data to its clients. -That object is called “event” in the framework. -An event has a name that allows clients to distinguish it from other -events. - -Events are created using the ***afb\_api\_make\_event*** function -that takes the api that creates the event and the name of the event. -Example: - -```C - event = afb_api_make_event(api, name); -``` - -Once created, the event can be used either to push data to its -subscribers or to broadcast data to any listener. - -The event must be used to establish the subscription for the requesting -client. -This is done using the ***afb\_req\_subscribe*** function -that takes the current request object and event and associates them -together. -Example: - -```C - rc = afb_req_subscribe(req, event); -``` - -When successful, this function make the connection between the event and -the client that emitted the request. -The client becomes a subscriber of the event until it unsubscribes or disconnects. -The ***afb\_req\_subscribe*** function will fail: - -- if the client connection is weak. -- if the request comes from a HTTP link. - -To receive signals, the client must be connected. - -The AGL framework allows connections using WebSocket. - -The name of the event is either a well known name or an ad hoc name -forged for the use case. - -Let's see a basic example: - -- client A expects to receive the speed in km/h every second. -- client B expects the speed in mph twice a second. - -In that case, there are two different events because it is not the same -unit and it is not the same frequency. -Having two different events allows to associate clients to the correct event. -But this doesn't tell any word about the name of these events. -The designer of the signaling agent has two options for naming: - -1. names can be the same (“speed” for example) with sent data - self describing itself or having a specific tag (requiring from - clients awareness about requesting both kinds of speed isn't safe). -2. names of the event include the variations (by example: - “speed-km/h-1Hz” and “speed-mph-2Hz”) and, in that case, sent data - can self describe itself or not. - -In both cases, the signaling agent might have to send the name of the -event and/or an associated tag to its client in the reply of the -subscription. -This is part of the step 5 above. - -The framework only uses the event (not its name) for: - -- subscription -- un-subscription -- pushing - -When the requested data is already generated and the event used for -pushing it already exists, the signaling agent must not instantiate a -new processing chain and must not create a new event object for pushing -data. -The signaling agent must reuse the existing chain and event. - -Unsubscribing is made by the signaling agent on a request of its client. -The ***afb\_req\_unsubscribe*** function tells the framework to -remove the requesting client from the event's list of subscribers. -Example: - -```C - afb_req_unsubscribe(req, event); -``` - -Subscription count does not matter to the framework: - -- Subscribing the same client several times has the same effect that subscribing only one time. - -Thus, when unsubscribing is invoked, it becomes immediately effective. - -#### More on naming events - -- Within the AGL framework, a signaling agent is a binding that has an API prefix. - -This prefix is meant to be unique and to identify the binding API. -The names of the events that this signaling agent creates are -automatically prefixed by the framework, using the API prefix of the -binding. - -Thus, if a signaling agent of API prefix ***api*** creates an event -of name ***event*** and pushes data to that event, the subscribers -will receive an event of name ***api/event***. - -### Generating and pushing signals and data - -- This of the responsibility of the designer of the signaling agent to establish the processing chain for generating events. - -In many cases, this can be achieved using I/O or timer or signal events inserted in the main loop. -For this case, the AGL framework uses **libsystemd** and -provide a way to integrates to the main loop of this library using -afb\_api\_get\_event\_loop. -Example: - -```C - sdev = afb_api_get_event_loop(api); - rc = sd_event_add_io(sdev, &source, fd, EPOLLIN, myfunction, NULL); -``` - -In some other cases, the events are coming from D-Bus. -In that case, the framework also uses **libsystemd** internally to access D-Bus. -It provides two methods to get the available D-Bus objects, already existing and -bound to the main **libsystemd** event loop. -Use either ***afb\_api\_get\_system\_bus*** or -***afb\_api\_get\_user\_bus*** to get the required instance. -Then use functions of **libsystemd** to handle D-Bus. - -In some rare cases, the generation of the data requires to start a new -thread. - -When a data is generated and ready to be pushed, the signaling agent -should call the function ***afb\_event\_push***. -Example: - -```C - rc = afb_event_push(event, JSON); - if (rc == 0) { - stop_generating(event); - afb_event_unref(event); - } -``` - -The function ***afb\_event\_push*** pushes json data to all the subscribers. -It then returns the count of subscribers. -When the count is zero, there is no subscriber listening for the event. -The example above shows that in that case, the signaling agent stops to -generate data for the event and tells that it doesn't use it anymore by calling -**afb\_event\_unref**. - -This is one possible option. -Other valuable options are: - -- do nothing and continue to generate and push the event. -- just stop to generate and push the data but keep the event existing. - -### Receiving the signals - -Understanding what a client expects when it receives signals, events or -data shall be the most important topic of the designer of a signaling -agent. -The good point here is that because JSON[^1] is the exchange -format, structured data can be sent in a flexible way. - -The good design is to allow as much as possible the client to describe -what is needed with the goal to optimize the processing to the -requirements only. - -### The exceptional case of wide broadcast - -Some data or events have so much importance that they can be widely -broadcasted to alert any listening client. -Examples of such an alert are: - -- system is entering/leaving “power safe” mode -- system is shutting down -- the car starts/stops moving -- ... - -An event can be broadcasted using one of the two following methods: - -- ***afb\_api\_broadcast\_event*** -- ***afb\_event\_broadcast*** - -Example 1: - -```C -afb_api_broadcast_event(api, name, json); -``` - -Example 2: - -```C -event = afb_api_make_event(api, name); -. . . . -afb_event_broadcast(event, json); -``` - -As for other events, the name of events broadcasted using -***afb\_api\_broadcast\_event*** are automatically prefixed by -the framework with API prefix. - -## Reference of functions - -See the [references for functions of class afb_event](3_Binder_References.md#v-FUNCTIONS-OF-CLASS-afb_event) - -### Function onevent (field of afbBindingExport) - -Binding can designate an event handling function using the field **onevent** -of the structure **afb_binding_t**. - -This function is called when an event is broadcasted or when an event that the -api subscribed to (through call or subcall mechanism) is pushed. -That behavior allows a service to react to an event and do what it is to do if -this is relevant for it. -(ie: car back camera detects imminent collision and broadcast it, then -appropriate service enable parking brake.). - -### Event handlers - -The apis functions allow to declare event handling callbacks. These callbacks are -called on reception of an event matching a pattern and a receive in more that -the event name and its companion JSON data, a user defiend closure and the api -that is used to create it. \ No newline at end of file diff --git a/docs/3_Developer_Guides/2_Application_Framework_Binder/5_Binder_Application_writing_guide.md b/docs/3_Developer_Guides/2_Application_Framework_Binder/5_Binder_Application_writing_guide.md deleted file mode 100644 index 4886e5d..0000000 --- a/docs/3_Developer_Guides/2_Application_Framework_Binder/5_Binder_Application_writing_guide.md +++ /dev/null @@ -1,319 +0,0 @@ ---- -title: Binder Application writing guide ---- - -### Writing an HTML5 application - -Developers of HTML5 applications (client side) can easily create -applications for AGL framework using their preferred -HTML5 framework. - -Developers may also take advantage of powerful server side bindings to improve -application behavior. -Server side bindings return an application/json mine-type -and can be accessed though either HTTP or Websockets. - -In a near future, JSON-RPC protocol should be added to complete the current -x-afb-json1 protocol. - -Two examples of HTML5 applications are given: - -- [afb-client](https://gerrit.automotivelinux.org/gerrit/gitweb?p=src/app-framework-demo.git;a=tree;f=afb-client) a simple "hello world" application template - -- [afm-client](https://gerrit.automotivelinux.org/gerrit/gitweb?p=src/app-framework-demo.git;a=tree;f=afm-client) a simple "Home screen" application template - -### Writing a Qt application - -Writing Qt applications is also supported. -Qt offers standard API to send request through HTTP or WebSockets. - -It is also possible to write QML applications. -A sample QML application token-websock is available: - -- [token-websock](https://gerrit.automotivelinux.org/gerrit/gitweb?p=src/app-framework-binder.git;a=blob;f=test/token-websock.qml) - -A simple "hello world" application in QML - -### Writing a "C" application - -C applications can use afb-daemon binder through a websocket connection. - -The library **libafbwsc** is provided for C clients that need -to connect with an afb-daemon binder. - -The program **afb-client-demo** is the C example that uses the -**libafbwsc** library. -Source code is available here -[src/afb-client-demo.c](https://gerrit.automotivelinux.org/gerrit/gitweb?p=src/app-framework-binder.git;a=blob;f=src/afb-client-demo.c). - -Current implementation relies on libsystemd and file descriptors. -This model may be reviewed in the future to support secure sockets -and get rid of libsystemd dependency. - -### Handling sessions within applications - -Applications should understand sessions and token management when interacting -with afb-daemon binder. - -Applications communicate with their private binder (afb-daemon) using -a network connection or any other potential connection channel. -While the current version does not yet implement Unix socket, -this feature might be added in the near future. -Developers need to be warn that HTTP protocol is a none -connected protocol and that using HTTP socket connection to authenticate -clients is not supported. - -For this reason, the binder should authenticate the application -by using a shared secret. -The secret is named "token" and the identification of client is named "session.” - -The examples **token-websock.qml** and **afb-client** are demonstrating -how authentication and sessions are managed. - -### Handling sessions - -Bindings and other binder features need to keep track of client -instances. -This is especially important for bindings running as services -as they may typically have to keep each client's data separated. - -For HTML5 applications, the web runtime handles the cookie of the session -that the binder afb-daemon automatically sets. - -Session identifier can be set using the parameter **uuid** or **x-afb-uuid** in -URI requests. -Within current version of the framework session UUID is supported -by both HTTP requests and websocket negotiation. - -### Exchanging tokens - -At application start, AGL framework communicates a shared secret to both binder -and client application. -This initial secret is called the "**initial token**". - -For each of its client application, the binder manages a current active -token for session management. -This authentication token can be use to restrict the access to some binding's methods. - -The token must be included in URI request on HTTP or during websockets -connection using parameter **token** or **x-afb-token**. - -To ensure security, tokens must be refreshed periodically. - -### Example of session management - -In following examples, we suppose that **afb-daemon** is launched with something -equivalent to: - -```bash -afb-daemon --port=1234 --token=123456 [...] -``` - -making the expectation that **AuthLogin** binding is requested as default. - -#### Using curl - -First, connects with the initial token, 123456: - -```bash -$ curl http://localhost:1234/api/auth/connect?token=123456 -{ - "jtype": "afb-reply", - "request": { - "status": "success", - "token": "0aef6841-2ddd-436d-b961-ae78da3b5c5f", - "uuid": "850c4594-1be1-4e9b-9fcc-38cc3e6ff015" - }, - "response": {"token": "A New Token and Session Context Was Created"} -} -``` - -It returns an answer containing session UUID, 850c4594-1be1-4e9b-9fcc-38cc3e6ff015, -and a refreshed token, 850c4594-1be1-4e9b-9fcc-38cc3e6ff015. - -Check if session and token is valid: - -```bash -$ curl http://localhost:1234/api/auth/check?token=0aef6841-2ddd-436d-b961-ae78da3b5c5f\&uuid=850c4594-1be1-4e9b-9fcc-38cc3e6ff015 -{ - "jtype": "afb-reply", - "request": {"status":"success"}, - "response": {"isvalid":true} -} -``` - -Refresh the token: - -```bash -$ curl http://localhost:1234/api/auth/refresh?token=0aef6841-2ddd-436d-b961-ae78da3b5c5f\&uuid=850c4594-1be1-4e9b-9fcc-38cc3e6ff015 -{ - "jtype": "afb-reply", - "request": { - "status":"success", - "token":"b8ec3ec3-6ffe-448c-9a6c-efda69ad7bd9" - }, - "response": {"token":"Token was refreshed"} -} -``` - -Close the session: - -```bash -$ curl http://localhost:1234/api/auth/logout?token=b8ec3ec3-6ffe-448c-9a6c-efda69ad7bd9\&uuid=850c4594-1be1-4e9b-9fcc-38cc3e6ff015 -{ - "jtype": "afb-reply", - "request": {"status": "success"}, - "response": {"info":"Token and all resources are released"} -} -``` - -Checking on closed session for uuid should be refused: - -```bash -$ curl http://localhost:1234/api/auth/check?token=b8ec3ec3-6ffe-448c-9a6c-efda69ad7bd9\&uuid=850c4594-1be1-4e9b-9fcc-38cc3e6ff015 -{ - "jtype": "afb-reply", - "request": { - "status": "failed", - "info": "invalid token's identity" - } -} -``` - -#### Using afb-client-demo - -- The program is packaged within AGL in the rpm **libafbwsc-dev** - -Here is an example of exchange using **afb-client-demo**: - -```bash -$ afb-client-demo ws://localhost:1234/api?token=123456 -auth connect -ON-REPLY 1:auth/connect: {"jtype":"afb-reply","request":{"status":"success", - "token":"63f71a29-8b52-4f9b-829f-b3028ba46b68","uuid":"5fcc3f3d-4b84-4fc7-ba66-2d8bd34ae7d1"}, - "response":{"token":"A New Token and Session Context Was Created"}} -auth check -ON-REPLY 2:auth/check: {"jtype":"afb-reply","request":{"status":"success"},"response":{"isvalid":true}} -auth refresh -ON-REPLY 4:auth/refresh: {"jtype":"afb-reply","request":{"status":"success", - "token":"8b8ba8f4-1b0c-48fa-962d-4a00a8c9157e"},"response":{"token":"Token was refreshed"}} -auth check -ON-REPLY 5:auth/check: {"jtype":"afb-reply","request":{"status":"success"},"response":{"isvalid":true}} -auth refresh -ON-REPLY 6:auth/refresh: {"jtype":"afb-reply","request":{"status":"success", - "token":"e83b36f8-d945-463d-b983-5d8ed73ba529"},"response":{"token":"Token was refreshed"}} -``` - -After closing connection, reconnect as here after: - -```bash -$ afb-client-demo ws://localhost:1234/api?token=e83b36f8-d945-463d-b983-5d8ed73ba529\&uuid=5fcc3f3d-4b84-4fc7-ba66-2d8bd34ae7d1 auth check -ON-REPLY 1:auth/check: {"jtype":"afb-reply","request":{"status":"success"},"response":{"isvalid":true}} -``` - -Same connection check using **curl**: - -```bash -$ curl http://localhost:1234/api/auth/check?token=e83b36f8-d945-463d-b983-5d8ed73ba529\&uuid=5fcc3f3d-4b84-4fc7-ba66-2d8bd34ae7d1 -{"jtype":"afb-reply","request":{"status":"success"},"response":{"isvalid":true}} -``` - -### Format of replies - -Replies use javascript object returned as serialized JSON. - -This object contains at least 2 mandatory fields of name **jtype** and -**request** and one optional field of name **response**. - -#### Template of replies - -This is a template of replies: - -```json -{ - "jtype": "afb-reply", - "request": { - "status": "success", - "info": "informationnal text", - "token": "e83b36f8-d945-463d-b983-5d8ed73ba52", - "uuid": "5fcc3f3d-4b84-4fc7-ba66-2d8bd34ae7d1", - "reqid": "application-generated-id-23456" - }, - "response": ....any response object.... -} -``` - -#### Field jtype of replies - -The field **jtype** must have a value of type string equal to **"afb-reply"**. - -#### Field request of replies - -The field **request** must have a value of type object. -This request object has at least one field named **status** -and four optional fields named **info**, **token**, **uuid**, **reqid**. - -##### Subfield request.status - -**status** must have a value of type string. This string is equal to **"success"** -only in case of success. - -##### Subfield request.info - -**info** is of type string and represent optional information added to the reply. - -##### Subfield request.token - -**token** is of type string. It is sent either at session creation -or when the token is refreshed. - -##### Subfield request.uuid - -**uuid** is of type string. It is sent at session creation. - -##### Subfield request.reqid - -**reqid** is of type string. It is sent in response to HTTP requests -that added a parameter of name **reqid** or **x-afb-reqid** at request time. -Value returns in the reply has the exact same value as the one received in the -request. - -#### Field response of replies - -This field response optionally contains an object returned when request -succeeded. - -### Format of events - -Events are javascript object serialized as JSON. - -This object contains at least 2 mandatory fields of name **jtype** and **event** -and one optional field of name **data**. - -#### Template of event - -Here is a template of event: - -```json -{ - "jtype": "afb-event", - "event": "sample_api_name/sample_event_name", - "data": ...any event data... -} -``` - -#### Field jtype of event - -The field **jtype** must have a value of type string equal to **"afb-event"**. - -#### Field event of event - -The field **event** carries the event's name. - -The name of the event is made of two parts separated by a slash: -the name of the name of the API that generated the event -and the name of event within the API. - -#### Field data of event - -This field data if present holds the data carried by the event. \ No newline at end of file diff --git a/docs/3_Developer_Guides/2_Application_Framework_Binder/7_Document_revisions.md b/docs/3_Developer_Guides/2_Application_Framework_Binder/7_Document_revisions.md deleted file mode 100644 index 06242ce..0000000 --- a/docs/3_Developer_Guides/2_Application_Framework_Binder/7_Document_revisions.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: Document revisions ---- - -Document revisions - -| Date | Version | Designation  | Author | -|--------------|:----------:|----------------------------------------------|-------------------------------------------------------| -| 23 May 2016 | 0.9 | Initial release | J. Bollo [ IoT.bzh ]
M. Bachmann [ IoT.bzh ] | -| 30 May 2016 | 1.0 | Master document edition, final review | S. Desneux [ IoT.bzh ]
F. Ar Foll [ IoT.bzh ] | -| 21 Sept 2016 | 2.0 | Updated with new sections (events,widgets) | J. Bollo [ IoT.bzh ]
S. Desneux [ IoT.bzh ] | -| 12 Dec 2016 | 2.1 | Updated for CC Release | S. Desneux [ IoT.bzh ] | -| 14 Dec 2016 | 3.0 | Minor fixes, alignment with CC version | S. Desneux [ IoT.bzh ] | -| 20 Mar 2017 | 3.1 | Systemd integration | J. Bollo [ IoT.bzh ]
S. Desneux [ IoT.bzh ] | -| 21 Jun 2017 | 4.0 | Update for AGL DD | J. Bollo [ IoT.bzh ]
S. Desneux [ IoT.bzh ] | -| 21 Sep 2017 | 4.99-EERC1 | Update for AGL EE-RC1 | J. Bollo [ IoT.bzh ]
S. Desneux [ IoT.bzh ] | -| 14 Jun 2018 | 5.99-FFRC1 | Update for AGL FF-RC1 | J. Bollo [ IoT.bzh ] | diff --git a/docs/3_Developer_Guides/2_Application_Framework_Binder/Annexes/1_Migration_to_bindings_v3.md b/docs/3_Developer_Guides/2_Application_Framework_Binder/Annexes/1_Migration_to_bindings_v3.md deleted file mode 100644 index bba5354..0000000 --- a/docs/3_Developer_Guides/2_Application_Framework_Binder/Annexes/1_Migration_to_bindings_v3.md +++ /dev/null @@ -1,199 +0,0 @@ ---- -title: Migration to bindings v3 ---- - -The ***binding*** interface evolved from version 1 to version 2 -for the following reasons: - -- integration of the security requirements within the bindings -- simplification of the API (after developer feedbacks) -- removal of obscure features and cleanup - -The ***binder*** can run ***bindings*** v1, v2 and/or v3 in any combination. -Thus moving from v1 or v2 to v3 is not enforced at this time. But ... - -In the face to face meeting in Karlsruhe it was decided to remove support -of bindings v1 and to deprecate the use of bindings v2. - -So at the end, **IT IS HIGHLY NEEDED TO SWITCH TO VERSION 3** - -This guide covers the migration of bindings from version 2 to version 3. - -The migration from version 1 is not treated here because bindings version 1 -are very old and probably do not exist anymore. If needed you can refer -to the old [guide to migrate bindings from v1 to v2](./6_LEGACY_Migration_from_v1_to_v2.md). - - -Differences between version 2 and version 3 -------------------------------------------- - -** *In v3 all is api.* ** - -The version 3 introduces the concept of "API" that gather what was called before -the daemon and the service. This is the new concept that predates the 2 others. - -The concept of API is intended to allow the definition of multiple APIs -by a same "binding" (a dynamically loaded library). - -Because there is potentially several "API", the functions that were without -context in bindings version 2 need now to tell what API is consumer. - -To be compatible with version 2, bindings v3 still have a default hidden -context: the default API named **afbBindingV3root**. - -To summarize, the functions of class **daemon** and **service** use the default -hidden API. - -It is encouraged to avoid use of functions of class **daemon** and **service**. -You should replace these implicit calls to explicit **api** calls that -reference **afbBindingV3root**. - -Same thing for the logging macros: **AFB_ERROR**, **AFB_WARNING**, -**AFB_NOTICE**, **AFB_INFO**, **AFB_DEBUG** that becomes respectively -**AFB_API_ERROR**, **AFB_API_WARNING**, **AFB_API_NOTICE**, **AFB_API_INFO**, -**AFB_API_DEBUG**. - -Example of 2 equivalent writes: - -```C - AFB_NOTICE("send stress event"); - afb_daemon_broadcast_event(stressed_event, NULL); -``` - -or - -```C - AFB_API_NOTICE(afbBindingV3root, "send stress event"); - afb_api_broadcast_event(afbBindingV3root, stressed_event, NULL); -``` - -**The reply mechanism predates success and fail. Subcall has more power.** - -Task list for the migration ---------------------------- - -This task list is: - -1. Use the automatic migration procedure described below -2. Adapt the functions **preinit**, **init** and **onevent** -3. Consider use of the new reply -4. Consider use of the new (sub)call -5. Consider use of event handlers - -The remaining chapters explain these task with more details. - -Automatic migration! --------------------- - -A tiny **sed** script is intended to perform a first pass on the code that -you want to upgrade. It can be done using **curl** and applied using **sed** -as below. - -```bash -BASE=https://git.automotivelinux.org/src/app-framework-binder/plain -SED=migration-to-binding-v3.sed -curl -o $SED $BASE/docs/$SED -sed -i -f $SED file1 file2 file3... -``` - -You can also follow -[this link](https://git.automotivelinux.org/src/app-framework-binder/plain/docs/migration-to-binding-v3.sed) -and save the file. - -This automatic action does most of the boring job but not all the job. -The remaining of this guide explains the missing part. - -Adapt the functions preinit, init and onevent ----------------------------------------------- - -The signature of the functions **preinit**, **init** and **onevent** changed -to include the target api. - -The functions of the v2: - -```C -int (*preinit)(); -int (*init)(); -void (*onevent)(const char *event, struct json_object *object); -``` - -Gain a new first argument of type **afb_api_t** as below: - -```C -int (*preinit)(afb_api_t api); -int (*init)(afb_api_t api); -void (*onevent)(afb_api_t api, const char *event, struct json_object *object); -``` - -For the migration, it is enough to just add the new argument without -using it. - -Consider use of the new reply ------------------------------ - -The v3 allows error reply with JSON object. To achieve it, an unified -reply function's family is introduced: - -```C -void afb_req_reply(afb_req_t req, json_object *obj, const char *error, const char *info); -void afb_req_reply_v(afb_req_t req, json_object *obj, const char *error, const char *info, va_list args); -void afb_req_reply_f(afb_req_t req, json_object *obj, const char *error, const char *info, ...); -``` - -The functions **success** and **fail** are still supported. -These functions are now implemented as the following macros: - - -```C -#define afb_req_success(r,o,i) afb_req_reply(r,o,NULL,i) -#define afb_req_success_f(r,o,...) afb_req_reply_f(r,o,NULL,__VA_ARGS__) -#define afb_req_success_v(r,o,f,v) afb_req_reply_v(r,o,NULL,f,v) -#define afb_req_fail(r,e,i) afb_req_reply(r,NULL,e,i) -#define afb_req_fail_f(r,e,...) afb_req_reply_f(r,NULL,e,__VA_ARGS__) -#define afb_req_fail_v(r,e,f,v) afb_req_reply_v(r,NULL,e,f,v) -``` - -This is a decision of the developer to switch to the new family -**afb_req_reply** or to keep the good old functions **afb_req_fail** -adn **afb_req_success**. - -Consider use of the new (sub)call ---------------------------------- - -The new call and subcall (the functions **afb_api_call**, **afb_api_call_sync**, -**afb_req_subcall** and **afb_req_subcall_sync**) functions are redesigned -to better fit the new reply behaviour. In most case the developer will benefit -of the new behavior that directly gives result and error without enforcing -to parse the JSON object result. - -The subcall functions are also fully redesigned to allow precise handling -of the context and event subscriptions. The new design allows you to specify: - - - whether the subcall is made in the session of the caller or in the session - of the service - - whether the credentials to use are those of the caller or those of the - service - - whether the caller or the service or both or none will receive the - eventually events during the subcall. - -See [calls](../3_Binder_References.md#afb_api_call) and -[subcalls](../3_Binder_References.md#subcall-functions). - -The table below list the changes to apply: - -| Name in Version 2 | New name of Version 3 -|:----------------------:|:----------------------------------------------------: -| afb_req_subcall | afb_req_subcall_legacy -| afb_req_subcall_sync | afb_req_subcall_sync_legacy -| afb_service_call | afb_service_call_legacy -| afb_service_call_sync | afb_service_call_sync_legacy -| afb_req_subcall_req | afb_req_subcall_req (same but obsolete) - - -Consider use of event handlers ------------------------------- - -Binding V3 brings new ways of handling event in services. You can register -functions that will handle specific events and that accept closure arguments. - -See [**afb_api_event_handler_add** and **afb_api_event_handler_del**](../3_Binder_References.md#event-functions) \ No newline at end of file diff --git a/docs/3_Developer_Guides/2_Application_Framework_Binder/Annexes/2_WebSocket_protocol_x-afb-ws-json1.md b/docs/3_Developer_Guides/2_Application_Framework_Binder/Annexes/2_WebSocket_protocol_x-afb-ws-json1.md deleted file mode 100644 index 7ebf22a..0000000 --- a/docs/3_Developer_Guides/2_Application_Framework_Binder/Annexes/2_WebSocket_protocol_x-afb-ws-json1.md +++ /dev/null @@ -1,308 +0,0 @@ ---- -title: WebSocket protocol x-afb-ws-json1 ---- - -The WebSocket protocol *x-afb-ws-json1* is used to communicate between -an application and a binder. It allows access to all registered apis -of the binder. - -This protocol is inspired from the protocol **OCPP - SRPC** as described for -example here: -[OCPP transport specification - SRPC over WebSocket](http://www.gir.fr/ocppjs/ocpp_srpc_spec.shtml). - -The registration to the IANA is still to be done, see: -[WebSocket Protocol Registries](https://www.iana.org/assignments/websocket/websocket.xml) - -This document gives a short description of the protocol *x-afb-ws-json1*. -A more formal description has to be done. - -## Architecture - -The protocol is intended to be symmetric. It allows: - -- to CALL a remote procedure that returns a result -- to push and receive EVENT - -## Messages - -Valid messages are made of *text* frames that are all valid JSON. - -Valid messages are: - -Calls: - -```txt -[ 2, ID, PROCN, ARGS ] -[ 2, ID, PROCN, ARGS, TOKEN ] -``` - -Replies (3: OK, 4: ERROR): - -```txt -[ 3, ID, RESP ] -[ 4, ID, RESP ] -``` - -Events: - -```txt -[ 5, EVTN, OBJ ] -``` - -Where: - -| Field | Type | Description -|-------|--------|------------------ -| ID | string | A string that identifies the call. A reply to that call use the ID of the CALL. -| PROCN | string | The procedure name to call of the form "api/verb" -| ARGS | any | Any argument to pass to the call (see afb_req_json that returns it) -| RESP | any | The response to the call -| TOKEN | string | The authorisation token -| EVTN | string | Name of the event in the form "api/event" -| OBJ | any | The companion object of the event - -Below, an example of exchange: - -```txt -C->S: [2,"156","hello/ping",null] -S->C: [3,"156",{"response":"Some String","jtype":"afb-reply","request":{"status":"success","info":"Ping Binder Daemon tag=pingSample count=1 query=\"null\"","uuid":"ec30120c-6997-4529-9d63-c0de0cce56c0"}}] -``` - -## History - -### 14 November 2019 - -Removal of token returning. The replies - -```txt -[ 3, ID, RESP, TOKEN ] -[ 4, ID, RESP, TOKEN ] -``` - -are removed from the specification. - -## Future - -Here are the planned extensions: - -- add binary messages with cbor data -- add calls with unstructured replies - -This could be implemented by extending the current protocol or by -allowing the binder to accept either protocol including the new ones. - -## Javascript implementation - -The file **AFB.js** is a javascript implementation of the protocol. - -Here is that code: - -```javascript -/* - * Copyright (C) 2017-2019 "IoT.bzh" - * Author: José Bollo - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -AFB = function(base, initialtoken){ - -if (typeof base != "object") - base = { base: base, token: initialtoken }; - -var initial = { - base: base.base || "api", - token: base.token || initialtoken || "HELLO", - host: base.host || window.location.host, - url: base.url || undefined -}; - -var urlws = initial.url || "ws://"+initial.host+"/"+initial.base; - -/*********************************************/ -/**** ****/ -/**** AFB_context ****/ -/**** ****/ -/*********************************************/ -var AFB_context; -{ - var UUID = undefined; - var TOKEN = initial.token; - - var context = function(token, uuid) { - this.token = token; - this.uuid = uuid; - } - - context.prototype = { - get token() {return TOKEN;}, - set token(tok) {if(tok) TOKEN=tok;}, - get uuid() {return UUID;}, - set uuid(id) {if(id) UUID=id;} - }; - - AFB_context = new context(); -} -/*********************************************/ -/**** ****/ -/**** AFB_websocket ****/ -/**** ****/ -/*********************************************/ -var AFB_websocket; -{ - var CALL = 2; - var RETOK = 3; - var RETERR = 4; - var EVENT = 5; - - var PROTO1 = "x-afb-ws-json1"; - - AFB_websocket = function(on_open, on_abort) { - var u = urlws; - if (AFB_context.token) { - u = u + '?x-afb-token=' + AFB_context.token; - if (AFB_context.uuid) - u = u + '&x-afb-uuid=' + AFB_context.uuid; - } - this.ws = new WebSocket(u, [ PROTO1 ]); - this.url = u; - this.pendings = {}; - this.awaitens = {}; - this.counter = 0; - this.ws.onopen = onopen.bind(this); - this.ws.onerror = onerror.bind(this); - this.ws.onclose = onclose.bind(this); - this.ws.onmessage = onmessage.bind(this); - this.onopen = on_open; - this.onabort = on_abort; - } - - function onerror(event) { - var f = this.onabort; - if (f) { - delete this.onopen; - delete this.onabort; - f && f(this); - } - this.onerror && this.onerror(this); - } - - function onopen(event) { - var f = this.onopen; - delete this.onopen; - delete this.onabort; - f && f(this); - } - - function onclose(event) { - for (var id in this.pendings) { - try { this.pendings[id][1](); } catch (x) {/*TODO?*/} - } - this.pendings = {}; - this.onclose && this.onclose(); - } - - function fire(awaitens, name, data) { - var a = awaitens[name]; - if (a) - a.forEach(function(handler){handler(data);}); - var i = name.indexOf("/"); - if (i >= 0) { - a = awaitens[name.substring(0,i)]; - if (a) - a.forEach(function(handler){handler(data);}); - } - a = awaitens["*"]; - if (a) - a.forEach(function(handler){handler(data);}); - } - - function reply(pendings, id, ans, offset) { - if (id in pendings) { - var p = pendings[id]; - delete pendings[id]; - try { p[offset](ans); } catch (x) {/*TODO?*/} - } - } - - function onmessage(event) { - var obj = JSON.parse(event.data); - var code = obj[0]; - var id = obj[1]; - var ans = obj[2]; - AFB_context.token = obj[3]; - switch (code) { - case RETOK: - reply(this.pendings, id, ans, 0); - break; - case RETERR: - reply(this.pendings, id, ans, 1); - break; - case EVENT: - default: - fire(this.awaitens, id, ans); - break; - } - } - - function close() { - this.ws.close(); - this.ws.onopen = - this.ws.onerror = - this.ws.onclose = - this.ws.onmessage = - this.onopen = - this.onabort = function(){}; - } - - function call(method, request, callid) { - return new Promise((function(resolve, reject){ - var id, arr; - if (callid) { - id = String(callid); - if (id in this.pendings) - throw new Error("pending callid("+id+") exists"); - } else { - do { - id = String(this.counter = 4095 & (this.counter + 1)); - } while (id in this.pendings); - } - this.pendings[id] = [ resolve, reject ]; - arr = [CALL, id, method, request ]; - if (AFB_context.token) arr.push(AFB_context.token); - this.ws.send(JSON.stringify(arr)); - }).bind(this)); - } - - function onevent(name, handler) { - var id = name; - var list = this.awaitens[id] || (this.awaitens[id] = []); - list.push(handler); - } - - AFB_websocket.prototype = { - close: close, - call: call, - onevent: onevent - }; -} -/*********************************************/ -/**** ****/ -/**** ****/ -/**** ****/ -/*********************************************/ -return { - context: AFB_context, - ws: AFB_websocket -}; -}; -``` diff --git a/docs/3_Developer_Guides/2_Application_Framework_Binder/Annexes/3_Installing_the_binder_on_a_desktop.md b/docs/3_Developer_Guides/2_Application_Framework_Binder/Annexes/3_Installing_the_binder_on_a_desktop.md deleted file mode 100644 index 8874bde..0000000 --- a/docs/3_Developer_Guides/2_Application_Framework_Binder/Annexes/3_Installing_the_binder_on_a_desktop.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -title: Installing the binder on a desktop ---- - -Packages of the ***binder*** (afb-daemon)exist -for common desktop linux distributions. - -- Fedora -- Ubuntu -- Debian -- Suse - -Installing the development package of the ***binder*** -allows to write ***bindings*** that runs on the desktop -computer of the developer. - -It is very convenient to quickly write and debug a binding. - -## Retrieving compiling option with pkg-config - -The ***binder*** afb-daemon provides a configuration -file for **pkg-config**. -Typing the command - -```bash -pkg-config --cflags afb-daemon -``` - -Print flags use for compilation: - -```bash -$ pkg-config --cflags afb-daemon --I/opt/local/include -I/usr/include/json-c -``` - -For linking, you should use - -```bash -$ pkg-config --libs afb-daemon --ljson-c -``` - -It automatically includes the dependency to json-c. -This is activated through **Requires** keyword in pkg-config. diff --git a/docs/3_Developer_Guides/2_Application_Framework_Binder/Annexes/4_Options_of_afb-daemon.md b/docs/3_Developer_Guides/2_Application_Framework_Binder/Annexes/4_Options_of_afb-daemon.md deleted file mode 100644 index 0b58eec..0000000 --- a/docs/3_Developer_Guides/2_Application_Framework_Binder/Annexes/4_Options_of_afb-daemon.md +++ /dev/null @@ -1,355 +0,0 @@ ---- -title: Options of afb-daemon ---- - -The launch options for binder **afb-daemon** are: - -``` - -v, --verbose Verbose Mode, repeat to increase verbosity - -c, --color Colorize the ouput - -q, --quiet Quiet Mode, repeat to decrease verbosity - -l, --log=xxxx Tune log level - --foreground Get all in foreground mode - --background Get all in background mode - -D, --daemon Get all in background mode - -n, --name=xxxx Set the visible name - -p, --port=xxxx HTTP listening TCP port [default 1234] - --roothttp=xxxx HTTP Root Directory [default no root http (files not served but apis still available)] - --rootbase=xxxx Angular Base Root URL [default /opa] - --rootapi=xxxx HTML Root API URL [default /api] - --alias=xxxx Multiple url map outside of rootdir [eg: --alias=/icons:/usr/share/icons] - --apitimeout=xxxx Binding API timeout in seconds [default 20] - --cntxtimeout=xxxx Client Session Context Timeout [default 32000000] - --cache-eol=xxxx Client cache end of live [default 100000] - -w, --workdir=xxxx Set the working directory [default: $PWD or current working directory] - -u, --uploaddir=xxxx Directory for uploading files [default: workdir] relative to workdir - --rootdir=xxxx Root Directory of the application [default: workdir] relative to workdir - --ldpaths=xxxx Load bindings from dir1:dir2:... [default: path of afb-dbus-binding.so] - -b, --binding=xxxx Load the binding of path - --weak-ldpaths=xxxx Same as --ldpaths but ignore errors - --no-ldpaths Discard default ldpaths loading - -t, --token=xxxx Initial Secret [default=random, use --token= to allow any token] - -r, --random-token Enforce a random token - -V, --version Display version and copyright - -h, --help Display this help - --ws-client=xxxx Bind to an afb service through websocket - --ws-server=xxxx Provide an afb service through websockets - -A, --auto-api=xxxx Automatic load of api of the given directory - --session-max=xxxx Max count of session simultaneously [default 200] - --tracereq=xxxx Log the requests: no, common, extra, all - --traceevt=xxxx Log the events: no, common, extra, all - --traceses=xxxx Log the sessions: no, all - --traceapi=xxxx Log the apis: no, common, api, event, all - --traceglob=xxxx Log the globals: none, all - --traceditf=xxxx Log the daemons: no, common, all - --tracesvc=xxxx Log the services: no, all - --call=xxxx call at start, format of val: API/VERB:json-args - --no-httpd Forbid HTTP service - -e, --exec Execute the remaining arguments - -M, --monitoring Enable HTTP monitoring at /monitoring/ - -C, --config=xxxx Load options from the given config file - -Z, --dump-config Dump the config to stdout and exit - -s, --set=xxxx Set parameters ([API]/[KEY]:JSON or {"API":{"KEY":JSON}} - -o, --output=xxxx Redirect stdout and stderr to output file (when --daemon) - --trap-faults=xxxx Trap faults: on, off, yes, no, true, false, 1, 0 (default: true) -``` - -## help - -Prints help with available options - -## version - -Display version and copyright - -## verbose - -Increases the verbosity, can be repeated - -## color - -Add basic colorization to the ouput. - -## quiet - -Decreases the verbosity, can be repeated - -## log=xxxx - -Tune the log level mask. The levels are: - - - error - - warning - - notice - - info - - debug - -The level can be set using + or -. - -| Examples | descritpion -|-----------------|------------------- -| error,warning | selects only the levels error and warning -| +debug | adds level debug to the current verbosity -| -warning | remove the level warning from the current verbosity -| +warning-debug,info | Adds error and remove errors and warnings - -## port=xxxx - -HTTP listening TCP port [default 1234] - -## workdir=xxxx - -Directory where the daemon must run [default: $PWD if defined -or the current working directory] - -## uploaddir=xxxx - -Directory where uploaded files are temporarily stored [default: workdir] - -## rootdir=xxxx - -Root directory of the application to serve [default: workdir] - -## roothttp=xxxx - -Directory of HTTP served files. If not set, files are not served -but apis are still accessible. - -## rootbase=xxxx - -Angular Base Root URL [default /opa] - -This is used for any application of kind OPA (one page application). -When set, any missing document whose url has the form /opa/zzz -is translated to /opa/#!zzz - -## rootapi=xxxx - -HTML Root API URL [default /api] - -The bindings are available within that url. - -## alias=xxxx - -Maps a path located anywhere in the file system to the -a subdirectory. The syntax for mapping a PATH to the -subdirectory NAME is: --alias=/NAME:PATH. - -Example: --alias=/icons:/usr/share/icons maps the -content of /usr/share/icons within the subpath /icons. - -This option can be repeated. - -## apitimeout=xxxx - -binding API timeout in seconds [default 20] - -Defines how many seconds maximum a method is allowed to run. -0 means no limit. - -## cntxtimeout=xxxx - -Client Session Timeout in seconds [default 32000000 that is 1 year] - -## cache-eol=xxxx - -Client cache end of live [default 100000 that is 27,7 hours] - -## session-max=xxxx - -Maximum count of simultaneous sessions [default 200] - -## ldpaths=xxxx - -Load bindings from given paths separated by colons -as for dir1:dir2:binding1.so:... [default = $libdir/afb] - -You can mix path to directories and to bindings. -The sub-directories of the given directories are searched -recursively. - -The bindings are the files terminated by '.so' (the extension -so denotes shared object) that contain the public entry symbol. - -## weak-ldpaths=xxxx - -Same as --ldpaths but instead of stopping on error, ignore errors and continue. - -## binding=xxxx - -Load the binding of given path. - -## token=xxxx - -Initial Secret token to authenticate. - -If not set, no client can authenticate. - -If set to the empty string, then any initial token is accepted. - -## random-token - -Generate a random starting token. See option --exec. - -## ws-client=xxxx - -Transparent binding to a binder afb-daemon service through a WebSocket. - -The value of xxxx is either a unix naming socket, of the form "unix:path/api", -or an internet socket, of the form "host:port/api". - -## ws-server=xxxx - -Provides a binder afb-daemon service through WebSocket. - -The value of xxxx is either a unix naming socket, of the form "unix:path/api", -or an internet socket, of the form "host:port/api". - -## foreground - -Get all in foreground mode (default) - -## daemon - -Get all in background mode - -## no-httpd - -Forbids HTTP serve - -## exec - -Must be the last option for afb-daemon. The remaining -arguments define a command that afb-daemon will launch. -The sequences @p, @t and @@ of the arguments are replaced -with the port, the token and @. - -## tracereq=xxxx - -Trace the processing of requests in the log file. - -Valid values are 'no' (default), 'common', 'extra' or 'all'. - -## traceapi=xxxx - -Trace the accesses to functions of class api. - -Valid values are 'no' (default), 'common', 'api', 'event' or 'all'. - -## traceevt=xxxx - -Trace the accesses to functions of class event. - -Valid values are 'no' (default), 'common', 'extra' or 'all'. - -## call=xxx - -Call a binding at start (can be be repeated). -The values are given in the form API/VERB:json-args. - -Example: --call 'monitor/set:{"verbosity":{"api":"debug"}}' - -## monitoring - -Enable HTTP monitoring at /monitoring/ - -## name=xxxx - -Set the visible name - -## auto-api=xxxx - -Automatic activation of api of the given directory when the api is missing. - -## config=xxxx - -Load options from the given config file - -This can be used instead of arguments on the command line. - -Example: - - afb-daemon \ - --no-ldpaths \ - --binding /home/15646/bindings/binding45.so \ - --binding /home/15646/bindings/binding3.so \ - --tracereq common \ - --port 5555 \ - --token SPYER \ - --set api45/key:54027a5e3c6cb2ca5ddb97679ce32f185b067b0a557d16a8333758910bc25a72 \ - --exec /home/15646/bin/test654 @p @t - -is equivalent to: - - afb-daemon --config /home/15646/config1 - -when the file **/home/15646/config1** is: - - { - "no-ldpaths": true, - "binding": [ - "\/home\/15646\/bindings\/binding45.so", - "\/home\/15646\/bindings\/binding3.so" - ], - "tracereq": "common", - "port": 5555, - "token": "SPYER", - "set" : { - "api45": { - "key": "54027a5e3c6cb2ca5ddb97679ce32f185b067b0a557d16a8333758910bc25a72" - } - }, - "exec": [ - "\/home\/15646\/bin\/test654", - "@p", - "@t" - ] - } - -The options are the keys of the config object. - -See option --dump-config - -## dump-config - -Output a JSON representation of the configuration resulting from -environment and options. - -## output=xxxx - -Redirect stdout and stderr to output file - -## set=xxxx - -Set values that can be retrieved by bindings. - -The set value can have different formats. - -The most generic format is **{"API1":{"KEY1":VALUE,"KEY2":VALUE2,...},"API2":...}** - -This example set 2 keys for the api *chook*: - - afb-daemon -Z --set '{"chook":{"account":"urn:chook:b2ca5ddb97679","delay":500}}' - { - "set": { - "chook": { - "account": "urn:chook:b2ca5ddb97679", - "delay": 500 - } - } - } - -An other format is: **[API]/[KEY]:VALUE**. -When API is omitted, it take the value " * ". -When KEY is ommitted, it take the value of " * ". - -The settings for the API \* are globals and apply to all bindings. - -The settings for the KEY \* are mixing the value for the API. - -The following examples are all setting the same values: - - afb-daemon --set '{"chook":{"account":"urn:chook:b2ca5ddb97679","delay":500}}' - afb-daemon --set 'chook/*:{"account":"urn:chook:b2ca5ddb97679","delay":500}' - afb-daemon --set 'chook/:{"account":"urn:chook:b2ca5ddb97679","delay":500}' - afb-daemon --set 'chook/account:"urn:chook:b2ca5ddb97679"' --set chook/delay:500 \ No newline at end of file diff --git a/docs/3_Developer_Guides/2_Application_Framework_Binder/Annexes/5_Debugging_binder_and_bindings.md b/docs/3_Developer_Guides/2_Application_Framework_Binder/Annexes/5_Debugging_binder_and_bindings.md deleted file mode 100644 index dbb9bdd..0000000 --- a/docs/3_Developer_Guides/2_Application_Framework_Binder/Annexes/5_Debugging_binder_and_bindings.md +++ /dev/null @@ -1,38 +0,0 @@ ---- -title: Debugging binder and bindings ---- - -When compiled with the symbol AGL_DEVEL defined, the ***binder*** -understands the 2 configuration variables: - - - AFB_DEBUG_BREAK: to emit interrupts - - AFB_DEBUG_WAIT: to wait interrupts - -To use these variables, assign it the list of break or wait points -to reach. - -Example: - -```bash -$ AFB_DEBUG_BREAK=main-entry AFB_DEBUG_WAIT=start-load,start-exec afb-daemon .... -``` - -This tells to ***afb-daemon*** to break at the point **main-entry** and to -wait at the points **start-load** and **start-exec**. - -The items of the list can be separated using comma, space, tab or new-line. - -The break/wait points are, in the order of their occurrence: - -- main-entry: before decode arguments -- main-args: before daemon setup -- main-start: before starting jobs -- start-entry: before initialisation of sessions and hooks -- start-load: before load and pre-init of bindings -- start-start: before init of bindings -- start-http: before start of http server -- start-call: before execution of requests of the command line (option --call) -- start-exec: before execution of child preocees - -Note also that a call to 'personality' is inserted just after -the point start-start. \ No newline at end of file diff --git a/docs/3_Developer_Guides/2_Application_Framework_Binder/Annexes/6_LEGACY_Migration_from_v1_to_v2.md b/docs/3_Developer_Guides/2_Application_Framework_Binder/Annexes/6_LEGACY_Migration_from_v1_to_v2.md deleted file mode 100644 index 6004aec..0000000 --- a/docs/3_Developer_Guides/2_Application_Framework_Binder/Annexes/6_LEGACY_Migration_from_v1_to_v2.md +++ /dev/null @@ -1,656 +0,0 @@ ---- -title: LEGACY Migration from v1 to v2 ---- - -> LEGACY!!! IT IS NOT EXPECTED THAT YOU STILL NEED THIS GUIDE. -> -> THIS GUIDE WILL BE REMOVED IN A NEAR FUTURE - - -The ***binding*** interface evolved from version 1 to version 2 -for the following reasons: - -- integration of the security requirements within the bindings -- simplification of the API (after developer feedbacks) -- removal of obscure features, cleanup - -The ***binder*** can run ***bindings*** v1 and/or v2 in any combination. -Thus moving from v1 to v2 is not enforced, there is no real need. - -More, it is possible to write a dual ***binding***: - -- a ***binding*** that implements the version 1 and the version 2. - -However, IT IS HIGHLY RECOMMENDED TO SWITCH TO ONLY VERSION 2: - -- any new development SHOULD start using ***binding*** V2 -- existing ***bindings*** SHOULD migrate to the version 2 - -This guide covers the migration of bindings from version 1 to version 2. - -It also explains some of the rationale taken when migrating from version 1 to version 2. - -In the future, if ***binding*** api evolves to fresh versions (3, 4, ...) -it might be necessarily to write bindings implementing more than -just one version. -For example: - -- a ***binding*** being v2 AND v3 will resolve the issue of running on older and newer version of AGL. - -This should always be possible even if more complicated. - -Important things to known when migrating ----------------------------------------- - -One of the most important change when migrating from v1 to v2 is -that many functions use an hidden *common* variable. -This affects the functions of the following classes: - -- functions of class **daemon**: - - functions starting with **afb_daemon_...** - - functions for logging: **ERROR**, **WARNING**, **NOTICE**, **INFO**, **DEBUG** -- functions of class **service**: - - functions starting with **afb_service_...** -- callback functions: - - the register function (that is removed) - - the service init function - - the onevent function - -For these functions, the first parameter is now implicit. - -Let takes an example. -For ***binding*** v1 you had to write: - -```C - afb_daemon_broadcast_event(afbitf->daemon, reason, description); -``` - -For ***binding*** v2, you simply write: - -```C - afb_daemon_broadcast_event(reason, description); -``` - -This simplification is possible because the header files included for the bindings -now provide a common variable for storing the **daemon** and **service** data. - -As a programmer, you shouldn't care much about that hidden variable. -It simplifies the job, that's all and that is the reason of the change. - -An other important difference is between the version 1 and the version 2 is -on how the ***binding***'s **API** is documented. -The version 2 emphasis the **OpenAPI v3** description of the **API**. -For this reason, to avoid duplication of descriptions, only one description is expected: - -- The **OpenAPI** one. - -Task list for the migration ---------------------------- - -This task list is: - -1. Enforce use of binding v2 by setting **AFB_BINDING_VERSION** -2. Rewrite the main structure and the list of exported verbs -3. Adapt the init and callback functions -4. Removes the first parameter of functions of classes **daemon** and **service** -5. Consider where to emit logs for requests -6. Take care of store/unstore changes -7. Consider use of synchronous (sub)call requests -8. Optionally, removes explicit struct - -The remaining chapters explain these task with more details. - -Enforce use of binding v2 by setting AFB_BINDING_VERSION --------------------------------------------------------- - -By defining **AFB_BINDING_VERSION** to **2** you switch to version 2. -This is done as below. - -```C -#define AFB_BINDING_VERSION 2 -#include -``` - -After that you will get many errors when compiling. - -Rewrite the main structures and the list of exported verbs ---------------------------------------------------------- - -The structures describing the ***binding** changed from version 1 to version 2. - -The structure for describing verbs changed to include security -requirements. - -In version 1 it was: - -```C -struct afb_verb_desc_v1 -{ - const char *name; /* name of the verb */ - enum afb_session_flags_v1 session; /* authorization and session requirements of the verb */ - void (*callback)(struct afb_req req); /* callback function implementing the verb */ - const char *info; /* textual description of the verb */ -}; -``` - -In version 2 it becomes: - -```C -struct afb_verb_v2 -{ - const char *verb; /* name of the verb */ - void (*callback)(struct afb_req req); /* callback function implementing the verb */ - const struct afb_auth *auth; /* required authorization */ - uint32_t session; /* authorization and session requirements of the verb */ -}; - -``` - -The migration of instances of that structure requires the following actions: - -- rename field **name** to **verb** -- remove field **info** -- adapt field **session** if needed -- set field **auth** to NULL - -Example: - -```C - { .name= "new", .session= AFB_SESSION_NONE, .callback= new, .info= "Starts a new game" } -``` - -Becomes - -```C - { .verb = "new", .session = AFB_SESSION_NONE, .callback = new, .auth = NULL } -``` - -The field **auth** can be set to a value describing the requested -authorization. - -The main describing structure also changed. - -In version 1 it was: - -```C -struct afb_binding_desc_v1 -{ - const char *info; /* textual information about the binding */ - const char *prefix; /* required prefix name for the binding */ - const struct afb_verb_desc_v1 *verbs; /* array of descriptions of verbs terminated by a NULL name */ -}; -``` - -In version 2 it becomes: - -```C -struct afb_binding_v2 -{ - const char *api; /* api name for the binding */ - const char *specification; /* textual specification of the binding */ - const struct afb_verb_v2 *verbs; /* array of descriptions of verbs terminated by a NULL name */ - int (*preinit)(); /* callback at load of the binding */ - int (*init)(); /* callback for starting the service */ - void (*onevent)(const char *event, struct json_object *object); /* callback for handling events */ - unsigned noconcurrency: 1; /* avoids concurrent requests to verbs */ -}; -``` - -The migration of instances of that structure requires the following actions: - -- declare, explore, name the structure as ```const struct afb_binding_v2 afbBindingV2``` -- rename the field **prefix** to **api** -- remove the field **info** -- setup the fields **preinit**, **init**, **onevent** according to the next section -- set the field **noconcurrency** to the right value: - - to 1 if you want to avoid concurrent calls to verbs. - - to 0 if you allow concurrent calls to verbs. - -Example: - -```C -static const struct afb_binding plugin_desc = { - .type = AFB_BINDING_VERSION_1, - .v1 = { - .info = "Minimal Hello World Sample", - .prefix = "hello", - .verbs = verbs - } -``` - -Becomes: - -```C -const struct afb_binding_v2 afbBindingV2 = { - .api = "hello", - .specification = NULL, - .verbs = verbs, - .preinit = preinit, - .init = init -}; -``` - -The **binder** now relies only on the exported names -to deduce the type of the binding. -This make the main structure more simple. - -Adapt the init and callback functions -------------------------------------- - -The ***bindings*** version 1 defined 3 exported functions: - -- **afbBindingV1Register** -- **afbBindingV1ServiceInit** -- **afbBindingV1ServiceEvent** - -These function should not be exported any more and there definition changed. - -The function **afbBindingV1Register** is no more used to describe the binding. -When a binding has to take actions when it is loaded, it must set the field -**preinit** of the structure **afbBindingV2**. -This field, this preinit, might be used to check features at load. -When it returns a negative number, the ***binder*** stops before initializing any ***binding***. - -The function **afbBindingV1ServiceInit** is replaced by the field **init** -of the structure **afbBindingV2**. -The init function should return 0 in case of success or a negative error code -in case of problem. -It is called during initialization of services. - -The function **afbBindingV1ServiceEvent**is replaced by the field **onevent** -of the structure **afbBindingV2**. - -The two functions **afbBindingV1Register** and **afbBindingV1ServiceInit**, -were taking as parameter the ***binder*** interface and the service interface respectively. -These interfaces are now managed hiddenly for the **binding** by the **binder**. -So the variable that ***bindings*** version used to store the ***binder*** interface -and the service interface are no more needed and can be removed. - -Example: - -```C -const struct afb_binding_interface *interface; -struct afb_service service; - -static const struct afb_binding plugin_desc = { - .type = AFB_BINDING_VERSION_1, - .v1 = { - .info = "Minimal Hello World Sample", - .prefix = "hello", - .verbs = verbs - } -} - -const struct afb_binding *afbBindingV1Register (const struct afb_binding_interface *itf) -{ - interface = itf; - NOTICE(interface, "binding register"); - return &plugin_desc; -} - -int afbBindingV1ServiceInit(struct afb_service svc) -{ - service = svc; - NOTICE(interface, "binding init"); - return 0; -} - -void afbBindingV1ServiceEvent(const char *event, struct json_object *object) -{ - NOTICE(interface, "onevent %s", event); -} -``` - -Becomes: - -```C -static int preinit() -{ - AFB_NOTICE("binding preinit (was register)"); - return 0; -} - -static int init() -{ - AFB_NOTICE("binding init"); - return 0; -} - -static void onevent(const char *event, struct json_object *object) -{ - AFB_NOTICE("onevent %s", event); -} - -const struct afb_binding_v2 afbBindingV2 = { - .api = "hello", - .specification = NULL, - .verbs = verbs, - .preinit = preinit, - .init = init, - .onevent = onevent -}; -``` - -The two functions **afbBindingV1Register** and **afbBindingV1ServiceInit**, -were taking as parameter the ***binder*** interface and the service interface respectively. -These interfaces are now managed hiddenly for the **binding** by the **binder**. -So the variable that ***bindings*** version used to store the ***binder*** interface -and the service interface are no more needed and can be removed. - -On the above example the following lines were removed: - -```C -const struct afb_binding_interface *interface; -struct afb_service service; - - interface = itf; - - service = svc; -``` - -Removes the first parameter of functions of classes **daemon** and **service** ------------------------------------------------------------------------------- - -As explained before, many functions loose there first -arguments, this are the functions of the following classes: - -- functions of class **daemon**: - - functions starting with **afb_daemon_...** - - functions for logging: **ERROR**, **WARNING**, **NOTICE**, **INFO**, **DEBUG** -- functions of class **service**: - - functions starting with **afb_service_...** -- callback functions: - - the register function (that is removed) - - the service init function - - the onevent function - -For these functions, the first parameter is now implicit. - -Example: - -```C - afb_daemon_broadcast_event(afbitf->daemon, reason, description); -``` - -Becomes: - -```C - afb_daemon_broadcast_event(reason, description); -``` - -Also, to avoid possible conflicts, we introduced prefixed logging functions: -the macros - -- **ERROR** -- **WARNING** -- **NOTICE** -- **INFO** -- **DEBUG** - -have now a prefixed version: - -- **AFB\_ERROR** -- **AFB\_WARNING** -- **AFB\_NOTICE** -- **AFB\_INFO** -- **AFB\_DEBUG** - -It is now recommended to use the prefixed version. - -Example: - -```C - NOTICE(interface, "hello plugin comes to live"); -``` - -Become: - -```C - NOTICE("hello plugin comes to live"); -``` - -or, better: - -```C - AFB_NOTICE("hello plugin comes to live"); -``` - -To remove definition of the un-prefixed versions of logging macros: - -- **ERROR** -- **WARNING** -- **NOTICE** -- **INFO** -- **DEBUG** - -and just define - -- **AFB_BINDING_PRAGMA_NO_VERBOSE_UNPREFIX** - -before to include **afb/afb-binding.h**. - -```C -#define AFB_BINDING_PRAGMA_NO_VERBOSE_UNPREFIX -#define AFB_BINDING_VERSION 2 -#include -``` - -Consider where to emit logs for requests ----------------------------------------- - -The ***bindings*** v2 now allows to emit log messages associated to ***requests***. -This feature is valuable when debugging because it allows to return -side information associated to a ***request***. - -The defined macros for logging to requests are: - -- **AFB_REQ_ERROR** -- **AFB_REQ_WARNING** -- **AFB_REQ_NOTICE** -- **AFB_REQ_INFO** -- **AFB_REQ_DEBUG** - -We encourage the use of these new logging facilities everywhere it makes sense. - -Example: - -```C - INFO(afbitf, "method 'new' called for boardid %d", board->id); -``` - -Might become: - -```C - AFB_REQ_INFO(req, "method 'new' called for boardid %d", board->id); -``` - -Take care of store/unstore change ---------------------------------- - -For efficiency, the version 2 redefined how storing/un-storing of -requests works. -Storing request is needed for asynchronous handling of requests. - -For ***bindings*** version, the signature of the functions were: - -```C -struct afb_req *afb_req_store(struct afb_req req); -struct afb_req afb_req_unstore(struct afb_req *req); -``` - -For version 2 it becomes - -```C -struct afb_stored_req *afb_req_store(struct afb_req req); -struct afb_req afb_req_unstore(struct afb_stored_req *sreq); -``` - -Where the structure ```struct afb_stored_req``` is opaque. - -It should require few code change. - -Also check the following chapter that explain that asynchronous (sub)calls -can be replaced by synchronous one, avoiding the need to store/unstore -requests. - -Consider use of synchronous (sub)call requests ----------------------------------------------- - -***Bindings*** can emit requests for themselves (calls) or for -their clients (subcalls). -With ***bindings*** version 2 comes also synchronous requests for both cases. - -So when migrating to bindings version 2, a developer can consider -to replace the asynchronous requests (with asynchronous call back) -by synchronous ones. - -See functions ***afb_service_call_sync*** and ***afb_req_subcall_sync***. - -Optionally, removes explicit struct ------------------------------------ - -The new definitions now includes **typedefs** for common -structures, as shown on below sample: - -```C -typedef struct afb_daemon afb_daemon; -typedef struct afb_event afb_event; -typedef struct afb_arg afb_arg; -typedef struct afb_req afb_req; -typedef struct afb_service afb_service; -``` - -So you can remove the keyword **struct** if it bores you. - -Example: - -```C -static void verb(struct afb_req req) -{ - ... -} -``` - -Might become: - -```C -static void verb(afb_req req) -{ - ... -} -``` - -Example of migration --------------------- - -The first ***binding*** that migrated from v1 to v2 was the sample **HelloWorld**. -Here is shown the differences between the version 1 and the version 2. - -```diff -diff --git a/bindings/samples/HelloWorld.c b/bindings/samples/HelloWorld.c -index c6fa779..505aee3 100644 ---- a/bindings/samples/HelloWorld.c -+++ b/bindings/samples/HelloWorld.c -@@ -21,9 +21,9 @@ - - #include - -+#define AFB_BINDING_VERSION 2 - #include - --const struct afb_binding_interface *interface; - static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; - - struct event -@@ -79,7 +80,7 @@ static int event_add(const char *tag, const char *name) - strcpy(e->tag, tag); - - /* make the event */ -- e->event = afb_daemon_make_event(interface->daemon, name); -+ e->event = afb_daemon_make_event(name); - if (!e->event.closure) { free(e); return -1; } - - /* link */ -@@ -140,7 +141,7 @@ static void pingBug (struct afb_req request) - static void pingEvent(struct afb_req request) - { - json_object *query = afb_req_json(request); -- afb_daemon_broadcast_event(interface->daemon, "event", json_object_get(query)); -+ afb_daemon_broadcast_event("event", json_object_get(query)); - ping(request, json_object_get(query), "event"); - } - -@@ -288,38 +289,43 @@ static void exitnow (struct afb_req request) - exit(0); - } - -+static int preinit() -+{ -+ AFB_NOTICE("hello binding comes to live"); -+ return 0; -+} -+ -+static int init() -+{ -+ AFB_NOTICE("hello binding starting"); -+ return 0; -+} -+ - // NOTE: this sample does not use session to keep test a basic as possible - // in real application most APIs should be protected with AFB_SESSION_CHECK --static const struct afb_verb_desc_v1 verbs[]= { -- {"ping" , AFB_SESSION_NONE, pingSample , "Ping Application Framework"}, -- {"pingfail" , AFB_SESSION_NONE, pingFail , "Fails"}, -- {"pingnull" , AFB_SESSION_NONE, pingNull , "Return NULL"}, -- {"pingbug" , AFB_SESSION_NONE, pingBug , "Do a Memory Violation"}, -- {"pingJson" , AFB_SESSION_NONE, pingJson , "Return a JSON object"}, -- {"pingevent", AFB_SESSION_NONE, pingEvent , "Send an event"}, -- {"subcall", AFB_SESSION_NONE, subcall , "Call api/verb(args)"}, -- {"subcallsync", AFB_SESSION_NONE, subcallsync , "Call api/verb(args)"}, -- {"eventadd", AFB_SESSION_NONE, eventadd , "adds the event of 'name' for the 'tag'"}, -- {"eventdel", AFB_SESSION_NONE, eventdel , "deletes the event of 'tag'"}, -- {"eventsub", AFB_SESSION_NONE, eventsub , "subscribes to the event of 'tag'"}, -- {"eventunsub",AFB_SESSION_NONE, eventunsub , "unsubscribes to the event of 'tag'"}, -- {"eventpush", AFB_SESSION_NONE, eventpush , "pushs the event of 'tag' with the 'data'"}, -- {"exit", AFB_SESSION_NONE, exitnow , "exits from afb-daemon"}, -- {NULL} -+static const struct afb_verb_v2 verbs[]= { -+ { "ping" , pingSample , NULL, AFB_SESSION_NONE }, -+ { "pingfail" , pingFail , NULL, AFB_SESSION_NONE }, -+ { "pingnull" , pingNull , NULL, AFB_SESSION_NONE }, -+ { "pingbug" , pingBug , NULL, AFB_SESSION_NONE }, -+ { "pingJson" , pingJson , NULL, AFB_SESSION_NONE }, -+ { "pingevent", pingEvent , NULL, AFB_SESSION_NONE }, -+ { "subcall", subcall , NULL, AFB_SESSION_NONE }, -+ { "subcallsync", subcallsync, NULL, AFB_SESSION_NONE }, -+ { "eventadd", eventadd , NULL, AFB_SESSION_NONE }, -+ { "eventdel", eventdel , NULL, AFB_SESSION_NONE }, -+ { "eventsub", eventsub , NULL, AFB_SESSION_NONE }, -+ { "eventunsub", eventunsub , NULL, AFB_SESSION_NONE }, -+ { "eventpush", eventpush , NULL, AFB_SESSION_NONE }, -+ { "exit", exitnow , NULL, AFB_SESSION_NONE }, -+ { NULL} - }; - --static const struct afb_binding plugin_desc = { -- .type = AFB_BINDING_VERSION_1, -- .v1 = { -- .info = "Minimal Hello World Sample", -- .prefix = "hello", -- .verbs = verbs -- } -+const struct afb_binding_v2 afbBindingV2 = { -+ .api = "hello", -+ .specification = NULL, -+ .verbs = verbs, -+ .preinit = preinit, -+ .init = init - }; - --const struct afb_binding *afbBindingV1Register (const struct afb_binding_interface *itf) --{ -- interface = itf; -- NOTICE(interface, "hello plugin comes to live"); -- return &plugin_desc; --} -``` \ No newline at end of file diff --git a/docs/3_Developer_Guides/2_Application_Framework_Binder/Annexes/7_LEGACY_Binding_v2_references.md b/docs/3_Developer_Guides/2_Application_Framework_Binder/Annexes/7_LEGACY_Binding_v2_references.md deleted file mode 100644 index c790db8..0000000 --- a/docs/3_Developer_Guides/2_Application_Framework_Binder/Annexes/7_LEGACY_Binding_v2_references.md +++ /dev/null @@ -1,757 +0,0 @@ ---- -title: LEGACY Binding V2 references ---- - -# Structure for declaring binding ---------------------------------- - -### struct afb_binding_v2 - -The main structure, of type **afb_binding_v2**, for describing the binding -must be exported under the name **afbBindingV2**. - -This structure is defined as below. - -```C -/* - * Description of the bindings of type version 2 - */ -struct afb_binding_v2 -{ - const char *api; /* api name for the binding */ - const char *specification; /* textual openAPIv3 specification of the binding */ - const char *info; /* some info about the api, can be NULL */ - const struct afb_verb_v2 *verbs; /* array of descriptions of verbs terminated by a NULL name */ - int (*preinit)(); /* callback at load of the binding */ - int (*init)(); /* callback for starting the service */ - void (*onevent)(const char *event, struct json_object *object); /* callback for handling events */ - unsigned noconcurrency: 1; /* avoids concurrent requests to verbs */ -}; -``` - -### struct afb_verb_v2 - -Each verb is described with a structure of type **afb_verb_v2** -defined below: - -```C -/* - * Description of one verb of the API provided by the binding - * This enumeration is valid for bindings of type version 2 - */ -struct afb_verb_v2 -{ - const char *verb; /* name of the verb */ - void (*callback)(struct afb_req req); /* callback function implementing the verb */ - const struct afb_auth *auth; /* required authorization */ - const char *info; /* some info about the verb, can be NULL */ - uint32_t session; /* authorization and session requirements of the verb */ -}; -``` - -The **session** flags is one of the constant defined below: - -- AFB_SESSION_NONE : no flag, synonym to 0 -- AFB_SESSION_LOA_0 : Requires the LOA to be 0 or more, synonym to 0 or AFB_SESSION_NONE -- AFB_SESSION_LOA_1 : Requires the LOA to be 1 or more -- AFB_SESSION_LOA_2 : Requires the LOA to be 2 or more -- AFB_SESSION_LOA_3 : Requires the LOA to be 3 or more -- AFB_SESSION_CHECK : Requires the token to be set and valid -- AFB_SESSION_REFRESH : Implies a token refresh -- AFB_SESSION_CLOSE : Implies cloing the session - -The LOA (Level Of Assurance) is set, by binding, using the function **afb_req_session_set_LOA**. - -### struct afb_auth and enum afb_auth_type - -The structure **afb_auth** is used within verb description to -set security requirements. -The interpretation of the structure depends on the value of the field **type**. - -```C -struct afb_auth -{ - const enum afb_auth_type type; - union { - const char *text; - const unsigned loa; - const struct afb_auth *first; - }; - const struct afb_auth *next; -}; -``` - -The possible values for **type** is defined here: - -```C -/* - * Enum for Session/Token/Assurance middleware. - */ -enum afb_auth_type -{ - afb_auth_No = 0, /** never authorized, no data */ - afb_auth_Token, /** authorized if token valid, no data */ - afb_auth_LOA, /** authorized if LOA greater than data 'loa' */ - afb_auth_Permission, /** authorized if permission 'text' is granted */ - afb_auth_Or, /** authorized if 'first' or 'next' is authorized */ - afb_auth_And, /** authorized if 'first' and 'next' are authorized */ - afb_auth_Not, /** authorized if 'first' is not authorized */ - afb_auth_Yes /** always authorized, no data */ -}; -``` - -Example: - -```C -static const struct afb_auth _afb_auths_v2_monitor[] = { - { .type = afb_auth_Permission, .text = "urn:AGL:permission:monitor:public:set" }, - { .type = afb_auth_Permission, .text = "urn:AGL:permission:monitor:public:get" }, - { .type = afb_auth_Or, .first = &_afb_auths_v2_monitor[1], .next = &_afb_auths_v2_monitor[0] } -}; -``` - -## Functions of class afb_daemon - -The 3 following functions are linked to libsystemd. -They allow use of **sd_event** features and access -to **sd_bus** features. - -```C -/* - * Retrieves the common systemd's event loop of AFB - */ -struct sd_event *afb_daemon_get_event_loop(); - -/* - * Retrieves the common systemd's user/session d-bus of AFB - */ -struct sd_bus *afb_daemon_get_user_bus(); - -/* - * Retrieves the common systemd's system d-bus of AFB - */ -struct sd_bus *afb_daemon_get_system_bus(); -``` - -The 2 following functions are linked to event management. -Broadcasting an event send it to any possible listener. - -```C -/* - * Broadcasts widely the event of 'name' with the data 'object'. - * 'object' can be NULL. - * - * 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. - * - * Calling this function is only forbidden during preinit. - * - * Returns the count of clients that received the event. - */ -int afb_daemon_broadcast_event(const char *name, struct json_object *object); - -/* - * Creates an event of 'name' and returns it. - * - * Calling this function is only forbidden during preinit. - * - * See afb_event_is_valid to check if there is an error. - */ -struct afb_event afb_daemon_make_event(const char *name); -``` - -The following function is used by logging macros and should normally -not be used. -Instead, you should use the macros: - -- **AFB\_ERROR** -- **AFB\_WARNING** -- **AFB\_NOTICE** -- **AFB\_INFO** -- **AFB\_DEBUG** - -```C -/* - * Send a message described by 'fmt' and following parameters - * to the journal for the verbosity 'level'. - * - * 'file', 'line' and 'func' are indicators of position of the code in source files - * (see macros __FILE__, __LINE__ and __func__). - * - * 'level' is defined by syslog standard: - * EMERGENCY 0 System is unusable - * ALERT 1 Action must be taken immediately - * CRITICAL 2 Critical conditions - * ERROR 3 Error conditions - * WARNING 4 Warning conditions - * NOTICE 5 Normal but significant condition - * INFO 6 Informational - * DEBUG 7 Debug-level messages - */ -void afb_daemon_verbose(int level, const char *file, int line, const char * func, const char *fmt, ...); -``` - -The 2 following functions MUST be used to access data of the bindings. - -```C -/* - * Get the root directory file descriptor. This file descriptor can - * be used with functions 'openat', 'fstatat', ... - */ -int afb_daemon_rootdir_get_fd(); - -/* - * Opens 'filename' within the root directory with 'flags' (see function openat) - * using the 'locale' definition (example: "jp,en-US") that can be NULL. - * Returns the file descriptor or -1 in case of error. - */ -int afb_daemon_rootdir_open_locale(const char *filename, int flags, const char *locale); -``` - -The following function is used to queue jobs. - -```C -/* - * Queue the job defined by 'callback' and 'argument' for being executed asynchronously - * in this thread (later) or in an other thread. - * If 'group' is not NUL, the jobs queued with a same value (as the pointer value 'group') - * are executed in sequence in the order of there submission. - * If 'timeout' is not 0, it represent the maximum execution time for the job in seconds. - * At first, the job is called with 0 as signum and the given argument. - * The job is executed with the monitoring of its time and some signals like SIGSEGV and - * SIGFPE. When a such signal is catched, the job is terminated and re-executed but with - * signum being the signal number (SIGALRM when timeout expired). - * - * Returns 0 in case of success or -1 in case of error. - */ -int afb_daemon_queue_job(void (*callback)(int signum, void *arg), void *argument, void *group, int timeout) -``` - -The following function must be used when a binding depends on other -bindings at its initialization. - -```C -/* - * Tells that it requires the API of "name" to exist - * and if 'initialized' is not null to be initialized. - * Calling this function is only allowed within init. - * Returns 0 in case of success or -1 in case of error. - */ -int afb_daemon_require_api(const char *name, int initialized) -``` - -This function allows to give a different name to the binding. -It can be called during pre-init. - -```C -/* - * Set the name of the API to 'name'. - * Calling this function is only allowed within preinit. - * Returns 0 in case of success or -1 in case of error. - */ -int afb_daemon_rename_api(const char *name); -``` - -## Functions of class afb_service - -The following functions allow services to call verbs of other -bindings for themselves. - -```C -/** - * Calls the 'verb' of the 'api' with the arguments 'args' and 'verb' in the name of the binding. - * The result of the call is delivered to the 'callback' function with the 'callback_closure'. - * - * For convenience, the function calls 'json_object_put' for 'args'. - * Thus, in the case where 'args' should remain available after - * the function returns, the function 'json_object_get' shall be used. - * - * The 'callback' receives 3 arguments: - * 1. 'closure' the user defined closure pointer 'callback_closure', - * 2. 'status' a status being 0 on success or negative when an error occurred, - * 2. 'result' the resulting data as a JSON object. - * - * @param api The api name of the method to call - * @param verb The verb name of the method to call - * @param args The arguments to pass to the method - * @param callback The to call on completion - * @param callback_closure The closure to pass to the callback - * - * @see also 'afb_req_subcall' - */ -void afb_service_call( - const char *api, - const char *verb, - struct json_object *args, - void (*callback)(void*closure, int status, struct json_object *result), - void *callback_closure); - -/** - * Calls the 'verb' of the 'api' with the arguments 'args' and 'verb' in the name of the binding. - * 'result' will receive the response. - * - * For convenience, the function calls 'json_object_put' for 'args'. - * Thus, in the case where 'args' should remain available after - * the function returns, the function 'json_object_get' shall be used. - * - * @param api The api name of the method to call - * @param verb The verb name of the method to call - * @param args The arguments to pass to the method - * @param result Where to store the result - should call json_object_put on it - - * - * @returns 0 in case of success or a negative value in case of error. - * - * @see also 'afb_req_subcall' - */ -int afb_service_call_sync( - const char *api, - const char *verb, - struct json_object *args, - struct json_object **result); -``` - -## Functions of class afb_event - -This function checks whether the event is valid. -It must be used when creating events. - -```C -/* - * Checks wether the 'event' is valid or not. - * - * Returns 0 if not valid or 1 if valid. - */ -int afb_event_is_valid(struct afb_event event); -``` - -The two following functions are used to broadcast or push -event with its data. - -```C -/* - * Broadcasts widely the 'event' with the data 'object'. - * 'object' can be NULL. - * - * 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. - * - * Returns the count of clients that received the event. - */ -int afb_event_broadcast(struct afb_event event, struct json_object *object); - -/* - * Pushes the 'event' with the data 'object' to its observers. - * 'object' can be NULL. - * - * 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. - * - * Returns the count of clients that received the event. - */ -int afb_event_push(struct afb_event event, struct json_object *object); -``` - -The following function destroys the event. - -```C -/* - * Drops the data associated to the 'event' - * After calling this function, the event - * MUST NOT BE USED ANYMORE. - */ -void afb_event_drop(struct afb_event event); -``` - -This function allows to retrieve the exact name of the event. - -```C -/* - * Gets the name associated to the 'event'. - */ -const char *afb_event_name(struct afb_event event); -``` - -## Functions of class afb_req - -This function checks the validity of the **req**. - -```C -/* - * Checks wether the request 'req' is valid or not. - * - * Returns 0 if not valid or 1 if valid. - */ -int afb_req_is_valid(struct afb_req req); -``` - -The following functions retrieves parameters of the request. - -```C -/* - * 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); - -/* - * 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 - */ -const char *afb_req_value(struct afb_req req, const char *name); - -/* - * 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 - */ -const char *afb_req_path(struct afb_req req, const char *name); - -/* - * 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); -``` - -The following functions emit the reply to the request. - -```C -/* - * 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 - * informational 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, ...); - -/* - * Same as 'afb_req_success_f' but the arguments to the format 'info' - * are given as a variable argument list instance. - * - * 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_v(struct afb_req req, struct json_object *obj, const char *info, va_list args); - -/* - * 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. - */ -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. - */ -void afb_req_fail_f(struct afb_req req, const char *status, const char *info, ...); - -/* - * Same as 'afb_req_fail_f' but the arguments to the format 'info' - * are given as a variable argument list instance. - */ -void afb_req_fail_v(struct afb_req req, const char *status, const char *info, va_list args); -``` - -The following functions handle the session data. - -```C -/* - * 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*)); - -/* - * 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'. - */ -void *afb_req_context(struct afb_req req, void *(*create_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) - */ -void afb_req_context_clear(struct afb_req req); - -/* - * Closes the session associated with 'req' - * and delete all associated contexts. - */ -void afb_req_session_close(struct afb_req req); - -/* - * Sets the level of assurance of the session of 'req' - * to 'level'. The effect of this function is subject of - * security policies. - * Returns 1 on success or 0 if failed. - */ -int afb_req_session_set_LOA(struct afb_req req, unsigned level); -``` - -The 4 following functions must be used for asynchronous handling requests. - -```C -/* - * Adds one to the count of references of 'req'. - * This function MUST be called by asynchronous implementations - * of verbs if no reply was sent before returning. - */ -void afb_req_addref(struct afb_req req); - -/* - * Substracts one to the count of references of 'req'. - * This function MUST be called by asynchronous implementations - * of verbs after sending the asynchronous reply. - */ -void afb_req_unref(struct afb_req req); - -/* - * Stores 'req' on heap for asynchronous use. - * Returns a handler to the stored 'req' or NULL on memory depletion. - * The count of reference to 'req' is incremented on success - * (see afb_req_addref). - */ -struct afb_stored_req *afb_req_store(struct afb_req req); - -/* - * Retrieves the afb_req stored at 'sreq'. - * Returns the stored request. - * The count of reference is UNCHANGED, thus, the - * function 'afb_req_unref' should be called on the result - * after that the asynchronous reply if sent. - */ -struct afb_req afb_req_unstore(struct afb_stored_req *sreq); -``` - -The two following functions are used to associate client with events -(subscription). - -```C -/* - * Establishes for the client link identified by 'req' a subscription - * to the 'event'. - * Returns 0 in case of successful subscription or -1 in case of error. - */ -int afb_req_subscribe(struct afb_req req, struct afb_event event); - -/* - * Revokes the subscription established to the 'event' for the client - * link identified by 'req'. - * Returns 0 in case of successful subscription or -1 in case of error. - */ -int afb_req_unsubscribe(struct afb_req req, struct afb_event event); -``` - -The following functions must be used to make request in the name of the -client (with its permissions). - -```C -/* - * Makes a call to the method of name 'api' / 'verb' with the object 'args'. - * This call is made in the context of the request 'req'. - * On completion, the function 'callback' is invoked with the - * 'closure' given at call and two other parameters: 'iserror' and 'result'. - * 'status' is 0 on success or negative when on an error reply. - * 'result' is the json object of the reply, you must not call json_object_put - * on the result. - * - * For convenience, the function calls 'json_object_put' for 'args'. - * Thus, in the case where 'args' should remain available after - * the function returns, the function 'json_object_get' shall be used. - * - * See also: - * - 'afb_req_subcall_req' that is convenient to keep request alive automatically. - * - 'afb_req_subcall_sync' the synchronous version - */ -void afb_req_subcall( - struct afb_req req, - const char *api, - const char *verb, - struct json_object *args, - void (*callback)(void *closure, int status, struct json_object *result), - void *closure); - -/* - * Makes a call to the method of name 'api' / 'verb' with the object 'args'. - * This call is made in the context of the request 'req'. - * On completion, the function 'callback' is invoked with the - * original request 'req', the 'closure' given at call and two - * other parameters: 'iserror' and 'result'. - * 'status' is 0 on success or negative when on an error reply. - * 'result' is the json object of the reply, you must not call json_object_put - * on the result. - * - * For convenience, the function calls 'json_object_put' for 'args'. - * Thus, in the case where 'args' should remain available after - * the function returns, the function 'json_object_get' shall be used. - * - * See also: - * - 'afb_req_subcall' that doesn't keep request alive automatically. - * - 'afb_req_subcall_sync' the synchronous version - */ -static inline void afb_req_subcall_req(struct afb_req req, const char *api, const char *verb, struct json_object *args, void (*callback)(void *closure, int iserror, struct json_object *result, struct afb_req req), void *closure) -{ - req.itf->subcall_req(req.closure, api, verb, args, callback, closure); -} - -/* - * Makes a call to the method of name 'api' / 'verb' with the object 'args'. - * This call is made in the context of the request 'req'. - * This call is synchronous, it waits until completion of the request. - * It returns 0 on success or a negative value on error answer. - * The object pointed by 'result' is filled and must be released by the caller - * after its use by calling 'json_object_put'. - * - * For convenience, the function calls 'json_object_put' for 'args'. - * Thus, in the case where 'args' should remain available after - * the function returns, the function 'json_object_get' shall be used. - * - * See also: - * - 'afb_req_subcall_req' that is convenient to keep request alive automatically. - * - 'afb_req_subcall' that doesn't keep request alive automatically. - */ -int afb_req_subcall_sync( - struct afb_req req, - const char *api, - const char *verb, - struct json_object *args, - struct json_object **result); -``` - -The following function is used by logging macros and should normally -not be used. -Instead, you should use the macros: - -- **AFB_REQ_ERROR** -- **AFB_REQ_WARNING** -- **AFB_REQ_NOTICE** -- **AFB_REQ_INFO** -- **AFB_REQ_DEBUG** - -```C -/* - * Send associated to 'req' a message described by 'fmt' and following parameters - * to the journal for the verbosity 'level'. - * - * 'file', 'line' and 'func' are indicators of position of the code in source files - * (see macros __FILE__, __LINE__ and __func__). - * - * 'level' is defined by syslog standard: - * EMERGENCY 0 System is unusable - * ALERT 1 Action must be taken immediately - * CRITICAL 2 Critical conditions - * ERROR 3 Error conditions - * WARNING 4 Warning conditions - * NOTICE 5 Normal but significant condition - * INFO 6 Informational - * DEBUG 7 Debug-level messages - */ -void afb_req_verbose(struct afb_req req, int level, const char *file, int line, const char * func, const char *fmt, ...); -``` - -The functions below allow a binding involved in the platform security -to explicitly check a permission of a client or to get the calling -application identity. - -```C -/* - * Check whether the 'permission' is granted or not to the client - * identified by 'req'. - * - * Returns 1 if the permission is granted or 0 otherwise. - */ -int afb_req_has_permission(struct afb_req req, const char *permission); - -/* - * Get the application identifier of the client application for the - * request 'req'. - * - * Returns the application identifier or NULL when the application - * can not be identified. - * - * The returned value if not NULL must be freed by the caller - */ -char *afb_req_get_application_id(struct afb_req req); - -/* - * Get the user identifier (UID) of the client application for the - * request 'req'. - * - * Returns -1 when the application can not be identified. - */ -int afb_req_get_uid(struct afb_req req); -``` - -## Logging macros - -The following macros must be used for logging: - -```C -AFB_ERROR(fmt,...) -AFB_WARNING(fmt,...) -AFB_NOTICE(fmt,...) -AFB_INFO(fmt,...) -AFB_DEBUG(fmt,...) -``` - -The following macros can be used for logging in the context -of a request **req** of type **afb_req**: - -```C -AFB_REQ_ERROR(req,fmt,...) -AFB_REQ_WARNING(req,fmt,...) -AFB_REQ_NOTICE(req,fmt,...) -AFB_REQ_INFO(req,fmt,...) -AFB_REQ_DEBUG(req,fmt,...) -``` - -By default, the logging macros add file, line and function -indication. \ No newline at end of file diff --git a/docs/3_Developer_Guides/2_Application_Framework_Binder/images/basis.svg b/docs/3_Developer_Guides/2_Application_Framework_Binder/images/basis.svg deleted file mode 100644 index 0d42d76..0000000 --- a/docs/3_Developer_Guides/2_Application_Framework_Binder/images/basis.svg +++ /dev/null @@ -1,356 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - APPLICATION - - - - - - - - BINDERafb-daemon - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - BINDING - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - BINDING - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - BINDING - - - - - - - - - - - - - - - - - - SECURITYCONTEXT - - - - - - http - - - - - - ws - - - - - - - - \ No newline at end of file diff --git a/docs/3_Developer_Guides/2_Application_Framework_Binder/images/interconnection.svg b/docs/3_Developer_Guides/2_Application_Framework_Binder/images/interconnection.svg deleted file mode 100644 index 4a10217..0000000 --- a/docs/3_Developer_Guides/2_Application_Framework_Binder/images/interconnection.svg +++ /dev/null @@ -1,854 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - APPLICATION - - - - - - - - BINDERafb-daemon - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - BINDING - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - BINDING - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - BINDING - - - - - - - - - - - - SECURITYCONTEXT - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - APPLICATION - - - - - - - - BINDERafb-daemon - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - BINDING - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - BINDING - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - BINDING - - - - - - - - - - - - SECURITYCONTEXT - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - APPLICATION - - - - - - - - BINDERafb-daemon - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - BINDING - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - BINDING - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - BINDING - - - - - - - - - - - - SECURITYCONTEXT - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - APPLICATION - - - - - - - - BINDERafb-daemon - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - BINDING - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - BINDING - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - BINDING - - - - - - - - - - - - SECURITYCONTEXT - - - - - - - - - interconnectiondbus, ws,bus1, tls,... - - - - - - - - A - - - - - - - - C - - - - - - - - B - - - - - - - - D - - - - - - - - \ No newline at end of file diff --git a/docs/3_Developer_Guides/2_Application_Framework_Binder/images/signaling-basis.svg b/docs/3_Developer_Guides/2_Application_Framework_Binder/images/signaling-basis.svg deleted file mode 100644 index b13fcf1..0000000 --- a/docs/3_Developer_Guides/2_Application_Framework_Binder/images/signaling-basis.svg +++ /dev/null @@ -1,145 +0,0 @@ - - - - - - - request-data - - - - - - client 1 - - - - - - - - client 2 - - - - - - - - : framework - - - - - - - - signaling agent - - - - - - - - - - - request-data - - - - - - afb_daemon_make_event - - - - - - - - - afb_req_subscribe - - - - - reply of request-data - - - - - - afb_req_subscribe - - - - - reply of request-data - - - - - - device - - - - - - - - - setup - - - - - << wake up >> - - - - - afb_event_push - - - - - << event >> - - - - - << event >> - - - - - reply of afb_event_push - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/docs/3_Developer_Guides/2_Creating_a_New_Service.md b/docs/3_Developer_Guides/2_Creating_a_New_Service.md index ce9a745..33a3fb5 100644 --- a/docs/3_Developer_Guides/2_Creating_a_New_Service.md +++ b/docs/3_Developer_Guides/2_Creating_a_New_Service.md @@ -2,509 +2,4 @@ title: Creating a New Service --- -This tutorial provides instructions on **Creating a New Service** from scratch. - -### 1. Create new project development directory - - ```sh - $ cd ~/agl-app - $ mkdir newservice/ - $ cd newservice/ - ``` - -### 2. Source the SDK environment setup - - ```sh - $ source ~/agl-app/agl-sdk/environment-setup-corei7-64-agl-linux - ``` - -### 3. Copy initial CMAKE configuration templates - - ```sh - $ mkdir -p conf.d/cmake - $ cp ${OECORE_NATIVE_SYSROOT}/usr/share/doc/CMakeAfbTemplates/samples.d/config.cmake.sample conf.d/cmake/config.cmake - $ cp ${OECORE_NATIVE_SYSROOT}/usr/share/doc/CMakeAfbTemplates/samples.d/CMakeLists.txt.sample CMakeLists.txt - ``` - -### 4. Edit CMAKE configuration template - - ```sh - $ vim ~/agl-app/newservice/conf.d/cmake/config.cmake - - ########################################################################### - # Copyright 2020 # INSERT YEAR - # - # author: John Doe # INSERT AUTHOR DETAILS - # - # Licensed under the Apache License, Version 2.0 (the "License"); - # you may not use this file except in compliance with the License. - # You may obtain a copy of the License at - # - # http://www.apache.org/licenses/LICENSE-2.0 - # - # Unless required by applicable law or agreed to in writing, software - # distributed under the License is distributed on an "AS IS" BASIS, - # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - # See the License for the specific language governing permissions and - # limitations under the License. - ########################################################################### - - # Project Info - # ------------------ - set(PROJECT_NAME hellocount) # INSERT NEW PROJECT NAME - set(API_NAME "hellocount") #INSERT NEW API NAME - set(PROJECT_PRETTY_NAME "Example") - set(PROJECT_DESCRIPTION "AGL hellocount application example") # INSERT CONCISE PROJECT DESCRIPTION - set(PROJECT_URL "https://gerrit.automotivelinux.org/gerrit/apps/cmake-apps-module") - set(PROJECT_ICON "icon.png") - set(PROJECT_AUTHOR "John Doe") # INSERT AUTHOR NAME - set(PROJECT_AUTHOR_MAIL "john.doe@example.com") # INSERT AUTHOR EMAIL - set(PROJECT_LICENSE "APL2.0") - set(PROJECT_LANGUAGES "C") - set(PROJECT_VERSION "1.0.0") # INSERT PROJECT VERSION - - # Which directories inspect to find CMakeLists.txt target files - # set(PROJECT_SRC_DIR_PATTERN "*") - - # Where are stored the project configuration files - # relative to the root project directory - set(PROJECT_CMAKE_CONF_DIR "conf.d/cmake") - - # Compilation Mode (DEBUG, RELEASE, COVERAGE or PROFILING) - # ---------------------------------- - set(BUILD_TYPE "RELEASE") # SELECT BUILD TYPE - #set(USE_EFENCE 1) - - # Kernel selection if needed. You can choose between a - # mandatory version to impose a minimal version. - # Or check Kernel minimal version and just print a Warning - # about missing features and define a preprocessor variable - # to be used as preprocessor condition in code to disable - # incompatibles features. Preprocessor define is named - # KERNEL_MINIMAL_VERSION_OK. - # - # NOTE*** FOR NOW IT CHECKS KERNEL Yocto environment and - # Yocto SDK Kernel version. - # ----------------------------------------------- - #set (kernel_mandatory_version 4.8) - #set (kernel_minimal_version 4.8) - - # Compiler selection if needed. Impose a minimal version. - # ----------------------------------------------- - set (gcc_minimal_version 4.9) - - # PKG_CONFIG required packages - # ----------------------------- - set (PKG_REQUIRED_LIST - json-c - afb-daemon - afb-helpers - ) - - # You can also consider to include libsystemd - # ----------------------------------- - #list (APPEND PKG_REQUIRED_LIST libsystemd>=222) - - if(IS_DIRECTORY $ENV{HOME}/opt/afb-monitoring) - set(MONITORING_ALIAS "--alias=/monitoring:$ENV{HOME}/opt/afb-monitoring") - endif() - - # Print a helper message when every thing is finished - # ---------------------------------------------------- - set(CLOSING_MESSAGE "Debug from afb-daemon --port=1234 ${MONITORING_ALIAS} --ldpaths=package --workdir=. --roothttp=../htdocs --token= --verbose ") - set(PACKAGE_MESSAGE "Install widget file using in the target : afm-util install ${PROJECT_NAME}.wgt") - - - - # Prefix path where will be installed the files - # Default: /usr/local (need root permission to write in) - # ------------------------------------------------------ - #set(INSTALL_PREFIX /opt/AGL CACHE PATH "INSTALL PREFIX PATH") - - # Customize link option - # ----------------------------- - #list(APPEND link_libraries -an-option) - - # Compilation options definition - # Use CMake generator expressions to specify only for a specific language - # Values are prefilled with default options that is currently used. - # Either separate options with ";", or each options must be quoted separately - # DO NOT PUT ALL OPTION QUOTED AT ONCE , COMPILATION COULD FAILED ! - # ---------------------------------------------------------------------------- - #set(COMPILE_OPTIONS - # -Wall - # -Wextra - # -Wconversion - # -Wno-unused-parameter - # -Wno-sign-compare - # -Wno-sign-conversion - # -Werror=maybe-uninitialized - # -Werror=implicit-function-declaration - # -ffunction-sections - # -fdata-sections - # -fPIC - # CACHE STRING "Compilation flags") - #set(C_COMPILE_OPTIONS "" CACHE STRING "Compilation flags for C language.") - #set(CXX_COMPILE_OPTIONS "" CACHE STRING "Compilation flags for C++ language.") - #set(PROFILING_COMPILE_OPTIONS - # -g - # -O0 - # -pg - # -Wp,-U_FORTIFY_SOURCE - # CACHE STRING "Compilation flags for PROFILING build type.") - #set(DEBUG_COMPILE_OPTIONS - # -g - # -ggdb - # CACHE STRING "Compilation flags for DEBUG build type.") - #set(COVERAGE_COMPILE_OPTIONS - # -g - # -O0 - # --coverage - # CACHE STRING "Compilation flags for COVERAGE build type.") - #set(RELEASE_COMPILE_OPTIONS - # -O2 - # -pipe - # -D_FORTIFY_SOURCE=2 - # -fstack-protector-strong - # -Wformat -Wformat-security - # -Werror=format-security - # -feliminate-unused-debug-types - # -Wl,-O1 - # -Wl,--hash-style=gnu - # -Wl,--as-needed - # -fstack-protector-strong - # -Wl,-z,relro,-z,now - # CACHE STRING "Compilation flags for RELEASE build type.") - - # (BUG!!!) as PKG_CONFIG_PATH does not work [should be an env variable] - # --------------------------------------------------------------------- - set(INSTALL_PREFIX $ENV{HOME}/opt) - set(CMAKE_PREFIX_PATH ${CMAKE_INSTALL_PREFIX}/lib64/pkgconfig ${CMAKE_INSTALL_PREFIX}/lib/pkgconfig) - set(LD_LIBRARY_PATH ${CMAKE_INSTALL_PREFIX}/lib64 ${CMAKE_INSTALL_PREFIX}/lib) - - # Location for config.xml.in template file. - # - # If you keep them commented then it will build with a default minimal widget - # template which is very simple and it is highly probable that it will not suit - # to your app. - # ----------------------------------------- - #set(WIDGET_ICON "conf.d/wgt/${PROJECT_ICON}" CACHE PATH "Path to the widget icon") - set(WIDGET_ICON ${PROJECT_APP_TEMPLATES_DIR}/wgt/${PROJECT_ICON}) - set(WIDGET_CONFIG_TEMPLATE ${CMAKE_SOURCE_DIR}/conf.d/wgt/config.xml.in CACHE PATH "Path to widget config file template (config.xml.in)") # UNCOMMENT WIDGET_CONFIG_TEMPLATE - #set(TEST_WIDGET_CONFIG_TEMPLATE "${CMAKE_CURRENT_SOURCE_DIR}/conf.d/wgt/test-config.xml.in" CACHE PATH "Path to the test widget config file template (test-config.xml.in)") - - # Mandatory widget Mimetype specification of the main unit - # -------------------------------------------------------------------------- - # Choose between : - #- text/html : HTML application, - # content.src designates the home page of the application - # - #- application/vnd.agl.native : AGL compatible native, - # content.src designates the relative path of the binary. - # - # - application/vnd.agl.service: AGL service, content.src is not used. - # - #- ***application/x-executable***: Native application, - # content.src designates the relative path of the binary. - # For such application, only security setup is made. - # - set(WIDGET_TYPE application/vnd.agl.service) # UNCOMMENT WIDGET_TYPE - - # Mandatory Widget entry point file of the main unit - # -------------------------------------------------------------- - # This is the file that will be executed, loaded, - # at launch time by the application framework. - # - set(WIDGET_ENTRY_POINT config.xml) # UNCOMMENT WIDGET_ENTRY_POINT - - # Optional dependencies order - # --------------------------- - #set(EXTRA_DEPENDENCIES_ORDER) - - # Optional Extra global include path - # ----------------------------------- - #set(EXTRA_INCLUDE_DIRS) - - # Optional extra libraries - # ------------------------- - #set(EXTRA_LINK_LIBRARIES) - - # Optional force binding Linking flag - # ------------------------------------ - # set(BINDINGS_LINK_FLAG LinkOptions ) - - # Optional force package prefix generation, like widget - # ----------------------------------------------------- - # set(PKG_PREFIX DestinationPath) - - # Optional Application Framework security token - # and port use for remote debugging. - #------------------------------------------------------------ - #set(AFB_TOKEN "" CACHE PATH "Default binder security token") # COMMENT AFB_TOKEN - #set(AFB_REMPORT "1234" CACHE PATH "Default binder listening port") # COMMENT AFB_REMPORT - - # Optional schema validator about now only XML, LUA and JSON - # are supported - #------------------------------------------------------------ - #set(LUA_CHECKER "luac" "-p" CACHE STRING "LUA compiler") - #set(XML_CHECKER "xmllint" CACHE STRING "XML linter") - #set(JSON_CHECKER "json_verify" CACHE STRING "JSON linter") - - include(CMakeAfbTemplates) - ``` - -### 5. Copy WGT configuration template - - ```sh - $ mkdir -p conf.d/wgt - $ cp ${OECORE_NATIVE_SYSROOT}/usr/share/doc/CMakeAfbTemplates/samples.d/config.xml.in.sample conf.d/wgt/config.xml.in - ``` - - Edit `config.xml` file - ```sh - $ vim conf.d/wgt/config.xml.in - - - - @PROJECT_NAME@ - - - @PROJECT_DESCRIPTION@ - @PROJECT_AUTHOR@ <@PROJECT_AUTHOR_MAIL@> - @PROJECT_LICENSE@ - - - - - - - - - - - - ``` - - -### 6. Run CMAKE and Generate autobuild - - ```sh - $ mkdir build/ - $ cd build/ - $ cmake .. - $ make autobuild - ``` - -### 7. Create service directory - - ```sh - $ cd .. - $ mkdir service/ - $ cd service/ - ``` - This `service` directory holds the C code & CMakeLists.txt ; - - - Add `hellocount-service.c` file which contains the functional C code : - - ```sh - $ vim hellocount-service.c - - /* - * Copyright 2020 The Linux Foundation # INSERT YEAR & ORG - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - #define _GNU_SOURCE - #include - #include - #include - - #define AFB_BINDING_VERSION 3 - #include - - static void pingSample(afb_req_t request) - { - static int pingcount = 0; - - afb_req_success_f(request, json_object_new_int(pingcount), "Ping count = %d", pingcount); - - AFB_API_NOTICE(afbBindingV3root, "Verbosity macro at level notice invoked at ping invocation count = %d", pingcount); - - pingcount++; - } - - static void count(afb_req_t request) - { - static int counter = 0; - - afb_req_success_f(request, json_object_new_int(counter), "Counter = %d", counter); - - AFB_API_NOTICE(afbBindingV3root, "Verbosity macro at level notice invoked at count invocation count = %d", counter); - - counter++; - } - - - - static const afb_verb_t verbs[] = - { - /*Without security*/ - {.verb = "ping", .session = AFB_SESSION_NONE, .callback = pingSample, .auth = NULL}, - {.verb = "count", .session = AFB_SESSION_NONE, .callback = count, .auth = NULL}, - {NULL} - }; - - const afb_binding_t afbBindingExport = - { - .api = "hellocount", - .specification = "HelloCount API", - .verbs = verbs, - .preinit = NULL, - .init = NULL, - .onevent = NULL, - .userdata = NULL, - .provide_class = NULL, - .require_class = NULL, - .require_api = NULL, - .noconcurrency = 0 - }; - ``` - -- Add `CMakeLists.txt` file : - - ```sh - $ vim CMakeLists.txt - - ########################################################################### - # Copyright 2020 The Linux Foundation # INSERT YEAR & ORG - # - # Licensed under the Apache License, Version 2.0 (the "License"); - # you may not use this file except in compliance with the License. - # You may obtain a copy of the License at - # - # http://www.apache.org/licenses/LICENSE-2.0 - # - # Unless required by applicable law or agreed to in writing, software - # distributed under the License is distributed on an "AS IS" BASIS, - # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - # See the License for the specific language governing permissions and - # limitations under the License. - ########################################################################### - - # Add target to project dependency list - PROJECT_TARGET_ADD(hellocount) - # Define project Targets - ADD_LIBRARY(${TARGET_NAME} MODULE hellocount-service.c) - - # Binder exposes a unique public entry point - SET_TARGET_PROPERTIES(${TARGET_NAME} PROPERTIES - PREFIX "afb-" - LABELS "BINDING" - OUTPUT_NAME ${TARGET_NAME} - ) - ``` - -### 8. Build and Package `wgt` using autobuild - - ```sh - $ cd .. - - $ ./autobuild/agl/autobuild build - - make[1]: Entering directory '/home/boron/agl-app/newservice/build' - make[2]: Entering directory '/home/boron/agl-app/newservice/build' - make[3]: Entering directory '/home/boron/agl-app/newservice/build' - make[3]: Leaving directory '/home/boron/agl-app/newservice/build' - [100%] Built target autobuild - make[2]: Leaving directory '/home/boron/agl-app/newservice/build' - make[1]: Leaving directory '/home/boron/agl-app/newservice/build' - - $ ./autobuild/agl/autobuild package - - make[1]: Entering directory '/home/boron/agl-app/newservice/build' - make[2]: Entering directory '/home/boron/agl-app/newservice/build' - make[3]: Entering directory '/home/boron/agl-app/newservice/build' - make[3]: Leaving directory '/home/boron/agl-app/newservice/build' - [100%] Built target autobuild - make[2]: Leaving directory '/home/boron/agl-app/newservice/build' - make[1]: Leaving directory '/home/boron/agl-app/newservice/build' - make[1]: Entering directory '/home/boron/agl-app/newservice/build' - make[2]: Entering directory '/home/boron/agl-app/newservice/build' - make[3]: Entering directory '/home/boron/agl-app/newservice/build' - make[4]: Entering directory '/home/boron/agl-app/newservice/build' - Scanning dependencies of target prepare_package - make[4]: Leaving directory '/home/boron/agl-app/newservice/build' - make[4]: Entering directory '/home/boron/agl-app/newservice/build' - [ 6%] Generating package - [ 12%] Generating package/bin - [ 18%] Generating package/etc - [ 25%] Generating package/lib - [ 31%] Generating package/htdocs - [ 37%] Generating package/var - make[4]: Leaving directory '/home/boron/agl-app/newservice/build' - [ 37%] Built target prepare_package - make[4]: Entering directory '/home/boron/agl-app/newservice/build' - Scanning dependencies of target prepare_package_test - make[4]: Leaving directory '/home/boron/agl-app/newservice/build' - make[4]: Entering directory '/home/boron/agl-app/newservice/build' - [ 43%] Generating package-test - [ 50%] Generating package-test/bin - [ 56%] Generating package-test/etc - [ 62%] Generating package-test/lib - [ 68%] Generating package-test/htdocs - [ 75%] Generating package-test/var - make[4]: Leaving directory '/home/boron/agl-app/newservice/build' - [ 75%] Built target prepare_package_test - make[4]: Entering directory '/home/boron/agl-app/newservice/build' - Scanning dependencies of target populate - make[4]: Leaving directory '/home/boron/agl-app/newservice/build' - [ 75%] Built target populate - make[4]: Entering directory '/home/boron/agl-app/newservice/build' - Scanning dependencies of target widget_files - make[4]: Leaving directory '/home/boron/agl-app/newservice/build' - make[4]: Entering directory '/home/boron/agl-app/newservice/build' - [ 81%] Generating package/icon.png - [ 87%] Generating package/config.xml - make[4]: Leaving directory '/home/boron/agl-app/newservice/build' - [ 93%] Built target widget_files - make[4]: Entering directory '/home/boron/agl-app/newservice/build' - Scanning dependencies of target widget - make[4]: Leaving directory '/home/boron/agl-app/newservice/build' - make[4]: Entering directory '/home/boron/agl-app/newservice/build' - [100%] Generating hellocount.wgt - NOTICE: -- PACKING widget hellocount.wgt from directory /home/boron/agl-app/newservice/build/package - ++ Install widget file using in the target : afm-util install hellocount.wgt - make[4]: Leaving directory '/home/boron/agl-app/newservice/build' - [100%] Built target widget - make[3]: Leaving directory '/home/boron/agl-app/newservice/build' - make[2]: Leaving directory '/home/boron/agl-app/newservice/build' - make[1]: Leaving directory '/home/boron/agl-app/newservice/build' - ``` - - - The `hellocount.wgt` file is packaged and available at `~/agl-app/newservice/build`. - -### 9. Install the service - - - Local System : - ```sh - # Copy hellocount.wgt to remote AGL system - $ scp ~/agl-app/newservice/build/hellocount.wgt root@:/home/0/ - ``` - - - Remote AGL System : - ```sh - # Install using the service using afm-util - $ afm-util install ./hellocount.wgt - # Reboot the system - $ reboot -f - ``` +TBD \ No newline at end of file diff --git a/docs/3_Developer_Guides/3_AppFW_Privileges_Management/03-AGL-AppFW-Privileges-Management.pdf b/docs/3_Developer_Guides/3_AppFW_Privileges_Management/03-AGL-AppFW-Privileges-Management.pdf deleted file mode 100644 index d468610..0000000 Binary files a/docs/3_Developer_Guides/3_AppFW_Privileges_Management/03-AGL-AppFW-Privileges-Management.pdf and /dev/null differ diff --git a/docs/3_Developer_Guides/3_AppFW_Privileges_Management/AppFW-Privileges_Management.md b/docs/3_Developer_Guides/3_AppFW_Privileges_Management/AppFW-Privileges_Management.md deleted file mode 100644 index 646732e..0000000 --- a/docs/3_Developer_Guides/3_AppFW_Privileges_Management/AppFW-Privileges_Management.md +++ /dev/null @@ -1,8 +0,0 @@ ---- -title: AGL Application Framework - Privileges Management ---- - - - - -[**AppFW - Privileges Management PDF**](03-AGL-AppFW-Privileges-Management.pdf) \ No newline at end of file diff --git a/docs/3_Developer_Guides/3_Creating_a_New_Application.md b/docs/3_Developer_Guides/3_Creating_a_New_Application.md index 757c151..6c382fd 100644 --- a/docs/3_Developer_Guides/3_Creating_a_New_Application.md +++ b/docs/3_Developer_Guides/3_Creating_a_New_Application.md @@ -2,543 +2,4 @@ title: Creating a New Application --- -This tutorial provides instructions on **Creating a New Application** from scratch. - -### 1. Create new project development directory - - ```sh - $ cd ~/agl-app - $ mkdir newapp/ - $ cd newapp/ - ``` - -### 2. Source the SDK environment setup - - ```sh - $ source ~/agl-app/agl-sdk/environment-setup-corei7-64-agl-linux - ``` - -### 3. Copy initial CMAKE configuration templates - - ```sh - $ mkdir -p conf.d/cmake - $ cp ${OECORE_NATIVE_SYSROOT}/usr/share/doc/CMakeAfbTemplates/samples.d/config.cmake.sample conf.d/cmake/config.cmake - $ cp ${OECORE_NATIVE_SYSROOT}/usr/share/doc/CMakeAfbTemplates/samples.d/CMakeLists.txt.sample CMakeLists.txt - ``` - -### 4. Edit CMAKE configuration template - - ```sh - $ vim ~/agl-app/newapp/conf.d/cmake/config.cmake - - ########################################################################### - # Copyright 2020 # INSERT YEAR - # - # author: John Doe # INSERT AUTHOR DETAILS - # - # Licensed under the Apache License, Version 2.0 (the "License"); - # you may not use this file except in compliance with the License. - # You may obtain a copy of the License at - # - # http://www.apache.org/licenses/LICENSE-2.0 - # - # Unless required by applicable law or agreed to in writing, software - # distributed under the License is distributed on an "AS IS" BASIS, - # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - # See the License for the specific language governing permissions and - # limitations under the License. - ########################################################################### - - # Project Info - # ------------------ - set(PROJECT_NAME hellocount) # INSERT NEW PROJECT NAME - set(API_NAME hellocount) #INSERT NEW API NAME - set(PROJECT_PRETTY_NAME "Example helloworld count app") #INSERT PRETTY NAME - set(PROJECT_DESCRIPTION "AGL hellocount application example") # INSERT CONCISE PROJECT DESCRIPTION - set(PROJECT_URL "https://git.somewhere.org/foo") - set(PROJECT_ICON "icon.png") - set(PROJECT_AUTHOR "John Doe") # INSERT AUTHOR NAME - set(PROJECT_AUTHOR_MAIL "john.doe@example.com") # INSERT AUTHOR EMAIL - set(PROJECT_LICENSE "APL2.0") - set(PROJECT_LANGUAGES "C") - set(PROJECT_VERSION "1.0.0") # INSERT PROJECT VERSION - - # Which directories inspect to find CMakeLists.txt target files - # set(PROJECT_SRC_DIR_PATTERN "*") - - # Where are stored the project configuration files - # relative to the root project directory - set(PROJECT_CMAKE_CONF_DIR "conf.d") - - # Compilation Mode (DEBUG, RELEASE, COVERAGE or PROFILING) - # ---------------------------------- - set(BUILD_TYPE "RELEASE") # SELECT BUILD TYPE - #set(USE_EFENCE 1) - - # Kernel selection if needed. You can choose between a - # mandatory version to impose a minimal version. - # Or check Kernel minimal version and just print a Warning - # about missing features and define a preprocessor variable - # to be used as preprocessor condition in code to disable - # incompatibles features. Preprocessor define is named - # KERNEL_MINIMAL_VERSION_OK. - # - # NOTE*** FOR NOW IT CHECKS KERNEL Yocto environment and - # Yocto SDK Kernel version. - # ----------------------------------------------- - #set (kernel_mandatory_version 4.8) - #set (kernel_minimal_version 4.8) - - # Compiler selection if needed. Impose a minimal version. - # ----------------------------------------------- - set (gcc_minimal_version 4.9) - - # PKG_CONFIG required packages - # ----------------------------- - set (PKG_REQUIRED_LIST - json-c - afb-daemon - ) - - # You can also consider to include libsystemd - # ----------------------------------- - #list (APPEND PKG_REQUIRED_LIST libsystemd>=222) - - # Prefix path where will be installed the files - # Default: /usr/local (need root permission to write in) - # ------------------------------------------------------ - #set(INSTALL_PREFIX /opt/AGL CACHE PATH "INSTALL PREFIX PATH") - - # Customize link option - # ----------------------------- - #list(APPEND link_libraries -an-option) - - # Compilation options definition - # Use CMake generator expressions to specify only for a specific language - # Values are prefilled with default options that is currently used. - # Either separate options with ";", or each options must be quoted separately - # DO NOT PUT ALL OPTION QUOTED AT ONCE , COMPILATION COULD FAILED ! - # ---------------------------------------------------------------------------- - #set(COMPILE_OPTIONS - # -Wall - # -Wextra - # -Wconversion - # -Wno-unused-parameter - # -Wno-sign-compare - # -Wno-sign-conversion - # -Werror=maybe-uninitialized - # -Werror=implicit-function-declaration - # -ffunction-sections - # -fdata-sections - # -fPIC - # CACHE STRING "Compilation flags") - #set(C_COMPILE_OPTIONS "" CACHE STRING "Compilation flags for C language.") - #set(CXX_COMPILE_OPTIONS "" CACHE STRING "Compilation flags for C++ language.") - #set(PROFILING_COMPILE_OPTIONS - # -g - # -O0 - # -pg - # -Wp,-U_FORTIFY_SOURCE - # CACHE STRING "Compilation flags for PROFILING build type.") - #set(DEBUG_COMPILE_OPTIONS - # -g - # -ggdb - # CACHE STRING "Compilation flags for DEBUG build type.") - #set(COVERAGE_COMPILE_OPTIONS - # -g - # -O0 - # --coverage - # CACHE STRING "Compilation flags for COVERAGE build type.") - #set(RELEASE_COMPILE_OPTIONS - # -O2 - # -pipe - # -D_FORTIFY_SOURCE=2 - # -fstack-protector-strong - # -Wformat -Wformat-security - # -Werror=format-security - # -feliminate-unused-debug-types - # -Wl,-O1 - # -Wl,--hash-style=gnu - # -Wl,--as-needed - # -fstack-protector-strong - # -Wl,-z,relro,-z,now - # CACHE STRING "Compilation flags for RELEASE build type.") - - # Location for config.xml.in template file. - # - # If you keep them commented then it will build with a default minimal widget - # template which is very simple and it is highly probable that it will not suit - # to your app. - # ----------------------------------------- - #set(WIDGET_ICON "conf.d/wgt/${PROJECT_ICON}" CACHE PATH "Path to the widget icon") - set(WIDGET_CONFIG_TEMPLATE "${CMAKE_CURRENT_SOURCE_DIR}/conf.d/wgt/config.xml.in" CACHE PATH "Path to widget config file template (config.xml.in)") # UNCOMMENT WIDGET_CONFIG_TEMPLATE - #set(TEST_WIDGET_CONFIG_TEMPLATE "${CMAKE_CURRENT_SOURCE_DIR}/conf.d/wgt/test-config.xml.in" CACHE PATH "Path to the test widget config file template (test-config.xml.in)") - - # Mandatory widget Mimetype specification of the main unit - # -------------------------------------------------------------------------- - # Choose between : - #- text/html : HTML application, - # content.src designates the home page of the application - # - #- application/vnd.agl.native : AGL compatible native, - # content.src designates the relative path of the binary. - # - # - application/vnd.agl.service: AGL service, content.src is not used. - # - #- ***application/x-executable***: Native application, - # content.src designates the relative path of the binary. - # For such application, only security setup is made. - # - set(WIDGET_TYPE application/vnd.agl.service) # UNCOMMENT WIDGET_TYPE - - # Mandatory Widget entry point file of the main unit - # -------------------------------------------------------------- - # This is the file that will be executed, loaded, - # at launch time by the application framework. - # - set(WIDGET_ENTRY_POINT hellocount) # UNCOMMENT WIDGET_ENTRY_POINT - - # Optional dependencies order - # --------------------------- - #set(EXTRA_DEPENDENCIES_ORDER) - - # Optional Extra global include path - # ----------------------------------- - #set(EXTRA_INCLUDE_DIRS) - - # Optional extra libraries - # ------------------------- - #set(EXTRA_LINK_LIBRARIES) - - # Optional force binding Linking flag - # ------------------------------------ - # set(BINDINGS_LINK_FLAG LinkOptions ) - - # Optional force package prefix generation, like widget - # ----------------------------------------------------- - # set(PKG_PREFIX DestinationPath) - - # Optional Application Framework security token - # and port use for remote debugging. - #------------------------------------------------------------ - #set(AFB_TOKEN "" CACHE PATH "Default binder security token") # COMMENT AFB_TOKEN - #set(AFB_REMPORT "1234" CACHE PATH "Default binder listening port") # COMMENT AFB_REMPORT - - # Print a helper message when every thing is finished - # ---------------------------------------------------- - set(CLOSING_MESSAGE "Typical binding launch: cd ${CMAKE_BINARY_DIR}/package \\&\\& afb-daemon --port=${AFB_REMPORT} --workdir=. --ldpaths=lib --roothttp=htdocs --token=\"${AFB_TOKEN}\" --tracereq=common --verbose") - set(PACKAGE_MESSAGE "Install widget file using in the target : afm-util install ${PROJECT_NAME}.wgt") - - # Optional schema validator about now only XML, LUA and JSON - # are supported - #------------------------------------------------------------ - #set(LUA_CHECKER "luac" "-p" CACHE STRING "LUA compiler") - #set(XML_CHECKER "xmllint" CACHE STRING "XML linter") - #set(JSON_CHECKER "json_verify" CACHE STRING "JSON linter") - - include(CMakeAfbTemplates) - ``` - -### 5. Copy WGT configuration template - - ```sh - $ mkdir -p conf.d/wgt - $ cp ${OECORE_NATIVE_SYSROOT}/usr/share/doc/CMakeAfbTemplates/samples.d/config.xml.in.sample conf.d/wgt/config.xml.in - ``` - -### 6. Run CMAKE and Generate autobuild - - ```sh - $ mkdir build/ - $ cd build/ - $ cmake .. - $ make autobuild - ``` - -### 7. Create app directory - - ```sh - $ cd .. - $ mkdir app/ - $ cd app/ - ``` - This `app` directory holds the C++, qrc, qml code & CMakeLists.txt ; - - - Add `main.cpp` file which contains the functional C code : - - ```sh - $ vim main.cpp - - /* - * Copyright (C) 2016 The Qt Company Ltd. # INSERT YEAR & ORG - * 2020 The Linux Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - #include - #include - #include - #include - #include - #include - #include - #include - - int main(int argc, char *argv[]) - { - QGuiApplication app(argc, argv); - app.setDesktopFileName("Hellocount"); - - QQmlApplicationEngine engine; - QQmlContext *context = engine.rootContext(); - - QCommandLineParser parser; - parser.addPositionalArgument("port", app.translate("main", "port for binding")); - parser.addPositionalArgument("secret", app.translate("main", "secret for binding")); - parser.addHelpOption(); - parser.addVersionOption(); - parser.process(app); - QStringList positionalArguments = parser.positionalArguments(); - - if (positionalArguments.length() == 2) { - int port = positionalArguments.takeFirst().toInt(); - QString secret = positionalArguments.takeFirst(); - - QUrl bindingAddress; - QUrlQuery query; - - bindingAddress.setScheme(QStringLiteral("ws")); - bindingAddress.setHost(QStringLiteral("localhost")); - bindingAddress.setPort(port); - bindingAddress.setPath(QStringLiteral("/api")); - - - query.addQueryItem(QStringLiteral("token"), secret); - bindingAddress.setQuery(query); - context->setContextProperty(QStringLiteral("bindingAddress"), bindingAddress); - } - - engine.load(QUrl(QStringLiteral("qrc:/Hellocount.qml"))); - return app.exec(); - - } - ``` - - - Add `Hellocount.qml` file which contains the functional qml code : - - ```sh - $ vim Hellocount.qml - - /* - * Copyright 2020 The Linux Foundation # INSERT YEAR & ORG - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - import QtQuick 2.6 - import QtQuick.Layouts 1.1 - import QtQuick.Controls 2.0 - import AGL.Demo.Controls 1.0 - - import QtQuick.Window 2.13 - - ApplicationWindow { - - // ----- Setup - id: root - width: Window.width * roles.scale - height: Window.height * roles.scale - - // ----- Childs - Label { - id: title - font.pixelSize: 48 - text: "Hello World Counter" - anchors.horizontalCenter: parent.horizontalCenter - } - - } - ``` - -- Add `Hellocount.qrc` file : - - ```sh - $ vim Hellocount.qrc - - - - Hellocount.qml - - - ``` - -- Add `CMakeLists.txt` file : - - ```sh - $ vim CMakeLists.txt - - ########################################################################### - # Copyright 2020 The Linux Foundation # INSERT YEAR & ORG - # - # Licensed under the Apache License, Version 2.0 (the "License"); - # you may not use this file except in compliance with the License. - # You may obtain a copy of the License at - # - # http://www.apache.org/licenses/LICENSE-2.0 - # - # Unless required by applicable law or agreed to in writing, software - # distributed under the License is distributed on an "AS IS" BASIS, - # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - # See the License for the specific language governing permissions and - # limitations under the License. - ########################################################################### - - set(CMAKE_INCLUDE_CURRENT_DIR ON) - set(CMAKE_AUTOMOC ON) - set(CMAKE_AUTORCC ON) - set(CMAKE_CXX_STANDARD 14) - set(CMAKE_CXX_STANDARD_REQUIRED ON) - set(OE_QMAKE_PATH_EXTERNAL_HOST_BINS $ENV{OE_QMAKE_PATH_HOST_BINS}) - - find_package(Qt5 COMPONENTS Core Gui QuickControls2 QuickWidgets WebSockets REQUIRED) - - PROJECT_TARGET_ADD(hellocount) - - add_executable(hellocount - "main.cpp" - "Hellocount.qrc" - ) - - set_target_properties(hellocount PROPERTIES - LABELS "EXECUTABLE" - PREFIX "" - COMPILE_FLAGS " -DFOR_AFB_BINDING" - LINK_FLAGS "${BINDINGS_LINK_FLAG}" - OUTPUT_NAME "${TARGET_NAME}" - ) - - target_link_libraries(hellocount - Qt5::WebSockets - Qt5::QuickWidgets - Qt5::QuickControls2 - json-c - libafb-helpers-qt.a - ) - ``` - -### 8. Build and Package `wgt` using autobuild - - ```sh - $ cd .. - - $ ./autobuild/agl/autobuild build - - make[1]: Entering directory '/home/boron/agl-app/newapp/build' - make[2]: Entering directory '/home/boron/agl-app/newapp/build' - make[3]: Entering directory '/home/boron/agl-app/newapp/build' - make[3]: Leaving directory '/home/boron/agl-app/newapp/build' - [100%] Built target autobuild - make[2]: Leaving directory '/home/boron/agl-app/newapp/build' - make[1]: Leaving directory '/home/boron/agl-app/newapp/build' - - - $ ./autobuild/agl/autobuild package - - make[1]: Entering directory '/home/boron/agl-app/newapp/build' - make[2]: Entering directory '/home/boron/agl-app/newapp/build' - make[3]: Entering directory '/home/boron/agl-app/newapp/build' - make[3]: Leaving directory '/home/boron/agl-app/newapp/build' - [100%] Built target autobuild - make[2]: Leaving directory '/home/boron/agl-app/newapp/build' - make[1]: Leaving directory '/home/boron/agl-app/newapp/build' - make[1]: Entering directory '/home/boron/agl-app/newapp/build' - make[2]: Entering directory '/home/boron/agl-app/newapp/build' - make[3]: Entering directory '/home/boron/agl-app/newapp/build' - make[4]: Entering directory '/home/boron/agl-app/newapp/build' - Scanning dependencies of target prepare_package - make[4]: Leaving directory '/home/boron/agl-app/newapp/build' - make[4]: Entering directory '/home/boron/agl-app/newapp/build' - [ 6%] Generating package - [ 12%] Generating package/bin - [ 18%] Generating package/etc - [ 25%] Generating package/lib - [ 31%] Generating package/htdocs - [ 37%] Generating package/var - make[4]: Leaving directory '/home/boron/agl-app/newapp/build' - [ 37%] Built target prepare_package - make[4]: Entering directory '/home/boron/agl-app/newapp/build' - Scanning dependencies of target prepare_package_test - make[4]: Leaving directory '/home/boron/agl-app/newapp/build' - make[4]: Entering directory '/home/boron/agl-app/newapp/build' - [ 43%] Generating package-test - [ 50%] Generating package-test/bin - [ 56%] Generating package-test/etc - [ 62%] Generating package-test/lib - [ 68%] Generating package-test/htdocs - [ 75%] Generating package-test/var - make[4]: Leaving directory '/home/boron/agl-app/newapp/build' - [ 75%] Built target prepare_package_test - make[4]: Entering directory '/home/boron/agl-app/newapp/build' - Scanning dependencies of target populate - make[4]: Leaving directory '/home/boron/agl-app/newapp/build' - [ 75%] Built target populate - make[4]: Entering directory '/home/boron/agl-app/newapp/build' - Scanning dependencies of target widget_files - make[4]: Leaving directory '/home/boron/agl-app/newapp/build' - make[4]: Entering directory '/home/boron/agl-app/newapp/build' - [ 81%] Generating package/icon.png - [ 87%] Generating package/config.xml - make[4]: Leaving directory '/home/boron/agl-app/newapp/build' - [ 93%] Built target widget_files - make[4]: Entering directory '/home/boron/agl-app/newapp/build' - Scanning dependencies of target widget - make[4]: Leaving directory '/home/boron/agl-app/newapp/build' - make[4]: Entering directory '/home/boron/agl-app/newapp/build' - [100%] Generating hellocount.wgt - NOTICE: -- PACKING widget hellocount.wgt from directory /home/boron/agl-app/newapp/build/package - ++ Install widget file using in the target : afm-util install hellocount.wgt - make[4]: Leaving directory '/home/boron/agl-app/newapp/build' - [100%] Built target widget - make[3]: Leaving directory '/home/boron/agl-app/newapp/build' - make[2]: Leaving directory '/home/boron/agl-app/newapp/build' - make[1]: Leaving directory '/home/boron/agl-app/newapp/build' - ``` - - - The `hellocount.wgt` file is packaged and available at `~/agl-app/newapp/build`. - -### 9. Install the service - - - Local System : - ```sh - # Copy hellocount.wgt to remote AGL system - $ scp ~/agl-app/newapp/build/hellocount.wgt root@:/home/0/ - ``` - - - Remote AGL System : - ```sh - # Install using the service using afm-util - $ afm-util install ./hellocount.wgt - # Reboot the system - $ reboot -f - ``` \ No newline at end of file +TBD \ No newline at end of file diff --git a/docs/3_Developer_Guides/4_AFB_Helper_Guide/1_Usage.md b/docs/3_Developer_Guides/4_AFB_Helper_Guide/1_Usage.md deleted file mode 100644 index 80c2c08..0000000 --- a/docs/3_Developer_Guides/4_AFB_Helper_Guide/1_Usage.md +++ /dev/null @@ -1,83 +0,0 @@ ---- -title: Usage ---- - -## Installation - -The afb-helpers library is integrated by default in the AGL SDK since the Guppy -version (>=7) and is also available as a package for the AGL supported linux -distributions. - -You could find the SDK build from Yocto which embed the afb-helpers library -here: - -- **x86** : [qemux86-64](https://download.automotivelinux.org/AGL/snapshots/master/latest/qemux86-64/deploy/sdk/poky-agl-glibc-x86_64-agl-demo-platform-crosssdk-corei7-64-qemux86-64-toolchain-10.90.0+snapshot.sh) - -- **ARM 32 bit** : [qemuarm](https://download.automotivelinux.org/AGL/snapshots/master/latest/qemuarm/deploy/sdk/poky-agl-glibc-x86_64-agl-demo-platform-crosssdk-armv7vet2hf-neon-vfpv4-qemuarm-toolchain-10.90.0+snapshot.sh) - -- **AARCH64 - ARM 64bit** : [qemuarm64](https://download.automotivelinux.org/AGL/snapshots/master/latest/qemuarm64/deploy/sdk/poky-agl-glibc-x86_64-agl-demo-platform-crosssdk-aarch64-qemuarm64-toolchain-10.90.0+snapshot.sh) - -Then use your package manager to install the library. - -### OpenSuse - -```bash -sudo zypper ref -sudo zypper install agl-libafb-helpers-devel -``` - -### Fedora - -```bash -sudo dnf ref -sudo dnf install agl-libafb-helpers-devel -``` - -### Ubuntu/Debian - -```bash -sudo apt-get update -sudo apt-get install agl-libafb-helpers-dev -``` - -## (Optional) Remove the git submodule version - -If you already use the afb-helpers component but using the submodule version -then you have to get rid of it to be sure to link and use the library version. -To do so, you have to do the following: - -* Deinitialize the submodule using `git` - -```bash -# This example assumes that the git submodule is named app-afb-helpers-submodule -# and is located at your root project repository. -git submodule deinit app-afb-helpers-submodule -``` - -* Remove the submodule relatives lines from the `.gitmodules` file - -```bash -vim .gitmodules -``` - -* Remove the `afb-helpers` target link from any CMake target you specified. - Those lines look like: - -```bash -TARGET_LINK_LIBRARIES(${TARGET_NAME} - afb-helpers # REMOVE THIS LINE - ${link_libraries} - ) -``` - -## Add the libafb-helpers as a static library to your binding - -In your `config.cmake` file, add a dependency to the controller library, i.e: - -```cmake -set(PKG_REQUIRED_LIST - json-c - afb-daemon - afb-helpers --> this is the afb-helpers library dependency name. -) -``` \ No newline at end of file diff --git a/docs/3_Developer_Guides/4_AFB_Helper_Guide/2_AFB_Timer.md b/docs/3_Developer_Guides/4_AFB_Helper_Guide/2_AFB_Timer.md deleted file mode 100644 index 3af5385..0000000 --- a/docs/3_Developer_Guides/4_AFB_Helper_Guide/2_AFB_Timer.md +++ /dev/null @@ -1,50 +0,0 @@ ---- -title: AFB Timer functions ---- - -## TimerHandleT - -Members are: - -* `count`: integer representing the number of times the timers should run. -* `delay`: millisecond integer representing the delay to wait before and between - the callback run. -* `uid`: a string identifying the timer. -* `context`: an opaq pointer that could be used in the callback function. -* `evtSource`: a systemd event source struct. Should be NULL. -* `api`: the AFB api pointer. -* `callback`: a function pointer for the callback to call at timer expiration -* `freeCB`: a function pointer called after expiration of the timer. Mainly meant - to release the context pointer by example. - -## void TimerEvtStart(afb_api_t api, TimerHandleT *timerHandle, timerCallbackT callback, void *context) - -Start a timer which invokes the callback when the delay expires for `count` -times. - -* `api`: AFB api pointer. -* `timerHandle`: pointer to struct representing a timer. -* `callback`: a function pointer for the callback to call at timer expiration -* `context`: an opaq pointer that could be used in the callback function. - -## void TimerEvtStop(TimerHandleT *timerHandle) - -Manually stop the timer's run. If the `count` isn't finished then it will end -the timer and no other runs will occur. - -* `timerHandle`: pointer to struct representing a timer. - -## uint64_t LockWait(afb_api_t api, uint64_t utimeout) - -It is function acting like a non-blocking sleep for an API. It lets the main API -event loop runs while you are waiting and will unlock at the first received -event and returns the remaining time to wait if an event occurs or 0 if no events -occured and timeout hits. Then you have to manually ensure that once an event -has been received that it was the one you are waiting for and if not launch again -the wait with the remaining time returned. - -* `api`: AFB api pointer. -* `timeout`: timeout in microsecond. - -Returns the remaining time in microsecond to wait if an event occurs or 0 if no -events occured and timeout hits. \ No newline at end of file diff --git a/docs/3_Developer_Guides/4_AFB_Helper_Guide/3_CURL_wrapper.md b/docs/3_Developer_Guides/4_AFB_Helper_Guide/3_CURL_wrapper.md deleted file mode 100644 index c0361fe..0000000 --- a/docs/3_Developer_Guides/4_AFB_Helper_Guide/3_CURL_wrapper.md +++ /dev/null @@ -1,113 +0,0 @@ ---- -title: CURL wrapping functions ---- - -## int curl_wrap_perform (CURL * curl, char **result, size_t * size) - -Perform the CURL operation for 'curl' and put the result in memory. If 'result' -isn't NULL it receives the returned content that then must be freed. If 'size' -isn't NULL, it receives the size of the returned content. Note that if not NULL, -the real content is one byte greater than the read size and the last byte -zero. This facility allows to handle the returned content as a null terminated -C-string. - -## void curl_wrap_do(CURL *curl, void (*callback)(void *closure, int status, CURL *curl, const char *result, size_t size), void *closure) - -Will perform the CURL operation and on success invokes the callback with the -result and size of the operation or error on a failure. - -## int curl_wrap_content_type_is (CURL * curl, const char *value) - -Request `Content-Type` information from the curl session with this function - -Returns non-zero value if the CURL content type match the `value` and 0 otherwize - -## long curl_wrap_response_code_get(CURL *curl) - -Request the response code to a CURL operation. - -Returns the response code received on success or 0 on failure. - -## CURL *curl_wrap_prepare_get_url(const char *url) - -Prepare a GET CURL operation on the url given as parameter and Returns the CURL -pointer. - -## CURL *curl_wrap_prepare_get(const char *base, const char *path, const char * const *args) - -Prepare a GET CURL operation on the decomposed url and escape it. The `url` has been -decomposed in 3 parts: - -* `base`: representing the FQDN of the url. -* `path`: the path to the requested page. -* `args`: optionnal array of arguments provided for the GET request. - -Returns the prepared CURL request. - -## int curl_wrap_add_header(CURL *curl, const char *header) - -Add a header to a CURL operation. - -Returns the prepared CURL request. - -## int curl_wrap_add_header_value(CURL *curl, const char *name, const char *value) - -Add a tuple `name`, `value` to the header of a CURL operation. - -Returns the prepared CURL request. - -## CURL *curl_wrap_prepare_post_url_data(const char *url, const char *datatype, const char *data, size_t szdata) - -Prepare a POST CURL operation on the provided `url`. - -* `url`: a HTTP url. -* `datatype`: HTTP `Content-Type` to use for the operation. -* `data`: data to send. -* `szdata`: size of the data to send. - -Returns the prepared CURL request. - -## CURL *curl_wrap_prepare_post_simple_unescaped(const char *base, const char *path, const char *args) - -Prepare a POST CURL operation on an unescaped `url` with arguments provided as -a simple string. - -* `base`: representing the FQDN of the url. -* `path`: the path to the requested page. -* `args`: optionnals argument for the POST http request. - -Returns the prepared CURL request. - -## CURL *curl_wrap_prepare_post_simple_escaped(const char *base, const char *path, char *args) - -Prepare a POST CURL operation on an escaped `url` with arguments provided as -a simple string. - -* `base`: representing the FQDN of the url. -* `path`: the path to the requested page. -* `args`: optionnals argument for the POST http request. - -Returns the prepared CURL request. - -## CURL *curl_wrap_prepare_post_unescaped(const char *base, const char *path, const char *separator, const char * const *args) - -Prepare a POST CURL operation on an unescaped `url` with arguments provided as -an array of string concatened with a provided separator string. - -* `base`: representing the FQDN of the url. -* `path`: the path to the requested page. -* `separator`: string used as a separator when concatening the arguments. -* `args`: optionnal array of arguments for the POST http request. - -Returns the prepared CURL request. - -## CURL *curl_wrap_prepare_post_escaped(const char *base, const char *path, const char * const *args) - -Prepare a POST CURL operation on an unescaped `url` with arguments provided as -an array of string concatened without any separator. - -* `base`: representing the FQDN of the url. -* `path`: the path to the requested page. -* `args`: optionnal array of arguments for the POST http request. - -Returns the prepared CURL request. \ No newline at end of file diff --git a/docs/3_Developer_Guides/4_AFB_Helper_Guide/4_URL_Escaping.md b/docs/3_Developer_Guides/4_AFB_Helper_Guide/4_URL_Escaping.md deleted file mode 100644 index 4070acb..0000000 --- a/docs/3_Developer_Guides/4_AFB_Helper_Guide/4_URL_Escaping.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -title: Escaping helpers functions ---- - -## char *escape_url(const char *base, const char *path, const char * const *args, size_t *length) - -Escape an `url` and `arguments` and returned it as a string. - -* `base`: representing the FQDN of the url. -* `path`: the path to the requested page. -* `args`: optionnal array of arguments provided for the GET request. -* `length`: length of the returned `url`. - -Returns the escaped `url`. - -## const char *escape_args(const char * const *args, size_t *length) - -Escape an array of arguments and returned the lenght of the escaped arguments -string. - -* `args`: array of arguments provided for the GET request. -* `length`: length of the returned `arguments`. - -Returns the escaped `arguments`. - -## const char *escape_str(const char *str, size_t *length) - -Escape a string and returns it. - -* `str`: the string to escape. -* `length`: length of the returned string. - -Returns the escaped string. - -## const char **unescape_args(const char *args) - -Unescape an argument and returns it. - -* `args`: the argument to unescape. diff --git a/docs/3_Developer_Guides/4_AFB_Helper_Guide/5_Filescan_Utils.md b/docs/3_Developer_Guides/4_AFB_Helper_Guide/5_Filescan_Utils.md deleted file mode 100644 index 5b220e1..0000000 --- a/docs/3_Developer_Guides/4_AFB_Helper_Guide/5_Filescan_Utils.md +++ /dev/null @@ -1,82 +0,0 @@ ---- -title: Filescan Utils functions ---- - -## const char *GetMiddleName(const char *name) - -Get rid of the binder name prefix 'afbd-' - -* name will be typically the full binder name - -Returns the process middle name of the running binder. - -## const char *GetBinderName() - -Get the Binder Name without the prefix set by the AGL appfw 'afbd-' - -Returns the Binder name without the prefix. - -## json_object* ScanForConfig (const char* searchPath, CtlScanDirModeT mode, const char *prefix, const char *extension) - -Scan a directory searching all files matching pattern: 'prefix*extention'. - -* `searchPath`: directory where to begin the searching. -* `mode`: either or not the search will be recursive. -* `prefix`: file prefix that will be looking for. -* `extention`: file extention that will be looking for. - -Returns a json_object array of object with 2 parts a 'fullpath' describing the -fullpath to reach the file and 'filename' containing the matched files. - -## char *GetAFBRootDirPathUsingFd(int fd) - -Get the binder root directory path (the path specified with '--rootdir' option -at binder launch, if the option is not used, the path from where the binder -is launched) using binder root directory file descriptor. - -* `fd` : Binder root directory file descriptor. - -Returns a string representing the path to binder root directory. - -## char *GetAFBRootDirPath(afb_api_t apiHandle) - -For binding with a version >= 3, same as 'GetAFBRootDirPathUsingFd' function, -but use pointer to the AFB API as parameter instead of -binder root directory file descriptor. - -* `apiHandle` : pointer to the AFB API. - -Returns a string representing the path to binder root directory. - -## char* GetBindingDirPath() - -For binding with a version <= 2, same as 'GetAFBRootDirPath' function, -but the pointer to the AFB API is not needed. -Kept for compatibility issues. - -## char* GetBindingDirPath(afb_api_t api) - -For binding with a version >= 3, same as 'GetAFBRootDirPath' function. -Deprecated, please use 'GetAFBRootDirPath' function. -Kept for compatibility issues. - -## char *GetRunningBindingDirPath(afb_api_t api) - -For binding with a version >= 3, get the binding directory path -(the path to the directory that contains the binding). - -* `api` : pointer to the AFB API. - -Returns a string representing the path to the binding directory. - -## const char *getEnvDirList(const char *prefix, const char *suffix) - -Get the environment directory colon separated path list. This take the prefix -add the binder's name then the suffix as environment variable name and also -search for another variable without the binder's name (so only prefix+suffix). - -* `prefix`: Environment variable prefix -* `suffix`: Environment variable suffix - -Returns a string representing a colon separated path list or NULL is case of -error or none environment variables found. \ No newline at end of file diff --git a/docs/3_Developer_Guides/4_AFB_Helper_Guide/6_Qt_AFB_Websocket_client.md b/docs/3_Developer_Guides/4_AFB_Helper_Guide/6_Qt_AFB_Websocket_client.md deleted file mode 100644 index 5572548..0000000 --- a/docs/3_Developer_Guides/4_AFB_Helper_Guide/6_Qt_AFB_Websocket_client.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -title: Qt AFB Websocket client ---- - -## QAfbWebsocketClient(QObject* parent = nullptr) - -Default constructor. - -* `parent`: Parent object. - -## QAbstractSocket::SocketError error() - -Get and return the last error code. - -## QString errorString() - -Get and return the last error as a string. - -## bool isValid() - -Check if connection is ready or not. - -Returns `true` if the connected is ready to read and write, `false` otherwise. - -## void call(const QString& api, const QString& verb, const QJsonValue& arg = QJsonValue(), closure_t closure = nullptr) - -Call an api's verb with an argument. - -* `api`: Api to call. -* `verb`: Verb to call. -* `arg`: Argument to pass. -* `closure`: callback function to call at the verb reply - -## void QAfbWebsocketClient::sendTextMessage(QString msg) - -Send a text message over the websocket. - -This is use for test only, you should not use this method because it sent text -**as-is**, so you have to follow the binder's protocol by your self. - -* `msg`: Message to send. \ No newline at end of file diff --git a/docs/3_Developer_Guides/4_AFB_Helper_Guide/7_JSON_library_for_modern_C++.md b/docs/3_Developer_Guides/4_AFB_Helper_Guide/7_JSON_library_for_modern_C++.md deleted file mode 100644 index e807476..0000000 --- a/docs/3_Developer_Guides/4_AFB_Helper_Guide/7_JSON_library_for_modern_C++.md +++ /dev/null @@ -1,894 +0,0 @@ ---- -title: JSON library for modern C++ ---- - -## Design goals - -There are myriads of [JSON](http://json.org) libraries out there, and each may even have its reason to exist. Our class had these design goals: - -- **Intuitive syntax**. In languages such as Python, JSON feels like a first class data type. We used all the operator magic of modern C++ to achieve the same feeling in your code. Check out the [examples below](#examples) and you'll know what I mean. - -- **Trivial integration**. Our whole code consists of a single header file [`json.hpp`](https://github.com/nlohmann/json/blob/develop/src/json.hpp). That's it. No library, no subproject, no dependencies, no complex build system. The class is written in vanilla C++11. All in all, everything should require no adjustment of your compiler flags or project settings. - -- **Serious testing**. Our class is heavily [unit-tested](https://github.com/nlohmann/json/blob/master/test/src/unit.cpp) and covers [100%](https://coveralls.io/r/nlohmann/json) of the code, including all exceptional behavior. Furthermore, we checked with [Valgrind](http://valgrind.org) that there are no memory leaks. To maintain high quality, the project is following the [Core Infrastructure Initiative (CII) best practices](https://bestpractices.coreinfrastructure.org/projects/289). - -Other aspects were not so important to us: - -- **Memory efficiency**. Each JSON object has an overhead of one pointer (the maximal size of a union) and one enumeration element (1 byte). The default generalization uses the following C++ data types: `std::string` for strings, `int64_t`, `uint64_t` or `double` for numbers, `std::map` for objects, `std::vector` for arrays, and `bool` for Booleans. However, you can template the generalized class `basic_json` to your needs. - -- **Speed**. There are certainly [faster JSON libraries](https://github.com/miloyip/nativejson-benchmark#parsing-time) out there. However, if your goal is to speed up your development by adding JSON support with a single header, then this library is the way to go. If you know how to use a `std::vector` or `std::map`, you are already set. - -See the [contribution guidelines](https://github.com/nlohmann/json/blob/master/.github/CONTRIBUTING.md#please-dont) for more information. - -## Integration - -The single required source, file `json.hpp` is in the `src` directory or [released here](https://github.com/nlohmann/json/releases). All you need to do is add - -```cpp -#include "json.hpp" - -// for convenience -using json = nlohmann::json; -``` - -to the files you want to use JSON objects. That's it. Do not forget to set the necessary switches to enable C++11 (e.g., `-std=c++11` for GCC and Clang). - -:beer: If you are using OS X and [Homebrew](http://brew.sh), just type `brew tap nlohmann/json` and `brew install nlohmann_json` and you're set. If you want the bleeding edge rather than the latest release, use `brew install nlohmann_json --HEAD`. - -If you are using the [Meson Build System](http://mesonbuild.com), then you can wrap this repo as a subproject. - -If you are using [Conan](https://www.conan.io/) to manage your dependencies, merely add `jsonformoderncpp/x.y.z@vthiery/stable` to your `conanfile.py`'s requires, where `x.y.z` is the release version you want to use. Please file issues [here](https://github.com/vthiery/conan-jsonformoderncpp/issues) if you experience problems with the packages. - -If you are using [hunter](https://github.com/ruslo/hunter/) on your project for external dependencies, then you can use the [nlohman_json package](https://github.com/ruslo/hunter/wiki/pkg.nlohmann_json). Please see the hunter project for any issues regarding the packaging. - -:warning: [Version 3.0.0](https://github.com/nlohmann/json/wiki/Road-toward-3.0.0) is currently under development. Branch `develop` is used for the ongoing work and is probably **unstable**. Please use the `master` branch for the last stable version 2.1.1. - -## Examples - -Beside the examples below, you may want to check the [documentation](https://nlohmann.github.io/json/) where each function contains a separate code example (e.g., check out [`emplace()`](https://nlohmann.github.io/json/classnlohmann_1_1basic__json_a602f275f0359ab181221384989810604.html#a602f275f0359ab181221384989810604)). All [example files](https://github.com/nlohmann/json/tree/develop/doc/examples) can be compiled and executed on their own (e.g., file [emplace.cpp](https://github.com/nlohmann/json/blob/develop/doc/examples/emplace.cpp)). - -### JSON as first-class data type - -Here are some examples to give you an idea how to use the class. - -Assume you want to create the JSON object - -```json -{ - "pi": 3.141, - "happy": true, - "name": "Niels", - "nothing": null, - "answer": { - "everything": 42 - }, - "list": [1, 0, 2], - "object": { - "currency": "USD", - "value": 42.99 - } -} -``` - -With the JSON class, you could write: - -```cpp -// create an empty structure (null) -json j; - -// add a number that is stored as double (note the implicit conversion of j to an object) -j["pi"] = 3.141; - -// add a Boolean that is stored as bool -j["happy"] = true; - -// add a string that is stored as std::string -j["name"] = "Niels"; - -// add another null object by passing nullptr -j["nothing"] = nullptr; - -// add an object inside the object -j["answer"]["everything"] = 42; - -// add an array that is stored as std::vector (using an initializer list) -j["list"] = { 1, 0, 2 }; - -// add another object (using an initializer list of pairs) -j["object"] = { {"currency", "USD"}, {"value", 42.99} }; - -// instead, you could also write (which looks very similar to the JSON above) -json j2 = { - {"pi", 3.141}, - {"happy", true}, - {"name", "Niels"}, - {"nothing", nullptr}, - {"answer", { - {"everything", 42} - }}, - {"list", {1, 0, 2}}, - {"object", { - {"currency", "USD"}, - {"value", 42.99} - }} -}; -``` - -Note that in all these cases, you never need to "tell" the compiler which JSON value you want to use. If you want to be explicit or express some edge cases, the functions `json::array` and `json::object` will help: - -```cpp -// a way to express the empty array [] -json empty_array_explicit = json::array(); - -// ways to express the empty object {} -json empty_object_implicit = json({}); -json empty_object_explicit = json::object(); - -// a way to express an _array_ of key/value pairs [["currency", "USD"], ["value", 42.99]] -json array_not_object = { json::array({"currency", "USD"}), json::array({"value", 42.99}) }; -``` - -### Serialization / Deserialization - -#### To/from strings - -You can create an object (deserialization) by appending `_json` to a string literal: - -```cpp -// create object from string literal -json j = "{ \"happy\": true, \"pi\": 3.141 }"_json; - -// or even nicer with a raw string literal -auto j2 = R"( - { - "happy": true, - "pi": 3.141 - } -)"_json; -``` - -Note that without appending the `_json` suffix, the passed string literal is not parsed, but just used as JSON string value. That is, `json j = "{ \"happy\": true, \"pi\": 3.141 }"` would just store the string `"{ "happy": true, "pi": 3.141 }"` rather than parsing the actual object. - -The above example can also be expressed explicitly using `json::parse()`: - -```cpp -// parse explicitly -auto j3 = json::parse("{ \"happy\": true, \"pi\": 3.141 }"); -``` - -You can also get a string representation (serialize): - -```cpp -// explicit conversion to string -std::string s = j.dump(); // {\"happy\":true,\"pi\":3.141} - -// serialization with pretty printing -// pass in the amount of spaces to indent -std::cout << j.dump(4) << std::endl; -// { -// "happy": true, -// "pi": 3.141 -// } -``` - -#### To/from streams (e.g. files, string streams) - -You can also use streams to serialize and deserialize: - -```cpp -// deserialize from standard input -json j; -std::cin >> j; - -// serialize to standard output -std::cout << j; - -// the setw manipulator was overloaded to set the indentation for pretty printing -std::cout << std::setw(4) << j << std::endl; -``` - -These operators work for any subclasses of `std::istream` or `std::ostream`. Here is the same example with files: - -```cpp -// read a JSON file -std::ifstream i("file.json"); -json j; -i >> j; - -// write prettified JSON to another file -std::ofstream o("pretty.json"); -o << std::setw(4) << j << std::endl; -``` - -Please note that setting the exception bit for `failbit` is inappropriate for this use case. It will result in program termination due to the `noexcept` specifier in use. - -#### Read from iterator range - -You can also read JSON from an iterator range; that is, from any container accessible by iterators whose content is stored as contiguous byte sequence, for instance a `std::vector`: - -```cpp -std::vector v = {'t', 'r', 'u', 'e'}; -json j = json::parse(v.begin(), v.end()); -``` - -You may leave the iterators for the range [begin, end): - -```cpp -std::vector v = {'t', 'r', 'u', 'e'}; -json j = json::parse(v); -``` - -### STL-like access - -We designed the JSON class to behave just like an STL container. In fact, it satisfies the [**ReversibleContainer**](http://en.cppreference.com/w/cpp/concept/ReversibleContainer) requirement. - -```cpp -// create an array using push_back -json j; -j.push_back("foo"); -j.push_back(1); -j.push_back(true); - -// also use emplace_back -j.emplace_back(1.78); - -// iterate the array -for (json::iterator it = j.begin(); it != j.end(); ++it) { - std::cout << *it << '\n'; -} - -// range-based for -for (auto& element : j) { - std::cout << element << '\n'; -} - -// getter/setter -const std::string tmp = j[0]; -j[1] = 42; -bool foo = j.at(2); - -// comparison -j == "[\"foo\", 1, true]"_json; // true - -// other stuff -j.size(); // 3 entries -j.empty(); // false -j.type(); // json::value_t::array -j.clear(); // the array is empty again - -// convenience type checkers -j.is_null(); -j.is_boolean(); -j.is_number(); -j.is_object(); -j.is_array(); -j.is_string(); - -// create an object -json o; -o["foo"] = 23; -o["bar"] = false; -o["baz"] = 3.141; - -// also use emplace -o.emplace("weather", "sunny"); - -// special iterator member functions for objects -for (json::iterator it = o.begin(); it != o.end(); ++it) { - std::cout << it.key() << " : " << it.value() << "\n"; -} - -// find an entry -if (o.find("foo") != o.end()) { - // there is an entry with key "foo" -} - -// or simpler using count() -int foo_present = o.count("foo"); // 1 -int fob_present = o.count("fob"); // 0 - -// delete an entry -o.erase("foo"); -``` - -### Conversion from STL containers - -Any sequence container (`std::array`, `std::vector`, `std::deque`, `std::forward_list`, `std::list`) whose values can be used to construct JSON types (e.g., integers, floating point numbers, Booleans, string types, or again STL containers described in this section) can be used to create a JSON array. The same holds for similar associative containers (`std::set`, `std::multiset`, `std::unordered_set`, `std::unordered_multiset`), but in these cases the order of the elements of the array depends how the elements are ordered in the respective STL container. - -```cpp -std::vector c_vector {1, 2, 3, 4}; -json j_vec(c_vector); -// [1, 2, 3, 4] - -std::deque c_deque {1.2, 2.3, 3.4, 5.6}; -json j_deque(c_deque); -// [1.2, 2.3, 3.4, 5.6] - -std::list c_list {true, true, false, true}; -json j_list(c_list); -// [true, true, false, true] - -std::forward_list c_flist {12345678909876, 23456789098765, 34567890987654, 45678909876543}; -json j_flist(c_flist); -// [12345678909876, 23456789098765, 34567890987654, 45678909876543] - -std::array c_array {{1, 2, 3, 4}}; -json j_array(c_array); -// [1, 2, 3, 4] - -std::set c_set {"one", "two", "three", "four", "one"}; -json j_set(c_set); // only one entry for "one" is used -// ["four", "one", "three", "two"] - -std::unordered_set c_uset {"one", "two", "three", "four", "one"}; -json j_uset(c_uset); // only one entry for "one" is used -// maybe ["two", "three", "four", "one"] - -std::multiset c_mset {"one", "two", "one", "four"}; -json j_mset(c_mset); // both entries for "one" are used -// maybe ["one", "two", "one", "four"] - -std::unordered_multiset c_umset {"one", "two", "one", "four"}; -json j_umset(c_umset); // both entries for "one" are used -// maybe ["one", "two", "one", "four"] -``` - -Likewise, any associative key-value containers (`std::map`, `std::multimap`, `std::unordered_map`, `std::unordered_multimap`) whose keys can construct an `std::string` and whose values can be used to construct JSON types (see examples above) can be used to create a JSON object. Note that in case of multimaps only one key is used in the JSON object and the value depends on the internal order of the STL container. - -```cpp -std::map c_map { {"one", 1}, {"two", 2}, {"three", 3} }; -json j_map(c_map); -// {"one": 1, "three": 3, "two": 2 } - -std::unordered_map c_umap { {"one", 1.2}, {"two", 2.3}, {"three", 3.4} }; -json j_umap(c_umap); -// {"one": 1.2, "two": 2.3, "three": 3.4} - -std::multimap c_mmap { {"one", true}, {"two", true}, {"three", false}, {"three", true} }; -json j_mmap(c_mmap); // only one entry for key "three" is used -// maybe {"one": true, "two": true, "three": true} - -std::unordered_multimap c_ummap { {"one", true}, {"two", true}, {"three", false}, {"three", true} }; -json j_ummap(c_ummap); // only one entry for key "three" is used -// maybe {"one": true, "two": true, "three": true} -``` - -### JSON Pointer and JSON Patch - -The library supports **JSON Pointer** ([RFC 6901](https://tools.ietf.org/html/rfc6901)) as alternative means to address structured values. On top of this, **JSON Patch** ([RFC 6902](https://tools.ietf.org/html/rfc6902)) allows to describe differences between two JSON values - effectively allowing patch and diff operations known from Unix. - -```cpp -// a JSON value -json j_original = R"({ - "baz": ["one", "two", "three"], - "foo": "bar" -})"_json; - -// access members with a JSON pointer (RFC 6901) -j_original["/baz/1"_json_pointer]; -// "two" - -// a JSON patch (RFC 6902) -json j_patch = R"([ - { "op": "replace", "path": "/baz", "value": "boo" }, - { "op": "add", "path": "/hello", "value": ["world"] }, - { "op": "remove", "path": "/foo"} -])"_json; - -// apply the patch -json j_result = j_original.patch(j_patch); -// { -// "baz": "boo", -// "hello": ["world"] -// } - -// calculate a JSON patch from two JSON values -json::diff(j_result, j_original); -// [ -// { "op":" replace", "path": "/baz", "value": ["one", "two", "three"] }, -// { "op": "remove","path": "/hello" }, -// { "op": "add", "path": "/foo", "value": "bar" } -// ] -``` - -### Implicit conversions - -The type of the JSON object is determined automatically by the expression to store. Likewise, the stored value is implicitly converted. - -```cpp -// strings -std::string s1 = "Hello, world!"; -json js = s1; -std::string s2 = js; - -// Booleans -bool b1 = true; -json jb = b1; -bool b2 = jb; - -// numbers -int i = 42; -json jn = i; -double f = jn; - -// etc. -``` - -You can also explicitly ask for the value: - -```cpp -std::string vs = js.get(); -bool vb = jb.get(); -int vi = jn.get(); - -// etc. -``` - -### Arbitrary types conversions - -Every type can be serialized in JSON, not just STL-containers and scalar types. Usually, you would do something along those lines: - -```cpp -namespace ns { - // a simple struct to model a person - struct person { - std::string name; - std::string address; - int age; - }; -} - -ns::person p = {"Ned Flanders", "744 Evergreen Terrace", 60}; - -// convert to JSON: copy each value into the JSON object -json j; -j["name"] = p.name; -j["address"] = p.address; -j["age"] = p.age; - -// ... - -// convert from JSON: copy each value from the JSON object -ns::person p { - j["name"].get(), - j["address"].get(), - j["age"].get() -}; -``` - -It works, but that's quite a lot of boilerplate... Fortunately, there's a better way: - -```cpp -// create a person -ns::person p {"Ned Flanders", "744 Evergreen Terrace", 60}; - -// conversion: person -> json -json j = p; - -std::cout << j << std::endl; -// {"address":"744 Evergreen Terrace","age":60,"name":"Ned Flanders"} - -// conversion: json -> person -ns::person p2 = j; - -// that's it -assert(p == p2); -``` - -#### Basic usage - -To make this work with one of your types, you only need to provide two functions: - -```cpp -using nlohmann::json; - -namespace ns { - void to_json(json& j, const person& p) { - j = json{ {"name", p.name}, {"address", p.address}, {"age", p.age} }; - } - - void from_json(const json& j, person& p) { - p.name = j.at("name").get(); - p.address = j.at("address").get(); - p.age = j.at("age").get(); - } -} // namespace ns -``` - -That's all! When calling the `json` constructor with your type, your custom `to_json` method will be automatically called. -Likewise, when calling `get()`, the `from_json` method will be called. - -Some important things: - -- Those methods **MUST** be in your type's namespace (which can be the global namespace), or the library will not be able to locate them (in this example, they are in namespace `ns`, where `person` is defined). -- When using `get()`, `your_type` **MUST** be [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible). (There is a way to bypass this requirement described later.) -- In function `from_json`, use function [`at()`](https://nlohmann.github.io/json/classnlohmann_1_1basic__json_a93403e803947b86f4da2d1fb3345cf2c.html#a93403e803947b86f4da2d1fb3345cf2c) to access the object values rather than `operator[]`. In case a key does not exists, `at` throws an exception that you can handle, whereas `operator[]` exhibits undefined behavior. -- In case your type contains several `operator=` definitions, code like `your_variable = your_json;` [may not compile](https://github.com/nlohmann/json/issues/667). You need to write `your_variable = your_json.get();` instead. -- You do not need to add serializers or deserializers for STL types like `std::vector`: the library already implements these. - -#### How do I convert third-party types? - -This requires a bit more advanced technique. But first, let's see how this conversion mechanism works: - -The library uses **JSON Serializers** to convert types to json. -The default serializer for `nlohmann::json` is `nlohmann::adl_serializer` (ADL means [Argument-Dependent Lookup](http://en.cppreference.com/w/cpp/language/adl)). - -It is implemented like this (simplified): - -```cpp -template -struct adl_serializer { - static void to_json(json& j, const T& value) { - // calls the "to_json" method in T's namespace - } - - static void from_json(const json& j, T& value) { - // same thing, but with the "from_json" method - } -}; -``` - -This serializer works fine when you have control over the type's namespace. However, what about `boost::optional`, or `std::filesystem::path` (C++17)? Hijacking the `boost` namespace is pretty bad, and it's illegal to add something other than template specializations to `std`... - -To solve this, you need to add a specialization of `adl_serializer` to the `nlohmann` namespace, here's an example: - -```cpp -// partial specialization (full specialization works too) -namespace nlohmann { - template - struct adl_serializer> { - static void to_json(json& j, const boost::optional& opt) { - if (opt == boost::none) { - j = nullptr; - } else { - j = *opt; // this will call adl_serializer::to_json which will - // find the free function to_json in T's namespace! - } - } - - static void from_json(const json& j, boost::optional& opt) { - if (j.is_null()) { - opt = boost::none; - } else { - opt = j.get(); // same as above, but with - // adl_serializer::from_json - } - } - }; -} -``` - -#### How can I use `get()` for non-default constructible/non-copyable types? - -There is a way, if your type is [MoveConstructible](http://en.cppreference.com/w/cpp/concept/MoveConstructible). You will need to specialize the `adl_serializer` as well, but with a special `from_json` overload: - -```cpp -struct move_only_type { - move_only_type() = delete; - move_only_type(int ii): i(ii) {} - move_only_type(const move_only_type&) = delete; - move_only_type(move_only_type&&) = default; - - int i; -}; - -namespace nlohmann { - template <> - struct adl_serializer { - // note: the return type is no longer 'void', and the method only takes - // one argument - static move_only_type from_json(const json& j) { - return {j.get()}; - } - - // Here's the catch! You must provide a to_json method! Otherwise you - // will not be able to convert move_only_type to json, since you fully - // specialized adl_serializer on that type - static void to_json(json& j, move_only_type t) { - j = t.i; - } - }; -} -``` - -#### Can I write my own serializer? (Advanced use) - -Yes. You might want to take a look at [`unit-udt.cpp`](https://github.com/nlohmann/json/blob/develop/test/src/unit-udt.cpp) in the test suite, to see a few examples. - -If you write your own serializer, you'll need to do a few things: - -- use a different `basic_json` alias than `nlohmann::json` (the last template parameter of `basic_json` is the `JSONSerializer`) -- use your `basic_json` alias (or a template parameter) in all your `to_json`/`from_json` methods -- use `nlohmann::to_json` and `nlohmann::from_json` when you need ADL - -Here is an example, without simplifications, that only accepts types with a size <= 32, and uses ADL. - -```cpp -// You should use void as a second template argument -// if you don't need compile-time checks on T -template::type> -struct less_than_32_serializer { - template - static void to_json(BasicJsonType& j, T value) { - // we want to use ADL, and call the correct to_json overload - using nlohmann::to_json; // this method is called by adl_serializer, - // this is where the magic happens - to_json(j, value); - } - - template - static void from_json(const BasicJsonType& j, T& value) { - // same thing here - using nlohmann::from_json; - from_json(j, value); - } -}; -``` - -Be **very** careful when reimplementing your serializer, you can stack overflow if you don't pay attention: - -```cpp -template -struct bad_serializer -{ - template - static void to_json(BasicJsonType& j, const T& value) { - // this calls BasicJsonType::json_serializer::to_json(j, value); - // if BasicJsonType::json_serializer == bad_serializer ... oops! - j = value; - } - - template - static void to_json(const BasicJsonType& j, T& value) { - // this calls BasicJsonType::json_serializer::from_json(j, value); - // if BasicJsonType::json_serializer == bad_serializer ... oops! - value = j.template get(); // oops! - } -}; -``` - -### Binary formats (CBOR and MessagePack) - -Though JSON is a ubiquitous data format, it is not a very compact format suitable for data exchange, for instance over a network. Hence, the library supports [CBOR](http://cbor.io) (Concise Binary Object Representation) and [MessagePack](http://msgpack.org) to efficiently encode JSON values to byte vectors and to decode such vectors. - -```cpp -// create a JSON value -json j = R"({"compact": true, "schema": 0})"_json; - -// serialize to CBOR -std::vector v_cbor = json::to_cbor(j); - -// 0xa2, 0x67, 0x63, 0x6f, 0x6d, 0x70, 0x61, 0x63, 0x74, 0xf5, 0x66, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x00 - -// roundtrip -json j_from_cbor = json::from_cbor(v_cbor); - -// serialize to MessagePack -std::vector v_msgpack = json::to_msgpack(j); - -// 0x82, 0xa7, 0x63, 0x6f, 0x6d, 0x70, 0x61, 0x63, 0x74, 0xc3, 0xa6, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x00 - -// roundtrip -json j_from_msgpack = json::from_msgpack(v_msgpack); -``` - -## Supported compilers - -Though it's 2016 already, the support for C++11 is still a bit sparse. Currently, the following compilers are known to work: - -- GCC 4.9 - 7.1 (and possibly later) -- Clang 3.4 - 5.0 (and possibly later) -- Microsoft Visual C++ 2015 / Build Tools 14.0.25123.0 (and possibly later) -- Microsoft Visual C++ 2017 / Build Tools 15.1.548.43366 (and possibly later) - -I would be happy to learn about other compilers/versions. - -Please note: - -- GCC 4.8 does not work because of two bugs ([55817](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=55817) and [57824](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=57824)) in the C++11 support. Note there is a [pull request](https://github.com/nlohmann/json/pull/212) to fix some of the issues. -- Android defaults to using very old compilers and C++ libraries. To fix this, add the following to your `Application.mk`. This will switch to the LLVM C++ library, the Clang compiler, and enable C++11 and other features disabled by default. - -```bb - APP_STL := c++_shared - NDK_TOOLCHAIN_VERSION := clang3.6 - APP_CPPFLAGS += -frtti -fexceptions -``` - -The code compiles successfully with [Android NDK](https://developer.android.com/ndk/index.html?hl=ml), Revision 9 - 11 (and possibly later) and [CrystaX's Android NDK](https://www.crystax.net/en/android/ndk) version 10. - -- For GCC running on MinGW or Android SDK, the error `'to_string' is not a member of 'std'` (or similarly, for `strtod`) may occur. Note this is not an issue with the code, but rather with the compiler itself. On Android, see above to build with a newer environment. For MinGW, please refer to [this site](http://tehsausage.com/mingw-to-string) and [this discussion](https://github.com/nlohmann/json/issues/136) for information on how to fix this bug. For Android NDK using `APP_STL := gnustl_static`, please refer to [this discussion](https://github.com/nlohmann/json/issues/219). - -The following compilers are currently used in continuous integration at [Travis](https://travis-ci.org/nlohmann/json) and [AppVeyor](https://ci.appveyor.com/project/nlohmann/json): - -| Compiler | Operating System | Version String | -|-----------------|------------------------------|----------------| -| GCC 4.9.4 | Ubuntu 14.04.5 LTS | g++-4.9 (Ubuntu 4.9.4-2ubuntu1~14.04.1) 4.9.4 | -| GCC 5.4.1 | Ubuntu 14.04.5 LTS | g++-5 (Ubuntu 5.4.1-2ubuntu1~14.04) 5.4.1 20160904 | -| GCC 6.3.0 | Ubuntu 14.04.5 LTS | g++-6 (Ubuntu/Linaro 6.3.0-18ubuntu2~14.04) 6.3.0 20170519 | -| GCC 7.1.0 | Ubuntu 14.04.5 LTS | g++-7 (Ubuntu 7.1.0-5ubuntu2~14.04) 7.1.0 -| Clang 3.5.0 | Ubuntu 14.04.5 LTS | clang version 3.5.0-4ubuntu2~trusty2 (tags/RELEASE_350/final) | -| Clang 3.6.2 | Ubuntu 14.04.5 LTS | clang version 3.6.2-svn240577-1~exp1 (branches/release_36) | -| Clang 3.7.1 | Ubuntu 14.04.5 LTS | clang version 3.7.1-svn253571-1~exp1 (branches/release_37) | -| Clang 3.8.0 | Ubuntu 14.04.5 LTS | clang version 3.8.0-2ubuntu3~trusty5 (tags/RELEASE_380/final) | -| Clang 3.9.1 | Ubuntu 14.04.5 LTS | clang version 3.9.1-4ubuntu3~14.04.2 (tags/RELEASE_391/rc2) | -| Clang 4.0.1 | Ubuntu 14.04.5 LTS | clang version 4.0.1-svn305264-1~exp1 (branches/release_40) | -| Clang 5.0.0 | Ubuntu 14.04.5 LTS | clang version 5.0.0-svn310902-1~exp1 (branches/release_50) | -| Clang Xcode 6.4 | Darwin Kernel Version 14.3.0 (OSX 10.10.3) | Apple LLVM version 6.1.0 (clang-602.0.53) (based on LLVM 3.6.0svn) | -| Clang Xcode 7.3 | Darwin Kernel Version 15.0.0 (OSX 10.10.5) | Apple LLVM version 7.3.0 (clang-703.0.29) | -| Clang Xcode 8.0 | Darwin Kernel Version 15.6.0 | Apple LLVM version 8.0.0 (clang-800.0.38) | -| Clang Xcode 8.1 | Darwin Kernel Version 16.1.0 (macOS 10.12.1) | Apple LLVM version 8.0.0 (clang-800.0.42.1) | -| Clang Xcode 8.2 | Darwin Kernel Version 16.1.0 (macOS 10.12.1) | Apple LLVM version 8.0.0 (clang-800.0.42.1) | -| Clang Xcode 8.3 | Darwin Kernel Version 16.5.0 (macOS 10.12.4) | Apple LLVM version 8.1.0 (clang-802.0.38) | -| Clang Xcode 9 beta | Darwin Kernel Version 16.6.0 (macOS 10.12.5) | Apple LLVM version 9.0.0 (clang-900.0.26) | -| Visual Studio 14 2015 | Windows Server 2012 R2 (x64) | Microsoft (R) Build Engine version 14.0.25420.1 | -| Visual Studio 2017 | Windows Server 2016 | Microsoft (R) Build Engine version 15.1.1012.6693 | - -## License - -The class is licensed under the [MIT License](http://opensource.org/licenses/MIT): - -Copyright © 2013-2017 [Niels Lohmann](http://nlohmann.me) - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -## Thanks - -I deeply appreciate the help of the following people. - -- [Teemperor](https://github.com/Teemperor) implemented CMake support and lcov integration, realized escape and Unicode handling in the string parser, and fixed the JSON serialization. -- [elliotgoodrich](https://github.com/elliotgoodrich) fixed an issue with double deletion in the iterator classes. -- [kirkshoop](https://github.com/kirkshoop) made the iterators of the class composable to other libraries. -- [wancw](https://github.com/wanwc) fixed a bug that hindered the class to compile with Clang. -- Tomas Åblad found a bug in the iterator implementation. -- [Joshua C. Randall](https://github.com/jrandall) fixed a bug in the floating-point serialization. -- [Aaron Burghardt](https://github.com/aburgh) implemented code to parse streams incrementally. Furthermore, he greatly improved the parser class by allowing the definition of a filter function to discard undesired elements while parsing. -- [Daniel Kopeček](https://github.com/dkopecek) fixed a bug in the compilation with GCC 5.0. -- [Florian Weber](https://github.com/Florianjw) fixed a bug in and improved the performance of the comparison operators. -- [Eric Cornelius](https://github.com/EricMCornelius) pointed out a bug in the handling with NaN and infinity values. He also improved the performance of the string escaping. -- [易思龙](https://github.com/likebeta) implemented a conversion from anonymous enums. -- [kepkin](https://github.com/kepkin) patiently pushed forward the support for Microsoft Visual studio. -- [gregmarr](https://github.com/gregmarr) simplified the implementation of reverse iterators and helped with numerous hints and improvements. In particular, he pushed forward the implementation of user-defined types. -- [Caio Luppi](https://github.com/caiovlp) fixed a bug in the Unicode handling. -- [dariomt](https://github.com/dariomt) fixed some typos in the examples. -- [Daniel Frey](https://github.com/d-frey) cleaned up some pointers and implemented exception-safe memory allocation. -- [Colin Hirsch](https://github.com/ColinH) took care of a small namespace issue. -- [Huu Nguyen](https://github.com/whoshuu) correct a variable name in the documentation. -- [Silverweed](https://github.com/silverweed) overloaded `parse()` to accept an rvalue reference. -- [dariomt](https://github.com/dariomt) fixed a subtlety in MSVC type support and implemented the `get_ref()` function to get a reference to stored values. -- [ZahlGraf](https://github.com/ZahlGraf) added a workaround that allows compilation using Android NDK. -- [whackashoe](https://github.com/whackashoe) replaced a function that was marked as unsafe by Visual Studio. -- [406345](https://github.com/406345) fixed two small warnings. -- [Glen Fernandes](https://github.com/glenfe) noted a potential portability problem in the `has_mapped_type` function. -- [Corbin Hughes](https://github.com/nibroc) fixed some typos in the contribution guidelines. -- [twelsby](https://github.com/twelsby) fixed the array subscript operator, an issue that failed the MSVC build, and floating-point parsing/dumping. He further added support for unsigned integer numbers and implemented better roundtrip support for parsed numbers. -- [Volker Diels-Grabsch](https://github.com/vog) fixed a link in the README file. -- [msm-](https://github.com/msm-) added support for american fuzzy lop. -- [Annihil](https://github.com/Annihil) fixed an example in the README file. -- [Themercee](https://github.com/Themercee) noted a wrong URL in the README file. -- [Lv Zheng](https://github.com/lv-zheng) fixed a namespace issue with `int64_t` and `uint64_t`. -- [abc100m](https://github.com/abc100m) analyzed the issues with GCC 4.8 and proposed a [partial solution](https://github.com/nlohmann/json/pull/212). -- [zewt](https://github.com/zewt) added useful notes to the README file about Android. -- [Róbert Márki](https://github.com/robertmrk) added a fix to use move iterators and improved the integration via CMake. -- [Chris Kitching](https://github.com/ChrisKitching) cleaned up the CMake files. -- [Tom Needham](https://github.com/06needhamt) fixed a subtle bug with MSVC 2015 which was also proposed by [Michael K.](https://github.com/Epidal). -- [Mário Feroldi](https://github.com/thelostt) fixed a small typo. -- [duncanwerner](https://github.com/duncanwerner) found a really embarrassing performance regression in the 2.0.0 release. -- [Damien](https://github.com/dtoma) fixed one of the last conversion warnings. -- [Thomas Braun](https://github.com/t-b) fixed a warning in a test case. -- [Théo DELRIEU](https://github.com/theodelrieu) patiently and constructively oversaw the long way toward [iterator-range parsing](https://github.com/nlohmann/json/issues/290). He also implemented the magic behind the serialization/deserialization of user-defined types. -- [Stefan](https://github.com/5tefan) fixed a minor issue in the documentation. -- [Vasil Dimov](https://github.com/vasild) fixed the documentation regarding conversions from `std::multiset`. -- [ChristophJud](https://github.com/ChristophJud) overworked the CMake files to ease project inclusion. -- [Vladimir Petrigo](https://github.com/vpetrigo) made a SFINAE hack more readable and added Visual Studio 17 to the build matrix. -- [Denis Andrejew](https://github.com/seeekr) fixed a grammar issue in the README file. -- [Pierre-Antoine Lacaze](https://github.com/palacaze) found a subtle bug in the `dump()` function. -- [TurpentineDistillery](https://github.com/TurpentineDistillery) pointed to [`std::locale::classic()`](http://en.cppreference.com/w/cpp/locale/locale/classic) to avoid too much locale joggling, found some nice performance improvements in the parser, improved the benchmarking code, and realized locale-independent number parsing and printing. -- [cgzones](https://github.com/cgzones) had an idea how to fix the Coverity scan. -- [Jared Grubb](https://github.com/jaredgrubb) silenced a nasty documentation warning. -- [Yixin Zhang](https://github.com/qwename) fixed an integer overflow check. -- [Bosswestfalen](https://github.com/Bosswestfalen) merged two iterator classes into a smaller one. -- [Daniel599](https://github.com/Daniel599) helped to get Travis execute the tests with Clang's sanitizers. -- [Jonathan Lee](https://github.com/vjon) fixed an example in the README file. -- [gnzlbg](https://github.com/gnzlbg) supported the implementation of user-defined types. -- [Alexej Harm](https://github.com/qis) helped to get the user-defined types working with Visual Studio. -- [Jared Grubb](https://github.com/jaredgrubb) supported the implementation of user-defined types. -- [EnricoBilla](https://github.com/EnricoBilla) noted a typo in an example. -- [Martin Hořeňovský](https://github.com/horenmar) found a way for a 2x speedup for the compilation time of the test suite. -- [ukhegg](https://github.com/ukhegg) found proposed an improvement for the examples section. -- [rswanson-ihi](https://github.com/rswanson-ihi) noted a typo in the README. -- [Mihai Stan](https://github.com/stanmihai4) fixed a bug in the comparison with `nullptr`s. -- [Tushar Maheshwari](https://github.com/tusharpm) added [cotire](https://github.com/sakra/cotire) support to speed up the compilation. -- [TedLyngmo](https://github.com/TedLyngmo) noted a typo in the README, removed unnecessary bit arithmetic, and fixed some `-Weffc++` warnings. -- [Krzysztof Woś](https://github.com/krzysztofwos) made exceptions more visible. -- [ftillier](https://github.com/ftillier) fixed a compiler warning. -- [tinloaf](https://github.com/tinloaf) made sure all pushed warnings are properly popped. -- [Fytch](https://github.com/Fytch) found a bug in the documentation. -- [Jay Sistar](https://github.com/Type1J) implemented a Meson build description. -- [Henry Lee](https://github.com/HenryRLee) fixed a warning in ICC and improved the iterator implementation. -- [Vincent Thiery](https://github.com/vthiery) maintains a package for the Conan package manager. -- [Steffen](https://github.com/koemeet) fixed a potential issue with MSVC and `std::min`. -- [Mike Tzou](https://github.com/Chocobo1) fixed some typos. -- [amrcode](https://github.com/amrcode) noted a missleading documentation about comparison of floats. -- [Oleg Endo](https://github.com/olegendo) reduced the memory consumption by replacing `` with ``. -- [dan-42](https://github.com/dan-42) cleaned up the CMake files to simplify including/reusing of the library. -- [Nikita Ofitserov](https://github.com/himikof) allowed for moving values from initializer lists. -- [Greg Hurrell](https://github.com/wincent) fixed a typo. -- [Dmitry Kukovinets](https://github.com/DmitryKuk) fixed a typo. -- [kbthomp1](https://github.com/kbthomp1) fixed an issue related to the Intel OSX compiler. -- [Markus Werle](https://github.com/daixtrose) fixed a typo. -- [WebProdPP](https://github.com/WebProdPP) fixed a subtle error in a precondition check. - -Thanks a lot for helping out! Please [let me know](mailto:mail@nlohmann.me) if I forgot someone. - -## Used third-party tools - -The library itself contains of a single header file licensed under the MIT license. However, it is built, tested, documented, and whatnot using a lot of third-party tools and services. Thanks a lot! - -- [**American fuzzy lop**](http://lcamtuf.coredump.cx/afl/) for fuzz testing -- [**AppVeyor**](https://www.appveyor.com) for [continuous integration](https://ci.appveyor.com/project/nlohmann/json) on Windows -- [**Artistic Style**](http://astyle.sourceforge.net) for automatic source code identation -- [**benchpress**](https://github.com/sbs-ableton/benchpress) to benchmark the code -- [**Catch**](https://github.com/philsquared/Catch) for the unit tests -- [**Clang**](http://clang.llvm.org) for compilation with code sanitizers -- [**Cmake**](https://cmake.org) for build automation -- [**Codacity**](https://www.codacy.com) for further [code analysis](https://www.codacy.com/app/nlohmann/json) -- [**cotire**](https://github.com/sakra/cotire) to speed of compilation -- [**Coveralls**](https://coveralls.io) to measure [code coverage](https://coveralls.io/github/nlohmann/json) -- [**Coverity Scan**](https://scan.coverity.com) for [static analysis](https://scan.coverity.com/projects/nlohmann-json) -- [**cppcheck**](http://cppcheck.sourceforge.net) for static analysis -- [**cxxopts**](https://github.com/jarro2783/cxxopts) to let benchpress parse command-line parameters -- [**Doxygen**](http://www.stack.nl/~dimitri/doxygen/) to generate [documentation](https://nlohmann.github.io/json/) -- [**git-update-ghpages**](https://github.com/rstacruz/git-update-ghpages) to upload the documentation to gh-pages -- [**Github Changelog Generator**](https://github.com/skywinder/github-changelog-generator) to generate the [ChangeLog](https://github.com/nlohmann/json/blob/develop/ChangeLog.md) -- [**libFuzzer**](http://llvm.org/docs/LibFuzzer.html) to implement fuzz testing for OSS-Fuzz -- [**OSS-Fuzz**](https://github.com/google/oss-fuzz) for continuous fuzz testing of the library -- [**send_to_wandbox**](https://github.com/nlohmann/json/blob/develop/doc/scripts/send_to_wandbox.py) to send code examples to [Wandbox](http://melpon.org/wandbox) -- [**Travis**](https://travis-ci.org) for [continuous integration](https://travis-ci.org/nlohmann/json) on Linux and macOS -- [**Valgrind**](http://valgrind.org) to check for correct memory management -- [**Wandbox**](http://melpon.org/wandbox) for [online examples](http://melpon.org/wandbox/permlink/4NEU6ZZMoM9lpIex) - -## Projects using JSON for Modern C++ - -The library is currently used in Apple macOS Sierra and iOS 10. I am not sure what they are using the library for, but I am happy that it runs on so many devices. - -## Notes - -- The code contains numerous debug **assertions** which can be switched off by defining the preprocessor macro `NDEBUG`, see the [documentation of `assert`](http://en.cppreference.com/w/cpp/error/assert). In particular, note [`operator[]`](https://nlohmann.github.io/json/classnlohmann_1_1basic__json_a2e26bd0b0168abb61f67ad5bcd5b9fa1.html#a2e26bd0b0168abb61f67ad5bcd5b9fa1) implements **unchecked access** for const objects: If the given key is not present, the behavior is undefined (think of a dereferenced null pointer) and yields an [assertion failure](https://github.com/nlohmann/json/issues/289) if assertions are switched on. If you are not sure whether an element in an object exists, use checked access with the [`at()` function](https://nlohmann.github.io/json/classnlohmann_1_1basic__json_a674de1ee73e6bf4843fc5dc1351fb726.html#a674de1ee73e6bf4843fc5dc1351fb726). -- As the exact type of a number is not defined in the [JSON specification](http://rfc7159.net/rfc7159), this library tries to choose the best fitting C++ number type automatically. As a result, the type `double` may be used to store numbers which may yield [**floating-point exceptions**](https://github.com/nlohmann/json/issues/181) in certain rare situations if floating-point exceptions have been unmasked in the calling code. These exceptions are not caused by the library and need to be fixed in the calling code, such as by re-masking the exceptions prior to calling library functions. -- The library supports **Unicode input** as follows: - - Only **UTF-8** encoded input is supported which is the default encoding for JSON according to [RFC 7159](http://rfc7159.net/rfc7159#rfc.section.8.1). - - Other encodings such as Latin-1, UTF-16, or UTF-32 are not supported and will yield parse errors. - - [Unicode noncharacters](http://www.unicode.org/faq/private_use.html#nonchar1) will not be replaced by the library. - - Invalid surrogates (e.g., incomplete pairs such as `\uDEAD`) will yield parse errors. - - The strings stored in the library are UTF-8 encoded. When using the default string type (`std::string`), note that its length/size functions return the number of stored bytes rather than the number of characters or glyphs. -- The code can be compiled without C++ **runtime type identification** features; that is, you can use the `-fno-rtti` compiler flag. -- **Exceptions** are used widely within the library. They can, however, be switched off with either using the compiler flag `-fno-exceptions` or by defining the symbol `JSON_NOEXCEPTION`. In this case, exceptions are replaced by an `abort()` call. -- By default, the library does not preserve the **insertion order of object elements**. This is standards-compliant, as the [JSON standard](https://tools.ietf.org/html/rfc7159.html) defines objects as "an unordered collection of zero or more name/value pairs". If you do want to preserve the insertion order, you can specialize the object type with containers like [`tsl::ordered_map`](https://github.com/Tessil/ordered-map) or [`nlohmann::fifo_map`](https://github.com/nlohmann/fifo_map). - -## Execute unit tests - -To compile and run the tests, you need to execute - -```sh -$ make json_unit -Ctest -$ ./test/json_unit "*" - -=============================================================================== -All tests passed (14504461 assertions in 48 test cases) -``` - -Alternatively, you can use [CMake](https://cmake.org) and run - -```sh -mkdir build -cd build -cmake .. -make -ctest -``` - -For more information, have a look at the file [.travis.yml](https://github.com/nlohmann/json/blob/master/.travis.yml). \ No newline at end of file diff --git a/docs/3_Developer_Guides/4_AFB_Helper_Guide/8_C_JSON_Wrapper.md b/docs/3_Developer_Guides/4_AFB_Helper_Guide/8_C_JSON_Wrapper.md deleted file mode 100644 index e106a18..0000000 --- a/docs/3_Developer_Guides/4_AFB_Helper_Guide/8_C_JSON_Wrapper.md +++ /dev/null @@ -1,341 +0,0 @@ ---- -title: C JSON Wrapper ---- - - - -WRAP-JSON facility -================== - -The facility wrap-json is based on the pack/unpack API on the -library jansson. The two chapters below are copied from the -documentation of jansson library copyrighted by Petri Lehtinen -(see at end). - -Building Values ---------------- - -This section describes functions that help to create, or *pack*, complex -JSON values, especially nested objects and arrays. Value building is -based on a *format string* that is used to tell the functions about the -expected arguments. - -For example, the format string `"i"` specifies a single integer value, -while the format string `"[ssb]"` or the equivalent `"[s, s, b]"` -specifies an array value with two strings and a boolean as its items: - - /* Create the JSON integer 42 */ - wrap_json_pack(&result, "i", 42); - - /* Create the JSON array ["foo", "bar", true] */ - wrap_json_pack(&result, "[ssb]", "foo", "bar", 1); - -Here's the full list of format specifiers. The type in parentheses -denotes the resulting JSON type, and the type in brackets (if any) -denotes the C type that is expected as the corresponding argument or -arguments. - -- `s` (string) \[const char \*\] - - Convert a null terminated UTF-8 string to a JSON string. - -- `s?` (string) \[const char \*\] - - Like `s`, but if the argument is *NULL*, output a JSON null value. - -- `s*` (string) \[const char \*\] - - Like `s`, but if the argument is *NULL*, do not output any value. - This format can only be used inside an object or an array. If used - inside an object, the corresponding key is additionally suppressed - when the value is omitted. See below for an example. - -- `s#` (string) \[const char \*, int\] - - Convert a UTF-8 buffer of a given length to a JSON string. - -- `s%` (string) \[const char \*, size\_t\] - - Like `s#` but the length argument is of type size\_t. - -- `+` \[const char \*\] - - Like `s`, but concatenate to the previous string. Only valid after - `s`, `s#`, `+` or `+#`. - -- `+#` \[const char \*, int\] - - Like `s#`, but concatenate to the previous string. Only valid after - `s`, `s#`, `+` or `+#`. - -- `+%` (string) \[const char \*, size\_t\] - - Like `+#` but the length argument is of type size\_t. - -- `y` (byte array) \[const uint8_t \*, size\_t\] - - Convert the byte array whose length is given to - its base64url string representation. - -- `Y` (byte array) \[const uint8_t \*, size\_t\] - - Like 'y' but output is base64. - -- `y?`, `Y?` (byte array or null) \[const uint8_t \*, size\_t\] - - Like 'y' or 'Y' but allows to output a JSON null value - either when the buffer is *NULL* or when the size is *0*. - -- `y*`, `y*` (optional byte array) \[const uint8_t \*, size\_t\] - - Like 'y' or 'Y' but do not put JSON value - either when the buffer is *NULL* or when the size is *0*. - This format can only be used inside an object or an array. If used - inside an object, the corresponding key is additionally suppressed - when the value is omitted. See below for an example. - -- `n` (null) - - Output a JSON null value. No argument is consumed. - -- `b` (boolean) \[int\] - - Convert a C int to JSON boolean value. Zero is converted to `false` - and non-zero to `true`. - -- `i` (integer) \[int\] - - Convert a C int to JSON integer. - -- `I` (integer) \[json\_int\_t\] - - Convert a C json\_int\_t to JSON integer. - -- `f` (real) \[double\] - - Convert a C double to JSON real. - -- `o` (any value) \[json\_t \*\] - - Output any given JSON value as-is. If the value is added to an array - or object, the reference to the value passed to `o` is stolen by the - container. - -- `O` (any value) \[json\_t \*\] - - Like `o`, but the argument's reference count is incremented. This is - useful if you pack into an array or object and want to keep the - reference for the JSON value consumed by `O` to yourself. - -- `o?`, `O?` (any value) \[json\_t \*\] - - Like `o` and `O`, respectively, but if the argument is *NULL*, - output a JSON null value. - -- `o*`, `O*` (any value) \[json\_t \*\] - - Like `o` and `O`, respectively, but if the argument is *NULL*, do - not output any value. This format can only be used inside an object - or an array. If used inside an object, the corresponding key is - additionally suppressed. See below for an example. - -- `[fmt]` (array) - - Build an array with contents from the inner format string. `fmt` may - contain objects and arrays, i.e. recursive value building is - supported. - -- `{fmt}` (object) - - Build an object with contents from the inner format string `fmt`. - The first, third, etc. format specifier represent a key, and must be - a string (see `s`, `s#`, `+` and `+#` above), as object keys are - always strings. The second, fourth, etc. format specifier represent - a value. Any value may be an object or array, i.e. recursive value - building is supported. - -Whitespace, `:` and `,` are ignored. - -More examples: - - /* Build an empty JSON object */ - wrap_json_pack(&result, "{}"); - - /* Build the JSON object {"foo": 42, "bar": 7} */ - wrap_json_pack(&result, "{sisi}", "foo", 42, "bar", 7); - - /* Like above, ':', ',' and whitespace are ignored */ - wrap_json_pack(&result, "{s:i, s:i}", "foo", 42, "bar", 7); - - /* Build the JSON array [[1, 2], {"cool": true}] */ - wrap_json_pack(&result, "[[i,i],{s:b}]", 1, 2, "cool", 1); - - /* Build a string from a non-null terminated buffer */ - char buffer[4] = {'t', 'e', 's', 't'}; - wrap_json_pack(&result, "s#", buffer, 4); - - /* Concatenate strings together to build the JSON string "foobarbaz" */ - wrap_json_pack(&result, "s++", "foo", "bar", "baz"); - - /* Create an empty object or array when optional members are missing */ - wrap_json_pack(&result, "{s:s*,s:o*,s:O*}", "foo", NULL, "bar", NULL, "baz", NULL); - wrap_json_pack(&result, "[s*,o*,O*]", NULL, NULL, NULL); - -Parsing and Validating Values ------------------------------ - -This section describes functions that help to validate complex values -and extract, or *unpack*, data from them. Like building values -<apiref-pack>, this is also based on format strings. - -While a JSON value is unpacked, the type specified in the format string -is checked to match that of the JSON value. This is the validation part -of the process. In addition to this, the unpacking functions can also -check that all items of arrays and objects are unpacked. This check be -enabled with the format specifier `!` or by using the flag -`JSON_STRICT`. See below for details. - -Here's the full list of format specifiers. The type in parentheses -denotes the JSON type, and the type in brackets (if any) denotes the C -type whose address should be passed. - -- `s` (string) \[const char \*\] - - Convert a JSON string to a pointer to a null terminated UTF-8 - string. The resulting string is extracted by using - json\_string\_value() internally, so it exists as long as there are - still references to the corresponding JSON string. - -- `s%` (string) \[const char \*, size\_t \*\] - - Convert a JSON string to a pointer to a null terminated UTF-8 string - and its length. - -- `y` (byte array) \[uint8_t \*\*, size\_t \*\] - - Convert an input string base64url encoded to its - byte array representation. The result and its length - are stored. The returned buffer must be freed by the caller. - -- `Y` (byte array) \[uint8_t \*\*, size\_t \*\] - - Like 'y' but input is base64. - -- `n` (null) - - Expect a JSON null value. Nothing is extracted. - -- `b` (boolean) \[int\] - - Convert a JSON boolean value to a C int, so that `true` is converted - to 1 and `false` to 0. - -- `i` (integer) \[int\] - - Convert a JSON integer to C int. - -- `I` (integer) \[json\_int\_t\] - - Convert a JSON integer to C json\_int\_t. - -- `f` (real) \[double\] - - Convert a JSON real to C double. - -- `F` (integer or real) \[double\] - - Convert a JSON number (integer or real) to C double. - -- `o` (any value) \[json\_t \*\] - - Store a JSON value with no conversion to a json\_t pointer. - -- `O` (any value) \[json\_t \*\] - - Like `O`, but the JSON value's reference count is incremented. - -- `[fmt]` (array) - - Convert each item in the JSON array according to the inner format - string. `fmt` may contain objects and arrays, i.e. recursive value - extraction is supported. - -- `{fmt}` (object) - - Convert each item in the JSON object according to the inner format - string `fmt`. The first, third, etc. format specifier represent a - key, and must be `s`. The corresponding argument to unpack functions - is read as the object key. The second fourth, etc. format specifier - represent a value and is written to the address given as the - corresponding argument. **Note** that every other argument is read - from and every other is written to. - - `fmt` may contain objects and arrays as values, i.e. recursive value - extraction is supported. - -- `!` - - This special format specifier is used to enable the check that all - object and array items are accessed, on a per-value basis. It must - appear inside an array or object as the last format specifier before - the closing bracket or brace. - -- `*` - - This special format specifier is the opposite of `!`. This is the default. - It must appear inside an array or object as the last format specifier - before the closing bracket or brace. - -Whitespace, `:` and `,` are ignored. - -Examples: - - /* root is the JSON integer 42 */ - int myint; - wrap_json_unpack(root, "i", &myint); - assert(myint == 42); - - /* root is the JSON object {"foo": "bar", "quux": true} */ - const char *str; - int boolean; - wrap_json_unpack(root, "{s:s, s:b}", "foo", &str, "quux", &boolean); - assert(strcmp(str, "bar") == 0 && boolean == 1); - - /* root is the JSON array [[1, 2], {"baz": null} */ - wrap_json_check(root, "[[i,i], {s:n}]", "baz"); - /* returns 0 for validation success, nothing is extracted */ - - /* root is the JSON array [1, 2, 3, 4, 5] */ - int myint1, myint2; - wrap_json_unpack(root, "[ii!]", &myint1, &myint2); - /* returns -1 for failed validation */ - - /* root is an empty JSON object */ - int myint = 0, myint2 = 0, myint3 = 0; - wrap_json_unpack(root, "{s?i, s?[ii]}", - "foo", &myint1, - "bar", &myint2, &myint3); - /* myint1, myint2 or myint3 is no touched as "foo" and "bar" don't exist */ - -Copyright ---------- - -Copyright (c) 2009-2016 Petri Lehtinen - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/docs/3_Developer_Guides/5_Using_CMAKE_Applications_Module/1_Project_Architecture.md b/docs/3_Developer_Guides/5_Using_CMAKE_Applications_Module/1_Project_Architecture.md deleted file mode 100644 index 0602ea1..0000000 --- a/docs/3_Developer_Guides/5_Using_CMAKE_Applications_Module/1_Project_Architecture.md +++ /dev/null @@ -1,74 +0,0 @@ ---- -title: Project Architecture ---- - -The following tree structure represents a typical CMake project -directory structure: - -```tree - -| -├── CMakeLists.txt -│ -├── autobuild/ -│ ├── agl -│ │ └── autobuild -│ ├── linux -│ │ └── autobuild -│ └── windows -│ └── autobuild -├── conf.d/ -│ ├── packaging/ -│ │ ├── rpm -│ │ │ └── package.spec -│ │ └── deb -│ │ ├── package.dsc -│ │ ├── debian.package.install -│ │ ├── debian.changelog -│ │ ├── debian.compat -│ │ ├── debian.control -│ │ └── debian.rules -│ ├── cmake -│ │ ├── 00-debian-osconfig.cmake -│ │ ├── 00-suse-osconfig.cmake -│ │ ├── 01-default-osconfig.cmake -│ │ └── config.cmake -│ └── wgt -│ ├── icon.png -│ └── config.xml.in -├── -│ └── -├── -│ └── -└── - └── -``` - -| File or Directory | Parent | Description | -|----|----|----| -| *root_path* | n/a | CMake project root path. Holds the master CMakeLists.txt file and all general project files. -| CMakeLists.txt | The master CMakeLists.txt file. -| autobuild/ | *root_path* | Scripts generated from app-templates to build packages the same way for differents platforms. -| conf.d/ | *root_path* | Holds needed files to build, install, debug, and package an AGL application project. -| packaging/ | conf.d/ | Contains output files used to build packages. -| cmake/ | conf.d/ | Minimally contains the config.cmake file, which is modified from the sample provided in the app-templates submodule. -| wgt/ | conf.d/ | Contains config.xml.in and optionaly the test-config.xml.in template files that are modified from the sample provided with the CMake module for the needs of the project. For more details, see the config.xml.in.sample and test-config.xml.in.sample files. -| *target* | *root_path* | A target to build, which is typically a library or executable. - -When building projects using CMake, the build process automatically detects -the `CMakeLists.txt` and `*.cmake` files. -To help with this process, the `PROJECT_SRC_DIR_PATTERN` variable -is used for recursive pattern searching from the CMake project's -*root_path* downward. -Each sub-folder below *root_path* in the project is searched and included -during compilation. -The directories matching the pattern `PROJECT_SRC_DIR_PATTERN` variable -are scanned. - -**NOTE:** The `PROJECT_SRC_DIR_PATTERN` variable defaults to "*". - -When the `CMakeLists.txt` file is found, the directory in which it is found -is automatically added to the CMake project. - -Similarly, when a file whose extension is `.cmake` is found, the directory in -which that file resides is also added to the CMake project. \ No newline at end of file diff --git a/docs/3_Developer_Guides/5_Using_CMAKE_Applications_Module/2_Configuring_AGL_CMake_Templates.md b/docs/3_Developer_Guides/5_Using_CMAKE_Applications_Module/2_Configuring_AGL_CMake_Templates.md deleted file mode 100644 index a4570ee..0000000 --- a/docs/3_Developer_Guides/5_Using_CMAKE_Applications_Module/2_Configuring_AGL_CMake_Templates.md +++ /dev/null @@ -1,136 +0,0 @@ ---- -title: Configuring AGL CMake Templates ---- - -Configuration consists of editing the `config.cmake` file for your -specific project. - -## Creating Your `config.cmake` File - -First, you need to create a `confd/cmake` file in your CMake project -directory. - -```bash -mkdir -p conf.d/cmake -``` - -Next, use one of the following commands to copy a `cmake.sample` file to -your `config.cmake` file. -The first command applies if you have the SDK installed, while the -second command applies if you installed the modules on your native Linux system. - -**NOTE:** The `OECORE_NATIVE_SYSROOT` variable is defined once you have -a project folder, the AGL SDK source files, and the CMake modules installed. - -```bash -mkdir -p conf.d/cmake -# From the SDK sysroot >= RC2 of the 7.0.0 Guppy release -cp ${OECORE_NATIVE_SYSROOT}/usr/share/doc/CMakeAfbTemplates/samples.d/config.cmake.sample conf.d/cmake/config.cmake -``` - -Once you have created your `config.cmake` file, you need to make the changes -specific to your project. - -## Creating Your `CMakeLists.txt` File - -To create this file, use the example in the **cmake module**. -Use one of the following two commands to create your file. -The first command applies if you have the SDK installed, while the -second command applies if you installed the modules on your native Linux system. - -**NOTE:** The `OECORE_NATIVE_SYSROOT` variable is defined once you have -a project folder, the AGL SDK source files, and the CMake modules installed. - -```bash -# From the SDK sysroot >= RC2 of the 7.0.0 Guppy release -cp ${OECORE_NATIVE_SYSROOT}/usr/share/doc/CMakeAfbTemplates/samples.d/CMakeLists.txt.sample CMakeLists.txt -``` - -## Creating Your CMake Targets - -Creating a CMake target is the result of editing your `CMakeLists.txt` file. - -For each target that is part of your project, you need to use the -***PROJECT_TARGET_ADD*** statement. -Using this statement includes the target in your project. - -Using the ***PROJECT_TARGET_ADD*** statement makes the CMake ***TARGET_NAME*** -variable available until the next ***PROJECT_TARGET_ADD*** statement is -encountered that uses a new target name. - -Following is typical use within the `CMakeLists.txt` file to create a target: - -```cmake -PROJECT_TARGET_ADD(target_name) --> Adds *target_name* to the project. -*target_name* is a sub-folder in the CMake project. - -add_executable/add_library(${TARGET_NAME}.... --> Defines the target sources. - -SET_TARGET_PROPERTIES(${TARGET_NAME} PROPERTIES.... --> Configures the target properties -so they can be used by macros. - -INSTALL(TARGETS ${TARGET_NAME}.... -``` - -## Target Properties - -Target properties are used to determine the nature of the -target and where the target is stored within the package being built. - -Use the **LABELS** property to specify the target type that you want -included in the widget package. -You can choose the following target types: - -Choose between: - -- **BINDING**: A shared library loaded by the AGL Application Framework. -- **BINDINGV2**: A shared library loaded by the AGL Application Framework. - This library must be accompanied by a JSON file named similar to the - *${OUTPUT_NAME}-apidef* of the target, which describes the API with OpenAPI - syntax (e.g: *mybinding-apidef*). - Alternatively, you can choose the name without the extension using the - **set_openapi_filename** macro. - If you use C++, you must set **PROJECT_LANGUAGES** through *CXX*. -- **BINDINGV3**: A shared library loaded by the AGL Application Framework. - This library must be accompanied by a JSON file named similar to the - *${OUTPUT_NAME}-apidef* of the target, which describes the API with OpenAPI - syntax (e.g: *mybinding-apidef*). - Alternatively, you can choose the name without the extension using the - **set_openapi_filename** macro. - If you use C++, you must set **PROJECT_LANGUAGES** through *CXX*. -- **PLUGIN**: A shared library meant to be used as a binding plugin, which - would load the library as a plugin consequently extending its - functionalities. - You should name the binding using a special extension that you choose - with `SUFFIX cmake target property`. - If you do not use the special extension, it defaults to **.ctlso**. -- **HTDOCS**: The root directory of a web application. - This target has to build its directory and puts its files in the - **${CMAKE_CURRENT_BINARY_DIR}/${TARGET_NAME}**. -- **DATA**: Resources used by your application. - This target has to build its directory and puts its files in the - **${CMAKE_CURRENT_BINARY_DIR}/${TARGET_NAME}**. -- **EXECUTABLE**: The entry point of your application executed by the AGL - Application Framework. -- **LIBRARY**: An external third-party library bundled with the binding. - The library is bundled in this manner because the platform does not - provide bundling. -- **BINDING-CONFIG**: Any files used as configuration by your binding. - -**TIP:** you should use the prefix _afb-_ (**Application Framework Binding**) -with your *BINDING* targets. - -Following is an example that uses the **BINDINGV3** property: - -```cmake -SET_TARGET_PROPERTIES(${TARGET_NAME} PROPERTIES - PREFIX "afb-" - LABELS "BINDINGV3" - OUTPUT_NAME "file_output_name") -``` - -**CAUTION**: You do not need to specify an **INSTALL** command for these -targets. -Installation is performed by the template. -Targets are installed in the **${CMAKE_INSTALL_PREFIX}/${PROJECT_NAME}** -directory. \ No newline at end of file diff --git a/docs/3_Developer_Guides/5_Using_CMAKE_Applications_Module/3_Advanced_Usage.md b/docs/3_Developer_Guides/5_Using_CMAKE_Applications_Module/3_Advanced_Usage.md deleted file mode 100644 index 13edf32..0000000 --- a/docs/3_Developer_Guides/5_Using_CMAKE_Applications_Module/3_Advanced_Usage.md +++ /dev/null @@ -1,305 +0,0 @@ ---- -title: Advanced Usage ---- - -This topic describes some advanced ways of using the CMake templates. - -## Building a Widget - -To build a widget, you need a `config.xml` file that describes -your application (widget) and how the Application Framework launches it. -Your repository contains a simple default file named -`config.xml.in` that should work for simple applications and should -not require interactions with other bindings. - -It is also recommended that you use the sample configuration -file that you can find in the location. -This file is named `config.xms.in.sample` and is more complete. -Copy the sample file to your `conf.d/wgt` directory and name it -`config.xml.in`. -Once you have your copy, edit the file to fit your needs. - -**CAUTION:** The default file is only meant to be used for a -simple widget application. -For more complicated applications that need to export -their API, or ship several applications in one widget -need to use the provided `config.xml.in.sample` file, which has -all new Application Framework features explained and provides -examples. - -## Using CMake Template Macros - -To leverage all CMake template features, you must specify properties -on your targets. -Some macros do not work unless you specify the target type. -If you do not specify a type (e.g. a custom target such as an -HTML5 application), the macro uses the `LABELS` property to -determine the target type. - -Aside from those values, the following optional values can be -assigned to the `LABELS` property. -These values define the resource types that make up your test materials: - -- **TEST-CONFIG**: JSON configuration files used by the `afb-test` - binding. - These files execute the tests. -- **TEST-DATA**: Resources used to test your binding. - Minimally, you need a test plan. - You should also consider fixtures and any files required by your tests. - These required files appear as part of a separate test widget. -- **TEST-PLUGIN**: A shared library used as a binding plugin. - A binding loads the library as a plugin to extend the binding's functionality. - You should use a special file extension when you name the library - by using the `SUFFIX` CMake target property. - If you do not choose an extension, `.ctlso` is used by default. -- **TEST-HTDOCS**: The root directory of a web application. - This target has to build its directory and put its files in - the `${CMAKE_CURRENT_BINARY_DIR}/${TARGET_NAME}` directory. -- **TEST-EXECUTABLE**: The entry point of your application executed by the AGL - Application Framework. -- **TEST-LIBRARY**: An external third-party library bundled with the binding - for its own purpose. - The platform does not provide this library. - -Following is a mapping between `LABELS` and directories where files reside in -the widget: - -- **EXECUTABLE** : `/bin` -- **BINDING-CONFIG** : `/etc` -- **BINDING** | **BINDINGV2** | **BINDINGV3** | **LIBRARY** : `/lib` -- **PLUGIN** : `/lib/plugins` -- **HTDOCS** : `/htdocs` -- **BINDING-DATA** : `/var` -- **DATA** : `/var` - -Following is a mapping between test-dedicated `LABELS` and directories where -files reside in the widget: - -- **TEST-EXECUTABLE** : `/bin` -- **TEST-CONFIG** : `/etc` -- **TEST-PLUGIN** : `/lib/plugins` -- **TEST-HTDOCS** : `/htdocs` -- **TEST-DATA** : `/var` - -**TIP:** Use the prefix `afb-` (Application Framework Binding) -with your **BINDING** targets. - -Following is an example that sets the `LABELS` and `OUTPUT_NAME` properties: - -```cmake -SET_TARGET_PROPERTIES(${TARGET_NAME} PROPERTIES - LABELS "HTDOCS" - OUTPUT_NAME dist.prod - ) -``` - -**NOTE**: You do not need to specify an **INSTALL** command for these - targets. - Installation is handled by the template and installs using the - following path : **${CMAKE_INSTALL_PREFIX}/${PROJECT_NAME}** - - Also, if you want to set and use `rpath` with your target, you should use - and set the target property `INSTALL_RPATH`. - -## Adding an External Third-Party Library - -You can add an external third-party library that is built, linked, -and shipped with the project. -Or, you can link and ship the library only with the project. - -### Building, Linking, and Shipping an External Library with the Project - -If you need to include an external library that is not shipped -with the project, you can bundle the required library in the -`lib` widget directory. - -Templates includes facilities to help you work with external -libraries. -A standard method is to declare as many CMake ExternalProject -modules as you need to match the number of needed libraries. - -An ExternalProject module is a special CMake module that lets you define how -to download, update, patch, configure, build, and install an external project. -The project does not need to be a CMake project. -Additionally, you can provide custom steps to account for special -needs using ExternalProject step. -See the CMake -[ExternalProject documentation site](https://cmake.org/cmake/help/v3.5/module/ExternalProject.html?highlight=externalproject) -for more information. - -Following is an example that includes the `mxml` library for the -[unicens2-binding](https://github.com/iotbzh/unicens2-binding) -project: - -```cmake -set(MXML external-mxml) -set(MXML_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/mxml) -ExternalProject_Add(${MXML} - GIT_REPOSITORY https://github.com/michaelrsweet/mxml.git - GIT_TAG release-2.10 - SOURCE_DIR ${MXML_SOURCE_DIR} - CONFIGURE_COMMAND ./configure --build x86_64 --host aarch64 - BUILD_COMMAND make libmxml.so.1.5 - BUILD_IN_SOURCE 1 - INSTALL_COMMAND "" -) - -PROJECT_TARGET_ADD(mxml) - -add_library(${TARGET_NAME} SHARED IMPORTED GLOBAL) - -SET_TARGET_PROPERTIES(${TARGET_NAME} PROPERTIES - LABELS LIBRARY - IMPORTED_LOCATION ${MXML_SOURCE_DIR}/libmxml.so.1 - INTERFACE_INCLUDE_DIRECTORIES ${MXML_SOURCE_DIR} -) - -add_dependencies(${TARGET_NAME} ${MXML}) -``` - -The example defines an external project that drives the building of the library. -The example also defines a new CMake target whose type is **IMPORTED**. -The **IMPORTED** target type indicates the target has yet to be built using -CMake but is available at the location defined using the **IMPORTED_LOCATION** -target property. - -You might want to build the library as **SHARED** or **STATIC** depending on your needs -and goals. -Next, the example only has to modify the external project configure step and change -the filename used by **IMPORTED** library target defined after external project. - -The target's **LABELS** property is set to **LIBRARY** to ship it in the widget. - -In this example, the Unicens project also needs header -information from this library. -Consequently, the **INTERFACE_INCLUDE_DIRECTORIES** target property -is used. -Setting that property when another target links to that imported target -allows access to included directories. - -Finally, the example binds the target to the external project -by using a CMake dependency. - -The target can now be linked and used like any other CMake target. - -### Link and Ship an External Library with the Project - -If you already have a binary version of the library that you want to use and you -cannot or do not want to build the library, you can use the **IMPORTED** -library target. - -To illustrate, consider the same example in the previous section. -Following are the relevant modifications: - -```cmake -PROJECT_TARGET_ADD(mxml) - -add_library(${TARGET_NAME} SHARED IMPORTED GLOBAL) - -SET_TARGET_PROPERTIES(${TARGET_NAME} PROPERTIES - LABELS LIBRARY - IMPORTED_LOCATION /path_to_library/libmxml.so.1 - INTERFACE_INCLUDE_DIRECTORIES /path_to_mxml/include/dir -) -``` - -In the previous example, notice the changes to the -`IMPORTED_LOCATION` and `INTERFACE_INCLUDE_DIRECTORIES` statements. -These locate the binary version of the library. - -Finally, you can link any other library or executable target with this imported -library just as you would for any other target. - -## Macro Reference - -Following are several macros that are useful for advanced CMake usage. - -### PROJECT_TARGET_ADD - -This macro adds the target to your project. -Following is a typical example that adds the target to your project. -You need to provide the name of your target as the macro's parameter: - -Example: - -```cmake -PROJECT_TARGET_ADD(low-can-demo) -``` - -The macro makes the variable `${TARGET_NAME}` available and it is defined -using the specified name (e.g. `low-can-demo`). -The variable changes each time the `PROJECT_TARGET_ADD` macro is called. - -### project_subdirs_add - -This macro searches within specified subfolders of the CMake project for -any `CMakeLists.txt` file. -If the file is found, it is added to your project. -You can use this macro in a hybrid application (e.g. where the binding -exists in a subfolder). - -The following example searches within all subfolders: - -Usage : - -```cmake -project_subdirs_add() -``` - -You might want to restrict the subfolders being searched. -If so, you can specify a -[globbing](https://en.wikipedia.org/wiki/Glob_(programming)) pattern -as the argument. -Doing so effectively creates a search filter. - -Following is an example that specifies all directories that begin -with a number, are followed by the dash character, and then followed -by any characters: - -```cmake -project_subdirs_add("[0-9]-*") -``` - -### set_openapi_filename - -This macro is used with a **BINDINGV2** target and defines the -binding definition filename. -You can use it to also define a relative path to -the current `CMakeLists.txt` file. - -If you do not use this macro to specify the name of your definition file, -the default one is used, which is `${OUTPUT_NAME}-apidef` and uses -**OUTPUT_NAME** as the [target property]. - -**CAUTION** When specifying the binding definition filename, -you must not use the file's extension as part of the name. -Following is an example: - -```cmake -set_openapi_filename('binding/mybinding_definition') -``` - -[target property]: https://cmake.org/cmake/help/v3.6/prop_tgt/OUTPUT_NAME.html "OUTPUT_NAME property documentation" - -### add_input_files - -This macro creates a custom target dedicated for HTML5 and data resource files. -The macro provides syntax and schema verification for different languages that -include LUA, JSON and XML. - -Alongside the macro are tools used to check files. -You can configure the tools by setting the -following variables: - -- XML_CHECKER: Uses **xmllint** that is provided with major linux distributions. -- LUA_CHECKER: Uses **luac** that is provided with major linux distributions. -- JSON_CHECKER: Currently, not used by any tools. - -Following is an example: - -```cmake -add_input_file("${MY_FILES_LIST}") -``` - -**NOTE**: If an issue occurs during the "check" step of the macro, -the build halts. \ No newline at end of file diff --git a/docs/3_Developer_Guides/5_Using_CMAKE_Applications_Module/4_Advanced_Customization.md b/docs/3_Developer_Guides/5_Using_CMAKE_Applications_Module/4_Advanced_Customization.md deleted file mode 100644 index 2b5963c..0000000 --- a/docs/3_Developer_Guides/5_Using_CMAKE_Applications_Module/4_Advanced_Customization.md +++ /dev/null @@ -1,112 +0,0 @@ ---- -title: Advanced Customization ---- - -This section describes how you can include additional CMake files -and custom template scripts. - -## Including Additional CMake Files - -You can include machine and system custom CMake files and -operating system custom CMake files. - -### Machine and System Custom CMake Files - -Advanced configuration is possible by automatically including -additional CMake files from specific locations. -Following are the locations from which you can add CMake -files. -Inclusions occur in the order shown here: - -- `/conf.d/app-templates/cmake/cmake.d` - normally located CMake project files -- `$HOME/.config/app-templates/cmake.d` - the home location -- `/etc/app-templates/cmake.d` - the system location - -The CMake files you include must be named using either of the following conventions: - -- `XX-common*.cmake` -- `XX-${PROJECT_NAME}*.cmake` - -In both formats, `XX` are numbers and indicate the order in which the file -is included. -The `*` character represents the filename. - -When naming the file, consider the projects in which the file needs to be -included. -If you want to include the file in all projects, use the keyword `common`. -If you want to include the file in a specific project, use the `${PROJECT_NAME}` -value. - -For example, if you want a CMake file whose name is `my_custom_file` -included first and you want it included in all projects, name the file -`01-common-my_custom_file.cmake`. -If you want the same file included in a single project defined by the -`PROJECT_NAME` variable, and you want it included after all other files, -name the file `99-${PROJECT_NAME}-my_custom_file.cmake`. - -When you include CMake files that use CMake variables, the values override -variables with the same name. -The exception to this rule is if you use a cached variable. -Following is an example: - -```cmake -set(VARIABLE_NAME 'value string random' CACHE STRING 'docstring') -``` - -In this example, the `VARIABLE_NAME` variable is defined as a cached -variable by using the **CACHE** keyword. -Consequently, `VARIABLE_NAME` does not get overridden as a result of -including a CMake file that sets the same variable. - -### Operating System Custom CMake Files - -Including custom CMake files based on the operating system -lets you personalize a project depending on the operating system -you are using. - -At the end of the `config.cmake` file `common.cmake` includes -CMake files to customize your project build depending on your platform. -The operating system is detected by using `/etc/os-release`, -which is the default method used in almost all Linux distributions. -Consequently, you can use the value of field **ID_LIKE** to -add a CMake file for that distribution. -The file comes from your `conf.d/cmake/` directory or relatively -from your `app-templates` submodule path `app-templates/../cmake/`. - -**NOTE:** If the **ID_LIKE** field does not exist, you can use the -**ID** field. - -Files that you add must be named according to the following file naming -convention: - -- `XX-${OSRELEASE}*.cmake` - -In the naming convention, `XX` represents numbers and is the order in which -you want a file included. -The ${OSRELEASE} value is taken from either the **ID_LIKE** or **ID** field -of the `/etc/os-release` file. - -You can also configure a CMake file to be included in cases where no -specific operating system can be found. -To do so, name your CMake file as follows: - -- `XX-default*.cmake` - -A good use case example for these two naming conventions is when you have -a several Linux distributions and all but one can use the same module. -For that case, name one CMake file using the `${OSRELEASE}` value and -name the CMake file to be used with the other distributions using -the `XX-default*.cmake` method. - -## Including Custom Template Scripts - -You can include your own custom template scripts that are passed to the -CMake command `configure_file`. - -Just create your own script and place it in either of the following directories: - -- `$HOME/.config/app-templates/scripts` - the home location -- `/etc/app-templates/scripts` - the system location - -Scripts only need to use the extension `.in` to be parsed and configured by -CMake. diff --git a/docs/3_Developer_Guides/5_Using_CMAKE_Applications_Module/5_Autobuild.md b/docs/3_Developer_Guides/5_Using_CMAKE_Applications_Module/5_Autobuild.md deleted file mode 100644 index c32a6da..0000000 --- a/docs/3_Developer_Guides/5_Using_CMAKE_Applications_Module/5_Autobuild.md +++ /dev/null @@ -1,152 +0,0 @@ ---- -title: Autobuild ---- - -Applications based on the AGL framework should have a -full build and packaging solution that is independent of the -[Yocto Project](https://www.yoctoproject.org) workflow. - -You can create a script named **autobuild** to control applications -build operations. -AGL provides a BitBake class file (`aglwgt.bbclass`) that calls the -**autobuild** script for all operations. -The class file is located at the top level of the application repository. - -You can write the **autobuild** script using any of the following languages: - -* Makefile -* Bash -* Python - -The script executes directly after applying a `chmod()` command. -The caller, which can be the `aglwgt.bbclass`, a Jenkins job, or an actual person, -must make the **autobuild** executable before calling it. -To facilitate direct execution, you need to start the script with a -[shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)) sequence: - -* '#!/usr/bin/make -f' for Makefile format -* '#!/usr/bin/bash' for Bash format - -The calling convention is similar to the convention used in `make`. -To pass arguments, use environment variables. - -**NOTE:** For Bash, an evaluation of the arguments -sets the environment variables correctly. - -The following format shows the generic call: - -```bash -autobuild/agl/autobuild [ARG1="value1" [ARG2="value2" ... ]] -``` - -The **autobuild** script can be invoked from any directory -with all paths considered to be relative to the -script's location. -For makefile scripts, this is the usual behavior. -For Bash scripts, a `cd $(dirname $0)` command must be run at -the beginning of the script. - -At build time, the following calls must be made in the following order: - -1. Initialize the build environment (e.g if the application uses - `cmake` the configure step runs CMake). - - ```bash - autobuild/agl/autobuild configure CONFIGURE_ARGS="..." - ``` - -2. Build the application (i.e. compile, link binaries, assembles javascript, - and so forth). - - ```bash - autobuild/agl/autobuild build BUILD_ARGS="...." - ``` - -3. Create the widget package(s) in the specified destination path - prepared by the caller. - - ```bash - autobuild/agl/autobuild package PACKAGE_ARGS="..." DEST= - ``` - -4. Create the test widget package(s) in the specified destination path - prepared by the caller. - - ```bash - autobuild/agl/autobuild package-test PACKAGE_ARGS="..." DEST= - ``` - -5. Clean the built files by removing the result of the **autobuild** build. - - ```bash - autobuild/agl/autobuild clean CLEAN_ARGS="..." - ``` - -6. Clean everything by removing the result of the **autobuild** build - and the **autobuild** configure. - - ```bash - autobuild/agl/autobuild distclean DISTCLEAN_ARGS="..." - ``` - -## Integrating **autobuild** into the Yocto Project Workflow - -If you want to integrate the **autobuild** script into the Yocto Project -workflow, you need to generate the script. -To generate the script, use the `autobuild` target. - -The following commands create the **autobuild** script in the -`autobuild/agl` directory: - -```bash -mkdir -p build -cd build -cmake .. && make autobuild -``` - -## Available Targets - -Following are the targets available from the **autobuild** script: - -- **clean**: Removes all the object files and target results generated by Makefile. -- **clean-{release,debug,coverage,test}**: Removes all the object files and target results generated by Makefile for the specified build type. -- **clean-all**: Deletes the build directories for all build types. -- **distclean**: Deletes the build directories for all build types. -- **configure**: Generates the project Makefile from the `CMakeLists.txt` files for the release build type. -- **configure-{release,debug,coverage,test}**: Generates the project Makefile from the `CMakeLists.txt` files for the specified build type. -- **build**: Compiles all project targets for the release build type. -- **build-{release,debug,coverage,test}**: Compiles all project targets for the specified build type. -- **build-all**: Compiles all project targets for all specified build types. -- **package**: Builds the widget (**wgt**) package for the release build type. -- **package-{release,debug,coverage}**: Builds the widget (**wgt**) package for the specified build type. -- **package-test**: Builds the test **wgt** package. -- **package-all**: Builds the widget (**wgt**) packages for all build types. -- **install**: Installs the project into your filesystem. - -Note that `aglwgt.bbclass` only will use the **package-{coverage,test}** targets (and thus the **build-{coverage,test}**, etc. targets) for service bindings by default, so **autobuild** scripts for applications may omit support for those. - -Specifying the following variables lets you modify compilation behavior: - -- **CLEAN_ARGS**: Variable used at **clean** time. -- **CONFIGURE_ARGS**: Variable used at **configure** time. -- **BUILD_ARGS**: Variable used at **build** time. -- **BUILD_DIR**: Build directory for release type build. - The default value is a "build" directory in the root of the project. -- **BUILD_DIR_DEBUG**: Build directory for debug type build. - The default value is a "build-debug" directory in the root of the project. -- **BUILD_DIR_TEST**: Build directory for test type build. - The default value is a "build-test" directory in the root of the project. -- **BUILD_DIR_COVERAGE**: Build directory for coverage type build. - The default value is a "build-coverage" directory in the root of the project. -- **DEST**: Directory in which to place the created ***wgt*** file(s). - The default directory is the build root directory. - -Note that the values of **BUILD_DIR_{DEBUG,TEST,COVERAGE}** are defined based on the value of **BUILD_DIR**, so this needs to be kept in mind if over-riding it and building those other widget types. - -When you provide a variable, use the CMake format (i.e. -BUILD_ARGS="-DC_FLAGS='-g -O2'"). -Following is an example: - -```bash -./autobuild/agl/autobuild package DEST=/tmp -``` diff --git a/docs/3_Developer_Guides/5_Using_CMAKE_Applications_Module/6_Using_CMake_Templates_from_Bitbake_Recipes.md b/docs/3_Developer_Guides/5_Using_CMAKE_Applications_Module/6_Using_CMake_Templates_from_Bitbake_Recipes.md deleted file mode 100644 index 26bf869..0000000 --- a/docs/3_Developer_Guides/5_Using_CMAKE_Applications_Module/6_Using_CMake_Templates_from_Bitbake_Recipes.md +++ /dev/null @@ -1,56 +0,0 @@ ---- -title: Using CMake Templates from BitBake Recipes ---- - -If you have developed an application and you want to include it in an AGL image, -you must add a BitBake recipe in one of the following layers: - -* [meta-agl](https://gerrit.automotivelinux.org/gerrit/#/admin/projects/AGL/meta-agl): - meta-agl layer (core AGL) -* [meta-agl-cluster-demo](https://gerrit.automotivelinux.org/gerrit/#/admin/projects/AGL/meta-agl-cluster-demo): - cluster demo specific recipes and configuration -* [meta-agl-demo](https://gerrit.automotivelinux.org/gerrit/#/admin/projects/AGL/meta-agl-demo): - meta-agl-demo layer (demo/staging/"one-shot") -* [meta-agl-devel](https://gerrit.automotivelinux.org/gerrit/#/admin/projects/AGL/meta-agl-devel): - meta-agl-devel (Development and Community BSPs) -* [meta-agl-extra](https://gerrit.automotivelinux.org/gerrit/#/admin/projects/AGL/meta-agl-extra): - meta-agl-extra (additional/optional components for AGL) - -Once you have the recipe in place, edit it to include the following -line to cause the `aglwgt` class to be inherited: - -```bb -inherit aglwgt -``` - -Following is an example that uses the HVAC application recipe (i.e. `hvac.bb`), which -builds the HVAC application: - -```bb -SUMMARY = "HVAC Service Binding" -DESCRIPTION = "AGL HVAC Service Binding" -HOMEPAGE = "https://gerrit.automotivelinux.org/gerrit/#/admin/projects/apps/agl-service-hvac" -SECTION = "apps" - -LICENSE = "Apache-2.0" -LIC_FILES_CHKSUM = "file://LICENSE;md5=ae6497158920d9524cf208c09cc4c984" - -SRC_URI = "gitsm://gerrit.automotivelinux.org/gerrit/apps/agl-service-hvac;protocol=https;branch=${AGL_BRANCH}" -SRCREV = "${AGL_APP_REVISION}" - -PV = "1.0+git${SRCPV}" -S = "${WORKDIR}/git" - -DEPENDS = "json-c" -RDEPENDS_${PN} += "agl-service-identity-agent" - -inherit cmake aglwgt pkgconfig -``` - -The following links provide more examples of recipes that use the -CMake templates: - -* [agl-service-helloworld](https://gerrit.automotivelinux.org/gerrit/admin/repos/apps/agl-service-helloworld) -* [agl-service-audio-4a](https://gerrit.automotivelinux.org/gerrit/#/admin/projects/apps/agl-service-audio-4a) -* [agl-service-unicens](https://gerrit.automotivelinux.org/gerrit/#/admin/projects/apps/agl-service-unicens) -* [4a-hal-unicens](https://gerrit.automotivelinux.org/gerrit/#/admin/projects/src/4a-hal-unicens) \ No newline at end of file diff --git a/docs/4_APIs_and_Services/0_API_Reference.md b/docs/4_APIs_and_Services/0_API_Reference.md deleted file mode 100644 index 4822bf0..0000000 --- a/docs/4_APIs_and_Services/0_API_Reference.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: API Reference ---- - -# Available APIs - -Introduction of Available APIs with categorization. If multiple categories apply, they will all be listed in the third column (e.g. first row in the following). - - - -| API | Description | Profile | -| --- | --- | --- | -| [agl-service-audiomixer](https://git.automotivelinux.org/apps/agl-service-audiomixer/about/) | Audio Mixer API | | -| [agl-service-bluetooth](https://git.automotivelinux.org/apps/agl-service-bluetooth/about/) | bluetooth binding | Infotainment | -| [agl-service-bluetooth-avrcp](https://git.automotivelinux.org/apps/agl-service-bluetooth-avrcp/) | AGL service that allow multimedia control over Bluetooth AVRCP profile | Infotainment | -| [agl-service-bluetooth-pbap](https://git.automotivelinux.org/apps/agl-service-bluetooth-pbap/about/) | Bluetooth Phone Book Access Protocoll service | Infotainment | -| [agl-service-can-low-level](https://git.automotivelinux.org/apps/agl-service-can-low-level/about/) | Low level CAN service made to decode and write on CAN bus. | Instrument Cluster | -| [agl-service-data-persistence](https://git.automotivelinux.org/apps/agl-service-data-persistence/about/) | AGL binding for data persistence | Instrument Cluster | -| [agl-service-geoclue](https://git.automotivelinux.org/apps/agl-service-geoclue/about/) | AGL Geoclue service to backup GPS positioning with network-based
positioning | Infotainment | -| [agl-service-geofence](https://git.automotivelinux.org/apps/agl-service-geofence/about/) | AGL geofence binding to signal vehicle POI bounding box events | Infotainment | -| [agl-service-gps](https://git.automotivelinux.org/apps/agl-service-gps/about/) | GPS binding | Infotainment | -| [agl-service-gstreamer](https://git.automotivelinux.org/apps/agl-service-gstreamer/) | (deprecated) GStreamer binding for multimedia control and playback | Infotainment | -| [agl-service-harvester](https://git.automotivelinux.org/apps/agl-service-harvester/about/) | V2C interface that collect data to TimeSeries database | | -| [agl-service-homescreen](https://git.automotivelinux.org/apps/agl-service-homescreen/about/) | Applications need a new binding to communicate with homescreen | Infotainment | -| [agl-service-homescreen-2017](https://git.automotivelinux.org/apps/agl-service-homescreen-2017/about/) | Binding for applications to communicate with the homescreen-2017 | Infotainment | -| [agl-service-hvac](https://git.automotivelinux.org/apps/agl-service-hvac/) | Unnamed repository | | -| [agl-service-identity-agent](https://git.automotivelinux.org/apps/agl-service-identity-agent/about/) | Identity Agent | | -| [agl-service-iiodevices](https://git.automotivelinux.org/apps/agl-service-iiodevices/about/) | iiodevices support | Telematics/Connectivity | -| [agl-service-mediaplayer](https://git.automotivelinux.org/apps/agl-service-mediaplayer/about/) | AGL Media Player service that allows applications to control
playing media. | Infotainment | -| [agl-service-mediascanner](https://git.automotivelinux.org/apps/agl-service-mediascanner/about/) | AGL Media Scanning service that allows applications to detect
and index media at... | Telematics/Connectivity | -| [agl-service-navigation](https://git.automotivelinux.org/apps/agl-service-navigation/) | Navigation API with binding | Infotainment | -| [agl-service-network](https://git.automotivelinux.org/apps/agl-service-network/about/) | AGL Network service providing support for management of networking
interfaces in... | | -| [agl-service-nfc](https://git.automotivelinux.org/apps/agl-service-nfc/about/) | AGL service NFC binding | | -| [agl-service-radio](https://git.automotivelinux.org/apps/agl-service-radio/about/) | radio binding | | -| [agl-service-signal-composer](https://git.automotivelinux.org/apps/agl-service-signal-composer/about/) | AGL High Level Signaling service to handle CAN, LIN, and others
signaling source... | Instrument Cluster | -| [agl-service-soundmanager](https://git.automotivelinux.org/apps/agl-service-soundmanager/about/) | Binding for applications to communicate with the soundmanager | | -| [agl-service-soundmanager-2017](https://git.automotivelinux.org/apps/agl-service-soundmanager-2017/about/) | Binding for applications to communicate with the soundmanager-2017 | | -| [agl-service-speech](https://git.automotivelinux.org/apps/agl-service-speech/about/) | AGL App Framework Binding for Speech Services | Telematics/Connectivity | -| [agl-service-steering-wheel](https://git.automotivelinux.org/apps/agl-service-steering-wheel/about/) | And binding service for steering wheel demo | Instrument Cluster | -| [agl-service-taskmanager](https://git.automotivelinux.org/apps/agl-service-taskmanager/about/) | Simple taskmanager service to retrieve data from procps | | -| [agl-service-telephony](https://git.automotivelinux.org/apps/agl-service-telephony/about/) | Unnamed repository | | -| [agl-service-unicens](https://git.automotivelinux.org/apps/agl-service-unicens/about/) | Infotainment network setup and access (using Unified Centralized
Network Stack) | Infotainment | -| [agl-service-weather](https://git.automotivelinux.org/apps/agl-service-weather/about/) | AGL binding that uses OpenWeathermap data to display current
conditions on Homes... | Telematics/Connectivity | -| [agl-service-wifi](https://git.automotivelinux.org/apps/agl-service-wifi/) | wifi binding | Telematics/Connectivity | -| [agl-service-windowmanager](https://git.automotivelinux.org/apps/agl-service-windowmanager/about/) | Binding for applications to communicate with the windowmanager | | -| [agl-service-windowmanager-2017](https://git.automotivelinux.org/apps/agl-service-windowmanager-2017/about/) | Binding for applications to communicate with the windowmanager-2017 | | -| [agl-service-xds](https://git.automotivelinux.org/apps/agl-service-xds/) | AGL binding used to control collected data from AGL
supervision. (empty) | | -| [agl-service-xds-monitoring](https://git.automotivelinux.org/apps/agl-service-xds-monitoring/about/) | UNDER DEVELOPMENT | | diff --git a/docs/4_APIs_and_Services/FIXME.md b/docs/4_APIs_and_Services/FIXME.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/5_Component_Documentation/5_appfw.md b/docs/5_Component_Documentation/5_application_framework.md similarity index 100% rename from docs/5_Component_Documentation/5_appfw.md rename to docs/5_Component_Documentation/5_application_framework.md diff --git a/docs/5_Component_Documentation/6_cynagora.md b/docs/5_Component_Documentation/6_cynagora.md deleted file mode 100644 index d2c74ce..0000000 --- a/docs/5_Component_Documentation/6_cynagora.md +++ /dev/null @@ -1,7 +0,0 @@ ---- -title: Cynagora ---- - -# cynagora - -FIXME. diff --git a/docs/5_Component_Documentation/8_pipewire_wireplumber.md b/docs/5_Component_Documentation/6_pipewire_wireplumber.md similarity index 100% rename from docs/5_Component_Documentation/8_pipewire_wireplumber.md rename to docs/5_Component_Documentation/6_pipewire_wireplumber.md diff --git a/docs/5_Component_Documentation/9_ic-sound-manager.md b/docs/5_Component_Documentation/7_ic-sound-manager.md similarity index 100% rename from docs/5_Component_Documentation/9_ic-sound-manager.md rename to docs/5_Component_Documentation/7_ic-sound-manager.md diff --git a/docs/5_Component_Documentation/7_pyagl.md b/docs/5_Component_Documentation/7_pyagl.md deleted file mode 100644 index 40f0a53..0000000 --- a/docs/5_Component_Documentation/7_pyagl.md +++ /dev/null @@ -1,250 +0,0 @@ ---- -title: PyAGL ---- - -# 0. Intro -## Main purpose -PyAGL was written to be used as a testing framework replacing the Lua afb-test one, -however the modules are written in a way that could be used as standalone utilities to query -and evaluate apis and verbs from the App Framework Binder services in AGL. - -## High level overview -Python compatibility: **Python 3.8 preferred**, **should** be compatible with **3.6** - -Initial development PyAGL was done with Python **3.6** in mind, heavily using f-strings and a few typings. As of writing this -documentation(June 3rd 2021), current stable AGL version is Koi 11.0.2 which has Python 3.8, and further development is -done using 3.8 and 3.9 runtimes although **no** version-specific features are used from later versions; -features **used** are kept within features offered by Python **3.8**. - -The test suite is written in a relatively standard way of extending **pytest** with a couple tweaks -tailored to Jenkins CI and LAVA for AGL with regards to output and timings/timeouts, and these tweaks -are enabled by running `pytest -L` in order to enable LAVA logging behavior. - -The way PyAGL works could be summarized in several bullets below: - -* `websockets` package is used to communicate to the services, `x-afb-ws-json1` is used as a subprotocol, -* base.py provides AGLBaseService to be extended for each service -* AGLBaseService has a `portfinder()` routine which will use `asyncssh` if used remotely, -to figure out the port of the service's websocket that is listening on. When this was implemented services had a hardcoded listening port, -and was often changed when a new service was introduced. If you specify port, pyagl will connect to it directly. If no port is specified and -portfinder() cannot find the process or listening port should throw an exception and exit. -* main() implementations in most PyAGL services' bindings are intended to be used as a convenient standalone utility to query verbs, although -not necessarily available. -* PyAGL bindings are organized in classes, method names and respective parameters mostly adhere to service verbs/apis described -per service in https://git.automotivelinux.org/apps/agl-service-*/about -For example, in https://git.automotivelinux.org/apps/agl-service-audiomixer/about/ the docs for the service describe 5 verbs - -subscribe, unsubscribe, list_controls, volume, mute - and their respective methods in audiomixer.py. -* as mentioned above `pytest` package is required for unit tests. -* `pytest-async` is needed by pytest to cooperate with asyncio -* `pytest-dependency` is used in cases where specific testing order is needed and used via decorators - -# 1. Using PyAGL -Command line execution is intended for debugging and quick evaluation. -There are few prerequisites to start using it. First, your AGL image **must** be bitbaked with **agl-devel** feature when sourcing __aglsetup.sh__; -if not - the running AGL instance won't have websocket services exposed to listening TCP ports and PyAGL will fail to connect. - -```bash -git clone "https://gerrit.automotivelinux.org/gerrit/src/pyagl" -``` -Preferably create a virtualenv and install the packages in the env -```bash -user@debian:~$ python3 -mvenv ~/.virtualenvs/aglenv -user@debian:~$ source ~/.virtualenvs/aglenv/bin/activate -(aglenv) user@debian:~$ pip install -r requirements.txt -``` -Hard requirements are asyncssh, websockets, pytest, pytest-dependency, pytest-async; the others in the file are dependencies of the mentioned packages. - -If you have installed PyAGL as python package or current working directory is in the project root: -``` -(aglenv) user@debian:~/pyagl$ python3 -m pyagl.services.audiomixer 192.168.234.34 --list_controls -``` -should produce the following or similar result depending on how many controls are exposed and which AGL version you are running: -``` -matching services: ['afm-service-agl-service-audiomixer--0.1--main@1001.service'] -Requesting list_controls with id 359450446 -[RESPONSE][Status: success][359450446][Info: None][Data: [{'control': 'Master Playback', 'volume': 1.0, 'mute': 0}, -{'control': 'Playback: Speech-Low', 'volume': 1.0, 'mute': 0}, {'control': 'Playback: Emergency', 'volume': 1.0, 'mute': 0}, -{'control': 'Playback: Speech-High', 'volume': 1.0, 'mute': 0}, {'control': 'Playback: Navigation', 'volume': 1.0, 'mute': 0}, -{'control': 'Playback: Multimedia', 'volume': 1.0, 'mute': 0}, {'control': 'Playback: Custom-Low', 'volume': 1.0, 'mute': 0}, -{'control': 'Playback: Communication', 'volume': 1.0, 'mute': 0}, {'control': 'Playback: Custom-High', 'volume': 1.0, 'mute': 0}]] -``` - -# 2. Running the tests - -## Markers -Before running the tests it must be noted that __Markers__ are metavariables applied to the tests which play important part -in the behavior of pyagl and add great flexibility when deciding which tests to run. -Each test suite usually have unambiguous marker and description in `pytest.ini` for the reason above. -The default markers are applied in the list variable `pytestmark` in the beginning of each test file. -Each test suite has at least 2 default markers. - -`pytest.mark.asyncio` is a special marker needed because we are running pytest in async mode, -and the other marker is the name of the testsuite - for example `pytest.mark.geoclue` is for `geoclue` tests. - -`pytest.mark.dependency` is another special marker used by the pytest-dependency library helping for -running tests in a particular order when a more complicated setup other than a fixture is needed for -a test or the setup itself is a test or sequence of tests. - -`pytest.mark.hwrequired` is a marker signifying that additional hardware is required for tests to be successful - e.g. bluetooth phonebook tests need a phone with a pbap profile connected - -`pytest.mark.internet` is a marker for tests which require internet connection - -As mentioned above, behavior of pytest is altered by the markers because pytest does expression matching by marker and test names for which suite to be run. -In the example below we select all internet requiring and subscription tests but skip those that require additional hardware. -If we have a match with `internet or subscribe` the test will be selected, but if the test has `hwrequired` will be skipped, otherwise deselected overall. -``` -h3ulcb:~# pyagl -vk "internet or subscribe and not hwrequired" -============================ test session starts ============================ -platform linux -- Python 3.8.2, pytest-5.3.5, py-1.8.1, pluggy-0.13.1 -- /usr/bin/python3 -cachedir: .pytest_cache -rootdir: /usr/lib/python3.8/site-packages/pyagl, inifile: pytest.ini -plugins: asyncio-0.10.0, dependency-0.5.1, reverse-1.0.1 -collected 218 items / 163 deselected / 55 selected - -test_bluetooth.py::test_subscribe_device_changes PASSED [ 1%] -... -test_radio.py::test_unsubscribe_all PASSED [ 90%] -test_signal_composer.py::test_subscribe SKIPPED [ 92%] -test_signal_composer.py::test_unsubscribe SKIPPED [ 94%] -test_weather.py::test_current_weather FAILED [ 96%] -test_weather.py::test_subscribe_weather PASSED [ 98%] -test_weather.py::test_unsubscribe_weather PASSED [100%] -==== 1 failed, 37 passed, 17 skipped, 163 deselected, 1 warning in 3.23s ==== - -``` - -## Locally - On the board itself -There is the /usr/bin/pyagl convenience wrapper script which invokes pytest -with the tests residing in `/usr/lib/python3.8/site-packages/pyagl/tests` which -also will pass all commandline arguments down to pytest - -```console -qemux86-64:~# pyagl -=================== test session starts ============================= -platform linux -- Python 3.8.2, pytest-5.3.5, py-1.8.1, pluggy-0.13.1 -rootdir: /usr/lib/python3.8/site-packages/pyagl, inifile: pytest.ini -plugins: dependency-0.5.1, asyncio-0.10.0, reverse-1.0.1 -collected 213 items - -test_audiomixer.py ....... [ 3%] -test_bluetooth.py ............xxxsxx [ 11%] -test_bluetooth_map.py .x.xs. [ 12%] -... -``` - -## Remotely -You must export `AGL_TGT_IP` environment variable first, containing a string with a reachable IP address -configured(either DHCP or static) on one of the interfeces on the AGL instance(board or vm) on your network. -`AGL_TGT_PORT` is not required, however can be exported to skip over connecting to the board via ssh first -in order to figure out the listening port of service. - -```console -user@debian:~$ source ~/.virtualenvs/aglenv/bin/activate -(pyagl) user@debian:~$ export AGL_TGT_IP=192.168.234.34 -(pyagl) user@debian:~$ cd pydev/pyagl/pyagl/tests -(pyagl) user@debian:~/pydev/pyagl/pyagl/tests$ pytest test_geoclue.py -========================= test session starts ========================= -platform linux -- Python 3.9.2, pytest-5.4.1, py-1.8.1, pluggy-0.13.1 -rootdir: /home/user/pydev/pyagl/pyagl, inifile: pytest.ini -plugins: dependency-0.5.1, asyncio-0.11.0 -collected 3 items - -test_geoclue.py ... [100%] -``` -# 3. Writing bindings and/or tests for new services -This assumes you have already went through ["3. Developer Guides > Creating a new service"](../3_Developer_Guides/2_Creating_a_New_Service.md). - -Templates directory contains barebone _cookiecutter_ templates to create your project. -If you do not intend to use cookiecutter, you need a simple service file in which you inherit AGLBaseService -from base.py. -You can take a look at pyagl/services/geoclue.py and pyagl/tests/test_geoclue.py which is probably the -simplest binding in PyAGL for a reference and example. All basic methods like -[send|receive|un/subscribe|portfinder] are implemented in the base class. -You would need to do minimal work to create new service binding from scratch and by example of the geoclue service you need to do the following: - -* do the basic imports -```python3 -from pyagl.services.base import AGLBaseService, AFBResponse -import asyncio -``` - -* inherit AGLBaseService and type in the service class member the service name presuming you are following the AGL naming convention: -(if your new service does not follow the convention, the portfider routine wont work and you'll have to specify service port manually) -```python3 -class GeoClueService(AGLBaseService): - service = 'agl-service-geoclue' -``` - -* if you intend to run the new service binding as a standalone utility, you might want to add your new options to the argparser -```python3 - parser = AGLBaseService.getparser() - parser.add_argument('--location', help='Get current location', action='store_true') -``` - -* override the __init__ method with the respective parameters as api(used in the binding) and systemd service slug -``` - def __init__(self, ip, port=None, api='geoclue'): - super().__init__(ip=ip, port=port, api=api, service='agl-service-geoclue') -``` - -* define your methods and send requests with .request() which prepares the data in a JSON format, request returns message id -``` - async def location(self): - return await self.request('location') -``` - -* get the raw response with data = await .response() or use .afbresponse() to get structured data - -PyAGL is written with asyncio so you'd need an event loop to get your code running. -Most modules have standalone CLI functionality, which is done via ArgumentParser and each module that -is CLI usable inherits static base parser and extends its arguments as shown in the example below: - -```python3 -async def main(loop): - args = GeoClueService.parser.parse_args() - gcs = await GeoClueService(args.ipaddr) - - if args.location: - msgid = await gcs.location() - print(f'Sent location request with messageid {msgid}') - print(await gcs.afbresponse()) - -if __name__ == '__main__': - loop = asyncio.get_event_loop() - loop.run_until_complete(main(loop)) -``` -`GeoClueService` will try to return an instance with connection to the service. It will throw an exception if it fails to do so. -`AGLBaseService.afbresponse()` method is a wrapper on top of .response() which will prepare, validate and format data for a convenient usage intended for CLI usage. -`AFBResponse.__str__` is also a convenience method to be able to print all relevant data in regarding state of the response. - -```console -(aglenv) user@debian:~$ python3 -m pyagl.services.geoclue 192.168.234.251 --location -matching services: ['afm-service-agl-service-geoclue--1.0--main.service'] -Sent location request with messageid 29188435 -[RESPONSE][Status: success][29188435][Info: GeoClue location data][Data: {'latitude': 42.6898421, 'longitude': 23.3099069, 'accuracy': 107.4702045}] -``` - - -# 4. Environment variables -The following environment variables are used in the PyAGL project: - -Variable | Description ---- | --- -**AGL_TGT_IP** | **required** -**AGL_TGT_PORT** | **optional**, when this is used portfinder() routine is skipped, attempts direct websocket connection to this port. -**AGL_TEST_TIMEOUT** | **optional**, over-ride the default 5 second timeout value for binding responses. This is useful in many cases where a long-standing request has taken place - e.g. importing few thousand entries from a phonebook -**AGL_AVAILABLE_INTERFACES** | **optional**, specify which of ethernet, wifi, and bluetooth interfaces are available. The value is a comma separated list, with a default value of "ethernet,wifi,bluetooth". -**AGL_BTMAP_RECIPIENT** | **optional**, when running Bluetooth MAP tests, this would be used as phone number to write text messages to. -**AGL_BTMAP_TEXT** | **optional**, when running Bluetooth MAP tests, messages will be composed with this text. -**AGL_CAN_INTERFACE** | **optional**, specify the CAN interface to use for CAN testing, default value is "can0". -**AGL_PBAP_PHONENUM** | **optional**, when running Bluetooth PBAP tests, this phone number will be used to .search(). -**AGL_PBAP_VCF** | **optional**, for the Bluetooh PBAP tests query a contact entry out of the phonebook. -**AGL_BT_TEST_ADDR** | **optional**, for the Bluetooth tests pair/connect/disconnect with an actual Bluetooth device(phone)'s address . The address should have the DBus address style as "dev_00_01_02_03_04_05" instead of a regular colon-separated MAC address. - -# 5. Debugging -PyAGL uses pythons logger library so you can rise the logging level and see the output from most of the modules, -but was disabled by default because of the massive amount of output produced. When the default logger is enabled -all other libraries will show their output with pyagl - e.g. websockets, asyncssh etc. - -README.md in the root directory of the project also contains useful information. - diff --git a/docs/index.md b/docs/index.md index 68e117b..dea00c8 100644 --- a/docs/index.md +++ b/docs/index.md @@ -38,6 +38,7 @@ You can find information on the AGL Unified Code Base on the "[Unified Code Base](https://www.automotivelinux.org/software/unified-code-base)" page. + What Can I Do Right Away Using AGL? -----------------------------------