1 (* Example showing how to create a disk image. *)
6 let output = "disk.img"
9 let g = new Guestfs.guestfs () in
11 (* Create a raw-format sparse disk image, 512 MB in size. *)
12 let fd = openfile output [O_WRONLY;O_CREAT;O_TRUNC;O_NOCTTY] 0o666 in
13 ftruncate fd (512 * 1024 * 1024);
16 (* Set the trace flag so that we can see each libguestfs call. *)
19 (* Set the autosync flag so that the disk will be synchronized
20 * automatically when the libguestfs handle is closed.
24 (* Attach the disk image to libguestfs. *)
25 g#add_drive_opts ~format:"raw" ~readonly:false output;
27 (* Run the libguestfs back-end. *)
30 (* Get the list of devices. Because we only added one drive
31 * above, we expect that this list should contain a single
34 let devices = g#list_devices () in
35 if Array.length devices <> 1 then
36 failwith "error: expected a single device from list-devices";
38 (* Partition the disk as one single MBR partition. *)
39 g#part_disk devices.(0) "mbr";
41 (* Get the list of partitions. We expect a single element, which
42 * is the partition we have just created.
44 let partitions = g#list_partitions () in
45 if Array.length partitions <> 1 then
46 failwith "error: expected a single partition from list-partitions";
48 (* Create a filesystem on the partition. *)
49 g#mkfs "ext4" partitions.(0);
51 (* Now mount the filesystem so that we can add files. *)
52 g#mount_options "" partitions.(0) "/";
54 (* Create some files and directories. *)
56 let message = "Hello, world\n" in
57 g#write "/hello" message;
60 (* This one uploads the local file /etc/resolv.conf into
63 g#upload "/etc/resolv.conf" "/foo/resolv.conf";
65 (* Because 'autosync' was set (above) we can just close the handle
66 * and the disk contents will be synchronized. You can also do
67 * this manually by calling g#umount_all and g#sync.
69 * Note also that handles are automatically closed if they are
70 * reaped by the garbage collector. You only need to call close
71 * if you want to close the handle right away.