perl: Translate C examples into Perl and include a manual page.
[libguestfs.git] / perl / examples / create_disk.pl
1 #!/usr/bin/perl -w
2
3 # Example showing how to create a disk image.
4
5 use strict;
6 use Sys::Guestfs;
7
8 my $output = "disk.img";
9
10 my $g = new Sys::Guestfs ();
11
12 # Create a raw-format sparse disk image, 512 MB in size.
13 open FILE, ">$output" or die "$output: $!";
14 truncate FILE, 512 * 1024 * 1024 or die "$output: truncate: $!";
15 close FILE or die "$output: $!";
16
17 # Set the trace flag so that we can see each libguestfs call.
18 $g->set_trace (1);
19
20 # Set the autosync flag so that the disk will be synchronized
21 # automatically when the libguestfs handle is closed.
22 $g->set_autosync (1);
23
24 # Attach the disk image to libguestfs.
25 $g->add_drive_opts ($output, format => "raw", readonly => 0);
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 my @devices = $g->list_devices ();
34 if (@devices != 1) {
35     die "error: expected a single device from list-devices";
36 }
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 my @partitions = $g->list_partitions ();
44 if (@partitions != 1) {
45     die "error: expected a single partition from list-partitions";
46 }
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 my $message = "Hello, world\n";
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 $g->upload ("/etc/resolv.conf", "/foo/resolv.conf");
63
64 # Because 'autosync' was set (above) we can just exit here
65 # and the disk contents will be synchronized.  You can also do
66 # this manually by calling $g->umount_all and $g->sync.
67 exit 0