3 * Copyright (C) 2009 Red Hat Inc.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 (* This script generates a large amount of code and documentation for
21 * all the daemon actions.
23 * To add a new action there are only two files you need to change,
24 * this one to describe the interface (see the big table below), and
25 * daemon/<somefile>.c to write the implementation.
27 * After editing this file, run it (./src/generator.ml) to regenerate
28 * all the output files.
30 * IMPORTANT: This script should NOT print any warnings. If it prints
31 * warnings, you should treat them as errors.
32 * [Need to add -warn-error to ocaml command line]
40 type style = ret * args
42 (* "RErr" as a return value means an int used as a simple error
43 * indication, ie. 0 or -1.
46 (* "RInt" as a return value means an int which is -1 for error
47 * or any value >= 0 on success. Only use this for smallish
48 * positive ints (0 <= i < 2^30).
51 (* "RInt64" is the same as RInt, but is guaranteed to be able
52 * to return a full 64 bit value, _except_ that -1 means error
53 * (so -1 cannot be a valid, non-error return value).
56 (* "RBool" is a bool return value which can be true/false or
60 (* "RConstString" is a string that refers to a constant value.
61 * Try to avoid using this. In particular you cannot use this
62 * for values returned from the daemon, because there is no
63 * thread-safe way to return them in the C API.
65 | RConstString of string
66 (* "RString" and "RStringList" are caller-frees. *)
68 | RStringList of string
69 (* Some limited tuples are possible: *)
70 | RIntBool of string * string
71 (* LVM PVs, VGs and LVs. *)
78 (* Key-value pairs of untyped strings. Turns into a hashtable or
79 * dictionary in languages which support it. DON'T use this as a
80 * general "bucket" for results. Prefer a stronger typed return
81 * value if one is available, or write a custom struct. Don't use
82 * this if the list could potentially be very long, since it is
83 * inefficient. Keys should be unique. NULLs are not permitted.
85 | RHashtable of string
87 and args = argt list (* Function parameters, guestfs handle is implicit. *)
89 (* Note in future we should allow a "variable args" parameter as
90 * the final parameter, to allow commands like
91 * chmod mode file [file(s)...]
92 * This is not implemented yet, but many commands (such as chmod)
93 * are currently defined with the argument order keeping this future
94 * possibility in mind.
97 | String of string (* const char *name, cannot be NULL *)
98 | OptString of string (* const char *name, may be NULL *)
99 | StringList of string(* list of strings (each string cannot be NULL) *)
100 | Bool of string (* boolean *)
101 | Int of string (* int (smallish ints, signed, <= 31 bits) *)
102 (* These are treated as filenames (simple string parameters) in
103 * the C API and bindings. But in the RPC protocol, we transfer
104 * the actual file content up to or down from the daemon.
105 * FileIn: local machine -> daemon (in request)
106 * FileOut: daemon -> local machine (in reply)
107 * In guestfish (only), the special name "-" means read from
108 * stdin or write to stdout.
114 | ProtocolLimitWarning (* display warning about protocol size limits *)
115 | DangerWillRobinson (* flags particularly dangerous commands *)
116 | FishAlias of string (* provide an alias for this cmd in guestfish *)
117 | FishAction of string (* call this function in guestfish *)
118 | NotInFish (* do not export via guestfish *)
119 | NotInDocs (* do not add this function to documentation *)
121 let protocol_limit_warning =
122 "Because of the message protocol, there is a transfer limit
123 of somewhere between 2MB and 4MB. To transfer large files you should use
126 let danger_will_robinson =
127 "B<This command is dangerous. Without careful use you
128 can easily destroy all your data>."
130 (* You can supply zero or as many tests as you want per API call.
132 * Note that the test environment has 3 block devices, of size 500MB,
133 * 50MB and 10MB (respectively /dev/sda, /dev/sdb, /dev/sdc).
134 * Note for partitioning purposes, the 500MB device has 63 cylinders.
136 * To be able to run the tests in a reasonable amount of time,
137 * the virtual machine and block devices are reused between tests.
138 * So don't try testing kill_subprocess :-x
140 * Between each test we blockdev-setrw, umount-all, lvm-remove-all.
142 * If the appliance is running an older Linux kernel (eg. RHEL 5) then
143 * devices are named /dev/hda etc. To cope with this, the test suite
144 * adds some hairly logic to detect this case, and then automagically
145 * replaces all strings which match "/dev/sd.*" with "/dev/hd.*".
146 * When writing test cases you shouldn't have to worry about this
149 * Don't assume anything about the previous contents of the block
150 * devices. Use 'Init*' to create some initial scenarios.
152 * You can add a prerequisite clause to any individual test. This
153 * is a run-time check, which, if it fails, causes the test to be
154 * skipped. Useful if testing a command which might not work on
155 * all variations of libguestfs builds. A test that has prerequisite
156 * of 'Always' is run unconditionally.
158 * In addition, packagers can skip individual tests by setting the
159 * environment variables: eg:
160 * SKIP_TEST_<CMD>_<NUM>=1 SKIP_TEST_COMMAND_3=1 (skips test #3 of command)
161 * SKIP_TEST_<CMD>=1 SKIP_TEST_ZEROFREE=1 (skips all zerofree tests)
163 type tests = (test_init * test_prereq * test) list
165 (* Run the command sequence and just expect nothing to fail. *)
167 (* Run the command sequence and expect the output of the final
168 * command to be the string.
170 | TestOutput of seq * string
171 (* Run the command sequence and expect the output of the final
172 * command to be the list of strings.
174 | TestOutputList of seq * string list
175 (* Run the command sequence and expect the output of the final
176 * command to be the integer.
178 | TestOutputInt of seq * int
179 (* Run the command sequence and expect the output of the final
180 * command to be a true value (!= 0 or != NULL).
182 | TestOutputTrue of seq
183 (* Run the command sequence and expect the output of the final
184 * command to be a false value (== 0 or == NULL, but not an error).
186 | TestOutputFalse of seq
187 (* Run the command sequence and expect the output of the final
188 * command to be a list of the given length (but don't care about
191 | TestOutputLength of seq * int
192 (* Run the command sequence and expect the output of the final
193 * command to be a structure.
195 | TestOutputStruct of seq * test_field_compare list
196 (* Run the command sequence and expect the final command (only)
199 | TestLastFail of seq
201 and test_field_compare =
202 | CompareWithInt of string * int
203 | CompareWithString of string * string
204 | CompareFieldsIntEq of string * string
205 | CompareFieldsStrEq of string * string
207 (* Test prerequisites. *)
209 (* Test always runs. *)
211 (* Test is currently disabled - eg. it fails, or it tests some
212 * unimplemented feature.
215 (* 'string' is some C code (a function body) that should return
216 * true or false. The test will run if the code returns true.
219 (* As for 'If' but the test runs _unless_ the code returns true. *)
222 (* Some initial scenarios for testing. *)
224 (* Do nothing, block devices could contain random stuff including
225 * LVM PVs, and some filesystems might be mounted. This is usually
229 (* Block devices are empty and no filesystems are mounted. *)
231 (* /dev/sda contains a single partition /dev/sda1, which is formatted
232 * as ext2, empty [except for lost+found] and mounted on /.
233 * /dev/sdb and /dev/sdc may have random content.
238 * /dev/sda1 (is a PV):
239 * /dev/VG/LV (size 8MB):
240 * formatted as ext2, empty [except for lost+found], mounted on /
241 * /dev/sdb and /dev/sdc may have random content.
245 (* Sequence of commands for testing. *)
247 and cmd = string list
249 (* Note about long descriptions: When referring to another
250 * action, use the format C<guestfs_other> (ie. the full name of
251 * the C function). This will be replaced as appropriate in other
254 * Apart from that, long descriptions are just perldoc paragraphs.
257 (* These test functions are used in the language binding tests. *)
259 let test_all_args = [
262 StringList "strlist";
269 let test_all_rets = [
270 (* except for RErr, which is tested thoroughly elsewhere *)
271 "test0rint", RInt "valout";
272 "test0rint64", RInt64 "valout";
273 "test0rbool", RBool "valout";
274 "test0rconststring", RConstString "valout";
275 "test0rstring", RString "valout";
276 "test0rstringlist", RStringList "valout";
277 "test0rintbool", RIntBool ("valout", "valout");
278 "test0rpvlist", RPVList "valout";
279 "test0rvglist", RVGList "valout";
280 "test0rlvlist", RLVList "valout";
281 "test0rstat", RStat "valout";
282 "test0rstatvfs", RStatVFS "valout";
283 "test0rhashtable", RHashtable "valout";
286 let test_functions = [
287 ("test0", (RErr, test_all_args), -1, [NotInFish; NotInDocs],
289 "internal test function - do not use",
291 This is an internal test function which is used to test whether
292 the automatically generated bindings can handle every possible
293 parameter type correctly.
295 It echos the contents of each parameter to stdout.
297 You probably don't want to call this function.");
301 [(name, (ret, [String "val"]), -1, [NotInFish; NotInDocs],
303 "internal test function - do not use",
305 This is an internal test function which is used to test whether
306 the automatically generated bindings can handle every possible
307 return type correctly.
309 It converts string C<val> to the return type.
311 You probably don't want to call this function.");
312 (name ^ "err", (ret, []), -1, [NotInFish; NotInDocs],
314 "internal test function - do not use",
316 This is an internal test function which is used to test whether
317 the automatically generated bindings can handle every possible
318 return type correctly.
320 This function always returns an error.
322 You probably don't want to call this function.")]
326 (* non_daemon_functions are any functions which don't get processed
327 * in the daemon, eg. functions for setting and getting local
328 * configuration values.
331 let non_daemon_functions = test_functions @ [
332 ("launch", (RErr, []), -1, [FishAlias "run"; FishAction "launch"],
334 "launch the qemu subprocess",
336 Internally libguestfs is implemented by running a virtual machine
339 You should call this after configuring the handle
340 (eg. adding drives) but before performing any actions.");
342 ("wait_ready", (RErr, []), -1, [NotInFish],
344 "wait until the qemu subprocess launches",
346 Internally libguestfs is implemented by running a virtual machine
349 You should call this after C<guestfs_launch> to wait for the launch
352 ("kill_subprocess", (RErr, []), -1, [],
354 "kill the qemu subprocess",
356 This kills the qemu subprocess. You should never need to call this.");
358 ("add_drive", (RErr, [String "filename"]), -1, [FishAlias "add"],
360 "add an image to examine or modify",
362 This function adds a virtual machine disk image C<filename> to the
363 guest. The first time you call this function, the disk appears as IDE
364 disk 0 (C</dev/sda>) in the guest, the second time as C</dev/sdb>, and
367 You don't necessarily need to be root when using libguestfs. However
368 you obviously do need sufficient permissions to access the filename
369 for whatever operations you want to perform (ie. read access if you
370 just want to read the image or write access if you want to modify the
373 This is equivalent to the qemu parameter C<-drive file=filename>.");
375 ("add_cdrom", (RErr, [String "filename"]), -1, [FishAlias "cdrom"],
377 "add a CD-ROM disk image to examine",
379 This function adds a virtual CD-ROM disk image to the guest.
381 This is equivalent to the qemu parameter C<-cdrom filename>.");
383 ("config", (RErr, [String "qemuparam"; OptString "qemuvalue"]), -1, [],
385 "add qemu parameters",
387 This can be used to add arbitrary qemu command line parameters
388 of the form C<-param value>. Actually it's not quite arbitrary - we
389 prevent you from setting some parameters which would interfere with
390 parameters that we use.
392 The first character of C<param> string must be a C<-> (dash).
394 C<value> can be NULL.");
396 ("set_qemu", (RErr, [String "qemu"]), -1, [FishAlias "qemu"],
398 "set the qemu binary",
400 Set the qemu binary that we will use.
402 The default is chosen when the library was compiled by the
405 You can also override this by setting the C<LIBGUESTFS_QEMU>
406 environment variable.
408 Setting C<qemu> to C<NULL> restores the default qemu binary.");
410 ("get_qemu", (RConstString "qemu", []), -1, [],
412 "get the qemu binary",
414 Return the current qemu binary.
416 This is always non-NULL. If it wasn't set already, then this will
417 return the default qemu binary name.");
419 ("set_path", (RErr, [String "path"]), -1, [FishAlias "path"],
421 "set the search path",
423 Set the path that libguestfs searches for kernel and initrd.img.
425 The default is C<$libdir/guestfs> unless overridden by setting
426 C<LIBGUESTFS_PATH> environment variable.
428 Setting C<path> to C<NULL> restores the default path.");
430 ("get_path", (RConstString "path", []), -1, [],
432 "get the search path",
434 Return the current search path.
436 This is always non-NULL. If it wasn't set already, then this will
437 return the default path.");
439 ("set_append", (RErr, [String "append"]), -1, [FishAlias "append"],
441 "add options to kernel command line",
443 This function is used to add additional options to the
444 guest kernel command line.
446 The default is C<NULL> unless overridden by setting
447 C<LIBGUESTFS_APPEND> environment variable.
449 Setting C<append> to C<NULL> means I<no> additional options
450 are passed (libguestfs always adds a few of its own).");
452 ("get_append", (RConstString "append", []), -1, [],
454 "get the additional kernel options",
456 Return the additional kernel options which are added to the
457 guest kernel command line.
459 If C<NULL> then no options are added.");
461 ("set_autosync", (RErr, [Bool "autosync"]), -1, [FishAlias "autosync"],
465 If C<autosync> is true, this enables autosync. Libguestfs will make a
466 best effort attempt to run C<guestfs_umount_all> followed by
467 C<guestfs_sync> when the handle is closed
468 (also if the program exits without closing handles).
470 This is disabled by default (except in guestfish where it is
471 enabled by default).");
473 ("get_autosync", (RBool "autosync", []), -1, [],
477 Get the autosync flag.");
479 ("set_verbose", (RErr, [Bool "verbose"]), -1, [FishAlias "verbose"],
483 If C<verbose> is true, this turns on verbose messages (to C<stderr>).
485 Verbose messages are disabled unless the environment variable
486 C<LIBGUESTFS_DEBUG> is defined and set to C<1>.");
488 ("get_verbose", (RBool "verbose", []), -1, [],
492 This returns the verbose messages flag.");
494 ("is_ready", (RBool "ready", []), -1, [],
496 "is ready to accept commands",
498 This returns true iff this handle is ready to accept commands
499 (in the C<READY> state).
501 For more information on states, see L<guestfs(3)>.");
503 ("is_config", (RBool "config", []), -1, [],
505 "is in configuration state",
507 This returns true iff this handle is being configured
508 (in the C<CONFIG> state).
510 For more information on states, see L<guestfs(3)>.");
512 ("is_launching", (RBool "launching", []), -1, [],
514 "is launching subprocess",
516 This returns true iff this handle is launching the subprocess
517 (in the C<LAUNCHING> state).
519 For more information on states, see L<guestfs(3)>.");
521 ("is_busy", (RBool "busy", []), -1, [],
523 "is busy processing a command",
525 This returns true iff this handle is busy processing a command
526 (in the C<BUSY> state).
528 For more information on states, see L<guestfs(3)>.");
530 ("get_state", (RInt "state", []), -1, [],
532 "get the current state",
534 This returns the current state as an opaque integer. This is
535 only useful for printing debug and internal error messages.
537 For more information on states, see L<guestfs(3)>.");
539 ("set_busy", (RErr, []), -1, [NotInFish],
543 This sets the state to C<BUSY>. This is only used when implementing
544 actions using the low-level API.
546 For more information on states, see L<guestfs(3)>.");
548 ("set_ready", (RErr, []), -1, [NotInFish],
550 "set state to ready",
552 This sets the state to C<READY>. This is only used when implementing
553 actions using the low-level API.
555 For more information on states, see L<guestfs(3)>.");
557 ("end_busy", (RErr, []), -1, [NotInFish],
559 "leave the busy state",
561 This sets the state to C<READY>, or if in C<CONFIG> then it leaves the
562 state as is. This is only used when implementing
563 actions using the low-level API.
565 For more information on states, see L<guestfs(3)>.");
569 (* daemon_functions are any functions which cause some action
570 * to take place in the daemon.
573 let daemon_functions = [
574 ("mount", (RErr, [String "device"; String "mountpoint"]), 1, [],
575 [InitEmpty, Always, TestOutput (
576 [["sfdisk"; "/dev/sda"; "0"; "0"; "0"; ","];
577 ["mkfs"; "ext2"; "/dev/sda1"];
578 ["mount"; "/dev/sda1"; "/"];
579 ["write_file"; "/new"; "new file contents"; "0"];
580 ["cat"; "/new"]], "new file contents")],
581 "mount a guest disk at a position in the filesystem",
583 Mount a guest disk at a position in the filesystem. Block devices
584 are named C</dev/sda>, C</dev/sdb> and so on, as they were added to
585 the guest. If those block devices contain partitions, they will have
586 the usual names (eg. C</dev/sda1>). Also LVM C</dev/VG/LV>-style
589 The rules are the same as for L<mount(2)>: A filesystem must
590 first be mounted on C</> before others can be mounted. Other
591 filesystems can only be mounted on directories which already
594 The mounted filesystem is writable, if we have sufficient permissions
595 on the underlying device.
597 The filesystem options C<sync> and C<noatime> are set with this
598 call, in order to improve reliability.");
600 ("sync", (RErr, []), 2, [],
601 [ InitEmpty, Always, TestRun [["sync"]]],
602 "sync disks, writes are flushed through to the disk image",
604 This syncs the disk, so that any writes are flushed through to the
605 underlying disk image.
607 You should always call this if you have modified a disk image, before
608 closing the handle.");
610 ("touch", (RErr, [String "path"]), 3, [],
611 [InitBasicFS, Always, TestOutputTrue (
613 ["exists"; "/new"]])],
614 "update file timestamps or create a new file",
616 Touch acts like the L<touch(1)> command. It can be used to
617 update the timestamps on a file, or, if the file does not exist,
618 to create a new zero-length file.");
620 ("cat", (RString "content", [String "path"]), 4, [ProtocolLimitWarning],
621 [InitBasicFS, Always, TestOutput (
622 [["write_file"; "/new"; "new file contents"; "0"];
623 ["cat"; "/new"]], "new file contents")],
624 "list the contents of a file",
626 Return the contents of the file named C<path>.
628 Note that this function cannot correctly handle binary files
629 (specifically, files containing C<\\0> character which is treated
630 as end of string). For those you need to use the C<guestfs_download>
631 function which has a more complex interface.");
633 ("ll", (RString "listing", [String "directory"]), 5, [],
634 [], (* XXX Tricky to test because it depends on the exact format
635 * of the 'ls -l' command, which changes between F10 and F11.
637 "list the files in a directory (long format)",
639 List the files in C<directory> (relative to the root directory,
640 there is no cwd) in the format of 'ls -la'.
642 This command is mostly useful for interactive sessions. It
643 is I<not> intended that you try to parse the output string.");
645 ("ls", (RStringList "listing", [String "directory"]), 6, [],
646 [InitBasicFS, Always, TestOutputList (
649 ["touch"; "/newest"];
650 ["ls"; "/"]], ["lost+found"; "new"; "newer"; "newest"])],
651 "list the files in a directory",
653 List the files in C<directory> (relative to the root directory,
654 there is no cwd). The '.' and '..' entries are not returned, but
655 hidden files are shown.
657 This command is mostly useful for interactive sessions. Programs
658 should probably use C<guestfs_readdir> instead.");
660 ("list_devices", (RStringList "devices", []), 7, [],
661 [InitEmpty, Always, TestOutputList (
662 [["list_devices"]], ["/dev/sda"; "/dev/sdb"; "/dev/sdc"])],
663 "list the block devices",
665 List all the block devices.
667 The full block device names are returned, eg. C</dev/sda>");
669 ("list_partitions", (RStringList "partitions", []), 8, [],
670 [InitBasicFS, Always, TestOutputList (
671 [["list_partitions"]], ["/dev/sda1"]);
672 InitEmpty, Always, TestOutputList (
673 [["sfdisk"; "/dev/sda"; "0"; "0"; "0"; ",10 ,20 ,"];
674 ["list_partitions"]], ["/dev/sda1"; "/dev/sda2"; "/dev/sda3"])],
675 "list the partitions",
677 List all the partitions detected on all block devices.
679 The full partition device names are returned, eg. C</dev/sda1>
681 This does not return logical volumes. For that you will need to
682 call C<guestfs_lvs>.");
684 ("pvs", (RStringList "physvols", []), 9, [],
685 [InitBasicFSonLVM, Always, TestOutputList (
686 [["pvs"]], ["/dev/sda1"]);
687 InitEmpty, Always, TestOutputList (
688 [["sfdisk"; "/dev/sda"; "0"; "0"; "0"; ",10 ,20 ,"];
689 ["pvcreate"; "/dev/sda1"];
690 ["pvcreate"; "/dev/sda2"];
691 ["pvcreate"; "/dev/sda3"];
692 ["pvs"]], ["/dev/sda1"; "/dev/sda2"; "/dev/sda3"])],
693 "list the LVM physical volumes (PVs)",
695 List all the physical volumes detected. This is the equivalent
696 of the L<pvs(8)> command.
698 This returns a list of just the device names that contain
699 PVs (eg. C</dev/sda2>).
701 See also C<guestfs_pvs_full>.");
703 ("vgs", (RStringList "volgroups", []), 10, [],
704 [InitBasicFSonLVM, Always, TestOutputList (
706 InitEmpty, Always, TestOutputList (
707 [["sfdisk"; "/dev/sda"; "0"; "0"; "0"; ",10 ,20 ,"];
708 ["pvcreate"; "/dev/sda1"];
709 ["pvcreate"; "/dev/sda2"];
710 ["pvcreate"; "/dev/sda3"];
711 ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
712 ["vgcreate"; "VG2"; "/dev/sda3"];
713 ["vgs"]], ["VG1"; "VG2"])],
714 "list the LVM volume groups (VGs)",
716 List all the volumes groups detected. This is the equivalent
717 of the L<vgs(8)> command.
719 This returns a list of just the volume group names that were
720 detected (eg. C<VolGroup00>).
722 See also C<guestfs_vgs_full>.");
724 ("lvs", (RStringList "logvols", []), 11, [],
725 [InitBasicFSonLVM, Always, TestOutputList (
726 [["lvs"]], ["/dev/VG/LV"]);
727 InitEmpty, Always, TestOutputList (
728 [["sfdisk"; "/dev/sda"; "0"; "0"; "0"; ",10 ,20 ,"];
729 ["pvcreate"; "/dev/sda1"];
730 ["pvcreate"; "/dev/sda2"];
731 ["pvcreate"; "/dev/sda3"];
732 ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
733 ["vgcreate"; "VG2"; "/dev/sda3"];
734 ["lvcreate"; "LV1"; "VG1"; "50"];
735 ["lvcreate"; "LV2"; "VG1"; "50"];
736 ["lvcreate"; "LV3"; "VG2"; "50"];
737 ["lvs"]], ["/dev/VG1/LV1"; "/dev/VG1/LV2"; "/dev/VG2/LV3"])],
738 "list the LVM logical volumes (LVs)",
740 List all the logical volumes detected. This is the equivalent
741 of the L<lvs(8)> command.
743 This returns a list of the logical volume device names
744 (eg. C</dev/VolGroup00/LogVol00>).
746 See also C<guestfs_lvs_full>.");
748 ("pvs_full", (RPVList "physvols", []), 12, [],
749 [], (* XXX how to test? *)
750 "list the LVM physical volumes (PVs)",
752 List all the physical volumes detected. This is the equivalent
753 of the L<pvs(8)> command. The \"full\" version includes all fields.");
755 ("vgs_full", (RVGList "volgroups", []), 13, [],
756 [], (* XXX how to test? *)
757 "list the LVM volume groups (VGs)",
759 List all the volumes groups detected. This is the equivalent
760 of the L<vgs(8)> command. The \"full\" version includes all fields.");
762 ("lvs_full", (RLVList "logvols", []), 14, [],
763 [], (* XXX how to test? *)
764 "list the LVM logical volumes (LVs)",
766 List all the logical volumes detected. This is the equivalent
767 of the L<lvs(8)> command. The \"full\" version includes all fields.");
769 ("read_lines", (RStringList "lines", [String "path"]), 15, [],
770 [InitBasicFS, Always, TestOutputList (
771 [["write_file"; "/new"; "line1\r\nline2\nline3"; "0"];
772 ["read_lines"; "/new"]], ["line1"; "line2"; "line3"]);
773 InitBasicFS, Always, TestOutputList (
774 [["write_file"; "/new"; ""; "0"];
775 ["read_lines"; "/new"]], [])],
776 "read file as lines",
778 Return the contents of the file named C<path>.
780 The file contents are returned as a list of lines. Trailing
781 C<LF> and C<CRLF> character sequences are I<not> returned.
783 Note that this function cannot correctly handle binary files
784 (specifically, files containing C<\\0> character which is treated
785 as end of line). For those you need to use the C<guestfs_read_file>
786 function which has a more complex interface.");
788 ("aug_init", (RErr, [String "root"; Int "flags"]), 16, [],
789 [], (* XXX Augeas code needs tests. *)
790 "create a new Augeas handle",
792 Create a new Augeas handle for editing configuration files.
793 If there was any previous Augeas handle associated with this
794 guestfs session, then it is closed.
796 You must call this before using any other C<guestfs_aug_*>
799 C<root> is the filesystem root. C<root> must not be NULL,
802 The flags are the same as the flags defined in
803 E<lt>augeas.hE<gt>, the logical I<or> of the following
808 =item C<AUG_SAVE_BACKUP> = 1
810 Keep the original file with a C<.augsave> extension.
812 =item C<AUG_SAVE_NEWFILE> = 2
814 Save changes into a file with extension C<.augnew>, and
815 do not overwrite original. Overrides C<AUG_SAVE_BACKUP>.
817 =item C<AUG_TYPE_CHECK> = 4
819 Typecheck lenses (can be expensive).
821 =item C<AUG_NO_STDINC> = 8
823 Do not use standard load path for modules.
825 =item C<AUG_SAVE_NOOP> = 16
827 Make save a no-op, just record what would have been changed.
829 =item C<AUG_NO_LOAD> = 32
831 Do not load the tree in C<guestfs_aug_init>.
835 To close the handle, you can call C<guestfs_aug_close>.
837 To find out more about Augeas, see L<http://augeas.net/>.");
839 ("aug_close", (RErr, []), 26, [],
840 [], (* XXX Augeas code needs tests. *)
841 "close the current Augeas handle",
843 Close the current Augeas handle and free up any resources
844 used by it. After calling this, you have to call
845 C<guestfs_aug_init> again before you can use any other
848 ("aug_defvar", (RInt "nrnodes", [String "name"; OptString "expr"]), 17, [],
849 [], (* XXX Augeas code needs tests. *)
850 "define an Augeas variable",
852 Defines an Augeas variable C<name> whose value is the result
853 of evaluating C<expr>. If C<expr> is NULL, then C<name> is
856 On success this returns the number of nodes in C<expr>, or
857 C<0> if C<expr> evaluates to something which is not a nodeset.");
859 ("aug_defnode", (RIntBool ("nrnodes", "created"), [String "name"; String "expr"; String "val"]), 18, [],
860 [], (* XXX Augeas code needs tests. *)
861 "define an Augeas node",
863 Defines a variable C<name> whose value is the result of
866 If C<expr> evaluates to an empty nodeset, a node is created,
867 equivalent to calling C<guestfs_aug_set> C<expr>, C<value>.
868 C<name> will be the nodeset containing that single node.
870 On success this returns a pair containing the
871 number of nodes in the nodeset, and a boolean flag
872 if a node was created.");
874 ("aug_get", (RString "val", [String "path"]), 19, [],
875 [], (* XXX Augeas code needs tests. *)
876 "look up the value of an Augeas path",
878 Look up the value associated with C<path>. If C<path>
879 matches exactly one node, the C<value> is returned.");
881 ("aug_set", (RErr, [String "path"; String "val"]), 20, [],
882 [], (* XXX Augeas code needs tests. *)
883 "set Augeas path to value",
885 Set the value associated with C<path> to C<value>.");
887 ("aug_insert", (RErr, [String "path"; String "label"; Bool "before"]), 21, [],
888 [], (* XXX Augeas code needs tests. *)
889 "insert a sibling Augeas node",
891 Create a new sibling C<label> for C<path>, inserting it into
892 the tree before or after C<path> (depending on the boolean
895 C<path> must match exactly one existing node in the tree, and
896 C<label> must be a label, ie. not contain C</>, C<*> or end
897 with a bracketed index C<[N]>.");
899 ("aug_rm", (RInt "nrnodes", [String "path"]), 22, [],
900 [], (* XXX Augeas code needs tests. *)
901 "remove an Augeas path",
903 Remove C<path> and all of its children.
905 On success this returns the number of entries which were removed.");
907 ("aug_mv", (RErr, [String "src"; String "dest"]), 23, [],
908 [], (* XXX Augeas code needs tests. *)
911 Move the node C<src> to C<dest>. C<src> must match exactly
912 one node. C<dest> is overwritten if it exists.");
914 ("aug_match", (RStringList "matches", [String "path"]), 24, [],
915 [], (* XXX Augeas code needs tests. *)
916 "return Augeas nodes which match path",
918 Returns a list of paths which match the path expression C<path>.
919 The returned paths are sufficiently qualified so that they match
920 exactly one node in the current tree.");
922 ("aug_save", (RErr, []), 25, [],
923 [], (* XXX Augeas code needs tests. *)
924 "write all pending Augeas changes to disk",
926 This writes all pending changes to disk.
928 The flags which were passed to C<guestfs_aug_init> affect exactly
929 how files are saved.");
931 ("aug_load", (RErr, []), 27, [],
932 [], (* XXX Augeas code needs tests. *)
933 "load files into the tree",
935 Load files into the tree.
937 See C<aug_load> in the Augeas documentation for the full gory
940 ("aug_ls", (RStringList "matches", [String "path"]), 28, [],
941 [], (* XXX Augeas code needs tests. *)
942 "list Augeas nodes under a path",
944 This is just a shortcut for listing C<guestfs_aug_match>
945 C<path/*> and sorting the resulting nodes into alphabetical order.");
947 ("rm", (RErr, [String "path"]), 29, [],
948 [InitBasicFS, Always, TestRun
951 InitBasicFS, Always, TestLastFail
953 InitBasicFS, Always, TestLastFail
958 Remove the single file C<path>.");
960 ("rmdir", (RErr, [String "path"]), 30, [],
961 [InitBasicFS, Always, TestRun
964 InitBasicFS, Always, TestLastFail
966 InitBasicFS, Always, TestLastFail
969 "remove a directory",
971 Remove the single directory C<path>.");
973 ("rm_rf", (RErr, [String "path"]), 31, [],
974 [InitBasicFS, Always, TestOutputFalse
976 ["mkdir"; "/new/foo"];
977 ["touch"; "/new/foo/bar"];
979 ["exists"; "/new"]]],
980 "remove a file or directory recursively",
982 Remove the file or directory C<path>, recursively removing the
983 contents if its a directory. This is like the C<rm -rf> shell
986 ("mkdir", (RErr, [String "path"]), 32, [],
987 [InitBasicFS, Always, TestOutputTrue
990 InitBasicFS, Always, TestLastFail
991 [["mkdir"; "/new/foo/bar"]]],
992 "create a directory",
994 Create a directory named C<path>.");
996 ("mkdir_p", (RErr, [String "path"]), 33, [],
997 [InitBasicFS, Always, TestOutputTrue
998 [["mkdir_p"; "/new/foo/bar"];
999 ["is_dir"; "/new/foo/bar"]];
1000 InitBasicFS, Always, TestOutputTrue
1001 [["mkdir_p"; "/new/foo/bar"];
1002 ["is_dir"; "/new/foo"]];
1003 InitBasicFS, Always, TestOutputTrue
1004 [["mkdir_p"; "/new/foo/bar"];
1005 ["is_dir"; "/new"]]],
1006 "create a directory and parents",
1008 Create a directory named C<path>, creating any parent directories
1009 as necessary. This is like the C<mkdir -p> shell command.");
1011 ("chmod", (RErr, [Int "mode"; String "path"]), 34, [],
1012 [], (* XXX Need stat command to test *)
1015 Change the mode (permissions) of C<path> to C<mode>. Only
1016 numeric modes are supported.");
1018 ("chown", (RErr, [Int "owner"; Int "group"; String "path"]), 35, [],
1019 [], (* XXX Need stat command to test *)
1020 "change file owner and group",
1022 Change the file owner to C<owner> and group to C<group>.
1024 Only numeric uid and gid are supported. If you want to use
1025 names, you will need to locate and parse the password file
1026 yourself (Augeas support makes this relatively easy).");
1028 ("exists", (RBool "existsflag", [String "path"]), 36, [],
1029 [InitBasicFS, Always, TestOutputTrue (
1031 ["exists"; "/new"]]);
1032 InitBasicFS, Always, TestOutputTrue (
1034 ["exists"; "/new"]])],
1035 "test if file or directory exists",
1037 This returns C<true> if and only if there is a file, directory
1038 (or anything) with the given C<path> name.
1040 See also C<guestfs_is_file>, C<guestfs_is_dir>, C<guestfs_stat>.");
1042 ("is_file", (RBool "fileflag", [String "path"]), 37, [],
1043 [InitBasicFS, Always, TestOutputTrue (
1045 ["is_file"; "/new"]]);
1046 InitBasicFS, Always, TestOutputFalse (
1048 ["is_file"; "/new"]])],
1049 "test if file exists",
1051 This returns C<true> if and only if there is a file
1052 with the given C<path> name. Note that it returns false for
1053 other objects like directories.
1055 See also C<guestfs_stat>.");
1057 ("is_dir", (RBool "dirflag", [String "path"]), 38, [],
1058 [InitBasicFS, Always, TestOutputFalse (
1060 ["is_dir"; "/new"]]);
1061 InitBasicFS, Always, TestOutputTrue (
1063 ["is_dir"; "/new"]])],
1064 "test if file exists",
1066 This returns C<true> if and only if there is a directory
1067 with the given C<path> name. Note that it returns false for
1068 other objects like files.
1070 See also C<guestfs_stat>.");
1072 ("pvcreate", (RErr, [String "device"]), 39, [],
1073 [InitEmpty, Always, TestOutputList (
1074 [["sfdisk"; "/dev/sda"; "0"; "0"; "0"; ",10 ,20 ,"];
1075 ["pvcreate"; "/dev/sda1"];
1076 ["pvcreate"; "/dev/sda2"];
1077 ["pvcreate"; "/dev/sda3"];
1078 ["pvs"]], ["/dev/sda1"; "/dev/sda2"; "/dev/sda3"])],
1079 "create an LVM physical volume",
1081 This creates an LVM physical volume on the named C<device>,
1082 where C<device> should usually be a partition name such
1085 ("vgcreate", (RErr, [String "volgroup"; StringList "physvols"]), 40, [],
1086 [InitEmpty, Always, TestOutputList (
1087 [["sfdisk"; "/dev/sda"; "0"; "0"; "0"; ",10 ,20 ,"];
1088 ["pvcreate"; "/dev/sda1"];
1089 ["pvcreate"; "/dev/sda2"];
1090 ["pvcreate"; "/dev/sda3"];
1091 ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
1092 ["vgcreate"; "VG2"; "/dev/sda3"];
1093 ["vgs"]], ["VG1"; "VG2"])],
1094 "create an LVM volume group",
1096 This creates an LVM volume group called C<volgroup>
1097 from the non-empty list of physical volumes C<physvols>.");
1099 ("lvcreate", (RErr, [String "logvol"; String "volgroup"; Int "mbytes"]), 41, [],
1100 [InitEmpty, Always, TestOutputList (
1101 [["sfdisk"; "/dev/sda"; "0"; "0"; "0"; ",10 ,20 ,"];
1102 ["pvcreate"; "/dev/sda1"];
1103 ["pvcreate"; "/dev/sda2"];
1104 ["pvcreate"; "/dev/sda3"];
1105 ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
1106 ["vgcreate"; "VG2"; "/dev/sda3"];
1107 ["lvcreate"; "LV1"; "VG1"; "50"];
1108 ["lvcreate"; "LV2"; "VG1"; "50"];
1109 ["lvcreate"; "LV3"; "VG2"; "50"];
1110 ["lvcreate"; "LV4"; "VG2"; "50"];
1111 ["lvcreate"; "LV5"; "VG2"; "50"];
1113 ["/dev/VG1/LV1"; "/dev/VG1/LV2";
1114 "/dev/VG2/LV3"; "/dev/VG2/LV4"; "/dev/VG2/LV5"])],
1115 "create an LVM volume group",
1117 This creates an LVM volume group called C<logvol>
1118 on the volume group C<volgroup>, with C<size> megabytes.");
1120 ("mkfs", (RErr, [String "fstype"; String "device"]), 42, [],
1121 [InitEmpty, Always, TestOutput (
1122 [["sfdisk"; "/dev/sda"; "0"; "0"; "0"; ","];
1123 ["mkfs"; "ext2"; "/dev/sda1"];
1124 ["mount"; "/dev/sda1"; "/"];
1125 ["write_file"; "/new"; "new file contents"; "0"];
1126 ["cat"; "/new"]], "new file contents")],
1127 "make a filesystem",
1129 This creates a filesystem on C<device> (usually a partition
1130 or LVM logical volume). The filesystem type is C<fstype>, for
1133 ("sfdisk", (RErr, [String "device";
1134 Int "cyls"; Int "heads"; Int "sectors";
1135 StringList "lines"]), 43, [DangerWillRobinson],
1137 "create partitions on a block device",
1139 This is a direct interface to the L<sfdisk(8)> program for creating
1140 partitions on block devices.
1142 C<device> should be a block device, for example C</dev/sda>.
1144 C<cyls>, C<heads> and C<sectors> are the number of cylinders, heads
1145 and sectors on the device, which are passed directly to sfdisk as
1146 the I<-C>, I<-H> and I<-S> parameters. If you pass C<0> for any
1147 of these, then the corresponding parameter is omitted. Usually for
1148 'large' disks, you can just pass C<0> for these, but for small
1149 (floppy-sized) disks, sfdisk (or rather, the kernel) cannot work
1150 out the right geometry and you will need to tell it.
1152 C<lines> is a list of lines that we feed to C<sfdisk>. For more
1153 information refer to the L<sfdisk(8)> manpage.
1155 To create a single partition occupying the whole disk, you would
1156 pass C<lines> as a single element list, when the single element being
1157 the string C<,> (comma).
1159 See also: C<guestfs_sfdisk_l>, C<guestfs_sfdisk_N>");
1161 ("write_file", (RErr, [String "path"; String "content"; Int "size"]), 44, [ProtocolLimitWarning],
1162 [InitBasicFS, Always, TestOutput (
1163 [["write_file"; "/new"; "new file contents"; "0"];
1164 ["cat"; "/new"]], "new file contents");
1165 InitBasicFS, Always, TestOutput (
1166 [["write_file"; "/new"; "\nnew file contents\n"; "0"];
1167 ["cat"; "/new"]], "\nnew file contents\n");
1168 InitBasicFS, Always, TestOutput (
1169 [["write_file"; "/new"; "\n\n"; "0"];
1170 ["cat"; "/new"]], "\n\n");
1171 InitBasicFS, Always, TestOutput (
1172 [["write_file"; "/new"; ""; "0"];
1173 ["cat"; "/new"]], "");
1174 InitBasicFS, Always, TestOutput (
1175 [["write_file"; "/new"; "\n\n\n"; "0"];
1176 ["cat"; "/new"]], "\n\n\n");
1177 InitBasicFS, Always, TestOutput (
1178 [["write_file"; "/new"; "\n"; "0"];
1179 ["cat"; "/new"]], "\n")],
1182 This call creates a file called C<path>. The contents of the
1183 file is the string C<content> (which can contain any 8 bit data),
1184 with length C<size>.
1186 As a special case, if C<size> is C<0>
1187 then the length is calculated using C<strlen> (so in this case
1188 the content cannot contain embedded ASCII NULs).
1190 I<NB.> Owing to a bug, writing content containing ASCII NUL
1191 characters does I<not> work, even if the length is specified.
1192 We hope to resolve this bug in a future version. In the meantime
1193 use C<guestfs_upload>.");
1195 ("umount", (RErr, [String "pathordevice"]), 45, [FishAlias "unmount"],
1196 [InitEmpty, Always, TestOutputList (
1197 [["sfdisk"; "/dev/sda"; "0"; "0"; "0"; ","];
1198 ["mkfs"; "ext2"; "/dev/sda1"];
1199 ["mount"; "/dev/sda1"; "/"];
1200 ["mounts"]], ["/dev/sda1"]);
1201 InitEmpty, Always, TestOutputList (
1202 [["sfdisk"; "/dev/sda"; "0"; "0"; "0"; ","];
1203 ["mkfs"; "ext2"; "/dev/sda1"];
1204 ["mount"; "/dev/sda1"; "/"];
1207 "unmount a filesystem",
1209 This unmounts the given filesystem. The filesystem may be
1210 specified either by its mountpoint (path) or the device which
1211 contains the filesystem.");
1213 ("mounts", (RStringList "devices", []), 46, [],
1214 [InitBasicFS, Always, TestOutputList (
1215 [["mounts"]], ["/dev/sda1"])],
1216 "show mounted filesystems",
1218 This returns the list of currently mounted filesystems. It returns
1219 the list of devices (eg. C</dev/sda1>, C</dev/VG/LV>).
1221 Some internal mounts are not shown.");
1223 ("umount_all", (RErr, []), 47, [FishAlias "unmount-all"],
1224 [InitBasicFS, Always, TestOutputList (
1227 (* check that umount_all can unmount nested mounts correctly: *)
1228 InitEmpty, Always, TestOutputList (
1229 [["sfdisk"; "/dev/sda"; "0"; "0"; "0"; ",10 ,20 ,"];
1230 ["mkfs"; "ext2"; "/dev/sda1"];
1231 ["mkfs"; "ext2"; "/dev/sda2"];
1232 ["mkfs"; "ext2"; "/dev/sda3"];
1233 ["mount"; "/dev/sda1"; "/"];
1235 ["mount"; "/dev/sda2"; "/mp1"];
1236 ["mkdir"; "/mp1/mp2"];
1237 ["mount"; "/dev/sda3"; "/mp1/mp2"];
1238 ["mkdir"; "/mp1/mp2/mp3"];
1241 "unmount all filesystems",
1243 This unmounts all mounted filesystems.
1245 Some internal mounts are not unmounted by this call.");
1247 ("lvm_remove_all", (RErr, []), 48, [DangerWillRobinson],
1249 "remove all LVM LVs, VGs and PVs",
1251 This command removes all LVM logical volumes, volume groups
1252 and physical volumes.");
1254 ("file", (RString "description", [String "path"]), 49, [],
1255 [InitBasicFS, Always, TestOutput (
1257 ["file"; "/new"]], "empty");
1258 InitBasicFS, Always, TestOutput (
1259 [["write_file"; "/new"; "some content\n"; "0"];
1260 ["file"; "/new"]], "ASCII text");
1261 InitBasicFS, Always, TestLastFail (
1262 [["file"; "/nofile"]])],
1263 "determine file type",
1265 This call uses the standard L<file(1)> command to determine
1266 the type or contents of the file. This also works on devices,
1267 for example to find out whether a partition contains a filesystem.
1269 The exact command which runs is C<file -bsL path>. Note in
1270 particular that the filename is not prepended to the output
1271 (the C<-b> option).");
1273 ("command", (RString "output", [StringList "arguments"]), 50, [ProtocolLimitWarning],
1274 [InitBasicFS, Always, TestOutput (
1275 [["upload"; "test-command"; "/test-command"];
1276 ["chmod"; "493"; "/test-command"];
1277 ["command"; "/test-command 1"]], "Result1");
1278 InitBasicFS, Always, TestOutput (
1279 [["upload"; "test-command"; "/test-command"];
1280 ["chmod"; "493"; "/test-command"];
1281 ["command"; "/test-command 2"]], "Result2\n");
1282 InitBasicFS, Always, TestOutput (
1283 [["upload"; "test-command"; "/test-command"];
1284 ["chmod"; "493"; "/test-command"];
1285 ["command"; "/test-command 3"]], "\nResult3");
1286 InitBasicFS, Always, TestOutput (
1287 [["upload"; "test-command"; "/test-command"];
1288 ["chmod"; "493"; "/test-command"];
1289 ["command"; "/test-command 4"]], "\nResult4\n");
1290 InitBasicFS, Always, TestOutput (
1291 [["upload"; "test-command"; "/test-command"];
1292 ["chmod"; "493"; "/test-command"];
1293 ["command"; "/test-command 5"]], "\nResult5\n\n");
1294 InitBasicFS, Always, TestOutput (
1295 [["upload"; "test-command"; "/test-command"];
1296 ["chmod"; "493"; "/test-command"];
1297 ["command"; "/test-command 6"]], "\n\nResult6\n\n");
1298 InitBasicFS, Always, TestOutput (
1299 [["upload"; "test-command"; "/test-command"];
1300 ["chmod"; "493"; "/test-command"];
1301 ["command"; "/test-command 7"]], "");
1302 InitBasicFS, Always, TestOutput (
1303 [["upload"; "test-command"; "/test-command"];
1304 ["chmod"; "493"; "/test-command"];
1305 ["command"; "/test-command 8"]], "\n");
1306 InitBasicFS, Always, TestOutput (
1307 [["upload"; "test-command"; "/test-command"];
1308 ["chmod"; "493"; "/test-command"];
1309 ["command"; "/test-command 9"]], "\n\n");
1310 InitBasicFS, Always, TestOutput (
1311 [["upload"; "test-command"; "/test-command"];
1312 ["chmod"; "493"; "/test-command"];
1313 ["command"; "/test-command 10"]], "Result10-1\nResult10-2\n");
1314 InitBasicFS, Always, TestOutput (
1315 [["upload"; "test-command"; "/test-command"];
1316 ["chmod"; "493"; "/test-command"];
1317 ["command"; "/test-command 11"]], "Result11-1\nResult11-2");
1318 InitBasicFS, Always, TestLastFail (
1319 [["upload"; "test-command"; "/test-command"];
1320 ["chmod"; "493"; "/test-command"];
1321 ["command"; "/test-command"]])],
1322 "run a command from the guest filesystem",
1324 This call runs a command from the guest filesystem. The
1325 filesystem must be mounted, and must contain a compatible
1326 operating system (ie. something Linux, with the same
1327 or compatible processor architecture).
1329 The single parameter is an argv-style list of arguments.
1330 The first element is the name of the program to run.
1331 Subsequent elements are parameters. The list must be
1332 non-empty (ie. must contain a program name).
1334 The return value is anything printed to I<stdout> by
1337 If the command returns a non-zero exit status, then
1338 this function returns an error message. The error message
1339 string is the content of I<stderr> from the command.
1341 The C<$PATH> environment variable will contain at least
1342 C</usr/bin> and C</bin>. If you require a program from
1343 another location, you should provide the full path in the
1346 Shared libraries and data files required by the program
1347 must be available on filesystems which are mounted in the
1348 correct places. It is the caller's responsibility to ensure
1349 all filesystems that are needed are mounted at the right
1352 ("command_lines", (RStringList "lines", [StringList "arguments"]), 51, [ProtocolLimitWarning],
1353 [InitBasicFS, Always, TestOutputList (
1354 [["upload"; "test-command"; "/test-command"];
1355 ["chmod"; "493"; "/test-command"];
1356 ["command_lines"; "/test-command 1"]], ["Result1"]);
1357 InitBasicFS, Always, TestOutputList (
1358 [["upload"; "test-command"; "/test-command"];
1359 ["chmod"; "493"; "/test-command"];
1360 ["command_lines"; "/test-command 2"]], ["Result2"]);
1361 InitBasicFS, Always, TestOutputList (
1362 [["upload"; "test-command"; "/test-command"];
1363 ["chmod"; "493"; "/test-command"];
1364 ["command_lines"; "/test-command 3"]], ["";"Result3"]);
1365 InitBasicFS, Always, TestOutputList (
1366 [["upload"; "test-command"; "/test-command"];
1367 ["chmod"; "493"; "/test-command"];
1368 ["command_lines"; "/test-command 4"]], ["";"Result4"]);
1369 InitBasicFS, Always, TestOutputList (
1370 [["upload"; "test-command"; "/test-command"];
1371 ["chmod"; "493"; "/test-command"];
1372 ["command_lines"; "/test-command 5"]], ["";"Result5";""]);
1373 InitBasicFS, Always, TestOutputList (
1374 [["upload"; "test-command"; "/test-command"];
1375 ["chmod"; "493"; "/test-command"];
1376 ["command_lines"; "/test-command 6"]], ["";"";"Result6";""]);
1377 InitBasicFS, Always, TestOutputList (
1378 [["upload"; "test-command"; "/test-command"];
1379 ["chmod"; "493"; "/test-command"];
1380 ["command_lines"; "/test-command 7"]], []);
1381 InitBasicFS, Always, TestOutputList (
1382 [["upload"; "test-command"; "/test-command"];
1383 ["chmod"; "493"; "/test-command"];
1384 ["command_lines"; "/test-command 8"]], [""]);
1385 InitBasicFS, Always, TestOutputList (
1386 [["upload"; "test-command"; "/test-command"];
1387 ["chmod"; "493"; "/test-command"];
1388 ["command_lines"; "/test-command 9"]], ["";""]);
1389 InitBasicFS, Always, TestOutputList (
1390 [["upload"; "test-command"; "/test-command"];
1391 ["chmod"; "493"; "/test-command"];
1392 ["command_lines"; "/test-command 10"]], ["Result10-1";"Result10-2"]);
1393 InitBasicFS, Always, TestOutputList (
1394 [["upload"; "test-command"; "/test-command"];
1395 ["chmod"; "493"; "/test-command"];
1396 ["command_lines"; "/test-command 11"]], ["Result11-1";"Result11-2"])],
1397 "run a command, returning lines",
1399 This is the same as C<guestfs_command>, but splits the
1400 result into a list of lines.");
1402 ("stat", (RStat "statbuf", [String "path"]), 52, [],
1403 [InitBasicFS, Always, TestOutputStruct (
1405 ["stat"; "/new"]], [CompareWithInt ("size", 0)])],
1406 "get file information",
1408 Returns file information for the given C<path>.
1410 This is the same as the C<stat(2)> system call.");
1412 ("lstat", (RStat "statbuf", [String "path"]), 53, [],
1413 [InitBasicFS, Always, TestOutputStruct (
1415 ["lstat"; "/new"]], [CompareWithInt ("size", 0)])],
1416 "get file information for a symbolic link",
1418 Returns file information for the given C<path>.
1420 This is the same as C<guestfs_stat> except that if C<path>
1421 is a symbolic link, then the link is stat-ed, not the file it
1424 This is the same as the C<lstat(2)> system call.");
1426 ("statvfs", (RStatVFS "statbuf", [String "path"]), 54, [],
1427 [InitBasicFS, Always, TestOutputStruct (
1428 [["statvfs"; "/"]], [CompareWithInt ("bfree", 487702);
1429 CompareWithInt ("blocks", 490020);
1430 CompareWithInt ("bsize", 1024)])],
1431 "get file system statistics",
1433 Returns file system statistics for any mounted file system.
1434 C<path> should be a file or directory in the mounted file system
1435 (typically it is the mount point itself, but it doesn't need to be).
1437 This is the same as the C<statvfs(2)> system call.");
1439 ("tune2fs_l", (RHashtable "superblock", [String "device"]), 55, [],
1441 "get ext2/ext3/ext4 superblock details",
1443 This returns the contents of the ext2, ext3 or ext4 filesystem
1444 superblock on C<device>.
1446 It is the same as running C<tune2fs -l device>. See L<tune2fs(8)>
1447 manpage for more details. The list of fields returned isn't
1448 clearly defined, and depends on both the version of C<tune2fs>
1449 that libguestfs was built against, and the filesystem itself.");
1451 ("blockdev_setro", (RErr, [String "device"]), 56, [],
1452 [InitEmpty, Always, TestOutputTrue (
1453 [["blockdev_setro"; "/dev/sda"];
1454 ["blockdev_getro"; "/dev/sda"]])],
1455 "set block device to read-only",
1457 Sets the block device named C<device> to read-only.
1459 This uses the L<blockdev(8)> command.");
1461 ("blockdev_setrw", (RErr, [String "device"]), 57, [],
1462 [InitEmpty, Always, TestOutputFalse (
1463 [["blockdev_setrw"; "/dev/sda"];
1464 ["blockdev_getro"; "/dev/sda"]])],
1465 "set block device to read-write",
1467 Sets the block device named C<device> to read-write.
1469 This uses the L<blockdev(8)> command.");
1471 ("blockdev_getro", (RBool "ro", [String "device"]), 58, [],
1472 [InitEmpty, Always, TestOutputTrue (
1473 [["blockdev_setro"; "/dev/sda"];
1474 ["blockdev_getro"; "/dev/sda"]])],
1475 "is block device set to read-only",
1477 Returns a boolean indicating if the block device is read-only
1478 (true if read-only, false if not).
1480 This uses the L<blockdev(8)> command.");
1482 ("blockdev_getss", (RInt "sectorsize", [String "device"]), 59, [],
1483 [InitEmpty, Always, TestOutputInt (
1484 [["blockdev_getss"; "/dev/sda"]], 512)],
1485 "get sectorsize of block device",
1487 This returns the size of sectors on a block device.
1488 Usually 512, but can be larger for modern devices.
1490 (Note, this is not the size in sectors, use C<guestfs_blockdev_getsz>
1493 This uses the L<blockdev(8)> command.");
1495 ("blockdev_getbsz", (RInt "blocksize", [String "device"]), 60, [],
1496 [InitEmpty, Always, TestOutputInt (
1497 [["blockdev_getbsz"; "/dev/sda"]], 4096)],
1498 "get blocksize of block device",
1500 This returns the block size of a device.
1502 (Note this is different from both I<size in blocks> and
1503 I<filesystem block size>).
1505 This uses the L<blockdev(8)> command.");
1507 ("blockdev_setbsz", (RErr, [String "device"; Int "blocksize"]), 61, [],
1509 "set blocksize of block device",
1511 This sets the block size of a device.
1513 (Note this is different from both I<size in blocks> and
1514 I<filesystem block size>).
1516 This uses the L<blockdev(8)> command.");
1518 ("blockdev_getsz", (RInt64 "sizeinsectors", [String "device"]), 62, [],
1519 [InitEmpty, Always, TestOutputInt (
1520 [["blockdev_getsz"; "/dev/sda"]], 1024000)],
1521 "get total size of device in 512-byte sectors",
1523 This returns the size of the device in units of 512-byte sectors
1524 (even if the sectorsize isn't 512 bytes ... weird).
1526 See also C<guestfs_blockdev_getss> for the real sector size of
1527 the device, and C<guestfs_blockdev_getsize64> for the more
1528 useful I<size in bytes>.
1530 This uses the L<blockdev(8)> command.");
1532 ("blockdev_getsize64", (RInt64 "sizeinbytes", [String "device"]), 63, [],
1533 [InitEmpty, Always, TestOutputInt (
1534 [["blockdev_getsize64"; "/dev/sda"]], 524288000)],
1535 "get total size of device in bytes",
1537 This returns the size of the device in bytes.
1539 See also C<guestfs_blockdev_getsz>.
1541 This uses the L<blockdev(8)> command.");
1543 ("blockdev_flushbufs", (RErr, [String "device"]), 64, [],
1544 [InitEmpty, Always, TestRun
1545 [["blockdev_flushbufs"; "/dev/sda"]]],
1546 "flush device buffers",
1548 This tells the kernel to flush internal buffers associated
1551 This uses the L<blockdev(8)> command.");
1553 ("blockdev_rereadpt", (RErr, [String "device"]), 65, [],
1554 [InitEmpty, Always, TestRun
1555 [["blockdev_rereadpt"; "/dev/sda"]]],
1556 "reread partition table",
1558 Reread the partition table on C<device>.
1560 This uses the L<blockdev(8)> command.");
1562 ("upload", (RErr, [FileIn "filename"; String "remotefilename"]), 66, [],
1563 [InitBasicFS, Always, TestOutput (
1564 (* Pick a file from cwd which isn't likely to change. *)
1565 [["upload"; "COPYING.LIB"; "/COPYING.LIB"];
1566 ["checksum"; "md5"; "/COPYING.LIB"]], "e3eda01d9815f8d24aae2dbd89b68b06")],
1567 "upload a file from the local machine",
1569 Upload local file C<filename> to C<remotefilename> on the
1572 C<filename> can also be a named pipe.
1574 See also C<guestfs_download>.");
1576 ("download", (RErr, [String "remotefilename"; FileOut "filename"]), 67, [],
1577 [InitBasicFS, Always, TestOutput (
1578 (* Pick a file from cwd which isn't likely to change. *)
1579 [["upload"; "COPYING.LIB"; "/COPYING.LIB"];
1580 ["download"; "/COPYING.LIB"; "testdownload.tmp"];
1581 ["upload"; "testdownload.tmp"; "/upload"];
1582 ["checksum"; "md5"; "/upload"]], "e3eda01d9815f8d24aae2dbd89b68b06")],
1583 "download a file to the local machine",
1585 Download file C<remotefilename> and save it as C<filename>
1586 on the local machine.
1588 C<filename> can also be a named pipe.
1590 See also C<guestfs_upload>, C<guestfs_cat>.");
1592 ("checksum", (RString "checksum", [String "csumtype"; String "path"]), 68, [],
1593 [InitBasicFS, Always, TestOutput (
1594 [["write_file"; "/new"; "test\n"; "0"];
1595 ["checksum"; "crc"; "/new"]], "935282863");
1596 InitBasicFS, Always, TestLastFail (
1597 [["checksum"; "crc"; "/new"]]);
1598 InitBasicFS, Always, TestOutput (
1599 [["write_file"; "/new"; "test\n"; "0"];
1600 ["checksum"; "md5"; "/new"]], "d8e8fca2dc0f896fd7cb4cb0031ba249");
1601 InitBasicFS, Always, TestOutput (
1602 [["write_file"; "/new"; "test\n"; "0"];
1603 ["checksum"; "sha1"; "/new"]], "4e1243bd22c66e76c2ba9eddc1f91394e57f9f83");
1604 InitBasicFS, Always, TestOutput (
1605 [["write_file"; "/new"; "test\n"; "0"];
1606 ["checksum"; "sha224"; "/new"]], "52f1bf093f4b7588726035c176c0cdb4376cfea53819f1395ac9e6ec");
1607 InitBasicFS, Always, TestOutput (
1608 [["write_file"; "/new"; "test\n"; "0"];
1609 ["checksum"; "sha256"; "/new"]], "f2ca1bb6c7e907d06dafe4687e579fce76b37e4e93b7605022da52e6ccc26fd2");
1610 InitBasicFS, Always, TestOutput (
1611 [["write_file"; "/new"; "test\n"; "0"];
1612 ["checksum"; "sha384"; "/new"]], "109bb6b5b6d5547c1ce03c7a8bd7d8f80c1cb0957f50c4f7fda04692079917e4f9cad52b878f3d8234e1a170b154b72d");
1613 InitBasicFS, Always, TestOutput (
1614 [["write_file"; "/new"; "test\n"; "0"];
1615 ["checksum"; "sha512"; "/new"]], "0e3e75234abc68f4378a86b3f4b32a198ba301845b0cd6e50106e874345700cc6663a86c1ea125dc5e92be17c98f9a0f85ca9d5f595db2012f7cc3571945c123")],
1616 "compute MD5, SHAx or CRC checksum of file",
1618 This call computes the MD5, SHAx or CRC checksum of the
1621 The type of checksum to compute is given by the C<csumtype>
1622 parameter which must have one of the following values:
1628 Compute the cyclic redundancy check (CRC) specified by POSIX
1629 for the C<cksum> command.
1633 Compute the MD5 hash (using the C<md5sum> program).
1637 Compute the SHA1 hash (using the C<sha1sum> program).
1641 Compute the SHA224 hash (using the C<sha224sum> program).
1645 Compute the SHA256 hash (using the C<sha256sum> program).
1649 Compute the SHA384 hash (using the C<sha384sum> program).
1653 Compute the SHA512 hash (using the C<sha512sum> program).
1657 The checksum is returned as a printable string.");
1659 ("tar_in", (RErr, [FileIn "tarfile"; String "directory"]), 69, [],
1660 [InitBasicFS, Always, TestOutput (
1661 [["tar_in"; "../images/helloworld.tar"; "/"];
1662 ["cat"; "/hello"]], "hello\n")],
1663 "unpack tarfile to directory",
1665 This command uploads and unpacks local file C<tarfile> (an
1666 I<uncompressed> tar file) into C<directory>.
1668 To upload a compressed tarball, use C<guestfs_tgz_in>.");
1670 ("tar_out", (RErr, [String "directory"; FileOut "tarfile"]), 70, [],
1672 "pack directory into tarfile",
1674 This command packs the contents of C<directory> and downloads
1675 it to local file C<tarfile>.
1677 To download a compressed tarball, use C<guestfs_tgz_out>.");
1679 ("tgz_in", (RErr, [FileIn "tarball"; String "directory"]), 71, [],
1680 [InitBasicFS, Always, TestOutput (
1681 [["tgz_in"; "../images/helloworld.tar.gz"; "/"];
1682 ["cat"; "/hello"]], "hello\n")],
1683 "unpack compressed tarball to directory",
1685 This command uploads and unpacks local file C<tarball> (a
1686 I<gzip compressed> tar file) into C<directory>.
1688 To upload an uncompressed tarball, use C<guestfs_tar_in>.");
1690 ("tgz_out", (RErr, [String "directory"; FileOut "tarball"]), 72, [],
1692 "pack directory into compressed tarball",
1694 This command packs the contents of C<directory> and downloads
1695 it to local file C<tarball>.
1697 To download an uncompressed tarball, use C<guestfs_tar_out>.");
1699 ("mount_ro", (RErr, [String "device"; String "mountpoint"]), 73, [],
1700 [InitBasicFS, Always, TestLastFail (
1702 ["mount_ro"; "/dev/sda1"; "/"];
1703 ["touch"; "/new"]]);
1704 InitBasicFS, Always, TestOutput (
1705 [["write_file"; "/new"; "data"; "0"];
1707 ["mount_ro"; "/dev/sda1"; "/"];
1708 ["cat"; "/new"]], "data")],
1709 "mount a guest disk, read-only",
1711 This is the same as the C<guestfs_mount> command, but it
1712 mounts the filesystem with the read-only (I<-o ro>) flag.");
1714 ("mount_options", (RErr, [String "options"; String "device"; String "mountpoint"]), 74, [],
1716 "mount a guest disk with mount options",
1718 This is the same as the C<guestfs_mount> command, but it
1719 allows you to set the mount options as for the
1720 L<mount(8)> I<-o> flag.");
1722 ("mount_vfs", (RErr, [String "options"; String "vfstype"; String "device"; String "mountpoint"]), 75, [],
1724 "mount a guest disk with mount options and vfstype",
1726 This is the same as the C<guestfs_mount> command, but it
1727 allows you to set both the mount options and the vfstype
1728 as for the L<mount(8)> I<-o> and I<-t> flags.");
1730 ("debug", (RString "result", [String "subcmd"; StringList "extraargs"]), 76, [],
1732 "debugging and internals",
1734 The C<guestfs_debug> command exposes some internals of
1735 C<guestfsd> (the guestfs daemon) that runs inside the
1738 There is no comprehensive help for this command. You have
1739 to look at the file C<daemon/debug.c> in the libguestfs source
1740 to find out what you can do.");
1742 ("lvremove", (RErr, [String "device"]), 77, [],
1743 [InitEmpty, Always, TestOutputList (
1744 [["sfdisk"; "/dev/sda"; "0"; "0"; "0"; ","];
1745 ["pvcreate"; "/dev/sda1"];
1746 ["vgcreate"; "VG"; "/dev/sda1"];
1747 ["lvcreate"; "LV1"; "VG"; "50"];
1748 ["lvcreate"; "LV2"; "VG"; "50"];
1749 ["lvremove"; "/dev/VG/LV1"];
1750 ["lvs"]], ["/dev/VG/LV2"]);
1751 InitEmpty, Always, TestOutputList (
1752 [["sfdisk"; "/dev/sda"; "0"; "0"; "0"; ","];
1753 ["pvcreate"; "/dev/sda1"];
1754 ["vgcreate"; "VG"; "/dev/sda1"];
1755 ["lvcreate"; "LV1"; "VG"; "50"];
1756 ["lvcreate"; "LV2"; "VG"; "50"];
1757 ["lvremove"; "/dev/VG"];
1759 InitEmpty, Always, TestOutputList (
1760 [["sfdisk"; "/dev/sda"; "0"; "0"; "0"; ","];
1761 ["pvcreate"; "/dev/sda1"];
1762 ["vgcreate"; "VG"; "/dev/sda1"];
1763 ["lvcreate"; "LV1"; "VG"; "50"];
1764 ["lvcreate"; "LV2"; "VG"; "50"];
1765 ["lvremove"; "/dev/VG"];
1767 "remove an LVM logical volume",
1769 Remove an LVM logical volume C<device>, where C<device> is
1770 the path to the LV, such as C</dev/VG/LV>.
1772 You can also remove all LVs in a volume group by specifying
1773 the VG name, C</dev/VG>.");
1775 ("vgremove", (RErr, [String "vgname"]), 78, [],
1776 [InitEmpty, Always, TestOutputList (
1777 [["sfdisk"; "/dev/sda"; "0"; "0"; "0"; ","];
1778 ["pvcreate"; "/dev/sda1"];
1779 ["vgcreate"; "VG"; "/dev/sda1"];
1780 ["lvcreate"; "LV1"; "VG"; "50"];
1781 ["lvcreate"; "LV2"; "VG"; "50"];
1784 InitEmpty, Always, TestOutputList (
1785 [["sfdisk"; "/dev/sda"; "0"; "0"; "0"; ","];
1786 ["pvcreate"; "/dev/sda1"];
1787 ["vgcreate"; "VG"; "/dev/sda1"];
1788 ["lvcreate"; "LV1"; "VG"; "50"];
1789 ["lvcreate"; "LV2"; "VG"; "50"];
1792 "remove an LVM volume group",
1794 Remove an LVM volume group C<vgname>, (for example C<VG>).
1796 This also forcibly removes all logical volumes in the volume
1799 ("pvremove", (RErr, [String "device"]), 79, [],
1800 [InitEmpty, Always, TestOutputList (
1801 [["sfdisk"; "/dev/sda"; "0"; "0"; "0"; ","];
1802 ["pvcreate"; "/dev/sda1"];
1803 ["vgcreate"; "VG"; "/dev/sda1"];
1804 ["lvcreate"; "LV1"; "VG"; "50"];
1805 ["lvcreate"; "LV2"; "VG"; "50"];
1807 ["pvremove"; "/dev/sda1"];
1809 InitEmpty, Always, TestOutputList (
1810 [["sfdisk"; "/dev/sda"; "0"; "0"; "0"; ","];
1811 ["pvcreate"; "/dev/sda1"];
1812 ["vgcreate"; "VG"; "/dev/sda1"];
1813 ["lvcreate"; "LV1"; "VG"; "50"];
1814 ["lvcreate"; "LV2"; "VG"; "50"];
1816 ["pvremove"; "/dev/sda1"];
1818 InitEmpty, Always, TestOutputList (
1819 [["sfdisk"; "/dev/sda"; "0"; "0"; "0"; ","];
1820 ["pvcreate"; "/dev/sda1"];
1821 ["vgcreate"; "VG"; "/dev/sda1"];
1822 ["lvcreate"; "LV1"; "VG"; "50"];
1823 ["lvcreate"; "LV2"; "VG"; "50"];
1825 ["pvremove"; "/dev/sda1"];
1827 "remove an LVM physical volume",
1829 This wipes a physical volume C<device> so that LVM will no longer
1832 The implementation uses the C<pvremove> command which refuses to
1833 wipe physical volumes that contain any volume groups, so you have
1834 to remove those first.");
1836 ("set_e2label", (RErr, [String "device"; String "label"]), 80, [],
1837 [InitBasicFS, Always, TestOutput (
1838 [["set_e2label"; "/dev/sda1"; "testlabel"];
1839 ["get_e2label"; "/dev/sda1"]], "testlabel")],
1840 "set the ext2/3/4 filesystem label",
1842 This sets the ext2/3/4 filesystem label of the filesystem on
1843 C<device> to C<label>. Filesystem labels are limited to
1846 You can use either C<guestfs_tune2fs_l> or C<guestfs_get_e2label>
1847 to return the existing label on a filesystem.");
1849 ("get_e2label", (RString "label", [String "device"]), 81, [],
1851 "get the ext2/3/4 filesystem label",
1853 This returns the ext2/3/4 filesystem label of the filesystem on
1856 ("set_e2uuid", (RErr, [String "device"; String "uuid"]), 82, [],
1857 [InitBasicFS, Always, TestOutput (
1858 [["set_e2uuid"; "/dev/sda1"; "a3a61220-882b-4f61-89f4-cf24dcc7297d"];
1859 ["get_e2uuid"; "/dev/sda1"]], "a3a61220-882b-4f61-89f4-cf24dcc7297d");
1860 InitBasicFS, Always, TestOutput (
1861 [["set_e2uuid"; "/dev/sda1"; "clear"];
1862 ["get_e2uuid"; "/dev/sda1"]], "");
1863 (* We can't predict what UUIDs will be, so just check the commands run. *)
1864 InitBasicFS, Always, TestRun (
1865 [["set_e2uuid"; "/dev/sda1"; "random"]]);
1866 InitBasicFS, Always, TestRun (
1867 [["set_e2uuid"; "/dev/sda1"; "time"]])],
1868 "set the ext2/3/4 filesystem UUID",
1870 This sets the ext2/3/4 filesystem UUID of the filesystem on
1871 C<device> to C<uuid>. The format of the UUID and alternatives
1872 such as C<clear>, C<random> and C<time> are described in the
1873 L<tune2fs(8)> manpage.
1875 You can use either C<guestfs_tune2fs_l> or C<guestfs_get_e2uuid>
1876 to return the existing UUID of a filesystem.");
1878 ("get_e2uuid", (RString "uuid", [String "device"]), 83, [],
1880 "get the ext2/3/4 filesystem UUID",
1882 This returns the ext2/3/4 filesystem UUID of the filesystem on
1885 ("fsck", (RInt "status", [String "fstype"; String "device"]), 84, [],
1886 [InitBasicFS, Always, TestOutputInt (
1887 [["umount"; "/dev/sda1"];
1888 ["fsck"; "ext2"; "/dev/sda1"]], 0);
1889 InitBasicFS, Always, TestOutputInt (
1890 [["umount"; "/dev/sda1"];
1891 ["zero"; "/dev/sda1"];
1892 ["fsck"; "ext2"; "/dev/sda1"]], 8)],
1893 "run the filesystem checker",
1895 This runs the filesystem checker (fsck) on C<device> which
1896 should have filesystem type C<fstype>.
1898 The returned integer is the status. See L<fsck(8)> for the
1899 list of status codes from C<fsck>.
1907 Multiple status codes can be summed together.
1911 A non-zero return code can mean \"success\", for example if
1912 errors have been corrected on the filesystem.
1916 Checking or repairing NTFS volumes is not supported
1921 This command is entirely equivalent to running C<fsck -a -t fstype device>.");
1923 ("zero", (RErr, [String "device"]), 85, [],
1924 [InitBasicFS, Always, TestOutput (
1925 [["umount"; "/dev/sda1"];
1926 ["zero"; "/dev/sda1"];
1927 ["file"; "/dev/sda1"]], "data")],
1928 "write zeroes to the device",
1930 This command writes zeroes over the first few blocks of C<device>.
1932 How many blocks are zeroed isn't specified (but it's I<not> enough
1933 to securely wipe the device). It should be sufficient to remove
1934 any partition tables, filesystem superblocks and so on.");
1936 ("grub_install", (RErr, [String "root"; String "device"]), 86, [],
1937 [InitBasicFS, Always, TestOutputTrue (
1938 [["grub_install"; "/"; "/dev/sda1"];
1939 ["is_dir"; "/boot"]])],
1942 This command installs GRUB (the Grand Unified Bootloader) on
1943 C<device>, with the root directory being C<root>.");
1945 ("cp", (RErr, [String "src"; String "dest"]), 87, [],
1946 [InitBasicFS, Always, TestOutput (
1947 [["write_file"; "/old"; "file content"; "0"];
1948 ["cp"; "/old"; "/new"];
1949 ["cat"; "/new"]], "file content");
1950 InitBasicFS, Always, TestOutputTrue (
1951 [["write_file"; "/old"; "file content"; "0"];
1952 ["cp"; "/old"; "/new"];
1953 ["is_file"; "/old"]]);
1954 InitBasicFS, Always, TestOutput (
1955 [["write_file"; "/old"; "file content"; "0"];
1957 ["cp"; "/old"; "/dir/new"];
1958 ["cat"; "/dir/new"]], "file content")],
1961 This copies a file from C<src> to C<dest> where C<dest> is
1962 either a destination filename or destination directory.");
1964 ("cp_a", (RErr, [String "src"; String "dest"]), 88, [],
1965 [InitBasicFS, Always, TestOutput (
1966 [["mkdir"; "/olddir"];
1967 ["mkdir"; "/newdir"];
1968 ["write_file"; "/olddir/file"; "file content"; "0"];
1969 ["cp_a"; "/olddir"; "/newdir"];
1970 ["cat"; "/newdir/olddir/file"]], "file content")],
1971 "copy a file or directory recursively",
1973 This copies a file or directory from C<src> to C<dest>
1974 recursively using the C<cp -a> command.");
1976 ("mv", (RErr, [String "src"; String "dest"]), 89, [],
1977 [InitBasicFS, Always, TestOutput (
1978 [["write_file"; "/old"; "file content"; "0"];
1979 ["mv"; "/old"; "/new"];
1980 ["cat"; "/new"]], "file content");
1981 InitBasicFS, Always, TestOutputFalse (
1982 [["write_file"; "/old"; "file content"; "0"];
1983 ["mv"; "/old"; "/new"];
1984 ["is_file"; "/old"]])],
1987 This moves a file from C<src> to C<dest> where C<dest> is
1988 either a destination filename or destination directory.");
1990 ("drop_caches", (RErr, [Int "whattodrop"]), 90, [],
1991 [InitEmpty, Always, TestRun (
1992 [["drop_caches"; "3"]])],
1993 "drop kernel page cache, dentries and inodes",
1995 This instructs the guest kernel to drop its page cache,
1996 and/or dentries and inode caches. The parameter C<whattodrop>
1997 tells the kernel what precisely to drop, see
1998 L<http://linux-mm.org/Drop_Caches>
2000 Setting C<whattodrop> to 3 should drop everything.
2002 This automatically calls L<sync(2)> before the operation,
2003 so that the maximum guest memory is freed.");
2005 ("dmesg", (RString "kmsgs", []), 91, [],
2006 [InitEmpty, Always, TestRun (
2008 "return kernel messages",
2010 This returns the kernel messages (C<dmesg> output) from
2011 the guest kernel. This is sometimes useful for extended
2012 debugging of problems.
2014 Another way to get the same information is to enable
2015 verbose messages with C<guestfs_set_verbose> or by setting
2016 the environment variable C<LIBGUESTFS_DEBUG=1> before
2017 running the program.");
2019 ("ping_daemon", (RErr, []), 92, [],
2020 [InitEmpty, Always, TestRun (
2021 [["ping_daemon"]])],
2022 "ping the guest daemon",
2024 This is a test probe into the guestfs daemon running inside
2025 the qemu subprocess. Calling this function checks that the
2026 daemon responds to the ping message, without affecting the daemon
2027 or attached block device(s) in any other way.");
2029 ("equal", (RBool "equality", [String "file1"; String "file2"]), 93, [],
2030 [InitBasicFS, Always, TestOutputTrue (
2031 [["write_file"; "/file1"; "contents of a file"; "0"];
2032 ["cp"; "/file1"; "/file2"];
2033 ["equal"; "/file1"; "/file2"]]);
2034 InitBasicFS, Always, TestOutputFalse (
2035 [["write_file"; "/file1"; "contents of a file"; "0"];
2036 ["write_file"; "/file2"; "contents of another file"; "0"];
2037 ["equal"; "/file1"; "/file2"]]);
2038 InitBasicFS, Always, TestLastFail (
2039 [["equal"; "/file1"; "/file2"]])],
2040 "test if two files have equal contents",
2042 This compares the two files C<file1> and C<file2> and returns
2043 true if their content is exactly equal, or false otherwise.
2045 The external L<cmp(1)> program is used for the comparison.");
2047 ("strings", (RStringList "stringsout", [String "path"]), 94, [ProtocolLimitWarning],
2048 [InitBasicFS, Always, TestOutputList (
2049 [["write_file"; "/new"; "hello\nworld\n"; "0"];
2050 ["strings"; "/new"]], ["hello"; "world"]);
2051 InitBasicFS, Always, TestOutputList (
2053 ["strings"; "/new"]], [])],
2054 "print the printable strings in a file",
2056 This runs the L<strings(1)> command on a file and returns
2057 the list of printable strings found.");
2059 ("strings_e", (RStringList "stringsout", [String "encoding"; String "path"]), 95, [ProtocolLimitWarning],
2060 [InitBasicFS, Always, TestOutputList (
2061 [["write_file"; "/new"; "hello\nworld\n"; "0"];
2062 ["strings_e"; "b"; "/new"]], []);
2063 InitBasicFS, Disabled, TestOutputList (
2064 [["write_file"; "/new"; "\000h\000e\000l\000l\000o\000\n\000w\000o\000r\000l\000d\000\n"; "24"];
2065 ["strings_e"; "b"; "/new"]], ["hello"; "world"])],
2066 "print the printable strings in a file",
2068 This is like the C<guestfs_strings> command, but allows you to
2069 specify the encoding.
2071 See the L<strings(1)> manpage for the full list of encodings.
2073 Commonly useful encodings are C<l> (lower case L) which will
2074 show strings inside Windows/x86 files.
2076 The returned strings are transcoded to UTF-8.");
2078 ("hexdump", (RString "dump", [String "path"]), 96, [ProtocolLimitWarning],
2079 [InitBasicFS, Always, TestOutput (
2080 [["write_file"; "/new"; "hello\nworld\n"; "12"];
2081 ["hexdump"; "/new"]], "00000000 68 65 6c 6c 6f 0a 77 6f 72 6c 64 0a |hello.world.|\n0000000c\n")],
2082 "dump a file in hexadecimal",
2084 This runs C<hexdump -C> on the given C<path>. The result is
2085 the human-readable, canonical hex dump of the file.");
2087 ("zerofree", (RErr, [String "device"]), 97, [],
2088 [InitNone, Always, TestOutput (
2089 [["sfdisk"; "/dev/sda"; "0"; "0"; "0"; ","];
2090 ["mkfs"; "ext3"; "/dev/sda1"];
2091 ["mount"; "/dev/sda1"; "/"];
2092 ["write_file"; "/new"; "test file"; "0"];
2093 ["umount"; "/dev/sda1"];
2094 ["zerofree"; "/dev/sda1"];
2095 ["mount"; "/dev/sda1"; "/"];
2096 ["cat"; "/new"]], "test file")],
2097 "zero unused inodes and disk blocks on ext2/3 filesystem",
2099 This runs the I<zerofree> program on C<device>. This program
2100 claims to zero unused inodes and disk blocks on an ext2/3
2101 filesystem, thus making it possible to compress the filesystem
2104 You should B<not> run this program if the filesystem is
2107 It is possible that using this program can damage the filesystem
2108 or data on the filesystem.");
2110 ("pvresize", (RErr, [String "device"]), 98, [],
2112 "resize an LVM physical volume",
2114 This resizes (expands or shrinks) an existing LVM physical
2115 volume to match the new size of the underlying device.");
2117 ("sfdisk_N", (RErr, [String "device"; Int "n";
2118 Int "cyls"; Int "heads"; Int "sectors";
2119 String "line"]), 99, [DangerWillRobinson],
2121 "modify a single partition on a block device",
2123 This runs L<sfdisk(8)> option to modify just the single
2124 partition C<n> (note: C<n> counts from 1).
2126 For other parameters, see C<guestfs_sfdisk>. You should usually
2127 pass C<0> for the cyls/heads/sectors parameters.");
2129 ("sfdisk_l", (RString "partitions", [String "device"]), 100, [],
2131 "display the partition table",
2133 This displays the partition table on C<device>, in the
2134 human-readable output of the L<sfdisk(8)> command. It is
2135 not intended to be parsed.");
2137 ("sfdisk_kernel_geometry", (RString "partitions", [String "device"]), 101, [],
2139 "display the kernel geometry",
2141 This displays the kernel's idea of the geometry of C<device>.
2143 The result is in human-readable format, and not designed to
2146 ("sfdisk_disk_geometry", (RString "partitions", [String "device"]), 102, [],
2148 "display the disk geometry from the partition table",
2150 This displays the disk geometry of C<device> read from the
2151 partition table. Especially in the case where the underlying
2152 block device has been resized, this can be different from the
2153 kernel's idea of the geometry (see C<guestfs_sfdisk_kernel_geometry>).
2155 The result is in human-readable format, and not designed to
2158 ("vg_activate_all", (RErr, [Bool "activate"]), 103, [],
2160 "activate or deactivate all volume groups",
2162 This command activates or (if C<activate> is false) deactivates
2163 all logical volumes in all volume groups.
2164 If activated, then they are made known to the
2165 kernel, ie. they appear as C</dev/mapper> devices. If deactivated,
2166 then those devices disappear.
2168 This command is the same as running C<vgchange -a y|n>");
2170 ("vg_activate", (RErr, [Bool "activate"; StringList "volgroups"]), 104, [],
2172 "activate or deactivate some volume groups",
2174 This command activates or (if C<activate> is false) deactivates
2175 all logical volumes in the listed volume groups C<volgroups>.
2176 If activated, then they are made known to the
2177 kernel, ie. they appear as C</dev/mapper> devices. If deactivated,
2178 then those devices disappear.
2180 This command is the same as running C<vgchange -a y|n volgroups...>
2182 Note that if C<volgroups> is an empty list then B<all> volume groups
2183 are activated or deactivated.");
2185 ("lvresize", (RErr, [String "device"; Int "mbytes"]), 105, [],
2186 [InitNone, Always, TestOutput (
2187 [["sfdisk"; "/dev/sda"; "0"; "0"; "0"; ","];
2188 ["pvcreate"; "/dev/sda1"];
2189 ["vgcreate"; "VG"; "/dev/sda1"];
2190 ["lvcreate"; "LV"; "VG"; "10"];
2191 ["mkfs"; "ext2"; "/dev/VG/LV"];
2192 ["mount"; "/dev/VG/LV"; "/"];
2193 ["write_file"; "/new"; "test content"; "0"];
2195 ["lvresize"; "/dev/VG/LV"; "20"];
2196 ["e2fsck_f"; "/dev/VG/LV"];
2197 ["resize2fs"; "/dev/VG/LV"];
2198 ["mount"; "/dev/VG/LV"; "/"];
2199 ["cat"; "/new"]], "test content")],
2200 "resize an LVM logical volume",
2202 This resizes (expands or shrinks) an existing LVM logical
2203 volume to C<mbytes>. When reducing, data in the reduced part
2206 ("resize2fs", (RErr, [String "device"]), 106, [],
2207 [], (* lvresize tests this *)
2208 "resize an ext2/ext3 filesystem",
2210 This resizes an ext2 or ext3 filesystem to match the size of
2211 the underlying device.
2213 I<Note:> It is sometimes required that you run C<guestfs_e2fsck_f>
2214 on the C<device> before calling this command. For unknown reasons
2215 C<resize2fs> sometimes gives an error about this and sometimes not.
2216 In any case, it is always safe to call C<guestfs_e2fsck_f> before
2217 calling this function.");
2219 ("find", (RStringList "names", [String "directory"]), 107, [],
2220 [InitBasicFS, Always, TestOutputList (
2221 [["find"; "/"]], ["lost+found"]);
2222 InitBasicFS, Always, TestOutputList (
2226 ["find"; "/"]], ["a"; "b"; "b/c"; "lost+found"]);
2227 InitBasicFS, Always, TestOutputList (
2228 [["mkdir_p"; "/a/b/c"];
2229 ["touch"; "/a/b/c/d"];
2230 ["find"; "/a/b/"]], ["c"; "c/d"])],
2231 "find all files and directories",
2233 This command lists out all files and directories, recursively,
2234 starting at C<directory>. It is essentially equivalent to
2235 running the shell command C<find directory -print> but some
2236 post-processing happens on the output, described below.
2238 This returns a list of strings I<without any prefix>. Thus
2239 if the directory structure was:
2245 then the returned list from C<guestfs_find> C</tmp> would be
2253 If C<directory> is not a directory, then this command returns
2256 The returned list is sorted.");
2258 ("e2fsck_f", (RErr, [String "device"]), 108, [],
2259 [], (* lvresize tests this *)
2260 "check an ext2/ext3 filesystem",
2262 This runs C<e2fsck -p -f device>, ie. runs the ext2/ext3
2263 filesystem checker on C<device>, noninteractively (C<-p>),
2264 even if the filesystem appears to be clean (C<-f>).
2266 This command is only needed because of C<guestfs_resize2fs>
2267 (q.v.). Normally you should use C<guestfs_fsck>.");
2271 let all_functions = non_daemon_functions @ daemon_functions
2273 (* In some places we want the functions to be displayed sorted
2274 * alphabetically, so this is useful:
2276 let all_functions_sorted =
2277 List.sort (fun (n1,_,_,_,_,_,_) (n2,_,_,_,_,_,_) ->
2278 compare n1 n2) all_functions
2280 (* Column names and types from LVM PVs/VGs/LVs. *)
2289 "pv_attr", `String (* XXX *);
2290 "pv_pe_count", `Int;
2291 "pv_pe_alloc_count", `Int;
2294 "pv_mda_count", `Int;
2295 "pv_mda_free", `Bytes;
2296 (* Not in Fedora 10:
2297 "pv_mda_size", `Bytes;
2304 "vg_attr", `String (* XXX *);
2307 "vg_sysid", `String;
2308 "vg_extent_size", `Bytes;
2309 "vg_extent_count", `Int;
2310 "vg_free_count", `Int;
2318 "vg_mda_count", `Int;
2319 "vg_mda_free", `Bytes;
2320 (* Not in Fedora 10:
2321 "vg_mda_size", `Bytes;
2327 "lv_attr", `String (* XXX *);
2330 "lv_kernel_major", `Int;
2331 "lv_kernel_minor", `Int;
2335 "snap_percent", `OptPercent;
2336 "copy_percent", `OptPercent;
2339 "mirror_log", `String;
2343 (* Column names and types from stat structures.
2344 * NB. Can't use things like 'st_atime' because glibc header files
2345 * define some of these as macros. Ugh.
2362 let statvfs_cols = [
2376 (* Useful functions.
2377 * Note we don't want to use any external OCaml libraries which
2378 * makes this a bit harder than it should be.
2380 let failwithf fs = ksprintf failwith fs
2382 let replace_char s c1 c2 =
2383 let s2 = String.copy s in
2384 let r = ref false in
2385 for i = 0 to String.length s2 - 1 do
2386 if String.unsafe_get s2 i = c1 then (
2387 String.unsafe_set s2 i c2;
2391 if not !r then s else s2
2395 (* || c = '\f' *) || c = '\n' || c = '\r' || c = '\t' (* || c = '\v' *)
2397 let triml ?(test = isspace) str =
2399 let n = ref (String.length str) in
2400 while !n > 0 && test str.[!i]; do
2405 else String.sub str !i !n
2407 let trimr ?(test = isspace) str =
2408 let n = ref (String.length str) in
2409 while !n > 0 && test str.[!n-1]; do
2412 if !n = String.length str then str
2413 else String.sub str 0 !n
2415 let trim ?(test = isspace) str =
2416 trimr ~test (triml ~test str)
2418 let rec find s sub =
2419 let len = String.length s in
2420 let sublen = String.length sub in
2422 if i <= len-sublen then (
2424 if j < sublen then (
2425 if s.[i+j] = sub.[j] then loop2 (j+1)
2431 if r = -1 then loop (i+1) else r
2437 let rec replace_str s s1 s2 =
2438 let len = String.length s in
2439 let sublen = String.length s1 in
2440 let i = find s s1 in
2443 let s' = String.sub s 0 i in
2444 let s'' = String.sub s (i+sublen) (len-i-sublen) in
2445 s' ^ s2 ^ replace_str s'' s1 s2
2448 let rec string_split sep str =
2449 let len = String.length str in
2450 let seplen = String.length sep in
2451 let i = find str sep in
2452 if i = -1 then [str]
2454 let s' = String.sub str 0 i in
2455 let s'' = String.sub str (i+seplen) (len-i-seplen) in
2456 s' :: string_split sep s''
2459 let files_equal n1 n2 =
2460 let cmd = sprintf "cmp -s %s %s" (Filename.quote n1) (Filename.quote n2) in
2461 match Sys.command cmd with
2464 | i -> failwithf "%s: failed with error code %d" cmd i
2466 let rec find_map f = function
2467 | [] -> raise Not_found
2471 | None -> find_map f xs
2474 let rec loop i = function
2476 | x :: xs -> f i x; loop (i+1) xs
2481 let rec loop i = function
2483 | x :: xs -> let r = f i x in r :: loop (i+1) xs
2487 let name_of_argt = function
2488 | String n | OptString n | StringList n | Bool n | Int n
2489 | FileIn n | FileOut n -> n
2491 let seq_of_test = function
2492 | TestRun s | TestOutput (s, _) | TestOutputList (s, _)
2493 | TestOutputInt (s, _) | TestOutputTrue s | TestOutputFalse s
2494 | TestOutputLength (s, _) | TestOutputStruct (s, _)
2495 | TestLastFail s -> s
2497 (* Check function names etc. for consistency. *)
2498 let check_functions () =
2499 let contains_uppercase str =
2500 let len = String.length str in
2502 if i >= len then false
2505 if c >= 'A' && c <= 'Z' then true
2512 (* Check function names. *)
2514 fun (name, _, _, _, _, _, _) ->
2515 if String.length name >= 7 && String.sub name 0 7 = "guestfs" then
2516 failwithf "function name %s does not need 'guestfs' prefix" name;
2518 failwithf "function name is empty";
2519 if name.[0] < 'a' || name.[0] > 'z' then
2520 failwithf "function name %s must start with lowercase a-z" name;
2521 if String.contains name '-' then
2522 failwithf "function name %s should not contain '-', use '_' instead."
2526 (* Check function parameter/return names. *)
2528 fun (name, style, _, _, _, _, _) ->
2529 let check_arg_ret_name n =
2530 if contains_uppercase n then
2531 failwithf "%s param/ret %s should not contain uppercase chars"
2533 if String.contains n '-' || String.contains n '_' then
2534 failwithf "%s param/ret %s should not contain '-' or '_'"
2537 failwithf "%s has a param/ret called 'value', which causes conflicts in the OCaml bindings, use something like 'val' or a more descriptive name" name;
2538 if n = "int" || n = "char" || n = "short" || n = "long" then
2539 failwithf "%s has a param/ret which conflicts with a C type (eg. 'int', 'char' etc.)" name;
2541 failwithf "%s has a param/ret called 'i', which will cause some conflicts in the generated code" name;
2542 if n = "argv" || n = "args" then
2543 failwithf "%s has a param/ret called 'argv' or 'args', which will cause some conflicts in the generated code" name
2546 (match fst style with
2548 | RInt n | RInt64 n | RBool n | RConstString n | RString n
2549 | RStringList n | RPVList n | RVGList n | RLVList n
2550 | RStat n | RStatVFS n
2552 check_arg_ret_name n
2554 check_arg_ret_name n;
2555 check_arg_ret_name m
2557 List.iter (fun arg -> check_arg_ret_name (name_of_argt arg)) (snd style)
2560 (* Check short descriptions. *)
2562 fun (name, _, _, _, _, shortdesc, _) ->
2563 if shortdesc.[0] <> Char.lowercase shortdesc.[0] then
2564 failwithf "short description of %s should begin with lowercase." name;
2565 let c = shortdesc.[String.length shortdesc-1] in
2566 if c = '\n' || c = '.' then
2567 failwithf "short description of %s should not end with . or \\n." name
2570 (* Check long dscriptions. *)
2572 fun (name, _, _, _, _, _, longdesc) ->
2573 if longdesc.[String.length longdesc-1] = '\n' then
2574 failwithf "long description of %s should not end with \\n." name
2577 (* Check proc_nrs. *)
2579 fun (name, _, proc_nr, _, _, _, _) ->
2580 if proc_nr <= 0 then
2581 failwithf "daemon function %s should have proc_nr > 0" name
2585 fun (name, _, proc_nr, _, _, _, _) ->
2586 if proc_nr <> -1 then
2587 failwithf "non-daemon function %s should have proc_nr -1" name
2588 ) non_daemon_functions;
2591 List.map (fun (name, _, proc_nr, _, _, _, _) -> name, proc_nr)
2594 List.sort (fun (_,nr1) (_,nr2) -> compare nr1 nr2) proc_nrs in
2595 let rec loop = function
2598 | (name1,nr1) :: ((name2,nr2) :: _ as rest) when nr1 < nr2 ->
2600 | (name1,nr1) :: (name2,nr2) :: _ ->
2601 failwithf "%s and %s have conflicting procedure numbers (%d, %d)"
2609 (* Ignore functions that have no tests. We generate a
2610 * warning when the user does 'make check' instead.
2612 | name, _, _, _, [], _, _ -> ()
2613 | name, _, _, _, tests, _, _ ->
2617 match seq_of_test test with
2619 failwithf "%s has a test containing an empty sequence" name
2620 | cmds -> List.map List.hd cmds
2622 let funcs = List.flatten funcs in
2624 let tested = List.mem name funcs in
2627 failwithf "function %s has tests but does not test itself" name
2630 (* 'pr' prints to the current output file. *)
2631 let chan = ref stdout
2632 let pr fs = ksprintf (output_string !chan) fs
2634 (* Generate a header block in a number of standard styles. *)
2635 type comment_style = CStyle | HashStyle | OCamlStyle | HaskellStyle
2636 type license = GPLv2 | LGPLv2
2638 let generate_header comment license =
2639 let c = match comment with
2640 | CStyle -> pr "/* "; " *"
2641 | HashStyle -> pr "# "; "#"
2642 | OCamlStyle -> pr "(* "; " *"
2643 | HaskellStyle -> pr "{- "; " " in
2644 pr "libguestfs generated file\n";
2645 pr "%s WARNING: THIS FILE IS GENERATED BY 'src/generator.ml'.\n" c;
2646 pr "%s ANY CHANGES YOU MAKE TO THIS FILE WILL BE LOST.\n" c;
2648 pr "%s Copyright (C) 2009 Red Hat Inc.\n" c;
2652 pr "%s This program is free software; you can redistribute it and/or modify\n" c;
2653 pr "%s it under the terms of the GNU General Public License as published by\n" c;
2654 pr "%s the Free Software Foundation; either version 2 of the License, or\n" c;
2655 pr "%s (at your option) any later version.\n" c;
2657 pr "%s This program is distributed in the hope that it will be useful,\n" c;
2658 pr "%s but WITHOUT ANY WARRANTY; without even the implied warranty of\n" c;
2659 pr "%s MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n" c;
2660 pr "%s GNU General Public License for more details.\n" c;
2662 pr "%s You should have received a copy of the GNU General Public License along\n" c;
2663 pr "%s with this program; if not, write to the Free Software Foundation, Inc.,\n" c;
2664 pr "%s 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n" c;
2667 pr "%s This library is free software; you can redistribute it and/or\n" c;
2668 pr "%s modify it under the terms of the GNU Lesser General Public\n" c;
2669 pr "%s License as published by the Free Software Foundation; either\n" c;
2670 pr "%s version 2 of the License, or (at your option) any later version.\n" c;
2672 pr "%s This library is distributed in the hope that it will be useful,\n" c;
2673 pr "%s but WITHOUT ANY WARRANTY; without even the implied warranty of\n" c;
2674 pr "%s MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n" c;
2675 pr "%s Lesser General Public License for more details.\n" c;
2677 pr "%s You should have received a copy of the GNU Lesser General Public\n" c;
2678 pr "%s License along with this library; if not, write to the Free Software\n" c;
2679 pr "%s Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n" c;
2682 | CStyle -> pr " */\n"
2684 | OCamlStyle -> pr " *)\n"
2685 | HaskellStyle -> pr "-}\n"
2689 (* Start of main code generation functions below this line. *)
2691 (* Generate the pod documentation for the C API. *)
2692 let rec generate_actions_pod () =
2694 fun (shortname, style, _, flags, _, _, longdesc) ->
2695 if not (List.mem NotInDocs flags) then (
2696 let name = "guestfs_" ^ shortname in
2697 pr "=head2 %s\n\n" name;
2699 generate_prototype ~extern:false ~handle:"handle" name style;
2701 pr "%s\n\n" longdesc;
2702 (match fst style with
2704 pr "This function returns 0 on success or -1 on error.\n\n"
2706 pr "On error this function returns -1.\n\n"
2708 pr "On error this function returns -1.\n\n"
2710 pr "This function returns a C truth value on success or -1 on error.\n\n"
2712 pr "This function returns a string, or NULL on error.
2713 The string is owned by the guest handle and must I<not> be freed.\n\n"
2715 pr "This function returns a string, or NULL on error.
2716 I<The caller must free the returned string after use>.\n\n"
2718 pr "This function returns a NULL-terminated array of strings
2719 (like L<environ(3)>), or NULL if there was an error.
2720 I<The caller must free the strings and the array after use>.\n\n"
2722 pr "This function returns a C<struct guestfs_int_bool *>,
2723 or NULL if there was an error.
2724 I<The caller must call C<guestfs_free_int_bool> after use>.\n\n"
2726 pr "This function returns a C<struct guestfs_lvm_pv_list *>
2727 (see E<lt>guestfs-structs.hE<gt>),
2728 or NULL if there was an error.
2729 I<The caller must call C<guestfs_free_lvm_pv_list> after use>.\n\n"
2731 pr "This function returns a C<struct guestfs_lvm_vg_list *>
2732 (see E<lt>guestfs-structs.hE<gt>),
2733 or NULL if there was an error.
2734 I<The caller must call C<guestfs_free_lvm_vg_list> after use>.\n\n"
2736 pr "This function returns a C<struct guestfs_lvm_lv_list *>
2737 (see E<lt>guestfs-structs.hE<gt>),
2738 or NULL if there was an error.
2739 I<The caller must call C<guestfs_free_lvm_lv_list> after use>.\n\n"
2741 pr "This function returns a C<struct guestfs_stat *>
2742 (see L<stat(2)> and E<lt>guestfs-structs.hE<gt>),
2743 or NULL if there was an error.
2744 I<The caller must call C<free> after use>.\n\n"
2746 pr "This function returns a C<struct guestfs_statvfs *>
2747 (see L<statvfs(2)> and E<lt>guestfs-structs.hE<gt>),
2748 or NULL if there was an error.
2749 I<The caller must call C<free> after use>.\n\n"
2751 pr "This function returns a NULL-terminated array of
2752 strings, or NULL if there was an error.
2753 The array of strings will always have length C<2n+1>, where
2754 C<n> keys and values alternate, followed by the trailing NULL entry.
2755 I<The caller must free the strings and the array after use>.\n\n"
2757 if List.mem ProtocolLimitWarning flags then
2758 pr "%s\n\n" protocol_limit_warning;
2759 if List.mem DangerWillRobinson flags then
2760 pr "%s\n\n" danger_will_robinson
2762 ) all_functions_sorted
2764 and generate_structs_pod () =
2765 (* LVM structs documentation. *)
2768 pr "=head2 guestfs_lvm_%s\n" typ;
2770 pr " struct guestfs_lvm_%s {\n" typ;
2773 | name, `String -> pr " char *%s;\n" name
2775 pr " /* The next field is NOT nul-terminated, be careful when printing it: */\n";
2776 pr " char %s[32];\n" name
2777 | name, `Bytes -> pr " uint64_t %s;\n" name
2778 | name, `Int -> pr " int64_t %s;\n" name
2779 | name, `OptPercent ->
2780 pr " /* The next field is [0..100] or -1 meaning 'not present': */\n";
2781 pr " float %s;\n" name
2784 pr " struct guestfs_lvm_%s_list {\n" typ;
2785 pr " uint32_t len; /* Number of elements in list. */\n";
2786 pr " struct guestfs_lvm_%s *val; /* Elements. */\n" typ;
2789 pr " void guestfs_free_lvm_%s_list (struct guestfs_free_lvm_%s_list *);\n"
2792 ) ["pv", pv_cols; "vg", vg_cols; "lv", lv_cols]
2794 (* Generate the protocol (XDR) file, 'guestfs_protocol.x' and
2795 * indirectly 'guestfs_protocol.h' and 'guestfs_protocol.c'.
2797 * We have to use an underscore instead of a dash because otherwise
2798 * rpcgen generates incorrect code.
2800 * This header is NOT exported to clients, but see also generate_structs_h.
2802 and generate_xdr () =
2803 generate_header CStyle LGPLv2;
2805 (* This has to be defined to get around a limitation in Sun's rpcgen. *)
2806 pr "typedef string str<>;\n";
2809 (* LVM internal structures. *)
2813 pr "struct guestfs_lvm_int_%s {\n" typ;
2815 | name, `String -> pr " string %s<>;\n" name
2816 | name, `UUID -> pr " opaque %s[32];\n" name
2817 | name, `Bytes -> pr " hyper %s;\n" name
2818 | name, `Int -> pr " hyper %s;\n" name
2819 | name, `OptPercent -> pr " float %s;\n" name
2823 pr "typedef struct guestfs_lvm_int_%s guestfs_lvm_int_%s_list<>;\n" typ typ;
2825 ) ["pv", pv_cols; "vg", vg_cols; "lv", lv_cols];
2827 (* Stat internal structures. *)
2831 pr "struct guestfs_int_%s {\n" typ;
2833 | name, `Int -> pr " hyper %s;\n" name
2837 ) ["stat", stat_cols; "statvfs", statvfs_cols];
2840 fun (shortname, style, _, _, _, _, _) ->
2841 let name = "guestfs_" ^ shortname in
2843 (match snd style with
2846 pr "struct %s_args {\n" name;
2849 | String n -> pr " string %s<>;\n" n
2850 | OptString n -> pr " str *%s;\n" n
2851 | StringList n -> pr " str %s<>;\n" n
2852 | Bool n -> pr " bool %s;\n" n
2853 | Int n -> pr " int %s;\n" n
2854 | FileIn _ | FileOut _ -> ()
2858 (match fst style with
2861 pr "struct %s_ret {\n" name;
2865 pr "struct %s_ret {\n" name;
2866 pr " hyper %s;\n" n;
2869 pr "struct %s_ret {\n" name;
2873 failwithf "RConstString cannot be returned from a daemon function"
2875 pr "struct %s_ret {\n" name;
2876 pr " string %s<>;\n" n;
2879 pr "struct %s_ret {\n" name;
2880 pr " str %s<>;\n" n;
2883 pr "struct %s_ret {\n" name;
2888 pr "struct %s_ret {\n" name;
2889 pr " guestfs_lvm_int_pv_list %s;\n" n;
2892 pr "struct %s_ret {\n" name;
2893 pr " guestfs_lvm_int_vg_list %s;\n" n;
2896 pr "struct %s_ret {\n" name;
2897 pr " guestfs_lvm_int_lv_list %s;\n" n;
2900 pr "struct %s_ret {\n" name;
2901 pr " guestfs_int_stat %s;\n" n;
2904 pr "struct %s_ret {\n" name;
2905 pr " guestfs_int_statvfs %s;\n" n;
2908 pr "struct %s_ret {\n" name;
2909 pr " str %s<>;\n" n;
2914 (* Table of procedure numbers. *)
2915 pr "enum guestfs_procedure {\n";
2917 fun (shortname, _, proc_nr, _, _, _, _) ->
2918 pr " GUESTFS_PROC_%s = %d,\n" (String.uppercase shortname) proc_nr
2920 pr " GUESTFS_PROC_NR_PROCS\n";
2924 (* Having to choose a maximum message size is annoying for several
2925 * reasons (it limits what we can do in the API), but it (a) makes
2926 * the protocol a lot simpler, and (b) provides a bound on the size
2927 * of the daemon which operates in limited memory space. For large
2928 * file transfers you should use FTP.
2930 pr "const GUESTFS_MESSAGE_MAX = %d;\n" (4 * 1024 * 1024);
2933 (* Message header, etc. *)
2935 /* The communication protocol is now documented in the guestfs(3)
2939 const GUESTFS_PROGRAM = 0x2000F5F5;
2940 const GUESTFS_PROTOCOL_VERSION = 1;
2942 /* These constants must be larger than any possible message length. */
2943 const GUESTFS_LAUNCH_FLAG = 0xf5f55ff5;
2944 const GUESTFS_CANCEL_FLAG = 0xffffeeee;
2946 enum guestfs_message_direction {
2947 GUESTFS_DIRECTION_CALL = 0, /* client -> daemon */
2948 GUESTFS_DIRECTION_REPLY = 1 /* daemon -> client */
2951 enum guestfs_message_status {
2952 GUESTFS_STATUS_OK = 0,
2953 GUESTFS_STATUS_ERROR = 1
2956 const GUESTFS_ERROR_LEN = 256;
2958 struct guestfs_message_error {
2959 string error_message<GUESTFS_ERROR_LEN>;
2962 struct guestfs_message_header {
2963 unsigned prog; /* GUESTFS_PROGRAM */
2964 unsigned vers; /* GUESTFS_PROTOCOL_VERSION */
2965 guestfs_procedure proc; /* GUESTFS_PROC_x */
2966 guestfs_message_direction direction;
2967 unsigned serial; /* message serial number */
2968 guestfs_message_status status;
2971 const GUESTFS_MAX_CHUNK_SIZE = 8192;
2973 struct guestfs_chunk {
2974 int cancel; /* if non-zero, transfer is cancelled */
2975 /* data size is 0 bytes if the transfer has finished successfully */
2976 opaque data<GUESTFS_MAX_CHUNK_SIZE>;
2980 (* Generate the guestfs-structs.h file. *)
2981 and generate_structs_h () =
2982 generate_header CStyle LGPLv2;
2984 (* This is a public exported header file containing various
2985 * structures. The structures are carefully written to have
2986 * exactly the same in-memory format as the XDR structures that
2987 * we use on the wire to the daemon. The reason for creating
2988 * copies of these structures here is just so we don't have to
2989 * export the whole of guestfs_protocol.h (which includes much
2990 * unrelated and XDR-dependent stuff that we don't want to be
2991 * public, or required by clients).
2993 * To reiterate, we will pass these structures to and from the
2994 * client with a simple assignment or memcpy, so the format
2995 * must be identical to what rpcgen / the RFC defines.
2998 (* guestfs_int_bool structure. *)
2999 pr "struct guestfs_int_bool {\n";
3005 (* LVM public structures. *)
3009 pr "struct guestfs_lvm_%s {\n" typ;
3012 | name, `String -> pr " char *%s;\n" name
3013 | name, `UUID -> pr " char %s[32]; /* this is NOT nul-terminated, be careful when printing */\n" name
3014 | name, `Bytes -> pr " uint64_t %s;\n" name
3015 | name, `Int -> pr " int64_t %s;\n" name
3016 | name, `OptPercent -> pr " float %s; /* [0..100] or -1 */\n" name
3020 pr "struct guestfs_lvm_%s_list {\n" typ;
3021 pr " uint32_t len;\n";
3022 pr " struct guestfs_lvm_%s *val;\n" typ;
3025 ) ["pv", pv_cols; "vg", vg_cols; "lv", lv_cols];
3027 (* Stat structures. *)
3031 pr "struct guestfs_%s {\n" typ;
3034 | name, `Int -> pr " int64_t %s;\n" name
3038 ) ["stat", stat_cols; "statvfs", statvfs_cols]
3040 (* Generate the guestfs-actions.h file. *)
3041 and generate_actions_h () =
3042 generate_header CStyle LGPLv2;
3044 fun (shortname, style, _, _, _, _, _) ->
3045 let name = "guestfs_" ^ shortname in
3046 generate_prototype ~single_line:true ~newline:true ~handle:"handle"
3050 (* Generate the client-side dispatch stubs. *)
3051 and generate_client_actions () =
3052 generate_header CStyle LGPLv2;
3058 #include \"guestfs.h\"
3059 #include \"guestfs_protocol.h\"
3061 #define error guestfs_error
3062 #define perrorf guestfs_perrorf
3063 #define safe_malloc guestfs_safe_malloc
3064 #define safe_realloc guestfs_safe_realloc
3065 #define safe_strdup guestfs_safe_strdup
3066 #define safe_memdup guestfs_safe_memdup
3068 /* Check the return message from a call for validity. */
3070 check_reply_header (guestfs_h *g,
3071 const struct guestfs_message_header *hdr,
3072 int proc_nr, int serial)
3074 if (hdr->prog != GUESTFS_PROGRAM) {
3075 error (g, \"wrong program (%%d/%%d)\", hdr->prog, GUESTFS_PROGRAM);
3078 if (hdr->vers != GUESTFS_PROTOCOL_VERSION) {
3079 error (g, \"wrong protocol version (%%d/%%d)\",
3080 hdr->vers, GUESTFS_PROTOCOL_VERSION);
3083 if (hdr->direction != GUESTFS_DIRECTION_REPLY) {
3084 error (g, \"unexpected message direction (%%d/%%d)\",
3085 hdr->direction, GUESTFS_DIRECTION_REPLY);
3088 if (hdr->proc != proc_nr) {
3089 error (g, \"unexpected procedure number (%%d/%%d)\", hdr->proc, proc_nr);
3092 if (hdr->serial != serial) {
3093 error (g, \"unexpected serial (%%d/%%d)\", hdr->serial, serial);
3100 /* Check we are in the right state to run a high-level action. */
3102 check_state (guestfs_h *g, const char *caller)
3104 if (!guestfs_is_ready (g)) {
3105 if (guestfs_is_config (g))
3106 error (g, \"%%s: call launch() before using this function\",
3108 else if (guestfs_is_launching (g))
3109 error (g, \"%%s: call wait_ready() before using this function\",
3112 error (g, \"%%s called from the wrong state, %%d != READY\",
3113 caller, guestfs_get_state (g));
3121 (* Client-side stubs for each function. *)
3123 fun (shortname, style, _, _, _, _, _) ->
3124 let name = "guestfs_" ^ shortname in
3126 (* Generate the context struct which stores the high-level
3127 * state between callback functions.
3129 pr "struct %s_ctx {\n" shortname;
3130 pr " /* This flag is set by the callbacks, so we know we've done\n";
3131 pr " * the callbacks as expected, and in the right sequence.\n";
3132 pr " * 0 = not called, 1 = reply_cb called.\n";
3134 pr " int cb_sequence;\n";
3135 pr " struct guestfs_message_header hdr;\n";
3136 pr " struct guestfs_message_error err;\n";
3137 (match fst style with
3140 failwithf "RConstString cannot be returned from a daemon function"
3142 | RBool _ | RString _ | RStringList _
3144 | RPVList _ | RVGList _ | RLVList _
3145 | RStat _ | RStatVFS _
3147 pr " struct %s_ret ret;\n" name
3152 (* Generate the reply callback function. *)
3153 pr "static void %s_reply_cb (guestfs_h *g, void *data, XDR *xdr)\n" shortname;
3155 pr " guestfs_main_loop *ml = guestfs_get_main_loop (g);\n";
3156 pr " struct %s_ctx *ctx = (struct %s_ctx *) data;\n" shortname shortname;
3158 pr " /* This should definitely not happen. */\n";
3159 pr " if (ctx->cb_sequence != 0) {\n";
3160 pr " ctx->cb_sequence = 9999;\n";
3161 pr " error (g, \"%%s: internal error: reply callback called twice\", \"%s\");\n" name;
3165 pr " ml->main_loop_quit (ml, g);\n";
3167 pr " if (!xdr_guestfs_message_header (xdr, &ctx->hdr)) {\n";
3168 pr " error (g, \"%%s: failed to parse reply header\", \"%s\");\n" name;
3171 pr " if (ctx->hdr.status == GUESTFS_STATUS_ERROR) {\n";
3172 pr " if (!xdr_guestfs_message_error (xdr, &ctx->err)) {\n";
3173 pr " error (g, \"%%s: failed to parse reply error\", \"%s\");\n"
3180 (match fst style with
3183 failwithf "RConstString cannot be returned from a daemon function"
3185 | RBool _ | RString _ | RStringList _
3187 | RPVList _ | RVGList _ | RLVList _
3188 | RStat _ | RStatVFS _
3190 pr " if (!xdr_%s_ret (xdr, &ctx->ret)) {\n" name;
3191 pr " error (g, \"%%s: failed to parse reply\", \"%s\");\n" name;
3197 pr " ctx->cb_sequence = 1;\n";
3200 (* Generate the action stub. *)
3201 generate_prototype ~extern:false ~semicolon:false ~newline:true
3202 ~handle:"g" name style;
3205 match fst style with
3206 | RErr | RInt _ | RInt64 _ | RBool _ -> "-1"
3208 failwithf "RConstString cannot be returned from a daemon function"
3209 | RString _ | RStringList _ | RIntBool _
3210 | RPVList _ | RVGList _ | RLVList _
3211 | RStat _ | RStatVFS _
3217 (match snd style with
3219 | _ -> pr " struct %s_args args;\n" name
3222 pr " struct %s_ctx ctx;\n" shortname;
3223 pr " guestfs_main_loop *ml = guestfs_get_main_loop (g);\n";
3224 pr " int serial;\n";
3226 pr " if (check_state (g, \"%s\") == -1) return %s;\n" name error_code;
3227 pr " guestfs_set_busy (g);\n";
3229 pr " memset (&ctx, 0, sizeof ctx);\n";
3232 (* Send the main header and arguments. *)
3233 (match snd style with
3235 pr " serial = guestfs__send_sync (g, GUESTFS_PROC_%s, NULL, NULL);\n"
3236 (String.uppercase shortname)
3241 pr " args.%s = (char *) %s;\n" n n
3243 pr " args.%s = %s ? (char **) &%s : NULL;\n" n n n
3245 pr " args.%s.%s_val = (char **) %s;\n" n n n;
3246 pr " for (args.%s.%s_len = 0; %s[args.%s.%s_len]; args.%s.%s_len++) ;\n" n n n n n n n;
3248 pr " args.%s = %s;\n" n n
3250 pr " args.%s = %s;\n" n n
3251 | FileIn _ | FileOut _ -> ()
3253 pr " serial = guestfs__send_sync (g, GUESTFS_PROC_%s,\n"
3254 (String.uppercase shortname);
3255 pr " (xdrproc_t) xdr_%s_args, (char *) &args);\n"
3258 pr " if (serial == -1) {\n";
3259 pr " guestfs_end_busy (g);\n";
3260 pr " return %s;\n" error_code;
3264 (* Send any additional files (FileIn) requested. *)
3265 let need_read_reply_label = ref false in
3272 pr " r = guestfs__send_file_sync (g, %s);\n" n;
3273 pr " if (r == -1) {\n";
3274 pr " guestfs_end_busy (g);\n";
3275 pr " return %s;\n" error_code;
3277 pr " if (r == -2) /* daemon cancelled */\n";
3278 pr " goto read_reply;\n";
3279 need_read_reply_label := true;
3285 (* Wait for the reply from the remote end. *)
3286 if !need_read_reply_label then pr " read_reply:\n";
3287 pr " guestfs__switch_to_receiving (g);\n";
3288 pr " ctx.cb_sequence = 0;\n";
3289 pr " guestfs_set_reply_callback (g, %s_reply_cb, &ctx);\n" shortname;
3290 pr " (void) ml->main_loop_run (ml, g);\n";
3291 pr " guestfs_set_reply_callback (g, NULL, NULL);\n";
3292 pr " if (ctx.cb_sequence != 1) {\n";
3293 pr " error (g, \"%%s reply failed, see earlier error messages\", \"%s\");\n" name;
3294 pr " guestfs_end_busy (g);\n";
3295 pr " return %s;\n" error_code;
3299 pr " if (check_reply_header (g, &ctx.hdr, GUESTFS_PROC_%s, serial) == -1) {\n"
3300 (String.uppercase shortname);
3301 pr " guestfs_end_busy (g);\n";
3302 pr " return %s;\n" error_code;
3306 pr " if (ctx.hdr.status == GUESTFS_STATUS_ERROR) {\n";
3307 pr " error (g, \"%%s\", ctx.err.error_message);\n";
3308 pr " free (ctx.err.error_message);\n";
3309 pr " guestfs_end_busy (g);\n";
3310 pr " return %s;\n" error_code;
3314 (* Expecting to receive further files (FileOut)? *)
3318 pr " if (guestfs__receive_file_sync (g, %s) == -1) {\n" n;
3319 pr " guestfs_end_busy (g);\n";
3320 pr " return %s;\n" error_code;
3326 pr " guestfs_end_busy (g);\n";
3328 (match fst style with
3329 | RErr -> pr " return 0;\n"
3330 | RInt n | RInt64 n | RBool n ->
3331 pr " return ctx.ret.%s;\n" n
3333 failwithf "RConstString cannot be returned from a daemon function"
3335 pr " return ctx.ret.%s; /* caller will free */\n" n
3336 | RStringList n | RHashtable n ->
3337 pr " /* caller will free this, but we need to add a NULL entry */\n";
3338 pr " ctx.ret.%s.%s_val =\n" n n;
3339 pr " safe_realloc (g, ctx.ret.%s.%s_val,\n" n n;
3340 pr " sizeof (char *) * (ctx.ret.%s.%s_len + 1));\n"
3342 pr " ctx.ret.%s.%s_val[ctx.ret.%s.%s_len] = NULL;\n" n n n n;
3343 pr " return ctx.ret.%s.%s_val;\n" n n
3345 pr " /* caller with free this */\n";
3346 pr " return safe_memdup (g, &ctx.ret, sizeof (ctx.ret));\n"
3347 | RPVList n | RVGList n | RLVList n
3348 | RStat n | RStatVFS n ->
3349 pr " /* caller will free this */\n";
3350 pr " return safe_memdup (g, &ctx.ret.%s, sizeof (ctx.ret.%s));\n" n n
3356 (* Generate daemon/actions.h. *)
3357 and generate_daemon_actions_h () =
3358 generate_header CStyle GPLv2;
3360 pr "#include \"../src/guestfs_protocol.h\"\n";
3364 fun (name, style, _, _, _, _, _) ->
3366 ~single_line:true ~newline:true ~in_daemon:true ~prefix:"do_"
3370 (* Generate the server-side stubs. *)
3371 and generate_daemon_actions () =
3372 generate_header CStyle GPLv2;
3374 pr "#include <config.h>\n";
3376 pr "#include <stdio.h>\n";
3377 pr "#include <stdlib.h>\n";
3378 pr "#include <string.h>\n";
3379 pr "#include <inttypes.h>\n";
3380 pr "#include <ctype.h>\n";
3381 pr "#include <rpc/types.h>\n";
3382 pr "#include <rpc/xdr.h>\n";
3384 pr "#include \"daemon.h\"\n";
3385 pr "#include \"../src/guestfs_protocol.h\"\n";
3386 pr "#include \"actions.h\"\n";
3390 fun (name, style, _, _, _, _, _) ->
3391 (* Generate server-side stubs. *)
3392 pr "static void %s_stub (XDR *xdr_in)\n" name;
3395 match fst style with
3396 | RErr | RInt _ -> pr " int r;\n"; "-1"
3397 | RInt64 _ -> pr " int64_t r;\n"; "-1"
3398 | RBool _ -> pr " int r;\n"; "-1"
3400 failwithf "RConstString cannot be returned from a daemon function"
3401 | RString _ -> pr " char *r;\n"; "NULL"
3402 | RStringList _ | RHashtable _ -> pr " char **r;\n"; "NULL"
3403 | RIntBool _ -> pr " guestfs_%s_ret *r;\n" name; "NULL"
3404 | RPVList _ -> pr " guestfs_lvm_int_pv_list *r;\n"; "NULL"
3405 | RVGList _ -> pr " guestfs_lvm_int_vg_list *r;\n"; "NULL"
3406 | RLVList _ -> pr " guestfs_lvm_int_lv_list *r;\n"; "NULL"
3407 | RStat _ -> pr " guestfs_int_stat *r;\n"; "NULL"
3408 | RStatVFS _ -> pr " guestfs_int_statvfs *r;\n"; "NULL" in
3410 (match snd style with
3413 pr " struct guestfs_%s_args args;\n" name;
3417 | OptString n -> pr " const char *%s;\n" n
3418 | StringList n -> pr " char **%s;\n" n
3419 | Bool n -> pr " int %s;\n" n
3420 | Int n -> pr " int %s;\n" n
3421 | FileIn _ | FileOut _ -> ()
3426 (match snd style with
3429 pr " memset (&args, 0, sizeof args);\n";
3431 pr " if (!xdr_guestfs_%s_args (xdr_in, &args)) {\n" name;
3432 pr " reply_with_error (\"%%s: daemon failed to decode procedure arguments\", \"%s\");\n" name;
3437 | String n -> pr " %s = args.%s;\n" n n
3438 | OptString n -> pr " %s = args.%s ? *args.%s : NULL;\n" n n n
3440 pr " %s = realloc (args.%s.%s_val,\n" n n n;
3441 pr " sizeof (char *) * (args.%s.%s_len+1));\n" n n;
3442 pr " if (%s == NULL) {\n" n;
3443 pr " reply_with_perror (\"realloc\");\n";
3446 pr " %s[args.%s.%s_len] = NULL;\n" n n n;
3447 pr " args.%s.%s_val = %s;\n" n n n;
3448 | Bool n -> pr " %s = args.%s;\n" n n
3449 | Int n -> pr " %s = args.%s;\n" n n
3450 | FileIn _ | FileOut _ -> ()
3455 (* Don't want to call the impl with any FileIn or FileOut
3456 * parameters, since these go "outside" the RPC protocol.
3459 List.filter (function FileIn _ | FileOut _ -> false | _ -> true)
3461 pr " r = do_%s " name;
3462 generate_call_args argsnofile;
3465 pr " if (r == %s)\n" error_code;
3466 pr " /* do_%s has already called reply_with_error */\n" name;
3470 (* If there are any FileOut parameters, then the impl must
3471 * send its own reply.
3474 List.exists (function FileOut _ -> true | _ -> false) (snd style) in
3476 pr " /* do_%s has already sent a reply */\n" name
3478 match fst style with
3479 | RErr -> pr " reply (NULL, NULL);\n"
3480 | RInt n | RInt64 n | RBool n ->
3481 pr " struct guestfs_%s_ret ret;\n" name;
3482 pr " ret.%s = r;\n" n;
3483 pr " reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
3486 failwithf "RConstString cannot be returned from a daemon function"
3488 pr " struct guestfs_%s_ret ret;\n" name;
3489 pr " ret.%s = r;\n" n;
3490 pr " reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
3493 | RStringList n | RHashtable n ->
3494 pr " struct guestfs_%s_ret ret;\n" name;
3495 pr " ret.%s.%s_len = count_strings (r);\n" n n;
3496 pr " ret.%s.%s_val = r;\n" n n;
3497 pr " reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
3499 pr " free_strings (r);\n"
3501 pr " reply ((xdrproc_t) xdr_guestfs_%s_ret, (char *) r);\n"
3503 pr " xdr_free ((xdrproc_t) xdr_guestfs_%s_ret, (char *) r);\n" name
3504 | RPVList n | RVGList n | RLVList n
3505 | RStat n | RStatVFS n ->
3506 pr " struct guestfs_%s_ret ret;\n" name;
3507 pr " ret.%s = *r;\n" n;
3508 pr " reply ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
3510 pr " xdr_free ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
3514 (* Free the args. *)
3515 (match snd style with
3520 pr " xdr_free ((xdrproc_t) xdr_guestfs_%s_args, (char *) &args);\n"
3527 (* Dispatch function. *)
3528 pr "void dispatch_incoming_message (XDR *xdr_in)\n";
3530 pr " switch (proc_nr) {\n";
3533 fun (name, style, _, _, _, _, _) ->
3534 pr " case GUESTFS_PROC_%s:\n" (String.uppercase name);
3535 pr " %s_stub (xdr_in);\n" name;
3540 pr " reply_with_error (\"dispatch_incoming_message: unknown procedure number %%d\", proc_nr);\n";
3545 (* LVM columns and tokenization functions. *)
3546 (* XXX This generates crap code. We should rethink how we
3552 pr "static const char *lvm_%s_cols = \"%s\";\n"
3553 typ (String.concat "," (List.map fst cols));
3556 pr "static int lvm_tokenize_%s (char *str, struct guestfs_lvm_int_%s *r)\n" typ typ;
3558 pr " char *tok, *p, *next;\n";
3562 pr " fprintf (stderr, \"%%s: <<%%s>>\\n\", __func__, str);\n";
3565 pr " if (!str) {\n";
3566 pr " fprintf (stderr, \"%%s: failed: passed a NULL string\\n\", __func__);\n";
3569 pr " if (!*str || isspace (*str)) {\n";
3570 pr " fprintf (stderr, \"%%s: failed: passed a empty string or one beginning with whitespace\\n\", __func__);\n";
3575 fun (name, coltype) ->
3576 pr " if (!tok) {\n";
3577 pr " fprintf (stderr, \"%%s: failed: string finished early, around token %%s\\n\", __func__, \"%s\");\n" name;
3580 pr " p = strchrnul (tok, ',');\n";
3581 pr " if (*p) next = p+1; else next = NULL;\n";
3582 pr " *p = '\\0';\n";
3585 pr " r->%s = strdup (tok);\n" name;
3586 pr " if (r->%s == NULL) {\n" name;
3587 pr " perror (\"strdup\");\n";
3591 pr " for (i = j = 0; i < 32; ++j) {\n";
3592 pr " if (tok[j] == '\\0') {\n";
3593 pr " fprintf (stderr, \"%%s: failed to parse UUID from '%%s'\\n\", __func__, tok);\n";
3595 pr " } else if (tok[j] != '-')\n";
3596 pr " r->%s[i++] = tok[j];\n" name;
3599 pr " if (sscanf (tok, \"%%\"SCNu64, &r->%s) != 1) {\n" name;
3600 pr " fprintf (stderr, \"%%s: failed to parse size '%%s' from token %%s\\n\", __func__, tok, \"%s\");\n" name;
3604 pr " if (sscanf (tok, \"%%\"SCNi64, &r->%s) != 1) {\n" name;
3605 pr " fprintf (stderr, \"%%s: failed to parse int '%%s' from token %%s\\n\", __func__, tok, \"%s\");\n" name;
3609 pr " if (tok[0] == '\\0')\n";
3610 pr " r->%s = -1;\n" name;
3611 pr " else if (sscanf (tok, \"%%f\", &r->%s) != 1) {\n" name;
3612 pr " fprintf (stderr, \"%%s: failed to parse float '%%s' from token %%s\\n\", __func__, tok, \"%s\");\n" name;
3616 pr " tok = next;\n";
3619 pr " if (tok != NULL) {\n";
3620 pr " fprintf (stderr, \"%%s: failed: extra tokens at end of string\\n\", __func__);\n";
3627 pr "guestfs_lvm_int_%s_list *\n" typ;
3628 pr "parse_command_line_%ss (void)\n" typ;
3630 pr " char *out, *err;\n";
3631 pr " char *p, *pend;\n";
3633 pr " guestfs_lvm_int_%s_list *ret;\n" typ;
3634 pr " void *newp;\n";
3636 pr " ret = malloc (sizeof *ret);\n";
3637 pr " if (!ret) {\n";
3638 pr " reply_with_perror (\"malloc\");\n";
3639 pr " return NULL;\n";
3642 pr " ret->guestfs_lvm_int_%s_list_len = 0;\n" typ;
3643 pr " ret->guestfs_lvm_int_%s_list_val = NULL;\n" typ;
3645 pr " r = command (&out, &err,\n";
3646 pr " \"/sbin/lvm\", \"%ss\",\n" typ;
3647 pr " \"-o\", lvm_%s_cols, \"--unbuffered\", \"--noheadings\",\n" typ;
3648 pr " \"--nosuffix\", \"--separator\", \",\", \"--units\", \"b\", NULL);\n";
3649 pr " if (r == -1) {\n";
3650 pr " reply_with_error (\"%%s\", err);\n";
3651 pr " free (out);\n";
3652 pr " free (err);\n";
3653 pr " free (ret);\n";
3654 pr " return NULL;\n";
3657 pr " free (err);\n";
3659 pr " /* Tokenize each line of the output. */\n";
3662 pr " while (p) {\n";
3663 pr " pend = strchr (p, '\\n'); /* Get the next line of output. */\n";
3664 pr " if (pend) {\n";
3665 pr " *pend = '\\0';\n";
3669 pr " while (*p && isspace (*p)) /* Skip any leading whitespace. */\n";
3672 pr " if (!*p) { /* Empty line? Skip it. */\n";
3677 pr " /* Allocate some space to store this next entry. */\n";
3678 pr " newp = realloc (ret->guestfs_lvm_int_%s_list_val,\n" typ;
3679 pr " sizeof (guestfs_lvm_int_%s) * (i+1));\n" typ;
3680 pr " if (newp == NULL) {\n";
3681 pr " reply_with_perror (\"realloc\");\n";
3682 pr " free (ret->guestfs_lvm_int_%s_list_val);\n" typ;
3683 pr " free (ret);\n";
3684 pr " free (out);\n";
3685 pr " return NULL;\n";
3687 pr " ret->guestfs_lvm_int_%s_list_val = newp;\n" typ;
3689 pr " /* Tokenize the next entry. */\n";
3690 pr " r = lvm_tokenize_%s (p, &ret->guestfs_lvm_int_%s_list_val[i]);\n" typ typ;
3691 pr " if (r == -1) {\n";
3692 pr " reply_with_error (\"failed to parse output of '%ss' command\");\n" typ;
3693 pr " free (ret->guestfs_lvm_int_%s_list_val);\n" typ;
3694 pr " free (ret);\n";
3695 pr " free (out);\n";
3696 pr " return NULL;\n";
3703 pr " ret->guestfs_lvm_int_%s_list_len = i;\n" typ;
3705 pr " free (out);\n";
3706 pr " return ret;\n";
3709 ) ["pv", pv_cols; "vg", vg_cols; "lv", lv_cols]
3711 (* Generate the tests. *)
3712 and generate_tests () =
3713 generate_header CStyle GPLv2;
3720 #include <sys/types.h>
3723 #include \"guestfs.h\"
3725 static guestfs_h *g;
3726 static int suppress_error = 0;
3728 /* This will be 's' or 'h' depending on whether the guest kernel
3729 * names IDE devices /dev/sd* or /dev/hd*.
3731 static char devchar = 's';
3733 static void print_error (guestfs_h *g, void *data, const char *msg)
3735 if (!suppress_error)
3736 fprintf (stderr, \"%%s\\n\", msg);
3739 static void print_strings (char * const * const argv)
3743 for (argc = 0; argv[argc] != NULL; ++argc)
3744 printf (\"\\t%%s\\n\", argv[argc]);
3748 static void print_table (char * const * const argv)
3752 for (i = 0; argv[i] != NULL; i += 2)
3753 printf (\"%%s: %%s\\n\", argv[i], argv[i+1]);
3757 static void no_test_warnings (void)
3763 | name, _, _, _, [], _, _ ->
3764 pr " fprintf (stderr, \"warning: \\\"guestfs_%s\\\" has no tests\\n\");\n" name
3765 | name, _, _, _, tests, _, _ -> ()
3771 (* Generate the actual tests. Note that we generate the tests
3772 * in reverse order, deliberately, so that (in general) the
3773 * newest tests run first. This makes it quicker and easier to
3778 fun (name, _, _, _, tests, _, _) ->
3779 mapi (generate_one_test name) tests
3780 ) (List.rev all_functions) in
3781 let test_names = List.concat test_names in
3782 let nr_tests = List.length test_names in
3785 int main (int argc, char *argv[])
3790 const char *filename;
3792 int nr_tests, test_num = 0;
3795 no_test_warnings ();
3797 g = guestfs_create ();
3799 printf (\"guestfs_create FAILED\\n\");
3803 guestfs_set_error_handler (g, print_error, NULL);
3805 guestfs_set_path (g, \"../appliance\");
3807 filename = \"test1.img\";
3808 fd = open (filename, O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK|O_TRUNC, 0666);
3813 if (lseek (fd, %d, SEEK_SET) == -1) {
3819 if (write (fd, &c, 1) == -1) {
3825 if (close (fd) == -1) {
3830 if (guestfs_add_drive (g, filename) == -1) {
3831 printf (\"guestfs_add_drive %%s FAILED\\n\", filename);
3835 filename = \"test2.img\";
3836 fd = open (filename, O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK|O_TRUNC, 0666);
3841 if (lseek (fd, %d, SEEK_SET) == -1) {
3847 if (write (fd, &c, 1) == -1) {
3853 if (close (fd) == -1) {
3858 if (guestfs_add_drive (g, filename) == -1) {
3859 printf (\"guestfs_add_drive %%s FAILED\\n\", filename);
3863 filename = \"test3.img\";
3864 fd = open (filename, O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK|O_TRUNC, 0666);
3869 if (lseek (fd, %d, SEEK_SET) == -1) {
3875 if (write (fd, &c, 1) == -1) {
3881 if (close (fd) == -1) {
3886 if (guestfs_add_drive (g, filename) == -1) {
3887 printf (\"guestfs_add_drive %%s FAILED\\n\", filename);
3891 if (guestfs_launch (g) == -1) {
3892 printf (\"guestfs_launch FAILED\\n\");
3895 if (guestfs_wait_ready (g) == -1) {
3896 printf (\"guestfs_wait_ready FAILED\\n\");
3900 /* Detect if the appliance uses /dev/sd* or /dev/hd* in device
3901 * names. This changed between RHEL 5 and RHEL 6 so we have to
3904 devs = guestfs_list_devices (g);
3905 if (devs == NULL || devs[0] == NULL) {
3906 printf (\"guestfs_list_devices FAILED\\n\");
3909 if (strncmp (devs[0], \"/dev/sd\", 7) == 0)
3911 else if (strncmp (devs[0], \"/dev/hd\", 7) == 0)
3914 printf (\"guestfs_list_devices returned unexpected string '%%s'\\n\",
3918 for (i = 0; devs[i] != NULL; ++i)
3924 " (500 * 1024 * 1024) (50 * 1024 * 1024) (10 * 1024 * 1024) nr_tests;
3928 pr " test_num++;\n";
3929 pr " printf (\"%%3d/%%3d %s\\n\", test_num, nr_tests);\n" test_name;
3930 pr " if (%s () == -1) {\n" test_name;
3931 pr " printf (\"%s FAILED\\n\");\n" test_name;
3937 pr " guestfs_close (g);\n";
3938 pr " unlink (\"test1.img\");\n";
3939 pr " unlink (\"test2.img\");\n";
3940 pr " unlink (\"test3.img\");\n";
3943 pr " if (failed > 0) {\n";
3944 pr " printf (\"***** %%d / %%d tests FAILED *****\\n\", failed, nr_tests);\n";
3952 and generate_one_test name i (init, prereq, test) =
3953 let test_name = sprintf "test_%s_%d" name i in
3956 static int %s_skip (void)
3960 str = getenv (\"SKIP_%s\");
3961 if (str && strcmp (str, \"1\") == 0) return 1;
3962 str = getenv (\"SKIP_TEST_%s\");
3963 if (str && strcmp (str, \"1\") == 0) return 1;
3967 " test_name (String.uppercase test_name) (String.uppercase name);
3970 | Disabled | Always -> ()
3971 | If code | Unless code ->
3972 pr "static int %s_prereq (void)\n" test_name;
3980 static int %s (void)
3983 printf (\"%%s skipped (reason: SKIP_TEST_* variable set)\\n\", \"%s\");
3987 " test_name test_name test_name;
3991 pr " printf (\"%%s skipped (reason: test disabled in generator)\\n\", \"%s\");\n" test_name
3993 pr " if (! %s_prereq ()) {\n" test_name;
3994 pr " printf (\"%%s skipped (reason: test prerequisite)\\n\", \"%s\");\n" test_name;
3998 generate_one_test_body name i test_name init test;
4000 pr " if (%s_prereq ()) {\n" test_name;
4001 pr " printf (\"%%s skipped (reason: test prerequisite)\\n\", \"%s\");\n" test_name;
4005 generate_one_test_body name i test_name init test;
4007 generate_one_test_body name i test_name init test
4015 and generate_one_test_body name i test_name init test =
4019 pr " /* InitNone|InitEmpty for %s */\n" test_name;
4020 List.iter (generate_test_command_call test_name)
4021 [["blockdev_setrw"; "/dev/sda"];
4025 pr " /* InitBasicFS for %s: create ext2 on /dev/sda1 */\n" test_name;
4026 List.iter (generate_test_command_call test_name)
4027 [["blockdev_setrw"; "/dev/sda"];
4030 ["sfdisk"; "/dev/sda"; "0"; "0"; "0"; ","];
4031 ["mkfs"; "ext2"; "/dev/sda1"];
4032 ["mount"; "/dev/sda1"; "/"]]
4033 | InitBasicFSonLVM ->
4034 pr " /* InitBasicFSonLVM for %s: create ext2 on /dev/VG/LV */\n"
4036 List.iter (generate_test_command_call test_name)
4037 [["blockdev_setrw"; "/dev/sda"];
4040 ["sfdisk"; "/dev/sda"; "0"; "0"; "0"; ","];
4041 ["pvcreate"; "/dev/sda1"];
4042 ["vgcreate"; "VG"; "/dev/sda1"];
4043 ["lvcreate"; "LV"; "VG"; "8"];
4044 ["mkfs"; "ext2"; "/dev/VG/LV"];
4045 ["mount"; "/dev/VG/LV"; "/"]]
4048 let get_seq_last = function
4050 failwithf "%s: you cannot use [] (empty list) when expecting a command"
4053 let seq = List.rev seq in
4054 List.rev (List.tl seq), List.hd seq
4059 pr " /* TestRun for %s (%d) */\n" name i;
4060 List.iter (generate_test_command_call test_name) seq
4061 | TestOutput (seq, expected) ->
4062 pr " /* TestOutput for %s (%d) */\n" name i;
4063 pr " char expected[] = \"%s\";\n" (c_quote expected);
4064 if String.length expected > 7 &&
4065 String.sub expected 0 7 = "/dev/sd" then
4066 pr " expected[5] = devchar;\n";
4067 let seq, last = get_seq_last seq in
4069 pr " if (strcmp (r, expected) != 0) {\n";
4070 pr " fprintf (stderr, \"%s: expected \\\"%%s\\\" but got \\\"%%s\\\"\\n\", expected, r);\n" test_name;
4074 List.iter (generate_test_command_call test_name) seq;
4075 generate_test_command_call ~test test_name last
4076 | TestOutputList (seq, expected) ->
4077 pr " /* TestOutputList for %s (%d) */\n" name i;
4078 let seq, last = get_seq_last seq in
4082 pr " if (!r[%d]) {\n" i;
4083 pr " fprintf (stderr, \"%s: short list returned from command\\n\");\n" test_name;
4084 pr " print_strings (r);\n";
4088 pr " char expected[] = \"%s\";\n" (c_quote str);
4089 if String.length str > 7 && String.sub str 0 7 = "/dev/sd" then
4090 pr " expected[5] = devchar;\n";
4091 pr " if (strcmp (r[%d], expected) != 0) {\n" i;
4092 pr " fprintf (stderr, \"%s: expected \\\"%%s\\\" but got \\\"%%s\\\"\\n\", expected, r[%d]);\n" test_name i;
4097 pr " if (r[%d] != NULL) {\n" (List.length expected);
4098 pr " fprintf (stderr, \"%s: extra elements returned from command\\n\");\n"
4100 pr " print_strings (r);\n";
4104 List.iter (generate_test_command_call test_name) seq;
4105 generate_test_command_call ~test test_name last
4106 | TestOutputInt (seq, expected) ->
4107 pr " /* TestOutputInt for %s (%d) */\n" name i;
4108 let seq, last = get_seq_last seq in
4110 pr " if (r != %d) {\n" expected;
4111 pr " fprintf (stderr, \"%s: expected %d but got %%d\\n\","
4117 List.iter (generate_test_command_call test_name) seq;
4118 generate_test_command_call ~test test_name last
4119 | TestOutputTrue seq ->
4120 pr " /* TestOutputTrue for %s (%d) */\n" name i;
4121 let seq, last = get_seq_last seq in
4124 pr " fprintf (stderr, \"%s: expected true, got false\\n\");\n"
4129 List.iter (generate_test_command_call test_name) seq;
4130 generate_test_command_call ~test test_name last
4131 | TestOutputFalse seq ->
4132 pr " /* TestOutputFalse for %s (%d) */\n" name i;
4133 let seq, last = get_seq_last seq in
4136 pr " fprintf (stderr, \"%s: expected false, got true\\n\");\n"
4141 List.iter (generate_test_command_call test_name) seq;
4142 generate_test_command_call ~test test_name last
4143 | TestOutputLength (seq, expected) ->
4144 pr " /* TestOutputLength for %s (%d) */\n" name i;
4145 let seq, last = get_seq_last seq in
4148 pr " for (j = 0; j < %d; ++j)\n" expected;
4149 pr " if (r[j] == NULL) {\n";
4150 pr " fprintf (stderr, \"%s: short list returned\\n\");\n"
4152 pr " print_strings (r);\n";
4155 pr " if (r[j] != NULL) {\n";
4156 pr " fprintf (stderr, \"%s: long list returned\\n\");\n"
4158 pr " print_strings (r);\n";
4162 List.iter (generate_test_command_call test_name) seq;
4163 generate_test_command_call ~test test_name last
4164 | TestOutputStruct (seq, checks) ->
4165 pr " /* TestOutputStruct for %s (%d) */\n" name i;
4166 let seq, last = get_seq_last seq in
4170 | CompareWithInt (field, expected) ->
4171 pr " if (r->%s != %d) {\n" field expected;
4172 pr " fprintf (stderr, \"%s: %s was %%d, expected %d\\n\",\n"
4173 test_name field expected;
4174 pr " (int) r->%s);\n" field;
4177 | CompareWithString (field, expected) ->
4178 pr " if (strcmp (r->%s, \"%s\") != 0) {\n" field expected;
4179 pr " fprintf (stderr, \"%s: %s was \"%%s\", expected \"%s\"\\n\",\n"
4180 test_name field expected;
4181 pr " r->%s);\n" field;
4184 | CompareFieldsIntEq (field1, field2) ->
4185 pr " if (r->%s != r->%s) {\n" field1 field2;
4186 pr " fprintf (stderr, \"%s: %s (%%d) <> %s (%%d)\\n\",\n"
4187 test_name field1 field2;
4188 pr " (int) r->%s, (int) r->%s);\n" field1 field2;
4191 | CompareFieldsStrEq (field1, field2) ->
4192 pr " if (strcmp (r->%s, r->%s) != 0) {\n" field1 field2;
4193 pr " fprintf (stderr, \"%s: %s (\"%%s\") <> %s (\"%%s\")\\n\",\n"
4194 test_name field1 field2;
4195 pr " r->%s, r->%s);\n" field1 field2;
4200 List.iter (generate_test_command_call test_name) seq;
4201 generate_test_command_call ~test test_name last
4202 | TestLastFail seq ->
4203 pr " /* TestLastFail for %s (%d) */\n" name i;
4204 let seq, last = get_seq_last seq in
4205 List.iter (generate_test_command_call test_name) seq;
4206 generate_test_command_call test_name ~expect_error:true last
4208 (* Generate the code to run a command, leaving the result in 'r'.
4209 * If you expect to get an error then you should set expect_error:true.
4211 and generate_test_command_call ?(expect_error = false) ?test test_name cmd =
4213 | [] -> assert false
4215 (* Look up the command to find out what args/ret it has. *)
4218 let _, style, _, _, _, _, _ =
4219 List.find (fun (n, _, _, _, _, _, _) -> n = name) all_functions in
4222 failwithf "%s: in test, command %s was not found" test_name name in
4224 if List.length (snd style) <> List.length args then
4225 failwithf "%s: in test, wrong number of args given to %s"
4232 | OptString n, "NULL" -> ()
4234 | OptString n, arg ->
4235 pr " char %s[] = \"%s\";\n" n (c_quote arg);
4236 if String.length arg > 7 && String.sub arg 0 7 = "/dev/sd" then
4237 pr " %s[5] = devchar;\n" n
4240 | FileIn _, _ | FileOut _, _ -> ()
4241 | StringList n, arg ->
4242 let strs = string_split " " arg in
4245 pr " char %s_%d[] = \"%s\";\n" n i (c_quote str);
4246 if String.length str > 7 && String.sub str 0 7 = "/dev/sd" then
4247 pr " %s_%d[5] = devchar;\n" n i
4249 pr " char *%s[] = {\n" n;
4251 fun i _ -> pr " %s_%d,\n" n i
4255 ) (List.combine (snd style) args);
4258 match fst style with
4259 | RErr | RInt _ | RBool _ -> pr " int r;\n"; "-1"
4260 | RInt64 _ -> pr " int64_t r;\n"; "-1"
4261 | RConstString _ -> pr " const char *r;\n"; "NULL"
4262 | RString _ -> pr " char *r;\n"; "NULL"
4263 | RStringList _ | RHashtable _ ->
4268 pr " struct guestfs_int_bool *r;\n"; "NULL"
4270 pr " struct guestfs_lvm_pv_list *r;\n"; "NULL"
4272 pr " struct guestfs_lvm_vg_list *r;\n"; "NULL"
4274 pr " struct guestfs_lvm_lv_list *r;\n"; "NULL"
4276 pr " struct guestfs_stat *r;\n"; "NULL"
4278 pr " struct guestfs_statvfs *r;\n"; "NULL" in
4280 pr " suppress_error = %d;\n" (if expect_error then 1 else 0);
4281 pr " r = guestfs_%s (g" name;
4283 (* Generate the parameters. *)
4286 | OptString _, "NULL" -> pr ", NULL"
4290 | FileIn _, arg | FileOut _, arg ->
4291 pr ", \"%s\"" (c_quote arg)
4292 | StringList n, _ ->
4296 try int_of_string arg
4297 with Failure "int_of_string" ->
4298 failwithf "%s: expecting an int, but got '%s'" test_name arg in
4301 let b = bool_of_string arg in pr ", %d" (if b then 1 else 0)
4302 ) (List.combine (snd style) args);
4305 if not expect_error then
4306 pr " if (r == %s)\n" error_code
4308 pr " if (r != %s)\n" error_code;
4311 (* Insert the test code. *)
4317 (match fst style with
4318 | RErr | RInt _ | RInt64 _ | RBool _ | RConstString _ -> ()
4319 | RString _ -> pr " free (r);\n"
4320 | RStringList _ | RHashtable _ ->
4321 pr " for (i = 0; r[i] != NULL; ++i)\n";
4322 pr " free (r[i]);\n";
4325 pr " guestfs_free_int_bool (r);\n"
4327 pr " guestfs_free_lvm_pv_list (r);\n"
4329 pr " guestfs_free_lvm_vg_list (r);\n"
4331 pr " guestfs_free_lvm_lv_list (r);\n"
4332 | RStat _ | RStatVFS _ ->
4339 let str = replace_str str "\r" "\\r" in
4340 let str = replace_str str "\n" "\\n" in
4341 let str = replace_str str "\t" "\\t" in
4342 let str = replace_str str "\000" "\\0" in
4345 (* Generate a lot of different functions for guestfish. *)
4346 and generate_fish_cmds () =
4347 generate_header CStyle GPLv2;
4351 fun (_, _, _, flags, _, _, _) -> not (List.mem NotInFish flags)
4353 let all_functions_sorted =
4355 fun (_, _, _, flags, _, _, _) -> not (List.mem NotInFish flags)
4356 ) all_functions_sorted in
4358 pr "#include <stdio.h>\n";
4359 pr "#include <stdlib.h>\n";
4360 pr "#include <string.h>\n";
4361 pr "#include <inttypes.h>\n";
4363 pr "#include <guestfs.h>\n";
4364 pr "#include \"fish.h\"\n";
4367 (* list_commands function, which implements guestfish -h *)
4368 pr "void list_commands (void)\n";
4370 pr " printf (\" %%-16s %%s\\n\", \"Command\", \"Description\");\n";
4371 pr " list_builtin_commands ();\n";
4373 fun (name, _, _, flags, _, shortdesc, _) ->
4374 let name = replace_char name '_' '-' in
4375 pr " printf (\"%%-20s %%s\\n\", \"%s\", \"%s\");\n"
4377 ) all_functions_sorted;
4378 pr " printf (\" Use -h <cmd> / help <cmd> to show detailed help for a command.\\n\");\n";
4382 (* display_command function, which implements guestfish -h cmd *)
4383 pr "void display_command (const char *cmd)\n";
4386 fun (name, style, _, flags, _, shortdesc, longdesc) ->
4387 let name2 = replace_char name '_' '-' in
4389 try find_map (function FishAlias n -> Some n | _ -> None) flags
4390 with Not_found -> name in
4391 let longdesc = replace_str longdesc "C<guestfs_" "C<" in
4393 match snd style with
4397 name2 (String.concat "> <" (List.map name_of_argt args)) in
4400 if List.mem ProtocolLimitWarning flags then
4401 ("\n\n" ^ protocol_limit_warning)
4404 (* For DangerWillRobinson commands, we should probably have
4405 * guestfish prompt before allowing you to use them (especially
4406 * in interactive mode). XXX
4410 if List.mem DangerWillRobinson flags then
4411 ("\n\n" ^ danger_will_robinson)
4414 let describe_alias =
4415 if name <> alias then
4416 sprintf "\n\nYou can use '%s' as an alias for this command." alias
4420 pr "strcasecmp (cmd, \"%s\") == 0" name;
4421 if name <> name2 then
4422 pr " || strcasecmp (cmd, \"%s\") == 0" name2;
4423 if name <> alias then
4424 pr " || strcasecmp (cmd, \"%s\") == 0" alias;
4426 pr " pod2text (\"%s - %s\", %S);\n"
4428 (" " ^ synopsis ^ "\n\n" ^ longdesc ^ warnings ^ describe_alias);
4431 pr " display_builtin_command (cmd);\n";
4435 (* print_{pv,vg,lv}_list functions *)
4439 pr "static void print_%s (struct guestfs_lvm_%s *%s)\n" typ typ typ;
4446 pr " printf (\"%s: %%s\\n\", %s->%s);\n" name typ name
4448 pr " printf (\"%s: \");\n" name;
4449 pr " for (i = 0; i < 32; ++i)\n";
4450 pr " printf (\"%%c\", %s->%s[i]);\n" typ name;
4451 pr " printf (\"\\n\");\n"
4453 pr " printf (\"%s: %%\" PRIu64 \"\\n\", %s->%s);\n" name typ name
4455 pr " printf (\"%s: %%\" PRIi64 \"\\n\", %s->%s);\n" name typ name
4456 | name, `OptPercent ->
4457 pr " if (%s->%s >= 0) printf (\"%s: %%g %%%%\\n\", %s->%s);\n"
4458 typ name name typ name;
4459 pr " else printf (\"%s: \\n\");\n" name
4463 pr "static void print_%s_list (struct guestfs_lvm_%s_list *%ss)\n"
4468 pr " for (i = 0; i < %ss->len; ++i)\n" typ;
4469 pr " print_%s (&%ss->val[i]);\n" typ typ;
4472 ) ["pv", pv_cols; "vg", vg_cols; "lv", lv_cols];
4474 (* print_{stat,statvfs} functions *)
4478 pr "static void print_%s (struct guestfs_%s *%s)\n" typ typ typ;
4483 pr " printf (\"%s: %%\" PRIi64 \"\\n\", %s->%s);\n" name typ name
4487 ) ["stat", stat_cols; "statvfs", statvfs_cols];
4489 (* run_<action> actions *)
4491 fun (name, style, _, flags, _, _, _) ->
4492 pr "static int run_%s (const char *cmd, int argc, char *argv[])\n" name;
4494 (match fst style with
4497 | RBool _ -> pr " int r;\n"
4498 | RInt64 _ -> pr " int64_t r;\n"
4499 | RConstString _ -> pr " const char *r;\n"
4500 | RString _ -> pr " char *r;\n"
4501 | RStringList _ | RHashtable _ -> pr " char **r;\n"
4502 | RIntBool _ -> pr " struct guestfs_int_bool *r;\n"
4503 | RPVList _ -> pr " struct guestfs_lvm_pv_list *r;\n"
4504 | RVGList _ -> pr " struct guestfs_lvm_vg_list *r;\n"
4505 | RLVList _ -> pr " struct guestfs_lvm_lv_list *r;\n"
4506 | RStat _ -> pr " struct guestfs_stat *r;\n"
4507 | RStatVFS _ -> pr " struct guestfs_statvfs *r;\n"
4514 | FileOut n -> pr " const char *%s;\n" n
4515 | StringList n -> pr " char **%s;\n" n
4516 | Bool n -> pr " int %s;\n" n
4517 | Int n -> pr " int %s;\n" n
4520 (* Check and convert parameters. *)
4521 let argc_expected = List.length (snd style) in
4522 pr " if (argc != %d) {\n" argc_expected;
4523 pr " fprintf (stderr, \"%%s should have %d parameter(s)\\n\", cmd);\n"
4525 pr " fprintf (stderr, \"type 'help %%s' for help on %%s\\n\", cmd, cmd);\n";
4531 | String name -> pr " %s = argv[%d];\n" name i
4533 pr " %s = strcmp (argv[%d], \"\") != 0 ? argv[%d] : NULL;\n"
4536 pr " %s = strcmp (argv[%d], \"-\") != 0 ? argv[%d] : \"/dev/stdin\";\n"
4539 pr " %s = strcmp (argv[%d], \"-\") != 0 ? argv[%d] : \"/dev/stdout\";\n"
4541 | StringList name ->
4542 pr " %s = parse_string_list (argv[%d]);\n" name i
4544 pr " %s = is_true (argv[%d]) ? 1 : 0;\n" name i
4546 pr " %s = atoi (argv[%d]);\n" name i
4549 (* Call C API function. *)
4551 try find_map (function FishAction n -> Some n | _ -> None) flags
4552 with Not_found -> sprintf "guestfs_%s" name in
4554 generate_call_args ~handle:"g" (snd style);
4557 (* Check return value for errors and display command results. *)
4558 (match fst style with
4559 | RErr -> pr " return r;\n"
4561 pr " if (r == -1) return -1;\n";
4562 pr " printf (\"%%d\\n\", r);\n";
4565 pr " if (r == -1) return -1;\n";
4566 pr " printf (\"%%\" PRIi64 \"\\n\", r);\n";
4569 pr " if (r == -1) return -1;\n";
4570 pr " if (r) printf (\"true\\n\"); else printf (\"false\\n\");\n";
4573 pr " if (r == NULL) return -1;\n";
4574 pr " printf (\"%%s\\n\", r);\n";
4577 pr " if (r == NULL) return -1;\n";
4578 pr " printf (\"%%s\\n\", r);\n";
4582 pr " if (r == NULL) return -1;\n";
4583 pr " print_strings (r);\n";
4584 pr " free_strings (r);\n";
4587 pr " if (r == NULL) return -1;\n";
4588 pr " printf (\"%%d, %%s\\n\", r->i,\n";
4589 pr " r->b ? \"true\" : \"false\");\n";
4590 pr " guestfs_free_int_bool (r);\n";
4593 pr " if (r == NULL) return -1;\n";
4594 pr " print_pv_list (r);\n";
4595 pr " guestfs_free_lvm_pv_list (r);\n";
4598 pr " if (r == NULL) return -1;\n";
4599 pr " print_vg_list (r);\n";
4600 pr " guestfs_free_lvm_vg_list (r);\n";
4603 pr " if (r == NULL) return -1;\n";
4604 pr " print_lv_list (r);\n";
4605 pr " guestfs_free_lvm_lv_list (r);\n";
4608 pr " if (r == NULL) return -1;\n";
4609 pr " print_stat (r);\n";
4613 pr " if (r == NULL) return -1;\n";
4614 pr " print_statvfs (r);\n";
4618 pr " if (r == NULL) return -1;\n";
4619 pr " print_table (r);\n";
4620 pr " free_strings (r);\n";
4627 (* run_action function *)
4628 pr "int run_action (const char *cmd, int argc, char *argv[])\n";
4631 fun (name, _, _, flags, _, _, _) ->
4632 let name2 = replace_char name '_' '-' in
4634 try find_map (function FishAlias n -> Some n | _ -> None) flags
4635 with Not_found -> name in
4637 pr "strcasecmp (cmd, \"%s\") == 0" name;
4638 if name <> name2 then
4639 pr " || strcasecmp (cmd, \"%s\") == 0" name2;
4640 if name <> alias then
4641 pr " || strcasecmp (cmd, \"%s\") == 0" alias;
4643 pr " return run_%s (cmd, argc, argv);\n" name;
4647 pr " fprintf (stderr, \"%%s: unknown command\\n\", cmd);\n";
4654 (* Readline completion for guestfish. *)
4655 and generate_fish_completion () =
4656 generate_header CStyle GPLv2;
4660 fun (_, _, _, flags, _, _, _) -> not (List.mem NotInFish flags)
4670 #ifdef HAVE_LIBREADLINE
4671 #include <readline/readline.h>
4676 #ifdef HAVE_LIBREADLINE
4678 static const char *const commands[] = {
4679 BUILTIN_COMMANDS_FOR_COMPLETION,
4682 (* Get the commands, including the aliases. They don't need to be
4683 * sorted - the generator() function just does a dumb linear search.
4687 fun (name, _, _, flags, _, _, _) ->
4688 let name2 = replace_char name '_' '-' in
4690 try find_map (function FishAlias n -> Some n | _ -> None) flags
4691 with Not_found -> name in
4693 if name <> alias then [name2; alias] else [name2]
4695 let commands = List.flatten commands in
4697 List.iter (pr " \"%s\",\n") commands;
4703 generator (const char *text, int state)
4705 static int index, len;
4710 len = strlen (text);
4713 while ((name = commands[index]) != NULL) {
4715 if (strncasecmp (name, text, len) == 0)
4716 return strdup (name);
4722 #endif /* HAVE_LIBREADLINE */
4724 char **do_completion (const char *text, int start, int end)
4726 char **matches = NULL;
4728 #ifdef HAVE_LIBREADLINE
4730 matches = rl_completion_matches (text, generator);
4737 (* Generate the POD documentation for guestfish. *)
4738 and generate_fish_actions_pod () =
4739 let all_functions_sorted =
4741 fun (_, _, _, flags, _, _, _) ->
4742 not (List.mem NotInFish flags || List.mem NotInDocs flags)
4743 ) all_functions_sorted in
4745 let rex = Str.regexp "C<guestfs_\\([^>]+\\)>" in
4748 fun (name, style, _, flags, _, _, longdesc) ->
4750 Str.global_substitute rex (
4753 try Str.matched_group 1 s
4755 failwithf "error substituting C<guestfs_...> in longdesc of function %s" name in
4756 "C<" ^ replace_char sub '_' '-' ^ ">"
4758 let name = replace_char name '_' '-' in
4760 try find_map (function FishAlias n -> Some n | _ -> None) flags
4761 with Not_found -> name in
4763 pr "=head2 %s" name;
4764 if name <> alias then
4771 | String n -> pr " %s" n
4772 | OptString n -> pr " %s" n
4773 | StringList n -> pr " '%s ...'" n
4774 | Bool _ -> pr " true|false"
4775 | Int n -> pr " %s" n
4776 | FileIn n | FileOut n -> pr " (%s|-)" n
4780 pr "%s\n\n" longdesc;
4782 if List.exists (function FileIn _ | FileOut _ -> true
4783 | _ -> false) (snd style) then
4784 pr "Use C<-> instead of a filename to read/write from stdin/stdout.\n\n";
4786 if List.mem ProtocolLimitWarning flags then
4787 pr "%s\n\n" protocol_limit_warning;
4789 if List.mem DangerWillRobinson flags then
4790 pr "%s\n\n" danger_will_robinson
4791 ) all_functions_sorted
4793 (* Generate a C function prototype. *)
4794 and generate_prototype ?(extern = true) ?(static = false) ?(semicolon = true)
4795 ?(single_line = false) ?(newline = false) ?(in_daemon = false)
4797 ?handle name style =
4798 if extern then pr "extern ";
4799 if static then pr "static ";
4800 (match fst style with
4802 | RInt _ -> pr "int "
4803 | RInt64 _ -> pr "int64_t "
4804 | RBool _ -> pr "int "
4805 | RConstString _ -> pr "const char *"
4806 | RString _ -> pr "char *"
4807 | RStringList _ | RHashtable _ -> pr "char **"
4809 if not in_daemon then pr "struct guestfs_int_bool *"
4810 else pr "guestfs_%s_ret *" name
4812 if not in_daemon then pr "struct guestfs_lvm_pv_list *"
4813 else pr "guestfs_lvm_int_pv_list *"
4815 if not in_daemon then pr "struct guestfs_lvm_vg_list *"
4816 else pr "guestfs_lvm_int_vg_list *"
4818 if not in_daemon then pr "struct guestfs_lvm_lv_list *"
4819 else pr "guestfs_lvm_int_lv_list *"
4821 if not in_daemon then pr "struct guestfs_stat *"
4822 else pr "guestfs_int_stat *"
4824 if not in_daemon then pr "struct guestfs_statvfs *"
4825 else pr "guestfs_int_statvfs *"
4827 pr "%s%s (" prefix name;
4828 if handle = None && List.length (snd style) = 0 then
4831 let comma = ref false in
4834 | Some handle -> pr "guestfs_h *%s" handle; comma := true
4838 if single_line then pr ", " else pr ",\n\t\t"
4845 | OptString n -> next (); pr "const char *%s" n
4846 | StringList n -> next (); pr "char * const* const %s" n
4847 | Bool n -> next (); pr "int %s" n
4848 | Int n -> next (); pr "int %s" n
4851 if not in_daemon then (next (); pr "const char *%s" n)
4855 if semicolon then pr ";";
4856 if newline then pr "\n"
4858 (* Generate C call arguments, eg "(handle, foo, bar)" *)
4859 and generate_call_args ?handle args =
4861 let comma = ref false in
4864 | Some handle -> pr "%s" handle; comma := true
4868 if !comma then pr ", ";
4870 pr "%s" (name_of_argt arg)
4874 (* Generate the OCaml bindings interface. *)
4875 and generate_ocaml_mli () =
4876 generate_header OCamlStyle LGPLv2;
4879 (** For API documentation you should refer to the C API
4880 in the guestfs(3) manual page. The OCaml API uses almost
4881 exactly the same calls. *)
4884 (** A [guestfs_h] handle. *)
4886 exception Error of string
4887 (** This exception is raised when there is an error. *)
4889 val create : unit -> t
4891 val close : t -> unit
4892 (** Handles are closed by the garbage collector when they become
4893 unreferenced, but callers can also call this in order to
4894 provide predictable cleanup. *)
4897 generate_ocaml_lvm_structure_decls ();
4899 generate_ocaml_stat_structure_decls ();
4903 fun (name, style, _, _, _, shortdesc, _) ->
4904 generate_ocaml_prototype name style;
4905 pr "(** %s *)\n" shortdesc;
4909 (* Generate the OCaml bindings implementation. *)
4910 and generate_ocaml_ml () =
4911 generate_header OCamlStyle LGPLv2;
4915 exception Error of string
4916 external create : unit -> t = \"ocaml_guestfs_create\"
4917 external close : t -> unit = \"ocaml_guestfs_close\"
4920 Callback.register_exception \"ocaml_guestfs_error\" (Error \"\")
4924 generate_ocaml_lvm_structure_decls ();
4926 generate_ocaml_stat_structure_decls ();
4930 fun (name, style, _, _, _, shortdesc, _) ->
4931 generate_ocaml_prototype ~is_external:true name style;
4934 (* Generate the OCaml bindings C implementation. *)
4935 and generate_ocaml_c () =
4936 generate_header CStyle LGPLv2;
4943 #include <caml/config.h>
4944 #include <caml/alloc.h>
4945 #include <caml/callback.h>
4946 #include <caml/fail.h>
4947 #include <caml/memory.h>
4948 #include <caml/mlvalues.h>
4949 #include <caml/signals.h>
4951 #include <guestfs.h>
4953 #include \"guestfs_c.h\"
4955 /* Copy a hashtable of string pairs into an assoc-list. We return
4956 * the list in reverse order, but hashtables aren't supposed to be
4959 static CAMLprim value
4960 copy_table (char * const * argv)
4963 CAMLlocal5 (rv, pairv, kv, vv, cons);
4967 for (i = 0; argv[i] != NULL; i += 2) {
4968 kv = caml_copy_string (argv[i]);
4969 vv = caml_copy_string (argv[i+1]);
4970 pairv = caml_alloc (2, 0);
4971 Store_field (pairv, 0, kv);
4972 Store_field (pairv, 1, vv);
4973 cons = caml_alloc (2, 0);
4974 Store_field (cons, 1, rv);
4976 Store_field (cons, 0, pairv);
4984 (* LVM struct copy functions. *)
4987 let has_optpercent_col =
4988 List.exists (function (_, `OptPercent) -> true | _ -> false) cols in
4990 pr "static CAMLprim value\n";
4991 pr "copy_lvm_%s (const struct guestfs_lvm_%s *%s)\n" typ typ typ;
4993 pr " CAMLparam0 ();\n";
4994 if has_optpercent_col then
4995 pr " CAMLlocal3 (rv, v, v2);\n"
4997 pr " CAMLlocal2 (rv, v);\n";
4999 pr " rv = caml_alloc (%d, 0);\n" (List.length cols);
5004 pr " v = caml_copy_string (%s->%s);\n" typ name
5006 pr " v = caml_alloc_string (32);\n";
5007 pr " memcpy (String_val (v), %s->%s, 32);\n" typ name
5010 pr " v = caml_copy_int64 (%s->%s);\n" typ name
5011 | name, `OptPercent ->
5012 pr " if (%s->%s >= 0) { /* Some %s */\n" typ name name;
5013 pr " v2 = caml_copy_double (%s->%s);\n" typ name;
5014 pr " v = caml_alloc (1, 0);\n";
5015 pr " Store_field (v, 0, v2);\n";
5016 pr " } else /* None */\n";
5017 pr " v = Val_int (0);\n";
5019 pr " Store_field (rv, %d, v);\n" i
5021 pr " CAMLreturn (rv);\n";
5025 pr "static CAMLprim value\n";
5026 pr "copy_lvm_%s_list (const struct guestfs_lvm_%s_list *%ss)\n"
5029 pr " CAMLparam0 ();\n";
5030 pr " CAMLlocal2 (rv, v);\n";
5033 pr " if (%ss->len == 0)\n" typ;
5034 pr " CAMLreturn (Atom (0));\n";
5036 pr " rv = caml_alloc (%ss->len, 0);\n" typ;
5037 pr " for (i = 0; i < %ss->len; ++i) {\n" typ;
5038 pr " v = copy_lvm_%s (&%ss->val[i]);\n" typ typ;
5039 pr " caml_modify (&Field (rv, i), v);\n";
5041 pr " CAMLreturn (rv);\n";
5045 ) ["pv", pv_cols; "vg", vg_cols; "lv", lv_cols];
5047 (* Stat copy functions. *)
5050 pr "static CAMLprim value\n";
5051 pr "copy_%s (const struct guestfs_%s *%s)\n" typ typ typ;
5053 pr " CAMLparam0 ();\n";
5054 pr " CAMLlocal2 (rv, v);\n";
5056 pr " rv = caml_alloc (%d, 0);\n" (List.length cols);
5061 pr " v = caml_copy_int64 (%s->%s);\n" typ name
5063 pr " Store_field (rv, %d, v);\n" i
5065 pr " CAMLreturn (rv);\n";
5068 ) ["stat", stat_cols; "statvfs", statvfs_cols];
5072 fun (name, style, _, _, _, _, _) ->
5074 "gv" :: List.map (fun arg -> name_of_argt arg ^ "v") (snd style) in
5076 pr "CAMLprim value\n";
5077 pr "ocaml_guestfs_%s (value %s" name (List.hd params);
5078 List.iter (pr ", value %s") (List.tl params);
5083 | [p1; p2; p3; p4; p5] ->
5084 pr " CAMLparam5 (%s);\n" (String.concat ", " params)
5085 | p1 :: p2 :: p3 :: p4 :: p5 :: rest ->
5086 pr " CAMLparam5 (%s);\n" (String.concat ", " [p1; p2; p3; p4; p5]);
5087 pr " CAMLxparam%d (%s);\n"
5088 (List.length rest) (String.concat ", " rest)
5090 pr " CAMLparam%d (%s);\n" (List.length ps) (String.concat ", " ps)
5092 pr " CAMLlocal1 (rv);\n";
5095 pr " guestfs_h *g = Guestfs_val (gv);\n";
5096 pr " if (g == NULL)\n";
5097 pr " caml_failwith (\"%s: used handle after closing it\");\n" name;
5105 pr " const char *%s = String_val (%sv);\n" n n
5107 pr " const char *%s =\n" n;
5108 pr " %sv != Val_int (0) ? String_val (Field (%sv, 0)) : NULL;\n"
5111 pr " char **%s = ocaml_guestfs_strings_val (g, %sv);\n" n n
5113 pr " int %s = Bool_val (%sv);\n" n n
5115 pr " int %s = Int_val (%sv);\n" n n
5118 match fst style with
5119 | RErr -> pr " int r;\n"; "-1"
5120 | RInt _ -> pr " int r;\n"; "-1"
5121 | RInt64 _ -> pr " int64_t r;\n"; "-1"
5122 | RBool _ -> pr " int r;\n"; "-1"
5123 | RConstString _ -> pr " const char *r;\n"; "NULL"
5124 | RString _ -> pr " char *r;\n"; "NULL"
5130 pr " struct guestfs_int_bool *r;\n"; "NULL"
5132 pr " struct guestfs_lvm_pv_list *r;\n"; "NULL"
5134 pr " struct guestfs_lvm_vg_list *r;\n"; "NULL"
5136 pr " struct guestfs_lvm_lv_list *r;\n"; "NULL"
5138 pr " struct guestfs_stat *r;\n"; "NULL"
5140 pr " struct guestfs_statvfs *r;\n"; "NULL"
5147 pr " caml_enter_blocking_section ();\n";
5148 pr " r = guestfs_%s " name;
5149 generate_call_args ~handle:"g" (snd style);
5151 pr " caml_leave_blocking_section ();\n";
5156 pr " ocaml_guestfs_free_strings (%s);\n" n;
5157 | String _ | OptString _ | Bool _ | Int _ | FileIn _ | FileOut _ -> ()
5160 pr " if (r == %s)\n" error_code;
5161 pr " ocaml_guestfs_raise_error (g, \"%s\");\n" name;
5164 (match fst style with
5165 | RErr -> pr " rv = Val_unit;\n"
5166 | RInt _ -> pr " rv = Val_int (r);\n"
5168 pr " rv = caml_copy_int64 (r);\n"
5169 | RBool _ -> pr " rv = Val_bool (r);\n"
5170 | RConstString _ -> pr " rv = caml_copy_string (r);\n"
5172 pr " rv = caml_copy_string (r);\n";
5175 pr " rv = caml_copy_string_array ((const char **) r);\n";
5176 pr " for (i = 0; r[i] != NULL; ++i) free (r[i]);\n";
5179 pr " rv = caml_alloc (2, 0);\n";
5180 pr " Store_field (rv, 0, Val_int (r->i));\n";
5181 pr " Store_field (rv, 1, Val_bool (r->b));\n";
5182 pr " guestfs_free_int_bool (r);\n";
5184 pr " rv = copy_lvm_pv_list (r);\n";
5185 pr " guestfs_free_lvm_pv_list (r);\n";
5187 pr " rv = copy_lvm_vg_list (r);\n";
5188 pr " guestfs_free_lvm_vg_list (r);\n";
5190 pr " rv = copy_lvm_lv_list (r);\n";
5191 pr " guestfs_free_lvm_lv_list (r);\n";
5193 pr " rv = copy_stat (r);\n";
5196 pr " rv = copy_statvfs (r);\n";
5199 pr " rv = copy_table (r);\n";
5200 pr " for (i = 0; r[i] != NULL; ++i) free (r[i]);\n";
5204 pr " CAMLreturn (rv);\n";
5208 if List.length params > 5 then (
5209 pr "CAMLprim value\n";
5210 pr "ocaml_guestfs_%s_byte (value *argv, int argn)\n" name;
5212 pr " return ocaml_guestfs_%s (argv[0]" name;
5213 iteri (fun i _ -> pr ", argv[%d]" i) (List.tl params);
5220 and generate_ocaml_lvm_structure_decls () =
5223 pr "type lvm_%s = {\n" typ;
5226 | name, `String -> pr " %s : string;\n" name
5227 | name, `UUID -> pr " %s : string;\n" name
5228 | name, `Bytes -> pr " %s : int64;\n" name
5229 | name, `Int -> pr " %s : int64;\n" name
5230 | name, `OptPercent -> pr " %s : float option;\n" name
5234 ) ["pv", pv_cols; "vg", vg_cols; "lv", lv_cols]
5236 and generate_ocaml_stat_structure_decls () =
5239 pr "type %s = {\n" typ;
5242 | name, `Int -> pr " %s : int64;\n" name
5246 ) ["stat", stat_cols; "statvfs", statvfs_cols]
5248 and generate_ocaml_prototype ?(is_external = false) name style =
5249 if is_external then pr "external " else pr "val ";
5250 pr "%s : t -> " name;
5253 | String _ | FileIn _ | FileOut _ -> pr "string -> "
5254 | OptString _ -> pr "string option -> "
5255 | StringList _ -> pr "string array -> "
5256 | Bool _ -> pr "bool -> "
5257 | Int _ -> pr "int -> "
5259 (match fst style with
5260 | RErr -> pr "unit" (* all errors are turned into exceptions *)
5261 | RInt _ -> pr "int"
5262 | RInt64 _ -> pr "int64"
5263 | RBool _ -> pr "bool"
5264 | RConstString _ -> pr "string"
5265 | RString _ -> pr "string"
5266 | RStringList _ -> pr "string array"
5267 | RIntBool _ -> pr "int * bool"
5268 | RPVList _ -> pr "lvm_pv array"
5269 | RVGList _ -> pr "lvm_vg array"
5270 | RLVList _ -> pr "lvm_lv array"
5271 | RStat _ -> pr "stat"
5272 | RStatVFS _ -> pr "statvfs"
5273 | RHashtable _ -> pr "(string * string) list"
5275 if is_external then (
5277 if List.length (snd style) + 1 > 5 then
5278 pr "\"ocaml_guestfs_%s_byte\" " name;
5279 pr "\"ocaml_guestfs_%s\"" name
5283 (* Generate Perl xs code, a sort of crazy variation of C with macros. *)
5284 and generate_perl_xs () =
5285 generate_header CStyle LGPLv2;
5288 #include \"EXTERN.h\"
5292 #include <guestfs.h>
5295 #define PRId64 \"lld\"
5299 my_newSVll(long long val) {
5300 #ifdef USE_64_BIT_ALL
5301 return newSViv(val);
5305 len = snprintf(buf, 100, \"%%\" PRId64, val);
5306 return newSVpv(buf, len);
5311 #define PRIu64 \"llu\"
5315 my_newSVull(unsigned long long val) {
5316 #ifdef USE_64_BIT_ALL
5317 return newSVuv(val);
5321 len = snprintf(buf, 100, \"%%\" PRIu64, val);
5322 return newSVpv(buf, len);
5326 /* http://www.perlmonks.org/?node_id=680842 */
5328 XS_unpack_charPtrPtr (SV *arg) {
5333 if (!arg || !SvOK (arg) || !SvROK (arg) || SvTYPE (SvRV (arg)) != SVt_PVAV)
5334 croak (\"array reference expected\");
5336 av = (AV *)SvRV (arg);
5337 ret = malloc ((av_len (av) + 1 + 1) * sizeof (char *));
5339 croak (\"malloc failed\");
5341 for (i = 0; i <= av_len (av); i++) {
5342 SV **elem = av_fetch (av, i, 0);
5344 if (!elem || !*elem)
5345 croak (\"missing element in list\");
5347 ret[i] = SvPV_nolen (*elem);
5355 MODULE = Sys::Guestfs PACKAGE = Sys::Guestfs
5362 RETVAL = guestfs_create ();
5364 croak (\"could not create guestfs handle\");
5365 guestfs_set_error_handler (RETVAL, NULL, NULL);
5378 fun (name, style, _, _, _, _, _) ->
5379 (match fst style with
5380 | RErr -> pr "void\n"
5381 | RInt _ -> pr "SV *\n"
5382 | RInt64 _ -> pr "SV *\n"
5383 | RBool _ -> pr "SV *\n"
5384 | RConstString _ -> pr "SV *\n"
5385 | RString _ -> pr "SV *\n"
5388 | RPVList _ | RVGList _ | RLVList _
5389 | RStat _ | RStatVFS _
5391 pr "void\n" (* all lists returned implictly on the stack *)
5393 (* Call and arguments. *)
5395 generate_call_args ~handle:"g" (snd style);
5397 pr " guestfs_h *g;\n";
5400 | String n | FileIn n | FileOut n -> pr " char *%s;\n" n
5401 | OptString n -> pr " char *%s;\n" n
5402 | StringList n -> pr " char **%s;\n" n
5403 | Bool n -> pr " int %s;\n" n
5404 | Int n -> pr " int %s;\n" n
5407 let do_cleanups () =
5410 | String _ | OptString _ | Bool _ | Int _
5411 | FileIn _ | FileOut _ -> ()
5412 | StringList n -> pr " free (%s);\n" n
5417 (match fst style with
5422 pr " r = guestfs_%s " name;
5423 generate_call_args ~handle:"g" (snd style);
5426 pr " if (r == -1)\n";
5427 pr " croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
5433 pr " %s = guestfs_%s " n name;
5434 generate_call_args ~handle:"g" (snd style);
5437 pr " if (%s == -1)\n" n;
5438 pr " croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
5439 pr " RETVAL = newSViv (%s);\n" n;
5444 pr " int64_t %s;\n" n;
5446 pr " %s = guestfs_%s " n name;
5447 generate_call_args ~handle:"g" (snd style);
5450 pr " if (%s == -1)\n" n;
5451 pr " croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
5452 pr " RETVAL = my_newSVll (%s);\n" n;
5457 pr " const char *%s;\n" n;
5459 pr " %s = guestfs_%s " n name;
5460 generate_call_args ~handle:"g" (snd style);
5463 pr " if (%s == NULL)\n" n;
5464 pr " croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
5465 pr " RETVAL = newSVpv (%s, 0);\n" n;
5470 pr " char *%s;\n" n;
5472 pr " %s = guestfs_%s " n name;
5473 generate_call_args ~handle:"g" (snd style);
5476 pr " if (%s == NULL)\n" n;
5477 pr " croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
5478 pr " RETVAL = newSVpv (%s, 0);\n" n;
5479 pr " free (%s);\n" n;
5482 | RStringList n | RHashtable n ->
5484 pr " char **%s;\n" n;
5487 pr " %s = guestfs_%s " n name;
5488 generate_call_args ~handle:"g" (snd style);
5491 pr " if (%s == NULL)\n" n;
5492 pr " croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
5493 pr " for (n = 0; %s[n] != NULL; ++n) /**/;\n" n;
5494 pr " EXTEND (SP, n);\n";
5495 pr " for (i = 0; i < n; ++i) {\n";
5496 pr " PUSHs (sv_2mortal (newSVpv (%s[i], 0)));\n" n;
5497 pr " free (%s[i]);\n" n;
5499 pr " free (%s);\n" n;
5502 pr " struct guestfs_int_bool *r;\n";
5504 pr " r = guestfs_%s " name;
5505 generate_call_args ~handle:"g" (snd style);
5508 pr " if (r == NULL)\n";
5509 pr " croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
5510 pr " EXTEND (SP, 2);\n";
5511 pr " PUSHs (sv_2mortal (newSViv (r->i)));\n";
5512 pr " PUSHs (sv_2mortal (newSViv (r->b)));\n";
5513 pr " guestfs_free_int_bool (r);\n";
5515 generate_perl_lvm_code "pv" pv_cols name style n do_cleanups
5517 generate_perl_lvm_code "vg" vg_cols name style n do_cleanups
5519 generate_perl_lvm_code "lv" lv_cols name style n do_cleanups
5521 generate_perl_stat_code "stat" stat_cols name style n do_cleanups
5523 generate_perl_stat_code
5524 "statvfs" statvfs_cols name style n do_cleanups
5530 and generate_perl_lvm_code typ cols name style n do_cleanups =
5532 pr " struct guestfs_lvm_%s_list *%s;\n" typ n;
5536 pr " %s = guestfs_%s " n name;
5537 generate_call_args ~handle:"g" (snd style);
5540 pr " if (%s == NULL)\n" n;
5541 pr " croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
5542 pr " EXTEND (SP, %s->len);\n" n;
5543 pr " for (i = 0; i < %s->len; ++i) {\n" n;
5544 pr " hv = newHV ();\n";
5548 pr " (void) hv_store (hv, \"%s\", %d, newSVpv (%s->val[i].%s, 0), 0);\n"
5549 name (String.length name) n name
5551 pr " (void) hv_store (hv, \"%s\", %d, newSVpv (%s->val[i].%s, 32), 0);\n"
5552 name (String.length name) n name
5554 pr " (void) hv_store (hv, \"%s\", %d, my_newSVull (%s->val[i].%s), 0);\n"
5555 name (String.length name) n name
5557 pr " (void) hv_store (hv, \"%s\", %d, my_newSVll (%s->val[i].%s), 0);\n"
5558 name (String.length name) n name
5559 | name, `OptPercent ->
5560 pr " (void) hv_store (hv, \"%s\", %d, newSVnv (%s->val[i].%s), 0);\n"
5561 name (String.length name) n name
5563 pr " PUSHs (sv_2mortal ((SV *) hv));\n";
5565 pr " guestfs_free_lvm_%s_list (%s);\n" typ n
5567 and generate_perl_stat_code typ cols name style n do_cleanups =
5569 pr " struct guestfs_%s *%s;\n" typ n;
5571 pr " %s = guestfs_%s " n name;
5572 generate_call_args ~handle:"g" (snd style);
5575 pr " if (%s == NULL)\n" n;
5576 pr " croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
5577 pr " EXTEND (SP, %d);\n" (List.length cols);
5581 pr " PUSHs (sv_2mortal (my_newSVll (%s->%s)));\n" n name
5583 pr " free (%s);\n" n
5585 (* Generate Sys/Guestfs.pm. *)
5586 and generate_perl_pm () =
5587 generate_header HashStyle LGPLv2;
5594 Sys::Guestfs - Perl bindings for libguestfs
5600 my $h = Sys::Guestfs->new ();
5601 $h->add_drive ('guest.img');
5604 $h->mount ('/dev/sda1', '/');
5605 $h->touch ('/hello');
5610 The C<Sys::Guestfs> module provides a Perl XS binding to the
5611 libguestfs API for examining and modifying virtual machine
5614 Amongst the things this is good for: making batch configuration
5615 changes to guests, getting disk used/free statistics (see also:
5616 virt-df), migrating between virtualization systems (see also:
5617 virt-p2v), performing partial backups, performing partial guest
5618 clones, cloning guests and changing registry/UUID/hostname info, and
5621 Libguestfs uses Linux kernel and qemu code, and can access any type of
5622 guest filesystem that Linux and qemu can, including but not limited
5623 to: ext2/3/4, btrfs, FAT and NTFS, LVM, many different disk partition
5624 schemes, qcow, qcow2, vmdk.
5626 Libguestfs provides ways to enumerate guest storage (eg. partitions,
5627 LVs, what filesystem is in each LV, etc.). It can also run commands
5628 in the context of the guest. Also you can access filesystems over FTP.
5632 All errors turn into calls to C<croak> (see L<Carp(3)>).
5640 package Sys::Guestfs;
5646 XSLoader::load ('Sys::Guestfs');
5648 =item $h = Sys::Guestfs->new ();
5650 Create a new guestfs handle.
5656 my $class = ref ($proto) || $proto;
5658 my $self = Sys::Guestfs::_create ();
5659 bless $self, $class;
5665 (* Actions. We only need to print documentation for these as
5666 * they are pulled in from the XS code automatically.
5669 fun (name, style, _, flags, _, _, longdesc) ->
5670 if not (List.mem NotInDocs flags) then (
5671 let longdesc = replace_str longdesc "C<guestfs_" "C<$h-E<gt>" in
5673 generate_perl_prototype name style;
5675 pr "%s\n\n" longdesc;
5676 if List.mem ProtocolLimitWarning flags then
5677 pr "%s\n\n" protocol_limit_warning;
5678 if List.mem DangerWillRobinson flags then
5679 pr "%s\n\n" danger_will_robinson
5681 ) all_functions_sorted;
5693 Copyright (C) 2009 Red Hat Inc.
5697 Please see the file COPYING.LIB for the full license.
5701 L<guestfs(3)>, L<guestfish(1)>.
5706 and generate_perl_prototype name style =
5707 (match fst style with
5713 | RString n -> pr "$%s = " n
5714 | RIntBool (n, m) -> pr "($%s, $%s) = " n m
5718 | RLVList n -> pr "@%s = " n
5721 | RHashtable n -> pr "%%%s = " n
5724 let comma = ref false in
5727 if !comma then pr ", ";
5730 | String n | OptString n | Bool n | Int n | FileIn n | FileOut n ->
5737 (* Generate Python C module. *)
5738 and generate_python_c () =
5739 generate_header CStyle LGPLv2;
5748 #include \"guestfs.h\"
5756 get_handle (PyObject *obj)
5759 assert (obj != Py_None);
5760 return ((Pyguestfs_Object *) obj)->g;
5764 put_handle (guestfs_h *g)
5768 PyCObject_FromVoidPtrAndDesc ((void *) g, (char *) \"guestfs_h\", NULL);
5771 /* This list should be freed (but not the strings) after use. */
5772 static const char **
5773 get_string_list (PyObject *obj)
5780 if (!PyList_Check (obj)) {
5781 PyErr_SetString (PyExc_RuntimeError, \"expecting a list parameter\");
5785 len = PyList_Size (obj);
5786 r = malloc (sizeof (char *) * (len+1));
5788 PyErr_SetString (PyExc_RuntimeError, \"get_string_list: out of memory\");
5792 for (i = 0; i < len; ++i)
5793 r[i] = PyString_AsString (PyList_GetItem (obj, i));
5800 put_string_list (char * const * const argv)
5805 for (argc = 0; argv[argc] != NULL; ++argc)
5808 list = PyList_New (argc);
5809 for (i = 0; i < argc; ++i)
5810 PyList_SetItem (list, i, PyString_FromString (argv[i]));
5816 put_table (char * const * const argv)
5818 PyObject *list, *item;
5821 for (argc = 0; argv[argc] != NULL; ++argc)
5824 list = PyList_New (argc >> 1);
5825 for (i = 0; i < argc; i += 2) {
5826 item = PyTuple_New (2);
5827 PyTuple_SetItem (item, 0, PyString_FromString (argv[i]));
5828 PyTuple_SetItem (item, 1, PyString_FromString (argv[i+1]));
5829 PyList_SetItem (list, i >> 1, item);
5836 free_strings (char **argv)
5840 for (argc = 0; argv[argc] != NULL; ++argc)
5846 py_guestfs_create (PyObject *self, PyObject *args)
5850 g = guestfs_create ();
5852 PyErr_SetString (PyExc_RuntimeError,
5853 \"guestfs.create: failed to allocate handle\");
5856 guestfs_set_error_handler (g, NULL, NULL);
5857 return put_handle (g);
5861 py_guestfs_close (PyObject *self, PyObject *args)
5866 if (!PyArg_ParseTuple (args, (char *) \"O:guestfs_close\", &py_g))
5868 g = get_handle (py_g);
5872 Py_INCREF (Py_None);
5878 (* LVM structures, turned into Python dictionaries. *)
5881 pr "static PyObject *\n";
5882 pr "put_lvm_%s (struct guestfs_lvm_%s *%s)\n" typ typ typ;
5884 pr " PyObject *dict;\n";
5886 pr " dict = PyDict_New ();\n";
5890 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
5891 pr " PyString_FromString (%s->%s));\n"
5894 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
5895 pr " PyString_FromStringAndSize (%s->%s, 32));\n"
5898 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
5899 pr " PyLong_FromUnsignedLongLong (%s->%s));\n"
5902 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
5903 pr " PyLong_FromLongLong (%s->%s));\n"
5905 | name, `OptPercent ->
5906 pr " if (%s->%s >= 0)\n" typ name;
5907 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
5908 pr " PyFloat_FromDouble ((double) %s->%s));\n"
5911 pr " Py_INCREF (Py_None);\n";
5912 pr " PyDict_SetItemString (dict, \"%s\", Py_None);" name;
5915 pr " return dict;\n";
5919 pr "static PyObject *\n";
5920 pr "put_lvm_%s_list (struct guestfs_lvm_%s_list *%ss)\n" typ typ typ;
5922 pr " PyObject *list;\n";
5925 pr " list = PyList_New (%ss->len);\n" typ;
5926 pr " for (i = 0; i < %ss->len; ++i)\n" typ;
5927 pr " PyList_SetItem (list, i, put_lvm_%s (&%ss->val[i]));\n" typ typ;
5928 pr " return list;\n";
5931 ) ["pv", pv_cols; "vg", vg_cols; "lv", lv_cols];
5933 (* Stat structures, turned into Python dictionaries. *)
5936 pr "static PyObject *\n";
5937 pr "put_%s (struct guestfs_%s *%s)\n" typ typ typ;
5939 pr " PyObject *dict;\n";
5941 pr " dict = PyDict_New ();\n";
5945 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
5946 pr " PyLong_FromLongLong (%s->%s));\n"
5949 pr " return dict;\n";
5952 ) ["stat", stat_cols; "statvfs", statvfs_cols];
5954 (* Python wrapper functions. *)
5956 fun (name, style, _, _, _, _, _) ->
5957 pr "static PyObject *\n";
5958 pr "py_guestfs_%s (PyObject *self, PyObject *args)\n" name;
5961 pr " PyObject *py_g;\n";
5962 pr " guestfs_h *g;\n";
5963 pr " PyObject *py_r;\n";
5966 match fst style with
5967 | RErr | RInt _ | RBool _ -> pr " int r;\n"; "-1"
5968 | RInt64 _ -> pr " int64_t r;\n"; "-1"
5969 | RConstString _ -> pr " const char *r;\n"; "NULL"
5970 | RString _ -> pr " char *r;\n"; "NULL"
5971 | RStringList _ | RHashtable _ -> pr " char **r;\n"; "NULL"
5972 | RIntBool _ -> pr " struct guestfs_int_bool *r;\n"; "NULL"
5973 | RPVList n -> pr " struct guestfs_lvm_pv_list *r;\n"; "NULL"
5974 | RVGList n -> pr " struct guestfs_lvm_vg_list *r;\n"; "NULL"
5975 | RLVList n -> pr " struct guestfs_lvm_lv_list *r;\n"; "NULL"
5976 | RStat n -> pr " struct guestfs_stat *r;\n"; "NULL"
5977 | RStatVFS n -> pr " struct guestfs_statvfs *r;\n"; "NULL" in
5981 | String n | FileIn n | FileOut n -> pr " const char *%s;\n" n
5982 | OptString n -> pr " const char *%s;\n" n
5984 pr " PyObject *py_%s;\n" n;
5985 pr " const char **%s;\n" n
5986 | Bool n -> pr " int %s;\n" n
5987 | Int n -> pr " int %s;\n" n
5992 (* Convert the parameters. *)
5993 pr " if (!PyArg_ParseTuple (args, (char *) \"O";
5996 | String _ | FileIn _ | FileOut _ -> pr "s"
5997 | OptString _ -> pr "z"
5998 | StringList _ -> pr "O"
5999 | Bool _ -> pr "i" (* XXX Python has booleans? *)
6002 pr ":guestfs_%s\",\n" name;
6006 | String n | FileIn n | FileOut n -> pr ", &%s" n
6007 | OptString n -> pr ", &%s" n
6008 | StringList n -> pr ", &py_%s" n
6009 | Bool n -> pr ", &%s" n
6010 | Int n -> pr ", &%s" n
6014 pr " return NULL;\n";
6016 pr " g = get_handle (py_g);\n";
6019 | String _ | FileIn _ | FileOut _ | OptString _ | Bool _ | Int _ -> ()
6021 pr " %s = get_string_list (py_%s);\n" n n;
6022 pr " if (!%s) return NULL;\n" n
6027 pr " r = guestfs_%s " name;
6028 generate_call_args ~handle:"g" (snd style);
6033 | String _ | FileIn _ | FileOut _ | OptString _ | Bool _ | Int _ -> ()
6035 pr " free (%s);\n" n
6038 pr " if (r == %s) {\n" error_code;
6039 pr " PyErr_SetString (PyExc_RuntimeError, guestfs_last_error (g));\n";
6040 pr " return NULL;\n";
6044 (match fst style with
6046 pr " Py_INCREF (Py_None);\n";
6047 pr " py_r = Py_None;\n"
6049 | RBool _ -> pr " py_r = PyInt_FromLong ((long) r);\n"
6050 | RInt64 _ -> pr " py_r = PyLong_FromLongLong (r);\n"
6051 | RConstString _ -> pr " py_r = PyString_FromString (r);\n"
6053 pr " py_r = PyString_FromString (r);\n";
6056 pr " py_r = put_string_list (r);\n";
6057 pr " free_strings (r);\n"
6059 pr " py_r = PyTuple_New (2);\n";
6060 pr " PyTuple_SetItem (py_r, 0, PyInt_FromLong ((long) r->i));\n";
6061 pr " PyTuple_SetItem (py_r, 1, PyInt_FromLong ((long) r->b));\n";
6062 pr " guestfs_free_int_bool (r);\n"
6064 pr " py_r = put_lvm_pv_list (r);\n";
6065 pr " guestfs_free_lvm_pv_list (r);\n"
6067 pr " py_r = put_lvm_vg_list (r);\n";
6068 pr " guestfs_free_lvm_vg_list (r);\n"
6070 pr " py_r = put_lvm_lv_list (r);\n";
6071 pr " guestfs_free_lvm_lv_list (r);\n"
6073 pr " py_r = put_stat (r);\n";
6076 pr " py_r = put_statvfs (r);\n";
6079 pr " py_r = put_table (r);\n";
6080 pr " free_strings (r);\n"
6083 pr " return py_r;\n";
6088 (* Table of functions. *)
6089 pr "static PyMethodDef methods[] = {\n";
6090 pr " { (char *) \"create\", py_guestfs_create, METH_VARARGS, NULL },\n";
6091 pr " { (char *) \"close\", py_guestfs_close, METH_VARARGS, NULL },\n";
6093 fun (name, _, _, _, _, _, _) ->
6094 pr " { (char *) \"%s\", py_guestfs_%s, METH_VARARGS, NULL },\n"
6097 pr " { NULL, NULL, 0, NULL }\n";
6101 (* Init function. *)
6104 initlibguestfsmod (void)
6106 static int initialized = 0;
6108 if (initialized) return;
6109 Py_InitModule ((char *) \"libguestfsmod\", methods);
6114 (* Generate Python module. *)
6115 and generate_python_py () =
6116 generate_header HashStyle LGPLv2;
6119 u\"\"\"Python bindings for libguestfs
6122 g = guestfs.GuestFS ()
6123 g.add_drive (\"guest.img\")
6126 parts = g.list_partitions ()
6128 The guestfs module provides a Python binding to the libguestfs API
6129 for examining and modifying virtual machine disk images.
6131 Amongst the things this is good for: making batch configuration
6132 changes to guests, getting disk used/free statistics (see also:
6133 virt-df), migrating between virtualization systems (see also:
6134 virt-p2v), performing partial backups, performing partial guest
6135 clones, cloning guests and changing registry/UUID/hostname info, and
6138 Libguestfs uses Linux kernel and qemu code, and can access any type of
6139 guest filesystem that Linux and qemu can, including but not limited
6140 to: ext2/3/4, btrfs, FAT and NTFS, LVM, many different disk partition
6141 schemes, qcow, qcow2, vmdk.
6143 Libguestfs provides ways to enumerate guest storage (eg. partitions,
6144 LVs, what filesystem is in each LV, etc.). It can also run commands
6145 in the context of the guest. Also you can access filesystems over FTP.
6147 Errors which happen while using the API are turned into Python
6148 RuntimeError exceptions.
6150 To create a guestfs handle you usually have to perform the following
6153 # Create the handle, call add_drive at least once, and possibly
6154 # several times if the guest has multiple block devices:
6155 g = guestfs.GuestFS ()
6156 g.add_drive (\"guest.img\")
6158 # Launch the qemu subprocess and wait for it to become ready:
6162 # Now you can issue commands, for example:
6167 import libguestfsmod
6170 \"\"\"Instances of this class are libguestfs API handles.\"\"\"
6172 def __init__ (self):
6173 \"\"\"Create a new libguestfs handle.\"\"\"
6174 self._o = libguestfsmod.create ()
6177 libguestfsmod.close (self._o)
6182 fun (name, style, _, flags, _, _, longdesc) ->
6184 generate_call_args ~handle:"self" (snd style);
6187 if not (List.mem NotInDocs flags) then (
6188 let doc = replace_str longdesc "C<guestfs_" "C<g." in
6190 match fst style with
6191 | RErr | RInt _ | RInt64 _ | RBool _ | RConstString _
6194 doc ^ "\n\nThis function returns a list of strings."
6196 doc ^ "\n\nThis function returns a tuple (int, bool).\n"
6198 doc ^ "\n\nThis function returns a list of PVs. Each PV is represented as a dictionary."
6200 doc ^ "\n\nThis function returns a list of VGs. Each VG is represented as a dictionary."
6202 doc ^ "\n\nThis function returns a list of LVs. Each LV is represented as a dictionary."
6204 doc ^ "\n\nThis function returns a dictionary, with keys matching the various fields in the stat structure."
6206 doc ^ "\n\nThis function returns a dictionary, with keys matching the various fields in the statvfs structure."
6208 doc ^ "\n\nThis function returns a dictionary." in
6210 if List.mem ProtocolLimitWarning flags then
6211 doc ^ "\n\n" ^ protocol_limit_warning
6214 if List.mem DangerWillRobinson flags then
6215 doc ^ "\n\n" ^ danger_will_robinson
6217 let doc = pod2text ~width:60 name doc in
6218 let doc = List.map (fun line -> replace_str line "\\" "\\\\") doc in
6219 let doc = String.concat "\n " doc in
6220 pr " u\"\"\"%s\"\"\"\n" doc;
6222 pr " return libguestfsmod.%s " name;
6223 generate_call_args ~handle:"self._o" (snd style);
6228 (* Useful if you need the longdesc POD text as plain text. Returns a
6231 * This is the slowest thing about autogeneration.
6233 and pod2text ~width name longdesc =
6234 let filename, chan = Filename.open_temp_file "gen" ".tmp" in
6235 fprintf chan "=head1 %s\n\n%s\n" name longdesc;
6237 let cmd = sprintf "pod2text -w %d %s" width (Filename.quote filename) in
6238 let chan = Unix.open_process_in cmd in
6239 let lines = ref [] in
6241 let line = input_line chan in
6242 if i = 1 then (* discard the first line of output *)
6245 let line = triml line in
6246 lines := line :: !lines;
6249 let lines = try loop 1 with End_of_file -> List.rev !lines in
6250 Unix.unlink filename;
6251 match Unix.close_process_in chan with
6252 | Unix.WEXITED 0 -> lines
6254 failwithf "pod2text: process exited with non-zero status (%d)" i
6255 | Unix.WSIGNALED i | Unix.WSTOPPED i ->
6256 failwithf "pod2text: process signalled or stopped by signal %d" i
6258 (* Generate ruby bindings. *)
6259 and generate_ruby_c () =
6260 generate_header CStyle LGPLv2;
6268 #include \"guestfs.h\"
6270 #include \"extconf.h\"
6272 /* For Ruby < 1.9 */
6274 #define RARRAY_LEN(r) (RARRAY((r))->len)
6277 static VALUE m_guestfs; /* guestfs module */
6278 static VALUE c_guestfs; /* guestfs_h handle */
6279 static VALUE e_Error; /* used for all errors */
6281 static void ruby_guestfs_free (void *p)
6284 guestfs_close ((guestfs_h *) p);
6287 static VALUE ruby_guestfs_create (VALUE m)
6291 g = guestfs_create ();
6293 rb_raise (e_Error, \"failed to create guestfs handle\");
6295 /* Don't print error messages to stderr by default. */
6296 guestfs_set_error_handler (g, NULL, NULL);
6298 /* Wrap it, and make sure the close function is called when the
6301 return Data_Wrap_Struct (c_guestfs, NULL, ruby_guestfs_free, g);
6304 static VALUE ruby_guestfs_close (VALUE gv)
6307 Data_Get_Struct (gv, guestfs_h, g);
6309 ruby_guestfs_free (g);
6310 DATA_PTR (gv) = NULL;
6318 fun (name, style, _, _, _, _, _) ->
6319 pr "static VALUE ruby_guestfs_%s (VALUE gv" name;
6320 List.iter (fun arg -> pr ", VALUE %sv" (name_of_argt arg)) (snd style);
6323 pr " guestfs_h *g;\n";
6324 pr " Data_Get_Struct (gv, guestfs_h, g);\n";
6326 pr " rb_raise (rb_eArgError, \"%%s: used handle after closing it\", \"%s\");\n"
6332 | String n | FileIn n | FileOut n ->
6333 pr " const char *%s = StringValueCStr (%sv);\n" n n;
6335 pr " rb_raise (rb_eTypeError, \"expected string for parameter %%s of %%s\",\n";
6336 pr " \"%s\", \"%s\");\n" n name
6338 pr " const char *%s = StringValueCStr (%sv);\n" n n
6342 pr " int i, len;\n";
6343 pr " len = RARRAY_LEN (%sv);\n" n;
6344 pr " %s = guestfs_safe_malloc (g, sizeof (char *) * (len+1));\n"
6346 pr " for (i = 0; i < len; ++i) {\n";
6347 pr " VALUE v = rb_ary_entry (%sv, i);\n" n;
6348 pr " %s[i] = StringValueCStr (v);\n" n;
6350 pr " %s[len] = NULL;\n" n;
6354 pr " int %s = NUM2INT (%sv);\n" n n
6359 match fst style with
6360 | RErr | RInt _ | RBool _ -> pr " int r;\n"; "-1"
6361 | RInt64 _ -> pr " int64_t r;\n"; "-1"
6362 | RConstString _ -> pr " const char *r;\n"; "NULL"
6363 | RString _ -> pr " char *r;\n"; "NULL"
6364 | RStringList _ | RHashtable _ -> pr " char **r;\n"; "NULL"
6365 | RIntBool _ -> pr " struct guestfs_int_bool *r;\n"; "NULL"
6366 | RPVList n -> pr " struct guestfs_lvm_pv_list *r;\n"; "NULL"
6367 | RVGList n -> pr " struct guestfs_lvm_vg_list *r;\n"; "NULL"
6368 | RLVList n -> pr " struct guestfs_lvm_lv_list *r;\n"; "NULL"
6369 | RStat n -> pr " struct guestfs_stat *r;\n"; "NULL"
6370 | RStatVFS n -> pr " struct guestfs_statvfs *r;\n"; "NULL" in
6373 pr " r = guestfs_%s " name;
6374 generate_call_args ~handle:"g" (snd style);
6379 | String _ | FileIn _ | FileOut _ | OptString _ | Bool _ | Int _ -> ()
6381 pr " free (%s);\n" n
6384 pr " if (r == %s)\n" error_code;
6385 pr " rb_raise (e_Error, \"%%s\", guestfs_last_error (g));\n";
6388 (match fst style with
6390 pr " return Qnil;\n"
6391 | RInt _ | RBool _ ->
6392 pr " return INT2NUM (r);\n"
6394 pr " return ULL2NUM (r);\n"
6396 pr " return rb_str_new2 (r);\n";
6398 pr " VALUE rv = rb_str_new2 (r);\n";
6402 pr " int i, len = 0;\n";
6403 pr " for (i = 0; r[i] != NULL; ++i) len++;\n";
6404 pr " VALUE rv = rb_ary_new2 (len);\n";
6405 pr " for (i = 0; r[i] != NULL; ++i) {\n";
6406 pr " rb_ary_push (rv, rb_str_new2 (r[i]));\n";
6407 pr " free (r[i]);\n";
6412 pr " VALUE rv = rb_ary_new2 (2);\n";
6413 pr " rb_ary_push (rv, INT2NUM (r->i));\n";
6414 pr " rb_ary_push (rv, INT2NUM (r->b));\n";
6415 pr " guestfs_free_int_bool (r);\n";
6418 generate_ruby_lvm_code "pv" pv_cols
6420 generate_ruby_lvm_code "vg" vg_cols
6422 generate_ruby_lvm_code "lv" lv_cols
6424 pr " VALUE rv = rb_hash_new ();\n";
6428 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), ULL2NUM (r->%s));\n" name name
6433 pr " VALUE rv = rb_hash_new ();\n";
6437 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), ULL2NUM (r->%s));\n" name name
6442 pr " VALUE rv = rb_hash_new ();\n";
6444 pr " for (i = 0; r[i] != NULL; i+=2) {\n";
6445 pr " rb_hash_aset (rv, rb_str_new2 (r[i]), rb_str_new2 (r[i+1]));\n";
6446 pr " free (r[i]);\n";
6447 pr " free (r[i+1]);\n";
6458 /* Initialize the module. */
6459 void Init__guestfs ()
6461 m_guestfs = rb_define_module (\"Guestfs\");
6462 c_guestfs = rb_define_class_under (m_guestfs, \"Guestfs\", rb_cObject);
6463 e_Error = rb_define_class_under (m_guestfs, \"Error\", rb_eStandardError);
6465 rb_define_module_function (m_guestfs, \"create\", ruby_guestfs_create, 0);
6466 rb_define_method (c_guestfs, \"close\", ruby_guestfs_close, 0);
6469 (* Define the rest of the methods. *)
6471 fun (name, style, _, _, _, _, _) ->
6472 pr " rb_define_method (c_guestfs, \"%s\",\n" name;
6473 pr " ruby_guestfs_%s, %d);\n" name (List.length (snd style))
6478 (* Ruby code to return an LVM struct list. *)
6479 and generate_ruby_lvm_code typ cols =
6480 pr " VALUE rv = rb_ary_new2 (r->len);\n";
6482 pr " for (i = 0; i < r->len; ++i) {\n";
6483 pr " VALUE hv = rb_hash_new ();\n";
6487 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_str_new2 (r->val[i].%s));\n" name name
6489 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_str_new (r->val[i].%s, 32));\n" name name
6492 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), ULL2NUM (r->val[i].%s));\n" name name
6493 | name, `OptPercent ->
6494 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_dbl2big (r->val[i].%s));\n" name name
6496 pr " rb_ary_push (rv, hv);\n";
6498 pr " guestfs_free_lvm_%s_list (r);\n" typ;
6501 (* Generate Java bindings GuestFS.java file. *)
6502 and generate_java_java () =
6503 generate_header CStyle LGPLv2;
6506 package com.redhat.et.libguestfs;
6508 import java.util.HashMap;
6509 import com.redhat.et.libguestfs.LibGuestFSException;
6510 import com.redhat.et.libguestfs.PV;
6511 import com.redhat.et.libguestfs.VG;
6512 import com.redhat.et.libguestfs.LV;
6513 import com.redhat.et.libguestfs.Stat;
6514 import com.redhat.et.libguestfs.StatVFS;
6515 import com.redhat.et.libguestfs.IntBool;
6518 * The GuestFS object is a libguestfs handle.
6522 public class GuestFS {
6523 // Load the native code.
6525 System.loadLibrary (\"guestfs_jni\");
6529 * The native guestfs_h pointer.
6534 * Create a libguestfs handle.
6536 * @throws LibGuestFSException
6538 public GuestFS () throws LibGuestFSException
6542 private native long _create () throws LibGuestFSException;
6545 * Close a libguestfs handle.
6547 * You can also leave handles to be collected by the garbage
6548 * collector, but this method ensures that the resources used
6549 * by the handle are freed up immediately. If you call any
6550 * other methods after closing the handle, you will get an
6553 * @throws LibGuestFSException
6555 public void close () throws LibGuestFSException
6561 private native void _close (long g) throws LibGuestFSException;
6563 public void finalize () throws LibGuestFSException
6571 fun (name, style, _, flags, _, shortdesc, longdesc) ->
6572 if not (List.mem NotInDocs flags); then (
6573 let doc = replace_str longdesc "C<guestfs_" "C<g." in
6575 if List.mem ProtocolLimitWarning flags then
6576 doc ^ "\n\n" ^ protocol_limit_warning
6579 if List.mem DangerWillRobinson flags then
6580 doc ^ "\n\n" ^ danger_will_robinson
6582 let doc = pod2text ~width:60 name doc in
6583 let doc = List.map ( (* RHBZ#501883 *)
6586 | nonempty -> nonempty
6588 let doc = String.concat "\n * " doc in
6591 pr " * %s\n" shortdesc;
6594 pr " * @throws LibGuestFSException\n";
6598 generate_java_prototype ~public:true ~semicolon:false name style;
6601 pr " if (g == 0)\n";
6602 pr " throw new LibGuestFSException (\"%s: handle is closed\");\n"
6605 if fst style <> RErr then pr "return ";
6607 generate_call_args ~handle:"g" (snd style);
6611 generate_java_prototype ~privat:true ~native:true name style;
6618 and generate_java_prototype ?(public=false) ?(privat=false) ?(native=false)
6619 ?(semicolon=true) name style =
6620 if privat then pr "private ";
6621 if public then pr "public ";
6622 if native then pr "native ";
6625 (match fst style with
6626 | RErr -> pr "void ";
6627 | RInt _ -> pr "int ";
6628 | RInt64 _ -> pr "long ";
6629 | RBool _ -> pr "boolean ";
6630 | RConstString _ | RString _ -> pr "String ";
6631 | RStringList _ -> pr "String[] ";
6632 | RIntBool _ -> pr "IntBool ";
6633 | RPVList _ -> pr "PV[] ";
6634 | RVGList _ -> pr "VG[] ";
6635 | RLVList _ -> pr "LV[] ";
6636 | RStat _ -> pr "Stat ";
6637 | RStatVFS _ -> pr "StatVFS ";
6638 | RHashtable _ -> pr "HashMap<String,String> ";
6641 if native then pr "_%s " name else pr "%s " name;
6643 let needs_comma = ref false in
6652 if !needs_comma then pr ", ";
6653 needs_comma := true;
6670 pr " throws LibGuestFSException";
6671 if semicolon then pr ";"
6673 and generate_java_struct typ cols =
6674 generate_header CStyle LGPLv2;
6677 package com.redhat.et.libguestfs;
6680 * Libguestfs %s structure.
6691 | name, `UUID -> pr " public String %s;\n" name
6693 | name, `Int -> pr " public long %s;\n" name
6694 | name, `OptPercent ->
6695 pr " /* The next field is [0..100] or -1 meaning 'not present': */\n";
6696 pr " public float %s;\n" name
6701 and generate_java_c () =
6702 generate_header CStyle LGPLv2;
6709 #include \"com_redhat_et_libguestfs_GuestFS.h\"
6710 #include \"guestfs.h\"
6712 /* Note that this function returns. The exception is not thrown
6713 * until after the wrapper function returns.
6716 throw_exception (JNIEnv *env, const char *msg)
6719 cl = (*env)->FindClass (env,
6720 \"com/redhat/et/libguestfs/LibGuestFSException\");
6721 (*env)->ThrowNew (env, cl, msg);
6724 JNIEXPORT jlong JNICALL
6725 Java_com_redhat_et_libguestfs_GuestFS__1create
6726 (JNIEnv *env, jobject obj)
6730 g = guestfs_create ();
6732 throw_exception (env, \"GuestFS.create: failed to allocate handle\");
6735 guestfs_set_error_handler (g, NULL, NULL);
6736 return (jlong) (long) g;
6739 JNIEXPORT void JNICALL
6740 Java_com_redhat_et_libguestfs_GuestFS__1close
6741 (JNIEnv *env, jobject obj, jlong jg)
6743 guestfs_h *g = (guestfs_h *) (long) jg;
6750 fun (name, style, _, _, _, _, _) ->
6752 (match fst style with
6753 | RErr -> pr "void ";
6754 | RInt _ -> pr "jint ";
6755 | RInt64 _ -> pr "jlong ";
6756 | RBool _ -> pr "jboolean ";
6757 | RConstString _ | RString _ -> pr "jstring ";
6758 | RIntBool _ | RStat _ | RStatVFS _ | RHashtable _ ->
6760 | RStringList _ | RPVList _ | RVGList _ | RLVList _ ->
6764 pr "Java_com_redhat_et_libguestfs_GuestFS_";
6765 pr "%s" (replace_str ("_" ^ name) "_" "_1");
6767 pr " (JNIEnv *env, jobject obj, jlong jg";
6774 pr ", jstring j%s" n
6776 pr ", jobjectArray j%s" n
6778 pr ", jboolean j%s" n
6784 pr " guestfs_h *g = (guestfs_h *) (long) jg;\n";
6785 let error_code, no_ret =
6786 match fst style with
6787 | RErr -> pr " int r;\n"; "-1", ""
6789 | RInt _ -> pr " int r;\n"; "-1", "0"
6790 | RInt64 _ -> pr " int64_t r;\n"; "-1", "0"
6791 | RConstString _ -> pr " const char *r;\n"; "NULL", "NULL"
6793 pr " jstring jr;\n";
6794 pr " char *r;\n"; "NULL", "NULL"
6796 pr " jobjectArray jr;\n";
6799 pr " jstring jstr;\n";
6800 pr " char **r;\n"; "NULL", "NULL"
6802 pr " jobject jr;\n";
6804 pr " jfieldID fl;\n";
6805 pr " struct guestfs_int_bool *r;\n"; "NULL", "NULL"
6807 pr " jobject jr;\n";
6809 pr " jfieldID fl;\n";
6810 pr " struct guestfs_stat *r;\n"; "NULL", "NULL"
6812 pr " jobject jr;\n";
6814 pr " jfieldID fl;\n";
6815 pr " struct guestfs_statvfs *r;\n"; "NULL", "NULL"
6817 pr " jobjectArray jr;\n";
6819 pr " jfieldID fl;\n";
6820 pr " jobject jfl;\n";
6821 pr " struct guestfs_lvm_pv_list *r;\n"; "NULL", "NULL"
6823 pr " jobjectArray jr;\n";
6825 pr " jfieldID fl;\n";
6826 pr " jobject jfl;\n";
6827 pr " struct guestfs_lvm_vg_list *r;\n"; "NULL", "NULL"
6829 pr " jobjectArray jr;\n";
6831 pr " jfieldID fl;\n";
6832 pr " jobject jfl;\n";
6833 pr " struct guestfs_lvm_lv_list *r;\n"; "NULL", "NULL"
6834 | RHashtable _ -> pr " char **r;\n"; "NULL", "NULL" in
6841 pr " const char *%s;\n" n
6843 pr " int %s_len;\n" n;
6844 pr " const char **%s;\n" n
6851 (match fst style with
6852 | RStringList _ | RPVList _ | RVGList _ | RLVList _ -> true
6853 | RErr | RBool _ | RInt _ | RInt64 _ | RConstString _
6854 | RString _ | RIntBool _ | RStat _ | RStatVFS _
6855 | RHashtable _ -> false) ||
6856 List.exists (function StringList _ -> true | _ -> false) (snd style) in
6862 (* Get the parameters. *)
6869 pr " %s = (*env)->GetStringUTFChars (env, j%s, NULL);\n" n n
6871 pr " %s_len = (*env)->GetArrayLength (env, j%s);\n" n n;
6872 pr " %s = guestfs_safe_malloc (g, sizeof (char *) * (%s_len+1));\n" n n;
6873 pr " for (i = 0; i < %s_len; ++i) {\n" n;
6874 pr " jobject o = (*env)->GetObjectArrayElement (env, j%s, i);\n"
6876 pr " %s[i] = (*env)->GetStringUTFChars (env, o, NULL);\n" n;
6878 pr " %s[%s_len] = NULL;\n" n n;
6881 pr " %s = j%s;\n" n n
6884 (* Make the call. *)
6885 pr " r = guestfs_%s " name;
6886 generate_call_args ~handle:"g" (snd style);
6889 (* Release the parameters. *)
6896 pr " (*env)->ReleaseStringUTFChars (env, j%s, %s);\n" n n
6898 pr " for (i = 0; i < %s_len; ++i) {\n" n;
6899 pr " jobject o = (*env)->GetObjectArrayElement (env, j%s, i);\n"
6901 pr " (*env)->ReleaseStringUTFChars (env, o, %s[i]);\n" n;
6903 pr " free (%s);\n" n
6908 (* Check for errors. *)
6909 pr " if (r == %s) {\n" error_code;
6910 pr " throw_exception (env, guestfs_last_error (g));\n";
6911 pr " return %s;\n" no_ret;
6915 (match fst style with
6917 | RInt _ -> pr " return (jint) r;\n"
6918 | RBool _ -> pr " return (jboolean) r;\n"
6919 | RInt64 _ -> pr " return (jlong) r;\n"
6920 | RConstString _ -> pr " return (*env)->NewStringUTF (env, r);\n"
6922 pr " jr = (*env)->NewStringUTF (env, r);\n";
6926 pr " for (r_len = 0; r[r_len] != NULL; ++r_len) ;\n";
6927 pr " cl = (*env)->FindClass (env, \"java/lang/String\");\n";
6928 pr " jstr = (*env)->NewStringUTF (env, \"\");\n";
6929 pr " jr = (*env)->NewObjectArray (env, r_len, cl, jstr);\n";
6930 pr " for (i = 0; i < r_len; ++i) {\n";
6931 pr " jstr = (*env)->NewStringUTF (env, r[i]);\n";
6932 pr " (*env)->SetObjectArrayElement (env, jr, i, jstr);\n";
6933 pr " free (r[i]);\n";
6938 pr " cl = (*env)->FindClass (env, \"com/redhat/et/libguestfs/IntBool\");\n";
6939 pr " jr = (*env)->AllocObject (env, cl);\n";
6940 pr " fl = (*env)->GetFieldID (env, cl, \"i\", \"I\");\n";
6941 pr " (*env)->SetIntField (env, jr, fl, r->i);\n";
6942 pr " fl = (*env)->GetFieldID (env, cl, \"i\", \"Z\");\n";
6943 pr " (*env)->SetBooleanField (env, jr, fl, r->b);\n";
6944 pr " guestfs_free_int_bool (r);\n";
6947 pr " cl = (*env)->FindClass (env, \"com/redhat/et/libguestfs/Stat\");\n";
6948 pr " jr = (*env)->AllocObject (env, cl);\n";
6952 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"J\");\n"
6954 pr " (*env)->SetLongField (env, jr, fl, r->%s);\n" name;
6959 pr " cl = (*env)->FindClass (env, \"com/redhat/et/libguestfs/StatVFS\");\n";
6960 pr " jr = (*env)->AllocObject (env, cl);\n";
6964 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"J\");\n"
6966 pr " (*env)->SetLongField (env, jr, fl, r->%s);\n" name;
6971 generate_java_lvm_return "pv" "PV" pv_cols
6973 generate_java_lvm_return "vg" "VG" vg_cols
6975 generate_java_lvm_return "lv" "LV" lv_cols
6978 pr " throw_exception (env, \"%s: internal error: please let us know how to make a Java HashMap from JNI bindings!\");\n" name;
6979 pr " return NULL;\n"
6986 and generate_java_lvm_return typ jtyp cols =
6987 pr " cl = (*env)->FindClass (env, \"com/redhat/et/libguestfs/%s\");\n" jtyp;
6988 pr " jr = (*env)->NewObjectArray (env, r->len, cl, NULL);\n";
6989 pr " for (i = 0; i < r->len; ++i) {\n";
6990 pr " jfl = (*env)->AllocObject (env, cl);\n";
6994 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
6995 pr " (*env)->SetObjectField (env, jfl, fl, (*env)->NewStringUTF (env, r->val[i].%s));\n" name;
6998 pr " char s[33];\n";
6999 pr " memcpy (s, r->val[i].%s, 32);\n" name;
7001 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
7002 pr " (*env)->SetObjectField (env, jfl, fl, (*env)->NewStringUTF (env, s));\n";
7004 | name, (`Bytes|`Int) ->
7005 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"J\");\n" name;
7006 pr " (*env)->SetLongField (env, jfl, fl, r->val[i].%s);\n" name;
7007 | name, `OptPercent ->
7008 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"F\");\n" name;
7009 pr " (*env)->SetFloatField (env, jfl, fl, r->val[i].%s);\n" name;
7011 pr " (*env)->SetObjectArrayElement (env, jfl, i, jfl);\n";
7013 pr " guestfs_free_lvm_%s_list (r);\n" typ;
7016 and generate_haskell_hs () =
7017 generate_header HaskellStyle LGPLv2;
7019 (* XXX We only know how to generate partial FFI for Haskell
7020 * at the moment. Please help out!
7022 let can_generate style =
7023 let check_no_bad_args =
7024 List.for_all (function Bool _ | Int _ -> false | _ -> true)
7027 | RErr, args -> check_no_bad_args args
7040 | RHashtable _, _ -> false in
7043 {-# INCLUDE <guestfs.h> #-}
7044 {-# LANGUAGE ForeignFunctionInterface #-}
7049 (* List out the names of the actions we want to export. *)
7051 fun (name, style, _, _, _, _, _) ->
7052 if can_generate style then pr ",\n %s" name
7060 import Control.Exception
7061 import Data.Typeable
7063 data GuestfsS = GuestfsS -- represents the opaque C struct
7064 type GuestfsP = Ptr GuestfsS -- guestfs_h *
7065 type GuestfsH = ForeignPtr GuestfsS -- guestfs_h * with attached finalizer
7067 -- XXX define properly later XXX
7071 data IntBool = IntBool
7073 data StatVFS = StatVFS
7074 data Hashtable = Hashtable
7076 foreign import ccall unsafe \"guestfs_create\" c_create
7078 foreign import ccall unsafe \"&guestfs_close\" c_close
7079 :: FunPtr (GuestfsP -> IO ())
7080 foreign import ccall unsafe \"guestfs_set_error_handler\" c_set_error_handler
7081 :: GuestfsP -> Ptr CInt -> Ptr CInt -> IO ()
7083 create :: IO GuestfsH
7086 c_set_error_handler p nullPtr nullPtr
7087 h <- newForeignPtr c_close p
7090 foreign import ccall unsafe \"guestfs_last_error\" c_last_error
7091 :: GuestfsP -> IO CString
7093 -- last_error :: GuestfsH -> IO (Maybe String)
7094 -- last_error h = do
7095 -- str <- withForeignPtr h (\\p -> c_last_error p)
7096 -- maybePeek peekCString str
7098 last_error :: GuestfsH -> IO (String)
7100 str <- withForeignPtr h (\\p -> c_last_error p)
7102 then return \"no error\"
7103 else peekCString str
7107 (* Generate wrappers for each foreign function. *)
7109 fun (name, style, _, _, _, _, _) ->
7110 if can_generate style then (
7111 pr "foreign import ccall unsafe \"guestfs_%s\" c_%s\n" name name;
7113 generate_haskell_prototype ~handle:"GuestfsP" style;
7117 generate_haskell_prototype ~handle:"GuestfsH" ~hs:true style;
7119 pr "%s %s = do\n" name
7120 (String.concat " " ("h" :: List.map name_of_argt (snd style)));
7126 | String n -> pr "withCString %s $ \\%s -> " n n
7127 | OptString n -> pr "maybeWith withCString %s $ \\%s -> " n n
7128 | StringList n -> pr "withMany withCString %s $ \\%s -> withArray0 nullPtr %s $ \\%s -> " n n n n
7130 (* XXX this doesn't work *)
7132 pr " %s = case %s of\n" n n;
7135 pr " in fromIntegral %s $ \\%s ->\n" n n
7136 | Int n -> pr "fromIntegral %s $ \\%s -> " n n
7138 pr "withForeignPtr h (\\p -> c_%s %s)\n" name
7139 (String.concat " " ("p" :: List.map name_of_argt (snd style)));
7140 (match fst style with
7141 | RErr | RInt _ | RInt64 _ | RBool _ ->
7142 pr " if (r == -1)\n";
7144 pr " err <- last_error h\n";
7146 | RConstString _ | RString _ | RStringList _ | RIntBool _
7147 | RPVList _ | RVGList _ | RLVList _ | RStat _ | RStatVFS _
7149 pr " if (r == nullPtr)\n";
7151 pr " err <- last_error h\n";
7154 (match fst style with
7156 pr " else return ()\n"
7158 pr " else return (fromIntegral r)\n"
7160 pr " else return (fromIntegral r)\n"
7162 pr " else return (toBool r)\n"
7173 pr " else return ()\n" (* XXXXXXXXXXXXXXXXXXXX *)
7179 and generate_haskell_prototype ~handle ?(hs = false) style =
7181 let string = if hs then "String" else "CString" in
7182 let int = if hs then "Int" else "CInt" in
7183 let bool = if hs then "Bool" else "CInt" in
7184 let int64 = if hs then "Integer" else "Int64" in
7188 | String _ -> pr "%s" string
7189 | OptString _ -> if hs then pr "Maybe String" else pr "CString"
7190 | StringList _ -> if hs then pr "[String]" else pr "Ptr CString"
7191 | Bool _ -> pr "%s" bool
7192 | Int _ -> pr "%s" int
7193 | FileIn _ -> pr "%s" string
7194 | FileOut _ -> pr "%s" string
7199 (match fst style with
7200 | RErr -> if not hs then pr "CInt"
7201 | RInt _ -> pr "%s" int
7202 | RInt64 _ -> pr "%s" int64
7203 | RBool _ -> pr "%s" bool
7204 | RConstString _ -> pr "%s" string
7205 | RString _ -> pr "%s" string
7206 | RStringList _ -> pr "[%s]" string
7207 | RIntBool _ -> pr "IntBool"
7208 | RPVList _ -> pr "[PV]"
7209 | RVGList _ -> pr "[VG]"
7210 | RLVList _ -> pr "[LV]"
7211 | RStat _ -> pr "Stat"
7212 | RStatVFS _ -> pr "StatVFS"
7213 | RHashtable _ -> pr "Hashtable"
7217 and generate_bindtests () =
7218 generate_header CStyle LGPLv2;
7223 #include <inttypes.h>
7226 #include \"guestfs.h\"
7227 #include \"guestfs_protocol.h\"
7229 #define error guestfs_error
7232 print_strings (char * const* const argv)
7237 for (argc = 0; argv[argc] != NULL; ++argc) {
7238 if (argc > 0) printf (\", \");
7239 printf (\"\\\"%%s\\\"\", argv[argc]);
7244 /* The test0 function prints its parameters to stdout. */
7248 match test_functions with
7249 | [] -> assert false
7250 | test0 :: tests -> test0, tests in
7253 let (name, style, _, _, _, _, _) = test0 in
7254 generate_prototype ~extern:false ~semicolon:false ~newline:true
7255 ~handle:"g" ~prefix:"guestfs_" name style;
7261 | FileOut n -> pr " printf (\"%%s\\n\", %s);\n" n
7262 | OptString n -> pr " printf (\"%%s\\n\", %s ? %s : \"null\");\n" n n
7263 | StringList n -> pr " print_strings (%s);\n" n
7264 | Bool n -> pr " printf (\"%%s\\n\", %s ? \"true\" : \"false\");\n" n
7265 | Int n -> pr " printf (\"%%d\\n\", %s);\n" n
7272 fun (name, style, _, _, _, _, _) ->
7273 if String.sub name (String.length name - 3) 3 <> "err" then (
7274 pr "/* Test normal return. */\n";
7275 generate_prototype ~extern:false ~semicolon:false ~newline:true
7276 ~handle:"g" ~prefix:"guestfs_" name style;
7278 (match fst style with
7283 pr " sscanf (val, \"%%d\", &r);\n";
7287 pr " sscanf (val, \"%%\" SCNi64, &r);\n";
7290 pr " return strcmp (val, \"true\") == 0;\n"
7292 (* Can't return the input string here. Return a static
7293 * string so we ensure we get a segfault if the caller
7296 pr " return \"static string\";\n"
7298 pr " return strdup (val);\n"
7300 pr " char **strs;\n";
7302 pr " sscanf (val, \"%%d\", &n);\n";
7303 pr " strs = malloc ((n+1) * sizeof (char *));\n";
7304 pr " for (i = 0; i < n; ++i) {\n";
7305 pr " strs[i] = malloc (16);\n";
7306 pr " snprintf (strs[i], 16, \"%%d\", i);\n";
7308 pr " strs[n] = NULL;\n";
7309 pr " return strs;\n"
7311 pr " struct guestfs_int_bool *r;\n";
7312 pr " r = malloc (sizeof (struct guestfs_int_bool));\n";
7313 pr " sscanf (val, \"%%\" SCNi32, &r->i);\n";
7317 pr " struct guestfs_lvm_pv_list *r;\n";
7319 pr " r = malloc (sizeof (struct guestfs_lvm_pv_list));\n";
7320 pr " sscanf (val, \"%%d\", &r->len);\n";
7321 pr " r->val = calloc (r->len, sizeof (struct guestfs_lvm_pv));\n";
7322 pr " for (i = 0; i < r->len; ++i) {\n";
7323 pr " r->val[i].pv_name = malloc (16);\n";
7324 pr " snprintf (r->val[i].pv_name, 16, \"%%d\", i);\n";
7328 pr " struct guestfs_lvm_vg_list *r;\n";
7330 pr " r = malloc (sizeof (struct guestfs_lvm_vg_list));\n";
7331 pr " sscanf (val, \"%%d\", &r->len);\n";
7332 pr " r->val = calloc (r->len, sizeof (struct guestfs_lvm_vg));\n";
7333 pr " for (i = 0; i < r->len; ++i) {\n";
7334 pr " r->val[i].vg_name = malloc (16);\n";
7335 pr " snprintf (r->val[i].vg_name, 16, \"%%d\", i);\n";
7339 pr " struct guestfs_lvm_lv_list *r;\n";
7341 pr " r = malloc (sizeof (struct guestfs_lvm_lv_list));\n";
7342 pr " sscanf (val, \"%%d\", &r->len);\n";
7343 pr " r->val = calloc (r->len, sizeof (struct guestfs_lvm_lv));\n";
7344 pr " for (i = 0; i < r->len; ++i) {\n";
7345 pr " r->val[i].lv_name = malloc (16);\n";
7346 pr " snprintf (r->val[i].lv_name, 16, \"%%d\", i);\n";
7350 pr " struct guestfs_stat *r;\n";
7351 pr " r = calloc (1, sizeof (*r));\n";
7352 pr " sscanf (val, \"%%\" SCNi64, &r->dev);\n";
7355 pr " struct guestfs_statvfs *r;\n";
7356 pr " r = calloc (1, sizeof (*r));\n";
7357 pr " sscanf (val, \"%%\" SCNi64, &r->bsize);\n";
7360 pr " char **strs;\n";
7362 pr " sscanf (val, \"%%d\", &n);\n";
7363 pr " strs = malloc ((n*2+1) * sizeof (char *));\n";
7364 pr " for (i = 0; i < n; ++i) {\n";
7365 pr " strs[i*2] = malloc (16);\n";
7366 pr " strs[i*2+1] = malloc (16);\n";
7367 pr " snprintf (strs[i*2], 16, \"%%d\", i);\n";
7368 pr " snprintf (strs[i*2+1], 16, \"%%d\", i);\n";
7370 pr " strs[n*2] = NULL;\n";
7371 pr " return strs;\n"
7376 pr "/* Test error return. */\n";
7377 generate_prototype ~extern:false ~semicolon:false ~newline:true
7378 ~handle:"g" ~prefix:"guestfs_" name style;
7380 pr " error (g, \"error\");\n";
7381 (match fst style with
7382 | RErr | RInt _ | RInt64 _ | RBool _ ->
7385 | RString _ | RStringList _ | RIntBool _
7386 | RPVList _ | RVGList _ | RLVList _ | RStat _ | RStatVFS _
7388 pr " return NULL;\n"
7395 let output_to filename =
7396 let filename_new = filename ^ ".new" in
7397 chan := open_out filename_new;
7402 (* Is the new file different from the current file? *)
7403 if Sys.file_exists filename && files_equal filename filename_new then
7404 Unix.unlink filename_new (* same, so skip it *)
7406 (* different, overwrite old one *)
7407 (try Unix.chmod filename 0o644 with Unix.Unix_error _ -> ());
7408 Unix.rename filename_new filename;
7409 Unix.chmod filename 0o444;
7410 printf "written %s\n%!" filename;
7419 if not (Sys.file_exists "configure.ac") then (
7421 You are probably running this from the wrong directory.
7422 Run it from the top source directory using the command
7428 let close = output_to "src/guestfs_protocol.x" in
7432 let close = output_to "src/guestfs-structs.h" in
7433 generate_structs_h ();
7436 let close = output_to "src/guestfs-actions.h" in
7437 generate_actions_h ();
7440 let close = output_to "src/guestfs-actions.c" in
7441 generate_client_actions ();
7444 let close = output_to "daemon/actions.h" in
7445 generate_daemon_actions_h ();
7448 let close = output_to "daemon/stubs.c" in
7449 generate_daemon_actions ();
7452 let close = output_to "capitests/tests.c" in
7456 let close = output_to "src/guestfs-bindtests.c" in
7457 generate_bindtests ();
7460 let close = output_to "fish/cmds.c" in
7461 generate_fish_cmds ();
7464 let close = output_to "fish/completion.c" in
7465 generate_fish_completion ();
7468 let close = output_to "guestfs-structs.pod" in
7469 generate_structs_pod ();
7472 let close = output_to "guestfs-actions.pod" in
7473 generate_actions_pod ();
7476 let close = output_to "guestfish-actions.pod" in
7477 generate_fish_actions_pod ();
7480 let close = output_to "ocaml/guestfs.mli" in
7481 generate_ocaml_mli ();
7484 let close = output_to "ocaml/guestfs.ml" in
7485 generate_ocaml_ml ();
7488 let close = output_to "ocaml/guestfs_c_actions.c" in
7489 generate_ocaml_c ();
7492 let close = output_to "perl/Guestfs.xs" in
7493 generate_perl_xs ();
7496 let close = output_to "perl/lib/Sys/Guestfs.pm" in
7497 generate_perl_pm ();
7500 let close = output_to "python/guestfs-py.c" in
7501 generate_python_c ();
7504 let close = output_to "python/guestfs.py" in
7505 generate_python_py ();
7508 let close = output_to "ruby/ext/guestfs/_guestfs.c" in
7512 let close = output_to "java/com/redhat/et/libguestfs/GuestFS.java" in
7513 generate_java_java ();
7516 let close = output_to "java/com/redhat/et/libguestfs/PV.java" in
7517 generate_java_struct "PV" pv_cols;
7520 let close = output_to "java/com/redhat/et/libguestfs/VG.java" in
7521 generate_java_struct "VG" vg_cols;
7524 let close = output_to "java/com/redhat/et/libguestfs/LV.java" in
7525 generate_java_struct "LV" lv_cols;
7528 let close = output_to "java/com/redhat/et/libguestfs/Stat.java" in
7529 generate_java_struct "Stat" stat_cols;
7532 let close = output_to "java/com/redhat/et/libguestfs/StatVFS.java" in
7533 generate_java_struct "StatVFS" statvfs_cols;
7536 let close = output_to "java/com_redhat_et_libguestfs_GuestFS.c" in
7540 let close = output_to "haskell/Guestfs.hs" in
7541 generate_haskell_hs ();