Add Erlang bindings.
[libguestfs.git] / erlang / examples / inspect_vm.erl
1 #!/usr/bin/env escript
2 %%! -smp enable -sname inspect_vm debug verbose
3 % Example showing how to inspect a virtual machine disk.
4
5 main([Disk]) ->
6     {ok, G} = guestfs:create(),
7
8     % Attach the disk image read-only to libguestfs.
9     ok = guestfs:add_drive_opts(G, Disk, [{readonly, true}]),
10
11     % Run the libguestfs back-end.
12     ok = guestfs:launch(G),
13
14     % Ask libguestfs to inspect for operating systems.
15     case guestfs:inspect_os(G) of
16         [] ->
17             io:fwrite("inspect_vm: no operating systems found~n"),
18             exit(no_operating_system);
19         Roots ->
20             list_os(G, Roots)
21     end.
22
23 list_os(_, []) ->
24     ok;
25 list_os(G, [Root|Roots]) ->
26     io:fwrite("Root device: ~s~n", [Root]),
27
28     % Print basic information about the operating system.
29     Product_name = guestfs:inspect_get_product_name(G, Root),
30     io:fwrite("  Product name: ~s~n", [Product_name]),
31     Major = guestfs:inspect_get_major_version(G, Root),
32     Minor = guestfs:inspect_get_minor_version(G, Root),
33     io:fwrite("  Version:      ~w.~w~n", [Major, Minor]),
34     Type = guestfs:inspect_get_type(G, Root),
35     io:fwrite("  Type:         ~s~n", [Type]),
36     Distro = guestfs:inspect_get_distro(G, Root),
37     io:fwrite("  Distro:       ~s~n", [Distro]),
38
39     % Mount up the disks, like guestfish -i.
40     Mps = sort_mps(guestfs:inspect_get_mountpoints(G, Root)),
41     mount_mps(G, Mps),
42
43     % If /etc/issue.net file exists, print up to 3 lines. *)
44     Filename = "/etc/issue.net",
45     Is_file = guestfs:is_file(G, Filename),
46     if Is_file ->
47             io:fwrite("--- ~s ---~n", [Filename]),
48             Lines = guestfs:head_n(G, 3, Filename),
49             write_lines(Lines);
50        true -> ok
51     end,
52
53     % Unmount everything.
54     ok = guestfs:umount_all(G),
55
56     list_os(G, Roots).
57
58 % Sort keys by length, shortest first, so that we end up
59 % mounting the filesystems in the correct order.
60 sort_mps(Mps) ->
61     Cmp = fun ({A,_}, {B,_}) ->
62                   length(A) =< length(B) end,
63     lists:sort(Cmp, Mps).
64
65 mount_mps(_, []) ->
66     ok;
67 mount_mps(G, [{Mp, Dev}|Mps]) ->
68     case guestfs:mount_ro(G, Dev, Mp) of
69         ok -> ok;
70         { error, Msg, _ } ->
71             io:fwrite("~s (ignored)~n", [Msg])
72     end,
73     mount_mps(G, Mps).
74
75 write_lines([]) ->
76     ok;
77 write_lines([Line|Lines]) ->
78     io:fwrite("~s~n", [Line]),
79     write_lines(Lines).