Provided by: nbdkit-plugin-dev_1.1.11-1build1_amd64 bug

NAME

       nbdkit-plugin - How to write nbdkit plugins

SYNOPSIS

        #include <nbdkit-plugin.h>

        #define THREAD_MODEL NBDKIT_THREAD_MODEL_SERIALIZE_ALL_REQUESTS

        static void *
        myplugin_open (void)
        {
          /* create a handle ... */
          return handle;
        }

        static struct nbdkit_plugin plugin = {
          .name              = "myplugin",
          .open              = myplugin_open,
          .get_size          = myplugin_get_size,
          .pread             = myplugin_pread,
          .pwrite            = myplugin_pwrite,
          /* etc */
        };

        NBDKIT_REGISTER_PLUGIN(plugin)

       When this has been compiled to a shared library, do:

        nbdkit [--args ...] ./myplugin.so [key=value ...]

       When debugging, use the -fv options:

        nbdkit -fv ./myplugin.so [key=value ...]

DESCRIPTION

       An nbdkit plugin is a new source device which can be served using the Network Block Device
       (NBD) protocol.  This manual page describes how to create an nbdkit plugin in C.

       For example plugins, take a look at the source of nbdkit, in the "plugins" directory.

       To write plugins in other languages, see: nbdkit-ocaml-plugin(3), nbdkit-perl-plugin(3),
       nbdkit-python-plugin(3).

"nbdkit-plugin.h"

       All plugins should start by including this header file:

        #include <nbdkit-plugin.h>

"#define THREAD_MODEL"

       All plugins must define a thread model.  See "THREADS" below for details.  It is generally
       safe to use:

        #define THREAD_MODEL NBDKIT_THREAD_MODEL_SERIALIZE_ALL_REQUESTS

"struct nbdkit_plugin"

       All plugins must define and register one "struct nbdkit_plugin", which contains the name
       of the plugin and pointers to callback functions.

        static struct nbdkit_plugin plugin = {
          .name              = "myplugin",
          .longname          = "My Plugin",
          .description       = "This is my great plugin for nbdkit",
          .open              = myplugin_open,
          .get_size          = myplugin_get_size,
          .pread             = myplugin_pread,
          .pwrite            = myplugin_pwrite,
          /* etc */
        };

        NBDKIT_REGISTER_PLUGIN(plugin)

       The ".name" field is the name of the plugin.

       The callbacks are described below (see "CALLBACKS").  Only ".name", ".open", ".get_size"
       and ".pread" are required.  All other callbacks can be omitted.  However almost all
       plugins should have a ".close" callback.  Most real-world plugins will also want to
       declare some of the other callbacks.

       The nbdkit server calls the callbacks in the following order over the lifetime of the
       plugin:

       ".load"
           is called once just after the plugin is loaded into memory.

       ".config" and ".config_complete"
           ".config" is called zero or more times during command line parsing.
           ".config_complete" is called once after all configuration information has been passed
           to the plugin.

           Both are called after loading the plugin but before any connections are accepted.

       ".open"
           A new client has connected.

       ".can_write", ".get_size" and other option negotiation callbacks
           These are called during option negotiation with the client, but before any data is
           served.

       ".pread", ".pwrite" and other data serving callbacks
           After option negotiation has finished, these may be called to serve data.  Depending
           on the thread model chosen, they might be called in parallel from multiple threads.

       ".close"
           The client has disconnected.

       ".open" ... ".close"
           The sequence ".open" ... ".close" can be called repeatedly over the lifetime of the
           plugin, and can be called in parallel (depending on the thread model).

       ".unload"
           is called once just before the plugin is unloaded from memory.

ERROR HANDLING

       If there is an error in the plugin, the plugin should call "nbdkit_error" with the error
       message, and then return an error indication from the callback, eg. NULL or -1.

       "nbdkit_error" has the following prototype and works like printf(3):

        void nbdkit_error (const char *fs, ...);

FILENAMES AND PATHS

       The server usually (not always) changes directory to "/" before it starts serving
       connections.  This means that any relative paths passed during configuration will not work
       when the server is running (example: "nbdkit plugin.so file=disk.img").

       To avoid problems, prepend relative paths with the current directory before storing them
       in the handle.  Or open files and store the file descriptor.

   "nbdkit_absolute_path"
        char *nbdkit_absolute_path (const char *filename);

       The utility function "nbdkit_absolute_path" converts any path to an absolute path.

       If conversion was not possible, this calls "nbdkit_error" and returns "NULL".  Note that
       this function does not check that the file exists.

       The returned string must be freed by the caller.

CALLBACKS

   ".name"
        const char *name;

       This field (a string) is required, and must contain only ASCII alphanumeric characters and
       be unique amongst all plugins.

   ".version"
        const char *version;

       Plugins may optionally set a version string which is displayed in help and debugging
       output.

   ".longname"
        const char *longname;

       An optional free text name of the plugin.  This field is used in error messages.

   ".description"
        const char *description;

       An optional multi-line description of the plugin.

   ".load"
        void load (void);

       This is called once just after the plugin is loaded into memory.  You can use this to
       perform any global initialization needed by the plugin.

   ".unload"
        void unload (void);

       This may be called once just before the plugin is unloaded from memory.  Note that it's
       not guaranteed that ".unload" will always be called (eg. the server might be killed or
       segfault), so you should try to make the plugin as robust as possible by not requiring
       cleanup.

   ".config"
        int config (const char *key, const char *value);

       On the nbdkit command line, after the plugin filename, come an optional list of
       "key=value" arguments.  These are passed to the plugin through this callback when the
       plugin is first loaded and before any connections are accepted.

       This callback may be called zero or more times.  Both "key" and "value" parameters will be
       non-NULL, but it is possible for either to be empty strings.  The strings are owned by
       nbdkit but will remain valid for the lifetime of the plugin, so the plugin does not need
       to copy them.

       The format of the "key" accepted by plugins is up to the plugin, but you should probably
       look at other plugins and follow the same conventions.

       If the value is a relative path, then note that the server changes directory when it
       starts up.  See "FILENAMES AND PATHS" above.

       If the ".config" callback is not provided by the plugin, and the user tries to specify any
       "key=value" arguments, then nbdkit will exit with an error.

       If there is an error, ".config" should call "nbdkit_error" with an error message and
       return "-1".

   ".config_complete"
        int config_complete (void);

       This optional callback is called after all the configuration has been passed to the
       plugin.  It is a good place to do checks, for example that the user has passed the
       required parameters to the plugin.

       If there is an error, ".config_complete" should call "nbdkit_error" with an error message
       and return "-1".

   ".config_help"
        const char *config_help;

       This optional multi-line help message should summarize any "key=value" parameters that it
       takes.  It does not need to repeat what already appears in ".description".

       If the plugin doesn't take any config parameters you should probably omit this.

   ".open"
        void *open (int readonly);

       This is called when a new client connects to the nbdkit server.  The callback should
       allocate a handle and return it.  This handle is passed back to other callbacks and could
       be freed in the ".close" callback.

       Note that the handle is completely opaque to nbdkit, but it must not be NULL.

       The "readonly" flag informs the plugin that the user requested a read-only connection
       using the -r flag on the command line.  Note that the plugin may additionally force the
       connection to be readonly (even if this flag is false) by returning false from the
       ".can_write" callback.  So if your plugin can only serve read-only, you can ignore this
       parameter.

       If there is an error, ".open" should call "nbdkit_error" with an error message and return
       "NULL".

   ".close"
        void close (void *handle);

       This is called when the client closes the connection.  It should clean up any per-
       connection resources.

       Note there is no way in the NBD protocol to communicate close errors back to the client,
       for example if your plugin calls close(2) and you are checking for errors (as you should
       do).  Therefore the best you can do is to log the error on the server.  Well-behaved NBD
       clients should try to flush the connection before it is closed and check for errors, but
       obviously this is outside the scope of nbdkit.

   ".get_size"
        int64_t get_size (void *handle);

       This is called during the option negotiation phase of the protocol to get the size (in
       bytes) of the block device being exported.

       The returned size must be ≥ 0.  If there is an error, ".get_size" should call
       "nbdkit_error" with an error message and return "-1".

   ".can_write"
        int can_write (void *handle);

       This is called during the option negotiation phase to find out if the handle supports
       writes.

       If there is an error, ".can_write" should call "nbdkit_error" with an error message and
       return "-1".

       This callback is not required.  If omitted, then we return true iff a ".pwrite" callback
       has been defined.

   ".can_flush"
        int can_flush (void *handle);

       This is called during the option negotiation phase to find out if the handle supports the
       flush-to-disk operation.

       If there is an error, ".can_flush" should call "nbdkit_error" with an error message and
       return "-1".

       This callback is not required.  If omitted, then we return true iff a ".flush" callback
       has been defined.

   ".is_rotational"
        int is_rotational (void *handle);

       This is called during the option negotiation phase to find out if the backing disk is a
       rotational medium (like a disk) or not (like an SSD).  If true, this may cause the client
       to reorder requests to make them more efficient for a slow rotating disk.

       If there is an error, ".is_rotational" should call "nbdkit_error" with an error message
       and return "-1".

       This callback is not required.  If omitted, then we return false.

   ".can_trim"
        int can_trim (void *handle);

       This is called during the option negotiation phase to find out if the plugin supports the
       trim/discard operation for punching holes in the backing storage.

       If there is an error, ".can_trim" should call "nbdkit_error" with an error message and
       return "-1".

       This callback is not required.  If omitted, then we return true iff a ".trim" callback has
       been defined.

   ".pread"
        int pread (void *handle, void *buf, uint32_t count, uint64_t offset);

       During the data serving phase, nbdkit calls this callback to read data from the backing
       store.  "count" bytes starting at "offset" in the backing store should be read and copied
       into "buf".  nbdkit takes care of all bounds- and sanity-checking, so the plugin does not
       need to worry about that.

       The callback must read the whole "count" bytes if it can.  The NBD protocol doesn't allow
       partial reads (instead, these would be errors).  If the whole "count" bytes was read, the
       callback should return 0 to indicate there was no error.

       If there is an error (including a short read which couldn't be recovered from), ".pread"
       should call "nbdkit_error" with an error message and return "-1".

   ".pwrite"
        int pwrite (void *handle, const void *buf, uint32_t count, uint64_t offset);

       During the data serving phase, nbdkit calls this callback to write data to the backing
       store.  "count" bytes starting at "offset" in the backing store should be written using
       the data in "buf".  nbdkit takes care of all bounds- and sanity-checking, so the plugin
       does not need to worry about that.

       The callback must write the whole "count" bytes if it can.  The NBD protocol doesn't allow
       partial writes (instead, these would be errors).  If the whole "count" bytes was written
       successfully, the callback should return 0 to indicate there was no error.

       If there is an error (including a short write which couldn't be recovered from), ".pwrite"
       should call "nbdkit_error" with an error message and return "-1".

   ".flush"
        int flush (void *handle);

       During the data serving phase, this callback is used to fdatasync(2) the backing store,
       ie. to ensure it has been completely written to a permanent medium.  If that is not
       possible then you can omit this callback.

       If there is an error, ".flush" should call "nbdkit_error" with an error message and return
       "-1".

   ".trim"
        int trim (void *handle, uint32_t count, uint64_t offset);

       During the data serving phase, this callback is used to "punch holes" in the backing
       store.  If that is not possible then you can omit this callback.

       If there is an error, ".trim" should call "nbdkit_error" with an error message and return
       "-1".

THREADS

       Each nbdkit plugin must declare its thread safety model by defining the "THREAD_MODEL"
       macro.  (This macro is used by "NBDKIT_REGISTER_PLUGIN").

       The possible settings for "THREAD_MODEL" are defined below.

       "#define THREAD_MODEL NBDKIT_THREAD_MODEL_SERIALIZE_CONNECTIONS"
           Only a single handle can be open at any time, and all requests happen from one thread.

           Note this means only one client can connect to the server at any time.  If a second
           client tries to connect it will block waiting for the first client to close the
           connection.

       "#define THREAD_MODEL NBDKIT_THREAD_MODEL_SERIALIZE_ALL_REQUESTS"
           This is a safe default for most plugins.

           Multiple handles can be open at the same time, but data requests are serialized so
           that for the plugin as a whole only one read/write/etc request will be in progress at
           any time.

           This is a useful setting if the library you are using is not thread-safe.  However
           performance may not be good.

       "#define THREAD_MODEL NBDKIT_THREAD_MODEL_SERIALIZE_REQUESTS"
           Multiple handles can be open and multiple data requests can happen in parallel.
           However only one request will happen per handle at a time (but requests on different
           handles might happen concurrently).

       "#define THREAD_MODEL NBDKIT_THREAD_MODEL_PARALLEL"
           Multiple handles can be open and multiple data requests can happen in parallel (even
           on the same handle).

           All the libraries you use must be thread-safe and reentrant.  You may also need to
           provide mutexes for fields in your connection handle.

       If none of the above thread models are suitable, then use "NBDKIT_THREAD_MODEL_PARALLEL"
       and implement your own locking using "pthread_mutex_t" etc.

PARSING SIZE PARAMETERS

       Use the "nbdkit_parse_size" utility function to parse human-readable size strings such as
       "100M" into the size in bytes.

        int64_t nbdkit_parse_size (const char *str);

       "str" can be a string in a number of common formats.  The function returns the size in
       bytes.  If there was an error, it returns "-1".

DEBUGGING

       Run the server with -f and -v options so it doesn't fork and you can see debugging
       information:

        nbdkit -fv ./myplugin.so [key=value [key=value [...]]]

       To print debugging information from within the plugin, call "nbdkit_debug", which has the
       following prototype and works like printf(3):

        void nbdkit_debug (const char *fs, ...);

       Note that "nbdkit_debug" only prints things when the server is in verbose mode (-v
       option).

INSTALLING THE PLUGIN

       The plugin is a "*.so" file and possibly a manual page.  You can of course install the
       plugin "*.so" file wherever you want, and users will be able to use it by running:

        nbdkit /path/to/plugin.so [args]

       However if the shared library has a name of the form "nbdkit-name-plugin.so" and if the
       library is installed in the $plugindir directory, then users can be run it by only typing:

        nbdkit name [args]

       The location of the $plugindir directory is set when nbdkit is compiled and can be found
       by doing:

        nbdkit --dump-config

WRITING PLUGINS IN OTHER PROGRAMMING LANGUAGES

       You can also write nbdkit plugins in OCaml, Perl or Python.  Other programming languages
       may be offered in future.

       For more information see: nbdkit-ocaml-plugin(3), nbdkit-perl-plugin(3),
       nbdkit-python-plugin(3).

SEE ALSO

       nbdkit(1), nbdkit-example1-plugin(1), nbdkit-example2-plugin(1),
       nbdkit-example3-plugin(1), nbdkit-ocaml-plugin(3), nbdkit-perl-plugin(3),
       nbdkit-python-plugin(3).

AUTHORS

       Richard W.M. Jones

COPYRIGHT

       Copyright (C) 2013 Red Hat Inc.

LICENSE

       Redistribution and use in source and binary forms, with or without modification, are
       permitted provided that the following conditions are met:

       •   Redistributions of source code must retain the above copyright notice, this list of
           conditions and the following disclaimer.

       •   Redistributions in binary form must reproduce the above copyright notice, this list of
           conditions and the following disclaimer in the documentation and/or other materials
           provided with the distribution.

       •   Neither the name of Red Hat nor the names of its contributors may be used to endorse
           or promote products derived from this software without specific prior written
           permission.

       THIS SOFTWARE IS PROVIDED BY RED HAT AND CONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED
       WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
       FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL RED HAT OR CONTRIBUTORS
       BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
       DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
       OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
       LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
       OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
       POSSIBILITY OF SUCH DAMAGE.