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