5 nbdkit-filter - How to write nbdkit filters
9 #include <nbdkit-filter.h>
11 #define THREAD_MODEL NBDKIT_THREAD_MODEL_PARALLEL
14 myfilter_config (nbdkit_next_config *next, void *nxdata,
15 const char *key, const char *value)
17 if (strcmp (key, "myparameter") == 0) {
22 // pass through to next filter or plugin
23 return next (nxdata, key, value);
27 static struct nbdkit_filter filter = {
29 .config = myfilter_config,
33 NBDKIT_REGISTER_FILTER(filter)
35 When this has been compiled to a shared library, do:
37 nbdkit [--args ...] --filter=./myfilter.so plugin [key=value ...]
39 When debugging, use the I<-fv> options:
41 nbdkit -fv --filter=./myfilter.so plugin [key=value ...]
45 One or more nbdkit filters can be placed in front of an nbdkit plugin
46 to modify the behaviour of the plugin. This manual page describes how
47 to create an nbdkit filter.
49 Filters can be used for example to limit requests to an offset/limit,
50 add copy-on-write support, or inject delays or errors (for testing).
52 Different filters can be stacked:
54 NBD ┌─────────┐ ┌─────────┐ ┌────────┐
55 client ───▶│ filter1 │───▶│ filter2 │── ─ ─ ──▶│ plugin │
56 request └─────────┘ └─────────┘ └────────┘
58 Each filter intercepts plugin functions (see L<nbdkit-plugin(3)>) and
59 can call the next filter or plugin in the chain, modifying parameters,
60 calling before the filter function, in the middle or after. Filters
61 may even short-cut the chain. As an example, to process its own
62 parameters the filter can intercept the C<.config> method:
65 myfilter_config (nbdkit_next_config *next, void *nxdata,
66 const char *key, const char *value)
68 if (strcmp (key, "myparameter") == 0) {
70 // here you would handle this key, value
75 // pass through to next filter or plugin
76 return next (nxdata, key, value);
80 static struct nbdkit_filter filter = {
82 .config = myfilter_config,
86 The call to C<next (nxdata, ...)> calls the C<.config> method of the
87 next filter or plugin in the chain. In the example above any
88 instances of C<myparameter=...> on the command line would not be seen
91 To see example filters, take a look at the source of nbdkit, in the
94 Filters must be written in C.
96 Unlike plugins, where we provide a stable ABI guarantee that permits
97 operation across version differences, filters can only be run with the
98 same version of nbdkit that they were compiled with. The reason for
99 this is two-fold: the filter API includes access to struct
100 nbdkit_next_ops that is likely to change if new callbacks are added
101 (old nbdkit cannot safely run new filters that access new methods);
102 and if we added new methods then an old filter would not see them and
103 so they would be passed unmodified through the filter, and in some
104 cases that leads to data corruption (new nbdkit cannot safely run old
105 filters unaware of new methods). Therefore, unlike plugins, you
106 should not expect to distribute filters separately from nbdkit.
108 =head1 C<nbdkit-filter.h>
110 All filters should start by including this header file:
112 #include <nbdkit-filter.h>
114 =head1 C<#define THREAD_MODEL>
116 All filters must define a thread model. See
117 L<nbdkit-plugin(3)/THREADS> for a discussion of thread models.
119 The final thread model is the smallest (ie. most serialized) out of
120 all the filters and the plugin. Filters cannot alter the thread model
121 to make it larger (more parallel).
123 If possible filters should be be written to handle fully parallel
124 requests (C<NBDKIT_THREAD_MODEL_PARALLEL>, even multiple requests
125 issued in parallel on the same connection). This ensures that they
126 don't slow down other filters or plugins.
128 =head1 C<struct nbdkit_filter>
130 All filters must define and register one C<struct nbdkit_filter>,
131 which contains the name of the filter and pointers to plugin methods
132 that the filter wants to intercept.
134 static struct nbdkit_filter filter = {
136 .longname = "My Filter",
137 .description = "This is my great filter for nbdkit",
138 .config = myfilter_config,
142 NBDKIT_REGISTER_FILTER(filter)
144 The C<.name> field is the name of the filter. This is the only field
149 F<nbdkit-filter.h> defines three function types
150 (C<nbdkit_next_config>, C<nbdkit_next_config_complete>,
151 C<nbdkit_next_open>) and a structure called C<struct nbdkit_next_ops>.
152 These abstract the next plugin or filter in the chain. There is also
153 an opaque pointer C<nxdata> which must be passed along when calling
156 The filter’s C<.config>, C<.config_complete> and C<.open> methods may
157 only call the next C<.config>, C<.config_complete> and C<.open> method
158 in the chain (optionally for C<.config>).
160 The filter’s C<.close> method is called when an old connection closed,
161 and this has no C<next> parameter because it cannot be
164 The filter’s other methods like C<.prepare>, C<.get_size>, C<.pread>
165 etc ― always called in the context of a connection ― are passed a
166 pointer to C<struct nbdkit_next_ops> which contains a comparable set
167 of accessors to plugin methods that can be called during a connection.
168 It is possible for a filter to issue (for example) extra read calls in
169 response to a single C<.pwrite> call. Note that the semantics of the
170 functions in C<struct nbdkit_next_ops> are slightly different from
171 what a plugin implements: for example, when a plugin's C<.pread>
172 returns -1 on error, the error value to advertise to the client is
173 implicit (via the plugin calling C<nbdkit_set_error> or setting
174 C<errno>), whereas C<next_ops-E<gt>pread> exposes this via an explicit
175 parameter, allowing a filter to learn or modify this error if desired.
177 You can modify parameters when you call the C<next> function. However
178 be careful when modifying strings because for some methods
179 (eg. C<.config>) the plugin may save the string pointer that you pass
180 along. So you may have to ensure that the string is not freed for the
181 lifetime of the server.
183 Note that if your filter registers a callback but in that callback it
184 doesn't call the C<next> function then the corresponding method in the
185 plugin will never be called. In particular, your C<.open> method, if
186 you have one, B<must> call the C<.next> method.
190 C<struct nbdkit_filter> has some static fields describing the filter
191 and optional callback functions which can be used to intercept plugin
198 This field (a string) is required, and B<must> contain only ASCII
199 alphanumeric characters and be unique amongst all filters.
205 Filters may optionally set a version string which is displayed in help
206 and debugging output.
210 const char *longname;
212 An optional free text name of the filter. This field is used in error
215 =head2 C<.description>
217 const char *description;
219 An optional multi-line description of the filter.
225 This is called once just after the filter is loaded into memory. You
226 can use this to perform any global initialization needed by the
233 This may be called once just before the filter is unloaded from
234 memory. Note that it's not guaranteed that C<.unload> will always be
235 called (eg. the server might be killed or segfault), so you should try
236 to make the filter as robust as possible by not requiring cleanup.
237 See also L<nbdkit-plugin(3)/SHUTDOWN>.
241 int (*config) (nbdkit_next_config *next, void *nxdata,
242 const char *key, const char *value);
244 This intercepts the plugin C<.config> method and can be used by the
245 filter to parse its own command line parameters. You should try to
246 make sure that command line parameter keys that the filter uses do not
247 conflict with ones that could be used by a plugin.
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) (nbdkit_next_config_complete *next, void *nxdata);
256 This intercepts the plugin C<.config_complete> method and can be used
257 to ensure that all parameters needed by the filter were supplied on
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 filter doesn't take any config parameters you should probably
276 void * (*open) (nbdkit_next_open *next, void *nxdata,
279 This is called when a new client connection is opened and can be used
280 to allocate any per-connection data structures needed by the filter.
281 The handle (which is not the same as the plugin handle) is passed back
282 to other filter callbacks and could be freed in the C<.close>
285 Note that the handle is completely opaque to nbdkit, but it must not
288 If there is an error, C<.open> should call C<nbdkit_error> with an
289 error message and return C<NULL>.
293 void (*close) (void *handle);
295 This is called when the client closes the connection. It should clean
296 up any per-connection resources used by the filter.
302 int (*prepare) (struct nbdkit_next_ops *next_ops, void *nxdata,
304 int (*finalize) (struct nbdkit_next_ops *next_ops, void *nxdata,
307 These two methods can be used to perform any necessary operations just
308 after opening the connection (C<.prepare>) or just before closing the
309 connection (C<.finalize>).
311 For example if you need to scan the underlying disk to check for a
312 partition table, you could do it in your C<.prepare> method (calling
313 the plugin's C<.pread> method via C<next_ops>). Or if you need to
314 cleanly update superblock data in the image on close you can do it in
315 your C<.finalize> method (calling the plugin's C<.pwrite> method).
316 Doing these things in the filter's C<.open> or C<.close> method is not
319 If there is an error, both callbacks should call C<nbdkit_error> with
320 an error message and return C<-1>.
324 int64_t (*get_size) (struct nbdkit_next_ops *next_ops, void *nxdata,
327 This intercepts the plugin C<.get_size> method and can be used to read
328 or modify the apparent size of the block device that the NBD client
331 The returned size must be E<ge> 0. If there is an error, C<.get_size>
332 should call C<nbdkit_error> with an error message and return C<-1>.
333 If this function is called more than once for the same connection, it
334 should return the same value; similarly, the filter may cache
335 C<next_ops-E<gt>get_size> for a given connection rather than repeating
342 =head2 C<.is_rotational>
346 int (*can_write) (struct nbdkit_next_ops *next_ops, void *nxdata,
348 int (*can_flush) (struct nbdkit_next_ops *next_ops, void *nxdata,
350 int (*is_rotational) (struct nbdkit_next_ops *next_ops,
353 int (*can_trim) (struct nbdkit_next_ops *next_ops, void *nxdata,
356 These intercept the corresponding plugin methods, and control feature
357 bits advertised to the client.
359 If there is an error, the callback should call C<nbdkit_error> with an
360 error message and return C<-1>. If these functions are called more
361 than once for the same connection, they should return the same value;
362 similarly, the filter may cache the results of each counterpart in
363 C<next_ops> for a given connection rather than repeating calls.
367 int (*can_zero) (struct nbdkit_next_ops *next_ops, void *nxdata,
370 This controls whether write zero support will be advertised to the
371 client. This function has no counterpart in plugins, because nbdkit
372 can always emulate zero by using pwrite; but a filter may want to
373 force different handling than the nbdkit implementation. If this
374 callback is omitted, the default returned for the plugin layer is
377 If there is an error, the callback should call C<nbdkit_error> with an
378 error message and return C<-1>. Like the other initial queries
379 documented above, per-connection caching the of return value of this
384 int (*can_fua) (struct nbdkit_next_ops *next_ops, void *nxdata,
387 This controls how the Forced Unit Access flag will be handled; it is
388 only relevant for connections that are not read-only. This intercepts
389 the corresponding plugin method, to control feature bits advertised to
390 the client. Unlike other feature functions with just two success
391 states, this one returns three success values: C<NBDKIT_FUA_NONE> to
392 avoid advertising FUA support to the client, C<NBDKIT_FUA_EMULATE> if
393 FUA is emulated by nbdkit calling flush after a write transaction, and
394 C<NBDKIT_FUA_NATIVE> if FUA semantics are handled by the plugin
395 without the overhead of an extra flush from nbdkit.
397 The difference between the two non-zero values may affect choices made
398 in the filter: when splitting a write request that requested FUA from
399 the client, native support should pass the FUA flag on to each
400 sub-request; while if it is known that FUA is emulated by a flush, it
401 is more efficient to only flush once after all sub-requests have
402 completed (often by passing C<NBDKIT_FLAG_FUA> on to only the final
403 sub-request, or by dropping the flag and ending with a direct call to
404 C<next_ops-E<gt>flush>).
406 If this callback is omitted, the default returned for the plugin layer
407 is C<NBDKIT_FUA_EMULATE> if C<can_flush> returned true, otherwise it
408 is C<NBDKIT_FUA_NONE>.
410 If there is an error, the callback should call C<nbdkit_error> with an
411 error message and return C<-1>. Like the other initial queries
412 documented above, per-connection caching of the return value of this
417 int (*pread) (struct nbdkit_next_ops *next_ops, void *nxdata,
418 void *handle, void *buf, uint32_t count, uint64_t offset,
419 uint32_t flags, int *err);
421 This intercepts the plugin C<.pread> method and can be used to read or
422 modify data read by the plugin.
424 The parameter C<flags> exists in case of future NBD protocol
425 extensions; at this time, it will be 0 on input, and the filter should
426 not pass any flags to C<next_ops-E<gt>pread>.
428 If there is an error (including a short read which couldn't be
429 recovered from), C<.pread> should call C<nbdkit_error> with an error
430 message B<and> return -1 with C<err> set to the positive errno value
431 to return to the client.
435 int (*pwrite) (struct nbdkit_next_ops *next_ops, void *nxdata,
437 const void *buf, uint32_t count, uint64_t offset,
438 uint32_t flags, int *err);
440 This intercepts the plugin C<.pwrite> method and can be used to modify
441 data written by the plugin.
443 This function will not be called if C<.can_write> returned false; in
444 turn, the filter should not call C<next_ops-E<gt>pwrite> if
445 C<next_ops-E<gt>can_write> did not return true.
447 The parameter C<flags> may include C<NBDKIT_FLAG_FUA> on input based
448 on the result of C<.can_fua>. In turn, the filter should only pass
449 C<NBDKIT_FLAG_FUA> on to C<next_ops-E<gt>pwrite> if
450 C<next_ops-E<gt>can_fua> returned a positive value.
452 If there is an error (including a short write which couldn't be
453 recovered from), C<.pwrite> should call C<nbdkit_error> with an error
454 message B<and> return -1 with C<err> set to the positive errno value
455 to return to the client.
459 int (*flush) (struct nbdkit_next_ops *next_ops, void *nxdata,
460 void *handle, uint32_t flags, int *err);
462 This intercepts the plugin C<.flush> method and can be used to modify
465 This function will not be called if C<.can_flush> returned false; in
466 turn, the filter should not call C<next_ops-E<gt>flush> if
467 C<next_ops-E<gt>can_flush> did not return true.
469 The parameter C<flags> exists in case of future NBD protocol
470 extensions; at this time, it will be 0 on input, and the filter should
471 not pass any flags to C<next_ops-E<gt>flush>.
473 If there is an error, C<.flush> should call C<nbdkit_error> with an
474 error message B<and> return -1 with C<err> set to the positive errno
475 value to return to the client.
479 int (*trim) (struct nbdkit_next_ops *next_ops, void *nxdata,
480 void *handle, uint32_t count, uint64_t offset,
481 uint32_t flags, int *err);
483 This intercepts the plugin C<.trim> method and can be used to modify
486 This function will not be called if C<.can_trim> returned false; in
487 turn, the filter should not call C<next_ops-E<gt>trim> if
488 C<next_ops-E<gt>can_trim> did not return true.
490 The parameter C<flags> may include C<NBDKIT_FLAG_FUA> on input based
491 on the result of C<.can_fua>. In turn, the filter should only pass
492 C<NBDKIT_FLAG_FUA> on to C<next_ops-E<gt>trim> if
493 C<next_ops-E<gt>can_fua> returned a positive value.
495 If there is an error, C<.trim> should call C<nbdkit_error> with an
496 error message B<and> return -1 with C<err> set to the positive errno
497 value to return to the client.
501 int (*zero) (struct nbdkit_next_ops *next_ops, void *nxdata,
502 void *handle, uint32_t count, uint64_t offset, uint32_t flags,
505 This intercepts the plugin C<.zero> method and can be used to modify
508 This function will not be called if C<.can_write> returned false; in
509 turn, the filter should not call C<next_ops-E<gt>zero> if
510 C<next_ops-E<gt>can_zero> did not return true.
512 On input, the parameter C<flags> may include C<NBDKIT_FLAG_MAY_TRIM>
513 unconditionally, and C<NBDKIT_FLAG_FUA> based on the result of
514 C<.can_fua>. In turn, the filter may pass C<NBDKIT_FLAG_MAY_TRIM>
515 unconditionally, but should only pass C<NBDKIT_FLAG_FUA> on to
516 C<next_ops-E<gt>zero> if C<next_ops-E<gt>can_fua> returned a positive
519 Note that unlike the plugin C<.zero> which is permitted to fail with
520 C<EOPNOTSUPP> to force a fallback to C<.pwrite>, the function
521 C<next_ops-E<gt>zero> will never fail with C<err> set to C<EOPNOTSUPP>
522 because the fallback has already taken place.
524 If there is an error, C<.zero> should call C<nbdkit_error> with an
525 error message B<and> return -1 with C<err> set to the positive errno
526 value to return to the client. The filter should never fail with
527 C<EOPNOTSUPP> (while plugins have automatic fallback to C<.pwrite>,
530 =head1 ERROR HANDLING
532 If there is an error in the filter itself, the filter should call
533 C<nbdkit_error> to report an error message. If the callback is
534 involved in serving data, the explicit C<err> parameter determines the
535 error code that will be sent to the client; other callbacks should
536 return the appropriate error indication, eg. C<NULL> or C<-1>.
538 C<nbdkit_error> has the following prototype and works like
541 void nbdkit_error (const char *fs, ...);
542 void nbdkit_verror (const char *fs, va_list args);
544 For convenience, C<nbdkit_error> preserves the value of C<errno>.
548 Run the server with I<-f> and I<-v> options so it doesn't fork and you
549 can see debugging information:
551 nbdkit -fv --filter=./myfilter.so plugin [key=value [key=value [...]]]
553 To print debugging information from within the filter, call
554 C<nbdkit_debug>, which has the following prototype and works like
557 void nbdkit_debug (const char *fs, ...);
558 void nbdkit_vdebug (const char *fs, va_list args);
560 For convenience, C<nbdkit_debug> preserves the value of C<errno>.
561 Note that C<nbdkit_debug> only prints things when the server is in
562 verbose mode (I<-v> option).
564 =head1 INSTALLING THE FILTER
566 The filter is a C<*.so> file and possibly a manual page. You can of
567 course install the filter C<*.so> file wherever you want, and users
568 will be able to use it by running:
570 nbdkit --filter=/path/to/filter.so plugin [args]
572 However B<if> the shared library has a name of the form
573 C<nbdkit-I<name>-filter.so> B<and if> the library is installed in the
574 C<$filterdir> directory, then users can be run it by only typing:
576 nbdkit --filter=name plugin [args]
578 The location of the C<$filterdir> directory is set when nbdkit is
579 compiled and can be found by doing:
583 If using the pkg-config/pkgconf system then you can also find the
584 filter directory at compile time by doing:
586 pkgconf nbdkit --variable=filterdir
588 =head1 PKG-CONFIG/PKGCONF
590 nbdkit provides a pkg-config/pkgconf file called C<nbdkit.pc> which
591 should be installed on the correct path when the nbdkit development
592 environment is installed. You can use this in autoconf
593 F<configure.ac> scripts to test for the development environment:
595 PKG_CHECK_MODULES([NBDKIT], [nbdkit >= 1.2.3])
597 The above will fail unless nbdkit E<ge> 1.2.3 and the header file is
598 installed, and will set C<NBDKIT_CFLAGS> and C<NBDKIT_LIBS>
599 appropriately for compiling filters.
601 You can also run pkg-config/pkgconf directly, for example:
603 if ! pkgconf nbdkit --exists; then
604 echo "you must install the nbdkit development environment"
615 L<nbdkit-blocksize-filter(1)>,
616 L<nbdkit-cache-filter(1)>,
617 L<nbdkit-cow-filter(1)>,
618 L<nbdkit-delay-filter(1)>,
619 L<nbdkit-fua-filter(1)>,
620 L<nbdkit-log-filter(1)>,
621 L<nbdkit-nozero-filter(1)>,
622 L<nbdkit-offset-filter(1)>,
623 L<nbdkit-partition-filter(1)>.
631 Copyright (C) 2013-2018 Red Hat Inc.
635 Redistribution and use in source and binary forms, with or without
636 modification, are permitted provided that the following conditions are
643 Redistributions of source code must retain the above copyright
644 notice, this list of conditions and the following disclaimer.
648 Redistributions in binary form must reproduce the above copyright
649 notice, this list of conditions and the following disclaimer in the
650 documentation and/or other materials provided with the distribution.
654 Neither the name of Red Hat nor the names of its contributors may be
655 used to endorse or promote products derived from this software without
656 specific prior written permission.
660 THIS SOFTWARE IS PROVIDED BY RED HAT AND CONTRIBUTORS ''AS IS'' AND
661 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
662 THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
663 PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL RED HAT OR
664 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
665 SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
666 LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
667 USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
668 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
669 OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
670 OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF