daemon: debug segv correct use of dereferencing NULL.
[libguestfs.git] / ocaml / examples / create_disk.ml
1 (* Example showing how to create a disk image. *)
2
3 open Unix
4 open Printf
5
6 let output = "disk.img"
7
8 let () =
9   let g = new Guestfs.guestfs () in
10
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);
14   close fd;
15
16   (* Set the trace flag so that we can see each libguestfs call. *)
17   g#set_trace true;
18
19   (* Set the autosync flag so that the disk will be synchronized
20    * automatically when the libguestfs handle is closed.
21    *)
22   g#set_autosync true;
23
24   (* Attach the disk image to libguestfs. *)
25   g#add_drive_opts ~format:"raw" ~readonly:false output;
26
27   (* Run the libguestfs back-end. *)
28   g#launch ();
29
30   (* Get the list of devices.  Because we only added one drive
31    * above, we expect that this list should contain a single
32    * element.
33    *)
34   let devices = g#list_devices () in
35   if Array.length devices <> 1 then
36     failwith "error: expected a single device from list-devices";
37
38   (* Partition the disk as one single MBR partition. *)
39   g#part_disk devices.(0) "mbr";
40
41   (* Get the list of partitions.  We expect a single element, which
42    * is the partition we have just created.
43    *)
44   let partitions = g#list_partitions () in
45   if Array.length partitions <> 1 then
46     failwith "error: expected a single partition from list-partitions";
47
48   (* Create a filesystem on the partition. *)
49   g#mkfs "ext4" partitions.(0);
50
51   (* Now mount the filesystem so that we can add files. *)
52   g#mount_options "" partitions.(0) "/";
53
54   (* Create some files and directories. *)
55   g#touch "/empty";
56   let message = "Hello, world\n" in
57   g#write "/hello" message;
58   g#mkdir "/foo";
59
60   (* This one uploads the local file /etc/resolv.conf into
61    * the disk image.
62    *)
63   g#upload "/etc/resolv.conf" "/foo/resolv.conf";
64
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.
68    *
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.
72    *)
73   g#close ()