plugins: Wire up rust plugin support for NBD_INFO_INIT_STATE
[nbdkit/ericb.git] / plugins / lua / example.lua
blobf5c2f2b86dbcce5cb250421370f2ef37a04a1c66
1 -- Example Lua plugin.
2 --
3 -- This example can be freely used for any purpose.
5 -- Run it from the build directory like this:
6 --
7 -- ./nbdkit -f -v lua ./plugins/lua/example.lua file=disk.img
8 --
9 -- Or run it after installing nbdkit like this:
11 -- nbdkit -f -v lua ./plugins/lua/example.lua file=disk.img
13 -- The -f -v arguments are optional. They cause the server to stay in
14 -- the foreground and print debugging, which is useful when testing.
16 -- You can connect to the server using guestfish or qemu, eg:
18 -- guestfish --format=raw -a nbd://localhost
19 -- ><fs> run
20 -- ><fs> part-disk /dev/sda mbr
21 -- ><fs> mkfs ext2 /dev/sda1
22 -- ><fs> list-filesystems
23 -- ><fs> mount /dev/sda1 /
24 -- ><fs> [etc]
26 -- This is called from: nbdkit lua example.lua --dump-plugin
27 function dump_plugin ()
28 print ("example_lua=1")
29 end
31 -- We expect a file=... parameter pointing to the file to serve.
32 function config (key, value)
33 if key == "file" then
34 file = value
35 else
36 error ("unknown parameter " .. key .. "=" .. value)
37 end
38 end
40 -- Check the file parameter was passed.
41 function config_complete ()
42 if not file then
43 error ("file parameter missing")
44 end
45 end
47 -- Open a new client connection.
48 function open (readonly)
49 -- Open the file.
50 local flags
51 if readonly then
52 flags="rb"
53 else
54 flags="r+b"
55 end
56 local fh = assert (io.open (file, flags))
58 -- We can return any Lua object as the handle. In this
59 -- plugin it's convenient to return the file handle.
60 return fh
61 end
63 -- Close a client connection.
64 function close (fh)
65 assert (fh:close())
66 end
68 function get_size (fh)
69 local size = assert (fh:seek ("end"))
70 return size
71 end
73 function pread (fh, count, offset)
74 assert (fh:seek ("set", offset))
75 local data = assert (fh:read (count))
76 return data
77 end
79 function pwrite (fh, buf, offset)
80 assert (fh:seek ("set", offset))
81 assert (fh:write (buf))
82 end