Elektra 0.11.0
High-Level API

Introduction

The goal of the high-level API is to increase the usability of libelektra for developers who want to integrate Elektra into their applications. Applications usually do not want to use low-level APIs. KDB and KeySet are useful for plugins and to implement APIs, but not to be directly used in applications. The high-level API should be extremely easy to get started with and at the same time it should be hard to use it in a wrong way. This tutorial gives an introduction for developers who want to elektrify their application using the high-level API.

The API supports all CORBA Basic Data Types, except for wchar, as well as the string type (see also Data Types below).

Setup

First you have to add elektra-highlevel, elektra-kdb and elektra-ease to the linked libraries of your application. To be able to use it in your source file, just include the main header with #include <elektra.h> at the top of your file.

Quickstart

The quickest way to get started is to adapt the following piece of code to your needs:

ElektraError * error = NULL;
Elektra * elektra = elektraOpen ("/sw/org/myapp/#0/current", NULL, NULL, &error);
if (elektra == NULL)
{
printf ("An error occurred: %s", elektraErrorDescription (error));
return -1;
}
kdb_long_t mylong = elektraGetLong (elektra, "mylong");
printf ("got long " ELEKTRA_LONG_F "\n", mylong);
elektraSetBoolean (elektra, "mybool", true, &error);
if (error != NULL)
{
printf ("An error occurred: %s", elektraErrorDescription (error));
}
elektraClose (elektra);
void elektraSetBoolean(Elektra *elektra, const char *keyname, kdb_boolean_t value, ElektraError **error)
Sets a boolean value.
Definition elektra_value.c:402
Elektra * elektraOpen(const char *application, KeySet *defaults, KeySet *contract, ElektraError **error)
Initializes a new Elektra instance.
Definition elektra.c:67
const char * elektraErrorDescription(const ElektraError *error)
Definition elektra_error.c:306
void elektraErrorReset(ElektraError **error)
Frees the memory used by the error and sets the referenced error variable to NULL.
Definition elektra_error.c:315
void elektraClose(Elektra *elektra)
Releases all resources used by the given elektra instance.
Definition elektra.c:484
kdb_long_t elektraGetLong(Elektra *elektra, const char *keyname)
Gets a long value.
Definition elektra_value.c:272

To run the application, the configuration should be specified:

sudo kdb meta-set /sw/org/myapp/#0/current/mylong type long
sudo kdb meta-set /sw/org/myapp/#0/current/mylong default 5

The getter and setter functions follow the simple naming scheme elektra(Get/Set)[Type]. Additionally for each one there is a variant to access array elements with the suffix ArrayElement. For more information see below.

You can find a complete example at the end of this document and here.

Core Concepts

Metadata and Specification

In Elektra keys may have attached metadata describing additional properties of the key. By using Elektra'snamespaces" and @ref doc_tutorials_cascading_md "cascading keys" it is also possible to have a full specification of your applications configuration. This specification should be placed into the <tt>spec</tt> namespace. From there the high-level API and Elektra's plugins will access it. A specification for use with the high-level API has to <strong>define at least the <tt>default</tt> and the <tt>type</tt> metadata for each key the application is going to use</strong>. The <tt>default</tt> metakey simply defines which value will be returned, if the user didn't set a value. <tt>type</tt> defines the data type of key. For more information on data types @ref "data-types" "see below". The API also supports passing a <tt>KeySet</tt> to <tt>elektraOpen</tt> that contains the specification. This is, however, not recommended for general use and is mainly useful for debugging and testing purposes. @subsection autotoc_md10 Struct <tt>Elektra</tt> <tt>Elektra</tt> is the handle you use to access the underlying KDB (hierarchical key database) that stores the configuration key-value pairs. All key-value read and write operations expect this handle to be passed as in as a parameter. To create the handle, you simply write: @icode{c} ElektraError * error = NULL; Elektra * elektra = elektraOpen ("/sw/org/myapp/#0/current", NULL, NULL, &error); @endicode Please replace <tt>"/sw/org/myapp/#0/current"</tt> with an appropriate value for your application (see @ref doc_tutorials_application-integration_md "here" for more information). You can use the parameter <tt>defaults</tt> to pass a <tt>KeySet</tt> containing <tt>Key</tt>s with default values to the <tt>Elektra</tt> instance. The <tt>ElektraError</tt> can be used to check for initialization errors. You can detect initialization errors by comparing the result of <tt>elektraOpen</tt> to NULL: @icode{c} if (elektra == NULL) { // handle the error, e.g. print description elektraErrorReset(&error); } @endicode If an error occurred, you must call <tt>elektraErrorReset</tt> before using the same error pointer in any other function calls (e.g. <tt>elektraSet*</tt> calls). It is also safe to call <tt>elektraErrorReset</tt>, if no error occurred. In order to give Elektra the chance to clean up all its allocated resources, you have to close your instance, when you are done using it, by calling: @icode{c} elektraClose (elektra); @endicode <em>NOTE:</em> Elektra is only thread-safe when you use one handle per thread or protect your handle. If you have multiple threads accessing key-values, create a separate handle for each thread to avoid concurrency issues. @subsection autotoc_md11 Struct <tt>ElektraError</tt> The library is designed to shield developers from the many errors one can encounter when using KDB directly. However it is not possible to hide all those issues. As with every library, things can go wrong and there needs to be a way to react to errors once they have occurred at runtime. Therefore the high-level API introduces a struct called <tt>ElektraError</tt>, which encapsulates all information necessary for the developer to handle runtime-errors appropriately in the application. Functions that can produce errors, despite correct use of the API, accept an <tt>ElektraError</tt> pointer as parameter, for example: @icode{c} Elektra * elektraOpen (const char * application, KeySet * defaults, KeySet * contract, ElektraError ** error); @endicode In most cases you'll want to set the error variable to <tt>NULL</tt> before passing it to the function. You can do this either by declaring and initializing a new variable with <tt>ElektraError * error = NULL</tt> or by reusing an already existing error variable by resetting it with <tt>elektraErrorReset (\&error)</tt>. Notice, that you should always check if an error occurred by comparing it to <tt>NULL</tt> after the function call. If an error happened, it is often useful to show an error message to the user. A description of what went wrong is provided in the <tt>ElektraError</tt> struct and can be accessed using <tt>elektraErrorDescription (error)</tt>. Additionally the error code can be accessed through <tt>elektraErrorCode (error)</tt>. NOTE: The error API is still a work in progress, so more functions will likely be added in the future. To avoid leakage of memory, you have to call <tt>elektraErrorReset (\&error)</tt> (ideally as soon as you are finished resolving the error): @icode{c} ElektraError * error = NULL; // Call a function and pass the error variable as an argument. // ... if (error != NULL) { // An error occurred, do something about it. // ... elektraErrorReset (&error); } @endicode @subsection autotoc_md12 Configuration Currently there is only one way to configure an <tt>Elektra</tt> instance: @icode{c} void elektraFatalErrorHandler (Elektra * elektra, ElektraErrorHandler fatalErrorHandler); @endicode This allows you to set the callback called by Elektra, when a fatal error occurs. Technically a fatal error could occur at any time, but the most common use case for this callback is inside of functions that do not take a separate <tt>ElektraError</tt> argument. For example, this function will be called, when any of the getter-functions is called on a non-existent key which is not part of any specification, and therefore has no specified default value. If you provide your own callback, it must interrupt the thread of execution in some way (e.g. by calling <tt>exit()</tt> or throwing an exception in C++). It <em>must not</em> return to the calling function. The handler will also be called whenever you pass <tt>NULL</tt> where a function expects an <tt>ElektraError **</tt>. In this case the error code will be <tt>ELEKTRA_ERROR_CODE_NULL_ERROR</tt>. The default callback simply logs the error with <tt>ELEKTRA_LOG_DEBUG</tt> and then calls <tt>exit()</tt> with exit code <tt>EXIT_FAILURE</tt> It is expected that you implement your own callback, so that you get proper error message logged in your applications preferred format. Using the default callback is only viable for very simple applications, because you won't get any indication as to which key caused the error (unless you compiled Elektra with debug logging enabled). @section autotoc_md13 Data Types The API determines the data type of a given key, by reading its <tt>type</tt> metadata. The API supports the following types, which are taken from the CORBA specification: - <strong>String</strong>: a string of characters, represented by <tt>string</tt> in metadata - <strong>Boolean</strong>: a boolean value <tt>true</tt> or <tt>false</tt>, represented by <tt>boolean</tt> in metadata, in the KDB the raw value <tt>"1"</tt> is regarded as true, <tt>"0"</tt> regarded as false and any other value is an error - <strong>Char</strong>: a single character, represented by <tt>char</tt> in metadata - <strong>Octet</strong>: a single byte, represented by <tt>octet</tt> in metadata - **(Unsigned) Short**: a 16-bit (unsigned) integer, represented by <tt>short</tt> (<tt>unsigned_short</tt>) in metadata - **(Unsigned) Long**: a 32-bit (unsigned) integer, represented by <tt>long</tt> (<tt>unsigned_long</tt>) in metadata - **(Unsigned) Long Long**: a 64-bit (unsigned) integer, represented by <tt>long_long</tt> (<tt>unsigned_long_long</tt>) in metadata - <strong>Float</strong>: whatever your compiler treats as <tt>float</tt>, probably IEEE-754 single-precision, represented by <tt>float</tt> in metadata - <strong>Double</strong>: whatever your compiler treats as <tt>double</tt>, probably IEEE-754 double-precision, represented by <tt>double</tt> in metadata - <strong>Long Double</strong>: whatever your compiler treats as <tt>long double</tt>, not always available, represented by <tt>long_double</tt> in metadata The API contains one header that is not automatically included from <tt>elektra.h</tt>. You can use it with <tt>\#include \<elektra/conversion.h\></tt>. The header provides the functions Elektra uses to convert your configuration values to and from strings. In most cases, you won't need to use these functions directly, but they might still be useful sometimes (e.g. in combination with <tt>elektraGetType</tt> and <tt>elektraGetRawString</tt>). We also provide a <tt>KDB_TPYE_*</tt> constant for each of the types listed above. Again, most users won't use these but, if you ever do need to use the raw type metadata using constants enables code completion and protects against typos. There is also the type <tt>enum</tt> with constant <tt>KDB_TYPE_ENUM</tt>. It is only supported via the @ref doc_help_elektra-highlevel-gen_md "code-generation API". @paragraph autotoc_md14 Note about Floating Point Types We enforce a few minimum properties for floating point types. They are taken from the IEE-754 specification and are: - For <tt>float</tt>: 32 bits, binary, 24 mantissa digits and exponent range of at least -125 to 128 - For <tt>double</tt>: 64 bits, binary, 53 mantissa digits and exponent range of at least -1021 to 1024 - For <tt>long double</tt>: at least 80 bits, binary, at least 64 mantissa digits and exponent range of at least -2^14 + 3 to 2^14 Additionally for C++ compilers we use a <tt>static_assert</tt> that will fail if <tt>std::numeric_limits\<T\>\::is_iec559</tt> is <tt>false</tt> when <tt>T</tt> is any of <tt>float</tt>, <tt>double</tt> or <tt>long double</tt>. While these checks won't ensure actual IEEE-754 arithmetic, they will at least ensure all values can be represented correctly. @anchor reading-and-writing-values <a></a> @section autotoc_md15 Reading and Writing Values @subsection autotoc_md16 Key Names When calling <tt>elektraOpen</tt> you pass the parent key for your application. Afterwards getters and setters get passed in only the part below that key in the KDB. For example, if you call <tt>elektraOpen</tt> with <tt>"/sw/org/myapp/#0/current"</tt>, you can access your applications configuration value for the key <tt>"/sw/org/myapp/#0/current/message"</tt> with the provided getters and setters by passing them only <tt>"message"</tt> as the name for the configuration value. @anchor read-values-from-the-kdb <a></a> @subsection autotoc_md17 Read Values from the KDB A typical application wants to read some configuration values at start. This should be made as easy as possible for the developer. Reading configuration data in most cases is not part of the business logic of the application and therefore should not "pollute" the applications source code with cumbersome setup and file-parsing code. This is exactly where Elektra comes in handy, because you can leave all the configuration file handling and parsing to the underlying layers of Elektra and just use the high-level API to access the desired data. Reading values from KDB can be done with elektra-getter functions that follow a simple naming scheme: <tt>elektraGet</tt> + the type of the value you want to read. For example, you can get the value for the key named "message" like this: @icode{c} const char * message = elektraGetString (elektra, "message"); @endicode Sometimes you'll want to access arrays as well. You can access single elements of an array using the provided array-getters following again a simple naming scheme: <tt>elektraGet</tt> + the type of the value you want to read + <tt>ArrayElement</tt>. For example, you can get the value at index 3 for the array "message" like this: @icode{c} const char * message = elektraGetStringArrayElement (elektra, "message", 3); @endicode To get the size of the array you would like to access you can use the function <tt>elektraArraySize</tt>: @icode{c} kdb_long_long_t arraySize = elektraArraySize (elektra, "message"); @endicode For some background information on arrays in Elektra see the @ref doc_tutorials_arrays_md "Array" tutorial, as well as our @ref doc_decisions_5_partially_implemented_array_md "decision document" on this topic. Please note that the high level API does not support arrays with missing elements. If an element is missing (and the specification provides no default value), getters will fail. Notice that both the getters for primitive types and the getters for array types do not accept error parameters. The library expects you to run a correct Elektra setup. If the configuration is well specified, no runtime errors can occur when reading a value. Therefore the getters do not accept an error variable as argument. If there is however a severe internal error, or you try to access a key which you have not specified correctly, then the library will call the error callback set with <tt>elektraFatalErrorHandler</tt> to prevent data inconsistencies or exceptions further down in your application. You can find the complete list of the available functions for all supported value types in <a href="/tmp/elektra-20230804-4719-dmjo9u/elektra-0.11.0/src/include/elektra.h" >elektra.h</a> @subsection autotoc_md18 Writing Values to the KDB Sometimes, after having read a value from the KDB, you will want to write back a modified value. As described in @ref "read-values-from-the-kdb" "Read values from the KDB" we follow a naming scheme for getters. The high-level API provides setters follow an analogous naming scheme as well. For example, to write back a modified "message", you can call <tt>elektraSetString</tt>: @icode{c} elektraSetString (elektra, "message", "This is the new message", NULL); @endicode The counterpart for array-getters again follows the same naming scheme: @icode{c} elektraSetStringArrayElement (elektra, "message", "This is the third new message", NULL); @endicode Because even the best specification and perfect usage as intended can not prevent any error from occurring, when saving the configuration, all setter-functions take an additional <tt>ElektraError</tt> argument, which will be set if an error occurs. @subsection autotoc_md19 Raw Values You can use <tt>const char * elektraGetRawString (Elektra * elektra, const char * name)</tt> to read the raw (string) value of a key. No type checking or type conversion will be attempted. Additionally this function does not call the fatal error handler. It will simply return <tt>NULL</tt>, if the key was not found. If you want to set a raw value, use <tt>void elektraSetRawString (Elektra * elektra, const char * name, const char * value, KDBType type, ElektraError ** error)</tt>. Obviously you have to provide a type for the value you set, so that the API can perform type checking, when reading the value next time. Similar functions are provided for array elements: @icode{c} const char * elektraGetRawStringArrayElement (Elektra * elektra, const char * name, kdb_long_long_t index); void elektraSetRawStringArrayElement (Elektra * elektra, const char * name, kdb_long_long_t index, const char * value, KDBType type, ElektraError ** error); @endicode @subsubsection autotoc_md20 Type Information The type information is stored in the <tt>"type"</tt> metakey. <tt>KDBType elektraGetType (Elektra * elektra, const char * keyname)</tt> (or <tt>KDBType elektraGetArrayElementType (Elektra * elektra, const char * name, kdb_long_long_t index)</tt> for array elements) lets you access this information. A setter is not provided, because Elektra assumes keys to always have the same type (as specified). @subsubsection autotoc_md21 Use cases for raw values <tt>elektraGetType</tt>, <tt>elektraGetRawString</tt> and <tt>elektraSetRawString</tt> can be used together to create custom data types. If your application for example uses arbitrary-precision integers, you could something similar to these functions: @icode{c} bignum * elektraGetBigNum (Elektra * elektra, const char * keyname) { KDBType type = elektraGetType (elektra, keyname); if (strcmp (type, "bignum") != 0) { return NULL; } const char * rawValue = elektraGetRawString (elektra, keyname); return rawValue == NULL ? NULL : stringToBigNum (rawValue); } void elektraSetBigNum (Elektra * elektra, const char * keyname, bignum * value, ElektraError ** error) { const char * rawValue = bigNumToString (value); elektraSetRawString (elektra, keyname, rawValue, "bignum", error); } @endicode To get the <tt>type</tt> plugin to validate your custom types you should make sure the <tt>check/type</tt> metadata is set to <tt>string</tt> (or <tt>any</tt>) on all keys that use custom types. This works, because the <tt>type</tt> plugin prefers the value of <tt>check/type</tt> over that of <tt>type</tt>. @subsection autotoc_md22 Binary Values The high-level API does not support binary key values at this time. @section autotoc_md23 Example @icode{c} #include <stdio.h> #include <elektra.h> int main () { ElektraError * error = NULL; Elektra * elektra = elektraOpen ("/sw/org/myapp/#0/current", NULL, NULL, &error); if (elektra == NULL) { printf ("Sorry, there seems to be an error with your Elektra setup: s
", elektraErrorDescription (error)); elektraErrorReset (&error); printf ("Will exit now...
"); exit (EXIT_FAILURE); } const char * message = elektraGetString (elektra, "message"); printf ("s", message);

elektraClose (elektra);

return 0; }