examples: Print more stats in the get_all_domain_stats.ml example.
[ocaml-libvirt.git] / examples / get_all_domain_stats.ml
1 (* Example of using Domain.get_all_domain_stats (virConnectGetAllDomainStats).
2  * Usage: get_all_domain_stats
3  * http://libvirt.org/
4  *)
5
6 open Printf
7
8 module C = Libvirt.Connect
9 module D = Libvirt.Domain
10
11 let print_stats stats =
12   try
13     Array.iter (
14       fun { D.dom = dom; D.params = params } ->
15         printf "domain %s:\n" (D.get_name dom);
16         Array.iteri (
17           fun i (field, value) ->
18             printf "\t%-20s = " field;
19             (match value with
20              | D.TypedFieldInt32 i -> printf "%ld" i
21              | D.TypedFieldUInt32 i -> printf "%ld" i
22              | D.TypedFieldInt64 i -> printf "%Ld" i
23              | D.TypedFieldUInt64 i -> printf "%Ld" i
24              | D.TypedFieldFloat f -> printf "%g" f
25              | D.TypedFieldBool b -> printf "%b" b
26              | D.TypedFieldString s -> printf "%S" s);
27             printf "\n";
28         ) params;
29         printf "\n"
30     ) stats
31   with
32     Libvirt.Virterror err ->
33       eprintf "error: %s\n" (Libvirt.Virterror.to_string err)
34
35 let () =
36   if Array.length Sys.argv <> 1 then (
37     eprintf "error: get_all_domain_stats\n";
38     exit 1
39   );
40
41   let conn = C.connect_readonly () in
42
43   let what = [
44     D.StatsState;
45     D.StatsCpuTotal;
46     D.StatsBalloon;
47     D.StatsVcpu;
48     D.StatsInterface;
49     D.StatsBlock;
50   ] in
51   let who = [] in (* empty list means returns all domains *)
52
53   let quit = ref false in
54
55   while not !quit do
56     let stats = D.get_all_domain_stats conn what who in
57
58     if stats <> [||] then print_stats stats
59     else (
60       printf "no guests found\n";
61       quit := true
62     );
63     flush stdout;
64
65     (* Run the garbage collector which is a good way to check for
66      * memory corruption errors and reference counting issues in
67      * libvirt.  You shouldn't do this in ordinary programs.
68      *)
69     Gc.compact ();
70
71     if not !quit then Unix.sleep 3
72   done