1 (* Example OCaml plugin.
3 This example can be freely copied and used for any purpose.
5 When building nbdkit this example is compiled as:
7 plugins/ocaml/nbdkit-ocamlexample-plugin.so
9 You can run it from the build directory like this:
11 ./nbdkit -f -v plugins/ocaml/nbdkit-ocamlexample-plugin.so [size=100M]
13 and connect to it with guestfish like this:
15 guestfish --format=raw -a nbd://localhost
17 ><fs> part-disk /dev/sda mbr
18 ><fs> mkfs ext2 /dev/sda1
19 ><fs> list-filesystems
20 ><fs> mount /dev/sda1 /
24 (* Disk image with default size. *)
25 let disk = ref (Bytes.make
(1024*1024) '
\000'
)
27 let ocamlexample_load () =
28 (* Debugging output is only printed when the server is in
29 * verbose mode (nbdkit -v option).
31 NBDKit.debug
"example OCaml plugin loaded"
33 let ocamlexample_unload () =
34 NBDKit.debug
"example OCaml plugin unloaded"
36 let ocamlexample_config key
value =
39 let size = Int64.to_int
(NBDKit.parse_size
value) in
40 disk := Bytes.make
size '
\000'
(* Reallocate the disk. *)
42 failwith
(Printf.sprintf
"unknown parameter: %s" key
)
44 (* Any type (even unit) can be used as a per-connection handle.
45 * This is just an example. The same value that you return from
46 * your [open_connection] function is passed back as the first
47 * parameter to connected functions like get_size and pread.
50 h_id
: int; (* just a useless example field *)
54 let ocamlexample_open readonly
=
55 NBDKit.debug
"example OCaml plugin handle opened readonly=%b" readonly
;
59 let ocamlexample_get_size h
=
60 Int64.of_int
(Bytes.length
!disk)
62 let ocamlexample_pread h count offset _
=
63 let count = Int32.to_int
count in
64 let buf = Bytes.create
count in
65 Bytes.blit
!disk (Int64.to_int offset
) buf 0 count;
66 Bytes.unsafe_to_string
buf
68 let ocamlexample_pwrite h
buf offset _
=
69 let len = String.length
buf in
70 let offset = Int64.to_int
offset in
71 String.blit
buf 0 !disk offset len
73 let ocamlexample_thread_model () =
74 NBDKit.THREAD_MODEL_SERIALIZE_CONNECTIONS
77 NBDKit.default_callbacks
with
78 (* name, open_connection, get_size and pread are required,
79 * everything else is optional.
81 NBDKit.name
= "ocamlexample";
84 load
= Some
ocamlexample_load;
85 unload
= Some
ocamlexample_unload;
87 config
= Some
ocamlexample_config;
89 open_connection
= Some
ocamlexample_open;
90 get_size
= Some
ocamlexample_get_size;
91 pread
= Some
ocamlexample_pread;
92 pwrite
= Some
ocamlexample_pwrite;
94 thread_model
= Some
ocamlexample_thread_model;
97 let () = NBDKit.register_plugin
plugin