Various small API doc improvements
[ocaml-libvirt.git] / examples / list_domains.ml
1 (* Simple demo program showing how to list out domains.
2    Usage: list_domains [URI]
3    (C) Copyright 2007 Richard W.M. Jones, Red Hat Inc.
4    https://libvirt.org/
5  *)
6
7 open Printf
8
9 module C = Libvirt.Connect
10 module D = Libvirt.Domain
11 module N = Libvirt.Network
12
13 let string_of_state = function
14   | D.InfoNoState -> "no state"
15   | D.InfoRunning -> "running"
16   | D.InfoBlocked -> "blocked"
17   | D.InfoPaused -> "paused"
18   | D.InfoShutdown -> "shutdown"
19   | D.InfoShutoff -> "shutoff"
20   | D.InfoCrashed -> "crashed"
21   | D.InfoPMSuspended -> "pm suspended"
22
23 let () =
24   try
25     let name =
26       if Array.length Sys.argv >= 2 then
27         Some (Sys.argv.(1))
28       else
29         None in
30     let conn = C.connect_auth_readonly ?name (C.get_auth_default ()) in
31
32     (* List all domains (running and inactive). *)
33     let domains = D.get_domains_and_infos conn [D.ListAll] in
34     List.iter (
35       fun (dom, info) ->
36         let id = D.get_id dom in
37         let name = D.get_name dom in
38         let state = string_of_state info.D.state in
39         if id >= 0 then
40           printf "%8d %-20s %s\n%!" id name state
41         else
42           printf "%8s %-20s %s\n%!" "inactive" name state
43     ) domains
44   with
45     Libvirt.Virterror err ->
46       eprintf "error: %s\n" (Libvirt.Virterror.to_string err)
47
48 let () =
49   (* Run the garbage collector which is a good way to check for
50    * memory corruption errors and reference counting issues in libvirt.
51    *)
52   Gc.compact ()