5 nbdkit-plugin - How to write nbdkit plugins
9 #include <nbdkit-plugin.h>
11 #define THREAD_MODEL NBDKIT_THREAD_MODEL_SERIALIZE_ALL_REQUESTS
16 /* create a handle ... */
20 static struct nbdkit_plugin plugin = {
22 .open = myplugin_open,
23 .get_size = myplugin_get_size,
24 .pread = myplugin_pread,
25 .pwrite = myplugin_pwrite,
29 NBDKIT_REGISTER_PLUGIN(plugin)
31 When this has been compiled to a shared library, do:
33 nbdkit [--args ...] ./myplugin.so [key=value ...]
35 When debugging, use the I<-fv> options:
37 nbdkit -fv ./myplugin.so [key=value ...]
41 An nbdkit plugin is a new source device which can be served using the
42 Network Block Device (NBD) protocol. This manual page describes how
43 to create an nbdkit plugin in C.
45 For example plugins, take a look at the source of nbdkit, in the
48 To write plugins in other languages, see:
49 L<nbdkit-ocaml-plugin(3)>,
50 L<nbdkit-perl-plugin(3)>,
51 L<nbdkit-python-plugin(3)>,
52 L<nbdkit-ruby-plugin(3)>.
54 =head1 C<nbdkit-plugin.h>
56 All plugins should start by including this header file:
58 #include <nbdkit-plugin.h>
60 =head1 C<#define THREAD_MODEL>
62 All plugins must define a thread model. See L</THREADS> below for
63 details. It is generally safe to use:
65 #define THREAD_MODEL NBDKIT_THREAD_MODEL_SERIALIZE_ALL_REQUESTS
67 =head1 C<struct nbdkit_plugin>
69 All plugins must define and register one C<struct nbdkit_plugin>,
70 which contains the name of the plugin and pointers to callback
73 static struct nbdkit_plugin plugin = {
75 .longname = "My Plugin",
76 .description = "This is my great plugin for nbdkit",
77 .open = myplugin_open,
78 .get_size = myplugin_get_size,
79 .pread = myplugin_pread,
80 .pwrite = myplugin_pwrite,
84 NBDKIT_REGISTER_PLUGIN(plugin)
86 The C<.name> field is the name of the plugin.
88 The callbacks are described below (see L</CALLBACKS>). Only C<.name>,
89 C<.open>, C<.get_size> and C<.pread> are required. All other
90 callbacks can be omitted. However almost all plugins should have a
91 C<.close> callback. Most real-world plugins will also want to declare
92 some of the other callbacks.
94 The nbdkit server calls the callbacks in the following order over the
95 lifetime of the plugin:
101 is called once just after the plugin is loaded into memory.
103 =item C<.config> and C<.config_complete>
105 C<.config> is called zero or more times during command line parsing.
106 C<.config_complete> is called once after all configuration information
107 has been passed to the plugin.
109 Both are called after loading the plugin but before any connections
114 A new client has connected.
116 =item C<.can_write>, C<.get_size> and other option negotiation callbacks
118 These are called during option negotiation with the client, but
119 before any data is served.
121 =item C<.pread>, C<.pwrite> and other data serving callbacks
123 After option negotiation has finished, these may be called to serve
124 data. Depending on the thread model chosen, they might be called in
125 parallel from multiple threads.
129 The client has disconnected.
131 =item C<.open> ... C<.close>
133 The sequence C<.open> ... C<.close> can be called repeatedly over the
134 lifetime of the plugin, and can be called in parallel (depending on
139 is called once just before the plugin is unloaded from memory.
143 =head1 ERROR HANDLING
145 If there is an error in the plugin, the plugin should call
146 C<nbdkit_error> with the error message, and then return an error
147 indication from the callback, eg. NULL or -1.
149 C<nbdkit_error> has the following prototype and works like
152 void nbdkit_error (const char *fs, ...);
154 =head1 FILENAMES AND PATHS
156 The server usually (not always) changes directory to C</> before it
157 starts serving connections. This means that any relative paths passed
158 during configuration will not work when the server is running
159 (example: S<C<nbdkit plugin.so file=disk.img>>).
161 To avoid problems, prepend relative paths with the current directory
162 before storing them in the handle. Or open files and store the file
165 =head2 C<nbdkit_absolute_path>
167 char *nbdkit_absolute_path (const char *filename);
169 The utility function C<nbdkit_absolute_path> converts any path to an
172 If conversion was not possible, this calls C<nbdkit_error> and returns
173 C<NULL>. Note that this function does not check that the file exists.
175 The returned string must be freed by the caller.
183 This field (a string) is required, and B<must> contain only ASCII
184 alphanumeric characters and be unique amongst all plugins.
190 Plugins may optionally set a version string which is displayed in help
191 and debugging output.
195 const char *longname;
197 An optional free text name of the plugin. This field is used in error
200 =head2 C<.description>
202 const char *description;
204 An optional multi-line description of the plugin.
210 This is called once just after the plugin is loaded into memory. You
211 can use this to perform any global initialization needed by the
218 This may be called once just before the plugin is unloaded from
219 memory. Note that it's not guaranteed that C<.unload> will always be
220 called (eg. the server might be killed or segfault), so you should try
221 to make the plugin as robust as possible by not requiring cleanup.
225 int config (const char *key, const char *value);
227 On the nbdkit command line, after the plugin filename, come an
228 optional list of C<key=value> arguments. These are passed to the
229 plugin through this callback when the plugin is first loaded and
230 before any connections are accepted.
232 This callback may be called zero or more times. Both C<key> and
233 C<value> parameters will be non-NULL, but it is possible for either to
234 be empty strings. The strings are owned by nbdkit but will remain
235 valid for the lifetime of the plugin, so the plugin does not need to
238 The format of the C<key> accepted by plugins is up to the plugin, but
239 you should probably look at other plugins and follow the same
242 If the value is a relative path, then note that the server changes
243 directory when it starts up. See L</FILENAMES AND PATHS> above.
245 If the C<.config> callback is not provided by the plugin, and the user
246 tries to specify any C<key=value> arguments, then nbdkit will exit
249 If there is an error, C<.config> should call C<nbdkit_error> with an
250 error message and return C<-1>.
252 =head2 C<.config_complete>
254 int config_complete (void);
256 This optional callback is called after all the configuration has been
257 passed to the plugin. It is a good place to do checks, for example
258 that the user has passed the required parameters to the plugin.
260 If there is an error, C<.config_complete> should call C<nbdkit_error>
261 with an error message and return C<-1>.
263 =head2 C<.config_help>
265 const char *config_help;
267 This optional multi-line help message should summarize any
268 C<key=value> parameters that it takes. It does I<not> need to repeat
269 what already appears in C<.description>.
271 If the plugin doesn't take any config parameters you should probably
276 void *open (int readonly);
278 This is called when a new client connects to the nbdkit server. The
279 callback should allocate a handle and return it. This handle
280 is passed back to other callbacks and could be freed in the C<.close>
283 Note that the handle is completely opaque to nbdkit, but it must not
286 The C<readonly> flag informs the plugin that the user requested a
287 read-only connection using the I<-r> flag on the command line. Note
288 that the plugin may I<additionally> force the connection to be
289 readonly (even if this flag is false) by returning false from the
290 C<.can_write> callback. So if your plugin can only serve read-only,
291 you can ignore this parameter.
293 If there is an error, C<.open> should call C<nbdkit_error> with an
294 error message and return C<NULL>.
298 void close (void *handle);
300 This is called when the client closes the connection. It should clean
301 up any per-connection resources.
303 Note there is no way in the NBD protocol to communicate close errors
304 back to the client, for example if your plugin calls L<close(2)> and
305 you are checking for errors (as you should do). Therefore the best
306 you can do is to log the error on the server. Well-behaved NBD
307 clients I<should> try to flush the connection before it is closed and
308 check for errors, but obviously this is outside the scope of nbdkit.
312 int64_t get_size (void *handle);
314 This is called during the option negotiation phase of the protocol
315 to get the size (in bytes) of the block device being exported.
317 The returned size must be E<ge> 0. If there is an error, C<.get_size>
318 should call C<nbdkit_error> with an error message and return C<-1>.
322 int can_write (void *handle);
324 This is called during the option negotiation phase to find out if the
325 handle supports writes.
327 If there is an error, C<.can_write> should call C<nbdkit_error> with
328 an error message and return C<-1>.
330 This callback is not required. If omitted, then we return true iff a
331 C<.pwrite> callback has been defined.
335 int can_flush (void *handle);
337 This is called during the option negotiation phase to find out if the
338 handle supports the flush-to-disk operation.
340 If there is an error, C<.can_flush> should call C<nbdkit_error> with
341 an error message and return C<-1>.
343 This callback is not required. If omitted, then we return true iff a
344 C<.flush> callback has been defined.
346 =head2 C<.is_rotational>
348 int is_rotational (void *handle);
350 This is called during the option negotiation phase to find out if the
351 backing disk is a rotational medium (like a disk) or not (like an
352 SSD). If true, this may cause the client to reorder requests to make
353 them more efficient for a slow rotating disk.
355 If there is an error, C<.is_rotational> should call C<nbdkit_error>
356 with an error message and return C<-1>.
358 This callback is not required. If omitted, then we return false.
362 int can_trim (void *handle);
364 This is called during the option negotiation phase to find out if the
365 plugin supports the trim/discard operation for punching holes in the
368 If there is an error, C<.can_trim> should call C<nbdkit_error> with an
369 error message and return C<-1>.
371 This callback is not required. If omitted, then we return true iff a
372 C<.trim> callback has been defined.
376 int pread (void *handle, void *buf, uint32_t count, uint64_t offset);
378 During the data serving phase, nbdkit calls this callback to read data
379 from the backing store. C<count> bytes starting at C<offset> in the
380 backing store should be read and copied into C<buf>. nbdkit takes
381 care of all bounds- and sanity-checking, so the plugin does not need
384 The callback must read the whole C<count> bytes if it can. The NBD
385 protocol doesn't allow partial reads (instead, these would be errors).
386 If the whole C<count> bytes was read, the callback should return C<0>
387 to indicate there was I<no> error.
389 If there is an error (including a short read which couldn't be
390 recovered from), C<.pread> should call C<nbdkit_error> with an error
391 message and return C<-1>.
395 int pwrite (void *handle, const void *buf, uint32_t count, uint64_t offset);
397 During the data serving phase, nbdkit calls this callback to write
398 data to the backing store. C<count> bytes starting at C<offset> in
399 the backing store should be written using the data in C<buf>. nbdkit
400 takes care of all bounds- and sanity-checking, so the plugin does not
401 need to worry about that.
403 The callback must write the whole C<count> bytes if it can. The NBD
404 protocol doesn't allow partial writes (instead, these would be
405 errors). If the whole C<count> bytes was written successfully, the
406 callback should return C<0> to indicate there was I<no> error.
408 If there is an error (including a short write which couldn't be
409 recovered from), C<.pwrite> should call C<nbdkit_error> with an error
410 message and return C<-1>.
414 int flush (void *handle);
416 During the data serving phase, this callback is used to
417 L<fdatasync(2)> the backing store, ie. to ensure it has been
418 completely written to a permanent medium. If that is not possible
419 then you can omit this callback.
421 If there is an error, C<.flush> should call C<nbdkit_error> with an
422 error message and return C<-1>.
426 int trim (void *handle, uint32_t count, uint64_t offset);
428 During the data serving phase, this callback is used to "punch holes"
429 in the backing store. If that is not possible then you can omit this
432 If there is an error, C<.trim> should call C<nbdkit_error> with an
433 error message and return C<-1>.
437 Each nbdkit plugin must declare its thread safety model by defining
438 the C<THREAD_MODEL> macro. (This macro is used by
439 C<NBDKIT_REGISTER_PLUGIN>).
441 The possible settings for C<THREAD_MODEL> are defined below.
445 =item C<#define THREAD_MODEL NBDKIT_THREAD_MODEL_SERIALIZE_CONNECTIONS>
447 Only a single handle can be open at any time, and all requests happen
450 Note this means only one client can connect to the server at any time.
451 If a second client tries to connect it will block waiting for the
452 first client to close the connection.
454 =item C<#define THREAD_MODEL NBDKIT_THREAD_MODEL_SERIALIZE_ALL_REQUESTS>
456 I<This is a safe default for most plugins>.
458 Multiple handles can be open at the same time, but data requests are
459 serialized so that for the plugin as a whole only one read/write/etc
460 request will be in progress at any time.
462 This is a useful setting if the library you are using is not
463 thread-safe. However performance may not be good.
465 =item C<#define THREAD_MODEL NBDKIT_THREAD_MODEL_SERIALIZE_REQUESTS>
467 Multiple handles can be open and multiple data requests can happen in
468 parallel. However only one request will happen per handle at a time
469 (but requests on different handles might happen concurrently).
471 =item C<#define THREAD_MODEL NBDKIT_THREAD_MODEL_PARALLEL>
473 Multiple handles can be open and multiple data requests can happen in
474 parallel (even on the same handle).
476 All the libraries you use must be thread-safe and reentrant. You may
477 also need to provide mutexes for fields in your connection handle.
481 If none of the above thread models are suitable, then use
482 C<NBDKIT_THREAD_MODEL_PARALLEL> and implement your own locking using
483 C<pthread_mutex_t> etc.
485 =head1 PARSING SIZE PARAMETERS
487 Use the C<nbdkit_parse_size> utility function to parse human-readable
488 size strings such as "100M" into the size in bytes.
490 int64_t nbdkit_parse_size (const char *str);
492 C<str> can be a string in a number of common formats. The function
493 returns the size in bytes. If there was an error, it returns C<-1>.
497 Run the server with I<-f> and I<-v> options so it doesn't fork and you
498 can see debugging information:
500 nbdkit -fv ./myplugin.so [key=value [key=value [...]]]
502 To print debugging information from within the plugin, call
503 C<nbdkit_debug>, which has the following prototype and works like
506 void nbdkit_debug (const char *fs, ...);
508 Note that C<nbdkit_debug> only prints things when the server is in
509 verbose mode (I<-v> option).
511 =head1 INSTALLING THE PLUGIN
513 The plugin is a C<*.so> file and possibly a manual page. You can of
514 course install the plugin C<*.so> file wherever you want, and users
515 will be able to use it by running:
517 nbdkit /path/to/plugin.so [args]
519 However B<if> the shared library has a name of the form
520 C<nbdkit-I<name>-plugin.so> B<and if> the library is installed in the
521 C<$plugindir> directory, then users can be run it by only typing:
525 The location of the C<$plugindir> directory is set when nbdkit is
526 compiled and can be found by doing:
530 =head1 WRITING PLUGINS IN OTHER PROGRAMMING LANGUAGES
532 You can also write nbdkit plugins in OCaml, Perl, Python or Ruby.
533 Other programming languages may be offered in future.
535 For more information see:
536 L<nbdkit-ocaml-plugin(3)>,
537 L<nbdkit-perl-plugin(3)>,
538 L<nbdkit-python-plugin(3)>,
539 L<nbdkit-ruby-plugin(3)>.
544 L<nbdkit-example1-plugin(1)>,
545 L<nbdkit-example2-plugin(1)>,
546 L<nbdkit-example3-plugin(1)>,
547 L<nbdkit-ocaml-plugin(3)>,
548 L<nbdkit-perl-plugin(3)>,
549 L<nbdkit-python-plugin(3)>,
550 L<nbdkit-ruby-plugin(3)>.
558 Copyright (C) 2013-2016 Red Hat Inc.
562 Redistribution and use in source and binary forms, with or without
563 modification, are permitted provided that the following conditions are
570 Redistributions of source code must retain the above copyright
571 notice, this list of conditions and the following disclaimer.
575 Redistributions in binary form must reproduce the above copyright
576 notice, this list of conditions and the following disclaimer in the
577 documentation and/or other materials provided with the distribution.
581 Neither the name of Red Hat nor the names of its contributors may be
582 used to endorse or promote products derived from this software without
583 specific prior written permission.
587 THIS SOFTWARE IS PROVIDED BY RED HAT AND CONTRIBUTORS ''AS IS'' AND
588 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
589 THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
590 PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL RED HAT OR
591 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
592 SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
593 LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
594 USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
595 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
596 OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
597 OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF