6b049323427a99081843e9bf5d4622fd67f51375
[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    http://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
22 let () =
23   try
24     let name =
25       if Array.length Sys.argv >= 2 then
26         Some (Sys.argv.(1))
27       else
28         None in
29     let conn = C.connect_readonly ?name () in
30
31     (* List all domains (running and inactive). *)
32     let domains = D.get_domains_and_infos conn [D.ListAll] in
33     List.iter (
34       fun (dom, info) ->
35         if info.D.state <> D.InfoShutoff then
36           printf "%8d %-20s %s\n%!"
37             (D.get_id dom) (D.get_name dom) (string_of_state info.D.state)
38         else
39           printf "%8s %-20s shutoff\n%!" "" (D.get_name dom)
40     ) domains
41   with
42     Libvirt.Virterror err ->
43       eprintf "error: %s\n" (Libvirt.Virterror.to_string err)
44
45 let () =
46   (* Run the garbage collector which is a good way to check for
47    * memory corruption errors and reference counting issues in libvirt.
48    *)
49   Gc.compact ()