Update Red Hat Copyright Notices
[nbdkit.git] / plugins / example4 / example4.pl
blob0b478a774088f6c4f6258864f8f8a0373ef24189
1 #!@sbindir@/nbdkit perl
2 # -*- perl -*-
4 =pod
6 =head1 NAME
8 nbdkit-example4-plugin - example nbdkit plugin written in Perl
10 =head1 SYNOPSIS
12 nbdkit example4 size=<N>
14 =head1 EXAMPLE
16 nbdkit example4 size=1048576
17 guestfish -a nbd://localhost
19 =head1 DESCRIPTION
21 C<nbdkit-example4-plugin> is an example L<nbdkit(1)> plugin
22 written in Perl.
24 The C<size=N> parameter is required. It specifies the disk size in
25 bytes. A single disk image, initially all zeroes, is created and can
26 be read and written by all clients. When nbdkit shuts down the disk
27 image is thrown away.
29 Mainly this is useful for testing and as an example of nbdkit plugins
30 written in Perl. You should also read L<nbdkit-plugin(3)> and
31 L<nbdkit-perl-plugin(3)>. Note that nbdkit plugins may be written in
32 C or other scripting languages.
34 =head1 VERSION
36 C<nbdkit-example4-plugin> first appeared in nbdkit 1.2.
38 =head1 SEE ALSO
40 L<https://gitlab.com/nbdkit/nbdkit/blob/master/plugins/example4/example4.pl>,
41 L<nbdkit(1)>,
42 L<nbdkit-plugin(3)>,
43 L<nbdkit-perl-plugin(3)>.
45 =head1 AUTHORS
47 Richard W.M. Jones
49 =head1 COPYRIGHT
51 Copyright Red Hat
53 =cut
55 use strict;
57 my $disk;
58 my $size;
60 # size=<N> (in bytes) is required on the command line.
61 # This example could be improved by parsing strings such as "1M".
62 sub config
64 my $k = shift;
65 my $v = shift;
67 if ($k eq "size") {
68 $size = int ($v);
70 else {
71 die "unknown parameter $k";
75 # After all the parameters have been parsed, this can be used to check
76 # for invalid or missing parameters.
77 sub config_complete
79 die "size was not set" unless defined $size;
82 # This is called just before forking into the background and is the
83 # last opportunity for the plugin to print an error message that the
84 # user can see (without digging through log files). Here we allocate
85 # the disk.
86 sub get_ready
88 $disk = "\0" x $size;
91 # Accept a connection from a client, create and return the handle
92 # which is passed back to other calls.
93 sub open
95 my $readonly = shift;
96 my $h = { readonly => $readonly };
97 return $h;
100 # Close the connection.
101 sub close
103 my $h = shift;
106 # Return the size.
107 sub get_size
109 my $h = shift;
110 return length ($disk);
113 # Read.
114 sub pread
116 my $h = shift;
117 my $count = shift;
118 my $offset = shift;
119 return substr ($disk, $offset, $count);
122 # Write.
123 sub pwrite
125 my $h = shift;
126 my $buf = shift;
127 my $count = length ($buf);
128 my $offset = shift;
129 substr ($disk, $offset, $count) = $buf;
132 # If you want to display extra information about the plugin when
133 # the user does ‘nbdkit example4 --dump-plugin’ then you can print
134 # ‘key=value’ lines here.
135 sub dump_plugin
137 print "example4_extra=hello\n";
138 flush STDOUT;