daemon: debug segv correct use of dereferencing NULL.
[libguestfs.git] / erlang / examples / create_disk.erl
1 #!/usr/bin/env escript
2 %%! -smp enable -sname create_disk debug verbose
3 % Example showing how to create a disk image.
4
5 main(_) ->
6     Output = "disk.img",
7
8     {ok, G} = guestfs:create(),
9
10     % Create a raw-format sparse disk image, 512 MB in size.
11     {ok, File} = file:open(Output, [raw, write, binary]),
12     {ok, _} = file:position(File, 512 * 1024 * 1024 - 1),
13     ok = file:write(File, " "),
14     ok = file:close(File),
15
16     % Set the trace flag so that we can see each libguestfs call.
17     ok = guestfs:set_trace(G, true),
18
19     % Set the autosync flag so that the disk will be synchronized
20     % automatically when the libguestfs handle is closed.
21     ok = guestfs:set_autosync(G, true),
22
23     % Attach the disk image to libguestfs.
24     ok = guestfs:add_drive_opts(G, Output,
25                                 [{format, "raw"}, {readonly, false}]),
26
27     % Run the libguestfs back-end.
28     ok = guestfs:launch(G),
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     [Device] = guestfs:list_devices(G),
34
35     % Partition the disk as one single MBR partition.
36     ok = guestfs:part_disk(G, Device, "mbr"),
37
38     % Get the list of partitions.  We expect a single element, which
39     % is the partition we have just created.
40     [Partition] = guestfs:list_partitions(G),
41
42     % Create a filesystem on the partition.
43     ok = guestfs:mkfs(G, "ext4", Partition),
44
45     % Now mount the filesystem so that we can add files. *)
46     ok = guestfs:mount_options(G, "", Partition, "/"),
47
48     % Create some files and directories. *)
49     ok = guestfs:touch(G, "/empty"),
50     Message = "Hello, world\n",
51     ok = guestfs:write(G, "/hello", Message),
52     ok = guestfs:mkdir(G, "/foo"),
53
54     % This one uploads the local file /etc/resolv.conf into
55     % the disk image.
56     ok = guestfs:upload(G, "/etc/resolv.conf", "/foo/resolv.conf"),
57
58     % Because 'autosync' was set (above) we can just close the handle
59     % and the disk contents will be synchronized.  You can also do
60     % this manually by calling guestfs:umount_all and guestfs:sync.
61     %
62     % Note also that handles are automatically closed if they are
63     % reaped by the garbage collector.  You only need to call close
64     % if you want to close the handle right away.
65     ok = guestfs:close(G).