Just fixed the README file.
[virt-top.git] / virt-top / virt_top.ml
1 (* 'top'-like tool for libvirt domains.
2  * $Id: virt_top.ml,v 1.5 2007/08/30 13:52:40 rjones Exp $
3  *)
4
5 open Printf
6 open ExtList
7 open Curses
8
9 open Virt_top_utils
10
11 module C = Libvirt.Connect
12 module D = Libvirt.Domain
13 module N = Libvirt.Network
14
15 (* Hook for XML support (see virt_top_xml.ml). *)
16 let parse_device_xml : (int -> [>`R] D.t -> string list * string list) ref =
17   ref (
18     fun _ _ -> [], []
19   )
20
21 (* Hooks for CSV support (see virt_top_csv.ml). *)
22 let csv_start : (string -> unit) ref =
23   ref (
24     fun _ -> failwith "virt-top was compiled without support for CSV"
25   )
26 let csv_write : (string list -> unit) ref =
27   ref (
28     fun _ -> ()
29   )
30
31 (* Int64 operators for convenience. *)
32 let (+^) = Int64.add
33 let (-^) = Int64.sub
34 let ( *^ ) = Int64.mul
35 let (/^) = Int64.div
36
37 (* Sort order. *)
38 type sort_order =
39   | DomainID | DomainName | Processor | Memory | Time
40   | NetRX | NetTX | BlockRdRq | BlockWrRq
41 let all_sort_fields = [
42   DomainID; DomainName; Processor; Memory; Time;
43   NetRX; NetTX; BlockRdRq; BlockWrRq
44 ]
45 let printable_sort_order = function
46   | Processor -> "%CPU"
47   | Memory -> "%MEM"
48   | Time -> "TIME (CPU time)"
49   | DomainID -> "Domain ID"
50   | DomainName -> "Domain name"
51   | NetRX -> "Net RX bytes"
52   | NetTX -> "Net TX bytes"
53   | BlockRdRq -> "Block read reqs"
54   | BlockWrRq -> "Block write reqs"
55 let sort_order_of_cli = function
56   | "cpu" | "processor" -> Processor
57   | "mem" | "memory" -> Memory
58   | "time" -> Time
59   | "id" -> DomainID
60   | "name" -> DomainName
61   | "netrx" -> NetRX | "nettx" -> NetTX
62   | "blockrdrq" -> BlockRdRq | "blockwrrq" -> BlockWrRq
63   | str -> failwith (str ^ ": sort order should be: cpu|mem|time|id|name|netrx|nettx|blockrdrq|blockwrrq")
64 let cli_of_sort_order = function
65   | Processor -> "cpu"
66   | Memory -> "mem"
67   | Time -> "time"
68   | DomainID -> "id"
69   | DomainName -> "name"
70   | NetRX -> "netrx"
71   | NetTX -> "nettx"
72   | BlockRdRq -> "blockrdrq"
73   | BlockWrRq -> "blockwrrq"
74
75 (* Current major display mode: TaskDisplay is the normal display. *)
76 type display = TaskDisplay | PCPUDisplay | BlockDisplay | NetDisplay
77
78 let display_of_cli = function
79   | "task" -> TaskDisplay
80   | "pcpu" -> PCPUDisplay
81   | "block" -> BlockDisplay
82   | "net" -> NetDisplay
83   | str -> failwith (str ^ ": display should be task|pcpu|block|net")
84 let cli_of_display = function
85   | TaskDisplay -> "task"
86   | PCPUDisplay -> "pcpu"
87   | BlockDisplay -> "block"
88   | NetDisplay -> "net"
89
90 (* Init file. *)
91 type init_file = NoInitFile | DefaultInitFile | InitFile of string
92
93 (* Settings. *)
94 let quit = ref false
95 let delay = ref 3000 (* milliseconds *)
96 let historical_cpu_delay = ref 20 (* secs *)
97 let iterations = ref (-1)
98 let batch_mode = ref false
99 let secure_mode = ref false
100 let sort_order = ref Processor
101 let display_mode = ref TaskDisplay
102 let uri = ref None
103 let debug_file = ref ""
104 let csv_enabled = ref false
105 let init_file = ref DefaultInitFile
106
107 (* Function to read command line arguments and go into curses mode. *)
108 let start_up () =
109   (* Read command line arguments. *)
110   let rec set_delay newdelay =
111     if newdelay <= 0. then
112       failwith "-d: cannot set a negative delay";
113     delay := int_of_float (newdelay *. 1000.)
114   and set_uri = function "" -> uri := None | u -> uri := Some u
115   and set_sort order = sort_order := sort_order_of_cli order
116   and set_pcpu_mode () = display_mode := PCPUDisplay
117   and set_net_mode () = display_mode := NetDisplay
118   and set_block_mode () = display_mode := BlockDisplay
119   and set_csv filename =
120     (!csv_start) filename;
121     csv_enabled := true
122   and no_init_file () = init_file := NoInitFile
123   and set_init_file filename = init_file := InitFile filename
124   in
125   let argspec = Arg.align [
126     "-1", Arg.Unit set_pcpu_mode, " Start by displaying pCPUs (default: tasks)";
127     "-2", Arg.Unit set_net_mode, " Start by displaying network interfaces";
128     "-3", Arg.Unit set_block_mode, " Start by displaying block devices";
129     "-b", Arg.Set batch_mode, " Batch mode";
130     "-c", Arg.String set_uri, "uri Connect to URI (default: Xen)";
131     "--connect", Arg.String set_uri, "uri Connect to URI (default: Xen)";
132     "--csv", Arg.String set_csv, "file Log statistics to CSV file";
133     "-d", Arg.Float set_delay, "delay Delay time interval (seconds)";
134     "--debug", Arg.Set_string debug_file, "file Send debug messages to file";
135     "--hist-cpu", Arg.Set_int historical_cpu_delay, "secs Historical CPU delay";
136     "--init-file", Arg.String set_init_file, "file Set name of init file";
137     "--no-init-file", Arg.Unit no_init_file, " Do not read init file";
138     "-n", Arg.Set_int iterations, "iterations Number of iterations to run";
139     "-o", Arg.String set_sort, "sort Set sort order (cpu|mem|time|id|name)";
140     "-s", Arg.Set secure_mode, " Secure (\"kiosk\") mode";
141   ] in
142   let anon_fun str = raise (Arg.Bad (str ^ ": unknown parameter")) in
143   let usage_msg = "virt-top : a 'top'-like utility for virtualization
144
145 SUMMARY
146   virt-top [-options]
147
148 OPTIONS" in
149   Arg.parse argspec anon_fun usage_msg;
150
151   (* Read the init file. *)
152   let try_to_read_init_file filename =
153     let config = read_config_file filename in
154     List.iter (
155       function
156       | _, "display", mode -> display_mode := display_of_cli mode
157       | _, "delay", secs -> set_delay (float_of_string secs)
158       | _, "hist-cpu", secs -> historical_cpu_delay := int_of_string secs
159       | _, "iterations", n -> iterations := int_of_string n
160       | _, "sort", order -> set_sort order
161       | _, "connect", uri -> set_uri uri
162       | _, "debug", filename -> debug_file := filename
163       | _, "csv", filename -> set_csv filename
164       | _, "batch", b -> batch_mode := bool_of_string b
165       | _, "secure", b -> secure_mode := bool_of_string b
166       | _, "overwrite-init-file", "false" -> no_init_file ()
167       | lineno, key, _ ->
168           eprintf "%s:%d: configuration item ``%s'' ignored\n%!"
169             filename lineno key
170     ) config
171   in
172   (match !init_file with
173    | NoInitFile -> ()
174    | DefaultInitFile ->
175        let home = try Sys.getenv "HOME" with Not_found -> "/" in
176        let filename = home // ".virt-toprc" in
177        try_to_read_init_file filename
178    | InitFile filename ->
179        try_to_read_init_file filename
180   );
181
182   (* Connect to the hypervisor before going into curses mode, since
183    * this is the most likely thing to fail.
184    *)
185   let conn =
186     let name = !uri in
187     try C.connect_readonly ?name ()
188     with
189       Libvirt.Virterror err ->
190         prerr_endline (Libvirt.Virterror.to_string err);
191         (* If non-root and no explicit connection URI, print a warning. *)
192         if Unix.geteuid () <> 0 && name = None then (
193           print_endline "NB: If you want to monitor a local Xen hypervisor, you usually need to be root";
194         );
195         exit 1 in
196
197   (* Get the node_info.  This never changes, right?  So we get it just once. *)
198   let node_info = C.get_node_info conn in
199
200   (* Hostname and libvirt library version also don't change. *)
201   let hostname =
202     try C.get_hostname conn
203     with
204     (* qemu:/// and other URIs didn't support virConnectGetHostname until
205      * libvirt 0.3.3.  Before that they'd throw a virterror. *)
206     | Libvirt.Virterror _
207     | Invalid_argument "virConnectGetHostname not supported" -> "unknown" in
208
209   let libvirt_version =
210     let v, _ = Libvirt.get_version () in
211     v / 1_000_000, (v / 1_000) mod 1_000, v mod 1_000 in
212
213   (* Open debug file if specified.
214    * NB: Do this just before jumping into curses mode.
215    *)
216   (match !debug_file with
217    | "" -> (* No debug file specified, send stderr to /dev/null. *)
218        (try
219           let fd = Unix.openfile "/dev/null" [Unix.O_WRONLY] 0o644 in
220           Unix.dup2 fd Unix.stderr;
221           Unix.close fd
222         with
223           Unix.Unix_error _ -> ()
224        )
225    | filename -> (* Send stderr to the named file. *)
226        let fd =
227          Unix.openfile filename [Unix.O_WRONLY;Unix.O_CREAT;Unix.O_TRUNC]
228            0o644 in
229        Unix.dup2 fd Unix.stderr;
230        Unix.close fd
231   );
232
233   (* Curses voodoo (see ncurses(3)). *)
234   let stdscr =
235     initscr ();
236     cbreak ();
237     noecho ();
238     nonl ();
239     let stdscr = stdscr () in
240     intrflush stdscr false;
241     keypad stdscr true;
242     stdscr in
243
244   (* This tuple of static information is called 'state' in other parts
245    * of this program, and is passed to other functions such as redraw and
246    * main_loop.  See virt_top_main.ml.  It's not really "state" though.
247    *)
248   conn, stdscr, node_info, hostname, libvirt_version
249
250 (* Show a percentage in 4 chars. *)
251 let show_percent percent =
252   if percent <= 0. then " 0.0"
253   else if percent <= 9.9 then sprintf " %1.1f" percent
254   else if percent <= 99.9 then sprintf "%2.1f" percent
255   else "100 "
256
257 (* Show an int64 option in 4 chars. *)
258 let rec show_int64_option = function
259   | None -> "    "
260   | Some n -> show_int64 n
261 (* Show an int64 in 4 chars. *)
262 and show_int64 = function
263   | n when n < 0L -> "-!!!"
264   | n when n <= 9999L ->
265       sprintf "%4Ld" n
266   | n when n /^ 1024L <= 999L ->
267       sprintf "%3LdK" (n /^ 1024L)
268   | n when n /^ 1_048_576L <= 999L ->
269       sprintf "%3LdM" (n /^ 1_048_576L)
270   | n when n /^ 1_073_741_824L <= 999L ->
271       sprintf "%3LdG" (n /^ 1_073_741_824L)
272   | _ -> ">!!!"
273
274 (* Format the total time (may be large!) in 9 chars. *)
275 let show_time ns =
276   let secs_in_ns = 1_000_000_000L in
277   let mins_in_ns = 60_000_000_000L in
278   let hours_in_ns = 3_600_000_000_000L in
279
280   let hours = ns /^ hours_in_ns in
281   let ns = ns -^ (hours *^ hours_in_ns) in
282   let mins = ns /^ mins_in_ns in
283   let ns = ns -^ (mins *^ mins_in_ns) in
284   let secs = ns /^ secs_in_ns in
285   let ns = ns -^ (secs *^ secs_in_ns) in
286   let pennies = ns /^ 10_000_000L in
287
288   if hours < 12L then
289     sprintf "%3Ld:%02Ld.%02Ld" (hours *^ 60L +^ mins) secs pennies
290   else if hours <= 999L then
291     sprintf "%3Ld:%02Ld:%02Ld" hours mins secs
292   else (
293     let days = hours /^ 24L in
294     let hours = hours -^ (days *^ 24L) in
295     sprintf "%3Ldd%02Ld:%02Ld" days hours mins
296   )
297
298 (* Show a domain state (the 'S' column). *)
299 let show_state = function
300   | D.InfoNoState -> '?'
301   | D.InfoRunning -> 'R'
302   | D.InfoBlocked -> 'S'
303   | D.InfoPaused -> 'P'
304   | D.InfoShutdown -> 'D'
305   | D.InfoShutoff -> 'O'
306   | D.InfoCrashed -> 'X'
307
308 (* Sum Domain.block_stats structures together.  Missing fields
309  * get forced to 0.  Empty list returns all 0.
310  *)
311 let zero_block_stats =
312   { D.rd_req = 0L; rd_bytes = 0L; wr_req = 0L; wr_bytes = 0L; errs = 0L }
313 let add_block_stats bs1 bs2 =
314   let add f1 f2 = if f1 >= 0L && f2 >= 0L then f1 +^ f2 else 0L in
315   { D.rd_req = add bs1.D.rd_req   bs2.D.rd_req;
316     rd_bytes = add bs1.D.rd_bytes bs2.D.rd_bytes;
317     wr_req   = add bs1.D.wr_req   bs2.D.wr_req;
318     wr_bytes = add bs1.D.wr_bytes bs2.D.wr_bytes;
319     errs     = add bs1.D.errs     bs2.D.errs }
320 let sum_block_stats =
321   List.fold_left add_block_stats zero_block_stats
322
323 (* Get the difference between two block_stats structures.  Missing data
324  * forces the difference to -1.
325  *)
326 let diff_block_stats curr prev =
327   let sub f1 f2 = if f1 >= 0L && f2 >= 0L then f1 -^ f2 else -1L in
328   { D.rd_req = sub curr.D.rd_req   prev.D.rd_req;
329     rd_bytes = sub curr.D.rd_bytes prev.D.rd_bytes;
330     wr_req   = sub curr.D.wr_req   prev.D.wr_req;
331     wr_bytes = sub curr.D.wr_bytes prev.D.wr_bytes;
332     errs     = sub curr.D.errs     prev.D.errs }
333
334 (* Sum Domain.interface_stats structures together.  Missing fields
335  * get forced to 0.  Empty list returns all 0.
336  *)
337 let zero_interface_stats =
338   { D.rx_bytes = 0L; rx_packets = 0L; rx_errs = 0L; rx_drop = 0L;
339     tx_bytes = 0L; tx_packets = 0L; tx_errs = 0L; tx_drop = 0L }
340 let add_interface_stats is1 is2 =
341   let add f1 f2 = if f1 >= 0L && f2 >= 0L then f1 +^ f2 else 0L in
342   { D.rx_bytes = add is1.D.rx_bytes   is2.D.rx_bytes;
343     rx_packets = add is1.D.rx_packets is2.D.rx_packets;
344     rx_errs    = add is1.D.rx_errs    is2.D.rx_errs;
345     rx_drop    = add is1.D.rx_drop    is2.D.rx_drop;
346     tx_bytes   = add is1.D.tx_bytes   is2.D.tx_bytes;
347     tx_packets = add is1.D.tx_packets is2.D.tx_packets;
348     tx_errs    = add is1.D.tx_errs    is2.D.tx_errs;
349     tx_drop    = add is1.D.tx_drop    is2.D.tx_drop }
350 let sum_interface_stats =
351   List.fold_left add_interface_stats zero_interface_stats
352
353 (* Get the difference between two interface_stats structures.
354  * Missing data forces the difference to -1.
355  *)
356 let diff_interface_stats curr prev =
357   let sub f1 f2 = if f1 >= 0L && f2 >= 0L then f1 -^ f2 else -1L in
358   { D.rx_bytes = sub curr.D.rx_bytes   prev.D.rx_bytes;
359     rx_packets = sub curr.D.rx_packets prev.D.rx_packets;
360     rx_errs    = sub curr.D.rx_errs    prev.D.rx_errs;
361     rx_drop    = sub curr.D.rx_drop    prev.D.rx_drop;
362     tx_bytes   = sub curr.D.tx_bytes   prev.D.tx_bytes;
363     tx_packets = sub curr.D.tx_packets prev.D.tx_packets;
364     tx_errs    = sub curr.D.tx_errs    prev.D.tx_errs;
365     tx_drop    = sub curr.D.tx_drop    prev.D.tx_drop }
366
367 (* Update the display and sleep for given number of seconds. *)
368 let sleep n = refresh (); Unix.sleep n
369
370 (* The curses getstr/getnstr functions are just weird.
371  * This helper function also enables echo temporarily.
372  *)
373 let get_string maxlen =
374   echo ();
375   let str = String.create maxlen in
376   let ok = getstr str in (* Safe because binding calls getnstr. *)
377   noecho ();
378   if not ok then ""
379   else (
380     (* Chop at first '\0'. *)
381     try
382       let i = String.index str '\000' in
383       String.sub str 0 i
384     with
385       Not_found -> str (* it is full maxlen bytes *)
386   )
387
388 (* Pad a string to the full width with spaces.  If too long, truncate. *)
389 let pad width str =
390   let n = String.length str in
391   if n = width then str
392   else if n > width then String.sub str 0 width
393   else (* if n < width then *) str ^ String.make (width-n) ' '
394
395 (* Line numbers. *)
396 let top_lineno = 0
397 let summary_lineno = 1 (* this takes 2 lines *)
398 let message_lineno = 3
399 let header_lineno = 4
400 let domains_lineno = 5
401
402 (* Print in the "message area". *)
403 let clear_msg () = move message_lineno 0; clrtoeol ()
404 let print_msg str = clear_msg (); mvaddstr message_lineno 0 str; ()
405
406 (* Write CSV header row. *)
407 let write_csv_header () =
408   (!csv_write) [ "Hostname"; "Time"; "Arch"; "Physical CPUs";
409                  "Count"; "Running"; "Blocked"; "Paused"; "Shutdown";
410                  "Shutoff"; "Crashed"; "Active"; "Inactive";
411                  "%CPU"; "Total memory KB"; "Total guest memory KB";
412                  "Total CPU time ns" ]
413
414 (* Intermediate "domain + stats" structure that we use to collect
415  * everything we know about a domain within the redraw function.
416  *)
417 type rd_domain = Inactive | Active of rd_active
418 and rd_active = {
419   rd_domid : int;                       (* Domain ID. *)
420   rd_dom : [`R] D.t;                    (* Domain object. *)
421   rd_info : D.info;                     (* Domain CPU info now. *)
422   rd_block_stats : (string * D.block_stats) list;
423                                         (* Domain block stats now. *)
424   rd_interface_stats : (string * D.interface_stats) list;
425                                         (* Domain net stats now. *)
426   rd_prev_info : D.info option;         (* Domain CPU info previously. *)
427   rd_prev_block_stats : (string * D.block_stats) list;
428                                         (* Domain block stats prev. *)
429   rd_prev_interface_stats : (string * D.interface_stats) list;
430                                         (* Domain interface stats prev. *)
431   (* The following are since the last slice, or 0 if cannot be calculated: *)
432   rd_cpu_time : float;                  (* CPU time used in nanoseconds. *)
433   rd_percent_cpu : float;               (* CPU time as percent of total. *)
434   (* The following are since the last slice, or None if cannot be calc'd: *)
435   rd_block_rd_reqs : int64 option;      (* Number of block device read rqs. *)
436   rd_block_wr_reqs : int64 option;      (* Number of block device write rqs. *)
437   rd_net_rx_bytes : int64 option;       (* Number of bytes received. *)
438   rd_net_tx_bytes : int64 option;       (* Number of bytes transmitted. *)
439 }
440
441 (* Redraw the display. *)
442 let redraw, clear_pcpu_display_data =
443   (* We cache the list of block devices and interfaces for each domain
444    * here, so we don't need to reparse the XML each time.
445    *)
446   let devices = Hashtbl.create 13 in
447
448   (* Function to get the list of block devices, network interfaces for
449    * a particular domain.  Get it from the devices cache, and if not
450    * there then parse the domain XML.
451    *)
452   let get_devices id dom =
453     try Hashtbl.find devices id
454     with Not_found ->
455       let blkdevs, netifs = (!parse_device_xml) id dom in
456       Hashtbl.replace devices id (blkdevs, netifs);
457       blkdevs, netifs
458   in
459
460   (* We save the state of domains across redraws here, which allows us
461    * to deduce %CPU usage from the running total.
462    *)
463   let last_info = Hashtbl.create 13 in
464   let last_time = ref (Unix.gettimeofday ()) in
465
466   (* Save vcpuinfo structures across redraws too (only for pCPU display). *)
467   let last_vcpu_info = Hashtbl.create 13 in
468
469   (* Keep a historical list of %CPU usages. *)
470   let historical_cpu = ref [] in
471   let historical_cpu_last_time = ref (Unix.gettimeofday ()) in
472
473   let redraw (conn, stdscr, node_info, hostname, _) =
474     clear ();
475
476     (* Get the screen/window size. *)
477     let lines, cols = get_size () in
478
479     (* Number of physical CPUs (some may be disabled). *)
480     let nr_pcpus = C.maxcpus_of_node_info node_info in
481
482     (* Get the current time. *)
483     let time = Unix.gettimeofday () in
484     let tm = Unix.localtime time in
485     let printable_time =
486       sprintf "%02d:%02d:%02d" tm.Unix.tm_hour tm.Unix.tm_min tm.Unix.tm_sec in
487     mvaddstr top_lineno 0 ("virt-top " ^ printable_time ^ " - ");
488
489     (* What's the total CPU time elapsed since we were last called? (ns) *)
490     let total_cpu_per_pcpu = 1_000_000_000. *. (time -. !last_time) in
491     (* Avoid division by zero. *)
492     let total_cpu_per_pcpu =
493       if total_cpu_per_pcpu <= 0. then 1. else total_cpu_per_pcpu in
494     let total_cpu = float node_info.C.cpus *. total_cpu_per_pcpu in
495
496     (* Basic node_info. *)
497     addstr (sprintf "%s %d/%dCPU %dMHz %LdMB "
498               node_info.C.model node_info.C.cpus nr_pcpus node_info.C.mhz
499               (node_info.C.memory /^ 1024L));
500     (* Save the cursor position for when we come to draw the
501      * historical CPU times (down in this function).
502      *)
503     let historical_cursor = getyx stdscr in
504
505     (* Get the domains.  Match up with their last_info (if any). *)
506     let doms =
507       (* Active domains. *)
508       let n = C.num_of_domains conn in
509       let ids =
510         if n > 0 then Array.to_list (C.list_domains conn n)
511         else [] in
512       let doms =
513         List.filter_map (
514           fun id ->
515             try
516               let dom = D.lookup_by_id conn id in
517               let name = D.get_name dom in
518               let blkdevs, netifs = get_devices id dom in
519
520               (* Get current CPU, block and network stats. *)
521               let info = D.get_info dom in
522               let block_stats =
523                 try List.map (fun dev -> dev, D.block_stats dom dev) blkdevs
524                 with
525                 | Invalid_argument "virDomainBlockStats not supported"
526                 | Libvirt.Virterror _ -> [] in
527               let interface_stats =
528                 try List.map (fun dev -> dev, D.interface_stats dom dev) netifs
529                 with
530                 | Invalid_argument "virDomainInterfaceStats not supported"
531                 | Libvirt.Virterror _ -> [] in
532
533               let prev_info, prev_block_stats, prev_interface_stats =
534                 try
535                   let prev_info, prev_block_stats, prev_interface_stats =
536                     Hashtbl.find last_info id in
537                   Some prev_info, prev_block_stats, prev_interface_stats
538                 with Not_found -> None, [], [] in
539
540               Some (name, Active {
541                       rd_domid = id; rd_dom = dom; rd_info = info;
542                       rd_block_stats = block_stats;
543                       rd_interface_stats = interface_stats;
544                       rd_prev_info = prev_info;
545                       rd_prev_block_stats = prev_block_stats;
546                       rd_prev_interface_stats = prev_interface_stats;
547                       rd_cpu_time = 0.; rd_percent_cpu = 0.;
548                       rd_block_rd_reqs = None; rd_block_wr_reqs = None;
549                       rd_net_rx_bytes = None; rd_net_tx_bytes = None;
550                     })
551             with
552               Libvirt.Virterror _ -> None (* ignore transient error *)
553         ) ids in
554
555       (* Inactive domains. *)
556       let doms_inactive =
557         try
558           let n = C.num_of_defined_domains conn in
559           let names =
560             if n > 0 then Array.to_list (C.list_defined_domains conn n)
561             else [] in
562           List.map (fun name -> name, Inactive) names
563         with
564           (* Ignore transient errors, in particular errors from
565            * num_of_defined_domains if it cannot contact xend.
566            *)
567         | Libvirt.Virterror _ -> [] in
568
569       doms @ doms_inactive in
570
571     (* Calculate the CPU time (ns) and %CPU used by each domain. *)
572     let doms =
573       List.map (
574         function
575         (* We have previous CPU info from which to calculate it? *)
576         | name, Active ({ rd_prev_info = Some prev_info } as rd) ->
577             let cpu_time =
578               Int64.to_float (rd.rd_info.D.cpu_time -^ prev_info.D.cpu_time) in
579             let percent_cpu = 100. *. cpu_time /. total_cpu in
580             let rd = { rd with
581                          rd_cpu_time = cpu_time;
582                          rd_percent_cpu = percent_cpu } in
583             name, Active rd
584         (* For all other domains we can't calculate it, so leave as 0 *)
585         | rd -> rd
586       ) doms in
587
588     (* Calculate the number of block device read/write requests across
589      * all block devices attached to a domain.
590      *)
591     let doms =
592       List.map (
593         function
594         (* Do we have stats from the previous slice? *)
595         | name, Active ({ rd_prev_block_stats = ((_::_) as prev_block_stats) }
596                           as rd) ->
597             let block_stats = rd.rd_block_stats in (* stats now *)
598
599             (* Add all the devices together.  Throw away device names. *)
600             let prev_block_stats =
601               sum_block_stats (List.map snd prev_block_stats) in
602             let block_stats =
603               sum_block_stats (List.map snd block_stats) in
604
605             (* Calculate increase in read & write requests. *)
606             let read_reqs =
607               block_stats.D.rd_req -^ prev_block_stats.D.rd_req in
608             let write_reqs =
609               block_stats.D.wr_req -^ prev_block_stats.D.wr_req in
610
611             let rd = { rd with
612                          rd_block_rd_reqs = Some read_reqs;
613                          rd_block_wr_reqs = Some write_reqs } in
614             name, Active rd
615         (* For all other domains we can't calculate it, so leave as None. *)
616         | rd -> rd
617       ) doms in
618
619     (* Calculate the same as above for network interfaces across
620      * all network interfaces attached to a domain.
621      *)
622     let doms =
623       List.map (
624         function
625         (* Do we have stats from the previous slice? *)
626         | name, Active ({ rd_prev_interface_stats =
627                               ((_::_) as prev_interface_stats) }
628                           as rd) ->
629             let interface_stats = rd.rd_interface_stats in (* stats now *)
630
631             (* Add all the devices together.  Throw away device names. *)
632             let prev_interface_stats =
633               sum_interface_stats (List.map snd prev_interface_stats) in
634             let interface_stats =
635               sum_interface_stats (List.map snd interface_stats) in
636
637             (* Calculate increase in rx & tx bytes. *)
638             let rx_bytes =
639               interface_stats.D.rx_bytes -^ prev_interface_stats.D.rx_bytes in
640             let tx_bytes =
641               interface_stats.D.tx_bytes -^ prev_interface_stats.D.tx_bytes in
642
643             let rd = { rd with
644                          rd_net_rx_bytes = Some rx_bytes;
645                          rd_net_tx_bytes = Some tx_bytes } in
646             name, Active rd
647         (* For all other domains we can't calculate it, so leave as None. *)
648         | rd -> rd
649       ) doms in
650
651     (match !display_mode with
652      | TaskDisplay -> (*---------- Showing domains ----------*)
653          (* Sort domains on current sort_order. *)
654          let doms =
655            let cmp =
656              match !sort_order with
657              | DomainName ->
658                  (fun _ -> 0) (* fallthrough to default name compare *)
659              | Processor ->
660                  (function
661                   | Active rd1, Active rd2 ->
662                       compare rd2.rd_percent_cpu rd1.rd_percent_cpu
663                   | Active _, Inactive -> -1
664                   | Inactive, Active _ -> 1
665                   | Inactive, Inactive -> 0)
666              | Memory ->
667                  (function
668                   | Active { rd_info = info1 }, Active { rd_info = info2 } ->
669                       compare info2.D.memory info1.D.memory
670                   | Active _, Inactive -> -1
671                   | Inactive, Active _ -> 1
672                   | Inactive, Inactive -> 0)
673              | Time ->
674                  (function
675                   | Active { rd_info = info1 }, Active { rd_info = info2 } ->
676                       compare info2.D.cpu_time info1.D.cpu_time
677                   | Active _, Inactive -> -1
678                   | Inactive, Active _ -> 1
679                   | Inactive, Inactive -> 0)
680              | DomainID ->
681                  (function
682                   | Active { rd_domid = id1 }, Active { rd_domid = id2 } ->
683                       compare id1 id2
684                   | Active _, Inactive -> -1
685                   | Inactive, Active _ -> 1
686                   | Inactive, Inactive -> 0)
687              | NetRX ->
688                  (function
689                   | Active { rd_net_rx_bytes = r1 }, Active { rd_net_rx_bytes = r2 } ->
690                       compare r2 r1
691                   | Active _, Inactive -> -1
692                   | Inactive, Active _ -> 1
693                   | Inactive, Inactive -> 0)
694              | NetTX ->
695                  (function
696                   | Active { rd_net_tx_bytes = r1 }, Active { rd_net_tx_bytes = r2 } ->
697                       compare r2 r1
698                   | Active _, Inactive -> -1
699                   | Inactive, Active _ -> 1
700                   | Inactive, Inactive -> 0)
701              | BlockRdRq ->
702                  (function
703                   | Active { rd_block_rd_reqs = r1 }, Active { rd_block_rd_reqs = r2 } ->
704                       compare r2 r1
705                   | Active _, Inactive -> -1
706                   | Inactive, Active _ -> 1
707                   | Inactive, Inactive -> 0)
708              | BlockWrRq ->
709                  (function
710                   | Active { rd_block_wr_reqs = r1 }, Active { rd_block_wr_reqs = r2 } ->
711                       compare r2 r1
712                   | Active _, Inactive -> -1
713                   | Inactive, Active _ -> 1
714                   | Inactive, Inactive -> 0)
715            in
716            let cmp (name1, dom1) (name2, dom2) =
717              let r = cmp (dom1, dom2) in
718              if r <> 0 then r
719              else compare name1 name2
720            in
721            List.sort ~cmp doms in
722
723          (* Print domains. *)
724          attron A.reverse;
725          mvaddstr header_lineno 0
726            (pad cols "   ID S RDRQ WRRQ RXBY TXBY %CPU %MEM    TIME   NAME");
727          attroff A.reverse;
728
729          let rec loop lineno = function
730            | [] -> ()
731            | (name, Active rd) :: doms ->
732                if lineno < lines then (
733                  let state = show_state rd.rd_info.D.state in
734                  let rd_req = show_int64_option rd.rd_block_rd_reqs in
735                  let wr_req = show_int64_option rd.rd_block_wr_reqs in
736                  let rx_bytes = show_int64_option rd.rd_net_rx_bytes in
737                  let tx_bytes = show_int64_option rd.rd_net_tx_bytes in
738                  let percent_cpu = show_percent rd.rd_percent_cpu in
739                  let percent_mem =
740                    100L *^ rd.rd_info.D.memory /^ node_info.C.memory in
741                  let percent_mem = Int64.to_float percent_mem in
742                  let percent_mem = show_percent percent_mem in
743                  let time = show_time rd.rd_info.D.cpu_time in
744
745                  let line = sprintf "%5d %c %s %s %s %s %s %s %s %s"
746                    rd.rd_domid state rd_req wr_req rx_bytes tx_bytes
747                    percent_cpu percent_mem time name in
748                  let line = pad cols line in
749                  mvaddstr lineno 0 line;
750                  loop (lineno+1) doms
751                )
752            | (name, Inactive) :: doms -> (* inactive domain *)
753                if lineno < lines then (
754                  let line =
755                    sprintf
756                      "    -                                           (%s)"
757                      name in
758                  let line = pad cols line in
759                  mvaddstr lineno 0 line;
760                  loop (lineno+1) doms
761                )
762          in
763          loop domains_lineno doms
764
765      | PCPUDisplay -> (*---------- Showing physical CPUs ----------*)
766          (* Get the VCPU info and VCPU->PCPU mappings for active domains.
767           * Also cull some data we don't care about.
768           *)
769          let doms = List.filter_map (
770            function
771            | (name, Active rd) ->
772                (try
773                   let domid = rd.rd_domid in
774                   let maplen = C.cpumaplen nr_pcpus in
775                   let maxinfo = rd.rd_info.D.nr_virt_cpu in
776                   let nr_vcpus, vcpu_infos, cpumaps =
777                     D.get_vcpus rd.rd_dom maxinfo maplen in
778
779                   (* Got previous vcpu_infos for this domain? *)
780                   let prev_vcpu_infos =
781                     try Some (Hashtbl.find last_vcpu_info domid)
782                     with Not_found -> None in
783                   (* Update last_vcpu_info. *)
784                   Hashtbl.replace last_vcpu_info domid vcpu_infos;
785
786                   (match prev_vcpu_infos with
787                    | Some prev_vcpu_infos
788                        when Array.length prev_vcpu_infos = Array.length vcpu_infos ->
789                        Some (domid, name, nr_vcpus, vcpu_infos, prev_vcpu_infos,
790                              cpumaps, maplen)
791                    | _ -> None (* ignore missing / unequal length prev_vcpu_infos *)
792                   );
793                 with
794                   Libvirt.Virterror _ -> None(* ignore transient libvirt errs *)
795                )
796            | (_, Inactive) -> None (* ignore inactive doms *)
797          ) doms in
798          let nr_doms = List.length doms in
799
800          (* Rearrange the data into a matrix.  Major axis (down) is
801           * pCPUs.  Minor axis (right) is domains.  At each node we store:
802           *  cpu_time (on this pCPU only, nanosecs),
803           *  average? (if set, then cpu_time is an average because the
804           *     vCPU is pinned to more than one pCPU)
805           *  running? (if set, we were instantaneously running on this pCPU)
806           *)
807          let empty_node = (0L, false, false) in
808          let pcpus = Array.make_matrix nr_pcpus nr_doms empty_node in
809
810          List.iteri (
811            fun di (domid, name, nr_vcpus, vcpu_infos, prev_vcpu_infos,
812                    cpumaps, maplen) ->
813              (* Which pCPUs can this dom run on? *)
814              for v = 0 to nr_vcpus-1 do
815                let pcpu = vcpu_infos.(v).D.cpu in (* instantaneous pCPU *)
816                let nr_poss_pcpus = ref 0 in (* how many pcpus can it run on? *)
817                for p = 0 to nr_pcpus-1 do
818                  (* vcpu v can reside on pcpu p *)
819                  if C.cpu_usable cpumaps maplen v p then
820                    incr nr_poss_pcpus
821                done;
822                let nr_poss_pcpus = Int64.of_int !nr_poss_pcpus in
823                for p = 0 to nr_pcpus-1 do
824                  (* vcpu v can reside on pcpu p *)
825                  if C.cpu_usable cpumaps maplen v p then
826                    let vcpu_time_on_pcpu =
827                      vcpu_infos.(v).D.vcpu_time
828                      -^ prev_vcpu_infos.(v).D.vcpu_time in
829                    let vcpu_time_on_pcpu =
830                      vcpu_time_on_pcpu /^ nr_poss_pcpus in
831                    pcpus.(p).(di) <-
832                      (vcpu_time_on_pcpu, nr_poss_pcpus > 1L, p = pcpu)
833                done
834              done
835          ) doms;
836
837          (* Sum the CPU time used by each pCPU, for the %CPU column. *)
838          let pcpus_cpu_time = Array.map (
839            fun row ->
840              let cpu_time = ref 0L in
841              for di = 0 to Array.length row-1 do
842                let t, _, _ = row.(di) in
843                cpu_time := !cpu_time +^ t
844              done;
845              Int64.to_float !cpu_time
846          ) pcpus in
847
848          (* Display the pCPUs. *)
849          let dom_names =
850            String.concat "" (
851              List.map (
852                fun (_, name, _, _, _, _, _) ->
853                  let len = String.length name in
854                  let width = max (len+1) 7 in
855                  pad width name
856              ) doms
857            ) in
858          attron A.reverse;
859          mvaddstr header_lineno 0 (pad cols ("PHYCPU %CPU " ^ dom_names));
860          attroff A.reverse;
861
862          Array.iteri (
863            fun p row ->
864              mvaddstr (p+domains_lineno) 0 (sprintf "%4d   " p);
865              let cpu_time = pcpus_cpu_time.(p) in (* ns used on this CPU *)
866              let percent_cpu = 100. *. cpu_time /. total_cpu_per_pcpu in
867              addstr (show_percent percent_cpu);
868              addch 32;
869
870              List.iteri (
871                fun di (domid, name, _, _, _, _, _) ->
872                  let t, is_average, is_running = pcpus.(p).(di) in
873                  let len = String.length name in
874                  let width = max (len+1) 7 in
875                  let str =
876                    if t <= 0L then ""
877                    else (
878                      let t = Int64.to_float t in
879                      let percent = 100. *. t /. total_cpu_per_pcpu in
880                      sprintf "%s%c%c " (show_percent percent)
881                        (if is_average then '=' else ' ')
882                        (if is_running then '#' else ' ')
883                    ) in
884                  addstr (pad width str);
885                  ()
886              ) doms
887          ) pcpus;
888
889      | NetDisplay -> (*---------- Showing network interfaces ----------*)
890          (* Only care about active domains. *)
891          let doms = List.filter_map (
892            function
893            | (name, Active rd) -> Some (name, rd)
894            | (_, Inactive) -> None
895          ) doms in
896
897          (* For each domain we have a list of network interfaces seen
898           * this slice, and seen in the previous slice, which we now
899           * match up to get a list of (domain, interface) for which
900           * we have current & previous knowledge.  (And ignore the rest).
901           *)
902          let devs =
903            List.map (
904              fun (name, rd) ->
905                List.filter_map (
906                  fun (dev, stats) ->
907                    try
908                      (* Have prev slice stats for this device? *)
909                      let prev_stats =
910                        List.assoc dev rd.rd_prev_interface_stats in
911                      Some (dev, name, rd, stats, prev_stats)
912                    with Not_found -> None
913                ) rd.rd_interface_stats
914            ) doms in
915
916          (* Finally we have a list of:
917           * device name, domain name, rd_* stuff, curr stats, prev stats.
918           *)
919          let devs : (string * string * rd_active *
920                        D.interface_stats * D.interface_stats) list =
921            List.flatten devs in
922
923          (* Difference curr slice & prev slice. *)
924          let devs = List.map (
925            fun (dev, name, rd, curr, prev) ->
926              dev, name, rd, diff_interface_stats curr prev
927          ) devs in
928
929          (* Sort by current sort order, but map some of the standard
930           * sort orders into ones which makes sense here.
931           *)
932          let devs =
933            let cmp =
934              match !sort_order with
935              | DomainName ->
936                  (fun _ -> 0) (* fallthrough to default name compare *)
937              | DomainID ->
938                  (fun (_, { rd_domid = id1 }, _, { rd_domid = id2 }) ->
939                     compare id1 id2)
940              | Processor | Memory | Time | BlockRdRq | BlockWrRq
941                  (* fallthrough to RXBY comparison. *)
942              | NetRX ->
943                  (fun ({ D.rx_bytes = b1 }, _, { D.rx_bytes = b2 }, _) ->
944                     compare b2 b1)
945              | NetTX ->
946                  (fun ({ D.tx_bytes = b1 }, _, { D.tx_bytes = b2 }, _) ->
947                     compare b2 b1)
948            in
949            let cmp (dev1, name1, rd1, stats1) (dev2, name2, rd2, stats2) =
950              let r = cmp (stats1, rd1, stats2, rd2) in
951              if r <> 0 then r
952              else compare (dev1, name1) (dev2, name2)
953            in
954            List.sort ~cmp devs in
955
956          (* Print the header for network devices. *)
957          attron A.reverse;
958          mvaddstr header_lineno 0
959            (pad cols "   ID S RXBY TXBY RXPK TXPK DOMAIN       INTERFACE");
960          attroff A.reverse;
961
962          (* Print domains and devices. *)
963          let rec loop lineno = function
964            | [] -> ()
965            | (dev, name, rd, stats) :: devs ->
966                if lineno < lines then (
967                  let state = show_state rd.rd_info.D.state in
968                  let rx_bytes =
969                    if stats.D.rx_bytes >= 0L
970                    then show_int64 stats.D.rx_bytes
971                    else "    " in
972                  let tx_bytes =
973                    if stats.D.tx_bytes >= 0L
974                    then show_int64 stats.D.tx_bytes
975                    else "    " in
976                  let rx_packets =
977                    if stats.D.rx_packets >= 0L
978                    then show_int64 stats.D.rx_packets
979                    else "    " in
980                  let tx_packets =
981                    if stats.D.tx_packets >= 0L
982                    then show_int64 stats.D.tx_packets
983                    else "    " in
984
985                  let line = sprintf "%5d %c %s %s %s %s %-12s %s"
986                    rd.rd_domid state
987                    rx_bytes tx_bytes
988                    rx_packets tx_packets
989                    (pad 12 name) dev in
990                  let line = pad cols line in
991                  mvaddstr lineno 0 line;
992                  loop (lineno+1) devs
993                )
994          in
995          loop domains_lineno devs
996
997      | BlockDisplay -> (*---------- Showing block devices ----------*)
998          (* Only care about active domains. *)
999          let doms = List.filter_map (
1000            function
1001            | (name, Active rd) -> Some (name, rd)
1002            | (_, Inactive) -> None
1003          ) doms in
1004
1005          (* For each domain we have a list of block devices seen
1006           * this slice, and seen in the previous slice, which we now
1007           * match up to get a list of (domain, device) for which
1008           * we have current & previous knowledge.  (And ignore the rest).
1009           *)
1010          let devs =
1011            List.map (
1012              fun (name, rd) ->
1013                List.filter_map (
1014                  fun (dev, stats) ->
1015                    try
1016                      (* Have prev slice stats for this device? *)
1017                      let prev_stats =
1018                        List.assoc dev rd.rd_prev_block_stats in
1019                      Some (dev, name, rd, stats, prev_stats)
1020                    with Not_found -> None
1021                ) rd.rd_block_stats
1022            ) doms in
1023
1024          (* Finally we have a list of:
1025           * device name, domain name, rd_* stuff, curr stats, prev stats.
1026           *)
1027          let devs : (string * string * rd_active *
1028                        D.block_stats * D.block_stats) list =
1029            List.flatten devs in
1030
1031          (* Difference curr slice & prev slice. *)
1032          let devs = List.map (
1033            fun (dev, name, rd, curr, prev) ->
1034              dev, name, rd, diff_block_stats curr prev
1035          ) devs in
1036
1037          (* Sort by current sort order, but map some of the standard
1038           * sort orders into ones which makes sense here.
1039           *)
1040          let devs =
1041            let cmp =
1042              match !sort_order with
1043              | DomainName ->
1044                  (fun _ -> 0) (* fallthrough to default name compare *)
1045              | DomainID ->
1046                  (fun (_, { rd_domid = id1 }, _, { rd_domid = id2 }) ->
1047                     compare id1 id2)
1048              | Processor | Memory | Time | NetRX | NetTX
1049                  (* fallthrough to RDRQ comparison. *)
1050              | BlockRdRq ->
1051                  (fun ({ D.rd_req = b1 }, _, { D.rd_req = b2 }, _) ->
1052                     compare b2 b1)
1053              | BlockWrRq ->
1054                  (fun ({ D.wr_req = b1 }, _, { D.wr_req = b2 }, _) ->
1055                     compare b2 b1)
1056            in
1057            let cmp (dev1, name1, rd1, stats1) (dev2, name2, rd2, stats2) =
1058              let r = cmp (stats1, rd1, stats2, rd2) in
1059              if r <> 0 then r
1060              else compare (dev1, name1) (dev2, name2)
1061            in
1062            List.sort ~cmp devs in
1063
1064          (* Print the header for block devices. *)
1065          attron A.reverse;
1066          mvaddstr header_lineno 0
1067            (pad cols "   ID S RDBY WRBY RDRQ WRRQ DOMAIN       DEVICE");
1068          attroff A.reverse;
1069
1070          (* Print domains and devices. *)
1071          let rec loop lineno = function
1072            | [] -> ()
1073            | (dev, name, rd, stats) :: devs ->
1074                if lineno < lines then (
1075                  let state = show_state rd.rd_info.D.state in
1076                  let rd_bytes =
1077                    if stats.D.rd_bytes >= 0L
1078                    then show_int64 stats.D.rd_bytes
1079                    else "    " in
1080                  let wr_bytes =
1081                    if stats.D.wr_bytes >= 0L
1082                    then show_int64 stats.D.wr_bytes
1083                    else "    " in
1084                  let rd_req =
1085                    if stats.D.rd_req >= 0L
1086                    then show_int64 stats.D.rd_req
1087                    else "    " in
1088                  let wr_req =
1089                    if stats.D.wr_req >= 0L
1090                    then show_int64 stats.D.wr_req
1091                    else "    " in
1092
1093                  let line = sprintf "%5d %c %s %s %s %s %-12s %s"
1094                    rd.rd_domid state
1095                    rd_bytes wr_bytes
1096                    rd_req wr_req
1097                    (pad 12 name) dev in
1098                  let line = pad cols line in
1099                  mvaddstr lineno 0 line;
1100                  loop (lineno+1) devs
1101                )
1102          in
1103          loop domains_lineno devs
1104     );
1105
1106     (* Calculate and print totals. *)
1107     let () =
1108       let totals = List.fold_left (
1109         fun (count, running, blocked, paused, shutdown, shutoff,
1110              crashed, active, inactive,
1111              total_cpu_time, total_memory, total_domU_memory) ->
1112           function
1113           | (name, Active rd) ->
1114               let test state orig =
1115                 if rd.rd_info.D.state = state then orig+1 else orig
1116               in
1117               let running = test D.InfoRunning running in
1118               let blocked = test D.InfoBlocked blocked in
1119               let paused = test D.InfoPaused paused in
1120               let shutdown = test D.InfoShutdown shutdown in
1121               let shutoff = test D.InfoShutoff shutoff in
1122               let crashed = test D.InfoCrashed crashed in
1123
1124               let total_cpu_time = total_cpu_time +. rd.rd_cpu_time in
1125               let total_memory = total_memory +^ rd.rd_info.D.memory in
1126               let total_domU_memory = total_domU_memory +^
1127                 if rd.rd_domid > 0 then rd.rd_info.D.memory else 0L in
1128
1129               (count+1, running, blocked, paused, shutdown, shutoff,
1130                crashed, active+1, inactive,
1131                total_cpu_time, total_memory, total_domU_memory)
1132
1133           | (name, Inactive) -> (* inactive domain *)
1134               (count+1, running, blocked, paused, shutdown, shutoff,
1135                crashed, active, inactive+1,
1136                total_cpu_time, total_memory, total_domU_memory)
1137       ) (0,0,0,0,0,0,0,0,0, 0.,0L,0L) doms in
1138
1139       let (count, running, blocked, paused, shutdown, shutoff,
1140            crashed, active, inactive,
1141            total_cpu_time, total_memory, total_domU_memory) = totals in
1142
1143       mvaddstr summary_lineno 0
1144         (sprintf "%d domains, %d active, %d running, %d sleeping, %d paused, %d inactive D:%d O:%d X:%d"
1145            count active running blocked paused inactive shutdown shutoff
1146            crashed);
1147
1148       (* Total %CPU used, and memory summary. *)
1149       let percent_cpu = 100. *. total_cpu_time /. total_cpu in
1150       mvaddstr (summary_lineno+1) 0
1151         (sprintf "CPU: %2.1f%%  Mem: %Ld MB (%Ld MB by guests)"
1152            percent_cpu (total_memory /^ 1024L) (total_domU_memory /^ 1024L));
1153
1154       (* Time to grab another historical %CPU for the list? *)
1155       if time >= !historical_cpu_last_time +. float !historical_cpu_delay
1156       then (
1157         historical_cpu := percent_cpu :: List.take 10 !historical_cpu;
1158         historical_cpu_last_time := time
1159       );
1160
1161       (* Display historical CPU time. *)
1162       let () =
1163         let x, y = historical_cursor in (* Yes, it's a bug in ocaml-curses *)
1164         let maxwidth = cols - x in
1165         let line =
1166           String.concat " "
1167             (List.map (sprintf "%2.1f%%") !historical_cpu) in
1168         let line = pad maxwidth line in
1169         mvaddstr y x line;
1170         () in
1171
1172       (* Write summary data to CSV file.  See also write_csv_header (). *)
1173       if !csv_enabled then (
1174         (!csv_write) [
1175           hostname; printable_time; node_info.C.model; string_of_int nr_pcpus;
1176           string_of_int count; string_of_int running; string_of_int blocked;
1177           string_of_int paused; string_of_int shutdown; string_of_int shutoff;
1178           string_of_int crashed; string_of_int active; string_of_int inactive;
1179           sprintf "%2.1f" percent_cpu;
1180           Int64.to_string total_memory; Int64.to_string total_domU_memory;
1181           Int64.to_string (Int64.of_float total_cpu_time)
1182         ]
1183       );
1184
1185       ()
1186     in
1187
1188     (* Update last_info, last_time. *)
1189     last_time := time;
1190     Hashtbl.clear last_info;
1191     List.iter (
1192       function
1193       | (_, Active rd) ->
1194           let info = rd.rd_info, rd.rd_block_stats, rd.rd_interface_stats in
1195           Hashtbl.add last_info rd.rd_domid info
1196       | _ -> ()
1197     ) doms;
1198
1199     move message_lineno 0 (* Park cursor in message area, as with top. *)
1200   in
1201
1202   let clear_pcpu_display_data () =
1203     (* Clear out vcpu_info used by PCPUDisplay
1204      * display_mode when we switch back to TaskDisplay mode.
1205      *)
1206     Hashtbl.clear last_vcpu_info
1207   in
1208
1209   redraw, clear_pcpu_display_data
1210
1211 (* Main loop. *)
1212 let rec main_loop state =
1213   if !csv_enabled then write_csv_header ();
1214
1215   while not !quit do
1216     redraw state;
1217     refresh ();
1218
1219     (* Clear up unused virDomainPtr objects. *)
1220     Gc.compact ();
1221
1222     if not !batch_mode then
1223       get_key_press state
1224     else (* Batch mode - just sleep, ignore keys. *)
1225       Unix.sleep (!delay / 1000);
1226
1227     (* Max iterations? *)
1228     if !iterations >= 0 then (
1229       decr iterations;
1230       if !iterations = 0 then quit := true
1231     );
1232   done
1233
1234 and get_key_press state =
1235   (* Read the next key, waiting up to !delay milliseconds. *)
1236   timeout !delay;
1237   let k = getch () in
1238   timeout (-1); (* Reset to blocking mode. *)
1239
1240   if k >= 0 && k <> 32 (* ' ' *) && k <> 12 (* ^L *) && k <> Key.resize
1241   then (
1242     if k = Char.code 'q' then quit := true
1243     else if k = Char.code 'h' then show_help state
1244     else if k = Char.code 's' || k = Char.code 'd' then change_delay ()
1245     else if k = Char.code 'M' then sort_order := Memory
1246     else if k = Char.code 'P' then sort_order := Processor
1247     else if k = Char.code 'T' then sort_order := Time
1248     else if k = Char.code 'N' then sort_order := DomainID
1249     else if k = Char.code 'F' then change_sort_order ()
1250     else if k = Char.code '0' then set_tasks_display ()
1251     else if k = Char.code '1' then toggle_pcpu_display ()
1252     else if k = Char.code '2' then toggle_net_display ()
1253     else if k = Char.code '3' then toggle_block_display ()
1254     else if k = Char.code 'W' then write_init_file ()
1255     else unknown_command k
1256   )
1257
1258 and change_delay () =
1259   print_msg (sprintf "Change delay from %.1f to: " (float !delay /. 1000.));
1260   let str = get_string 16 in
1261   (* Try to parse the number. *)
1262   let error =
1263     try
1264       let newdelay = float_of_string str in
1265       if newdelay <= 0. then (
1266         print_msg "Delay must be > 0"; true
1267       ) else (
1268         delay := int_of_float (newdelay *. 1000.); false
1269       )
1270     with
1271       Failure "float_of_string" ->
1272         print_msg "Not a valid number"; true in
1273   sleep (if error then 2 else 1)
1274
1275 and change_sort_order () =
1276   clear ();
1277   let lines, cols = get_size () in
1278
1279   mvaddstr top_lineno 0 "Set sort order for main display";
1280   mvaddstr summary_lineno 0 "Type key or use up and down cursor keys.";
1281
1282   attron A.reverse;
1283   mvaddstr header_lineno 0 (pad cols "KEY   Sort field");
1284   attroff A.reverse;
1285
1286   let accelerator_key = function
1287     | Memory -> "(key: M)"
1288     | Processor -> "(key: P)"
1289     | Time -> "(key: T)"
1290     | DomainID -> "(key: N)"
1291     | _ -> (* all others have to be changed from here *) ""
1292   in
1293
1294   let rec key_of_int = function
1295     | i when i < 10 -> Char.chr (i + Char.code '0')
1296     | i when i < 20 -> Char.chr (i + Char.code 'a')
1297     | _ -> assert false
1298   and int_of_key = function
1299     | k when k >= 0x30 && k <= 0x39 (* '0' - '9' *) -> k - 0x30
1300     | k when k >= 0x61 && k <= 0x7a (* 'a' - 'j' *) -> k - 0x61 + 10
1301     | k when k >= 0x41 && k <= 0x6a (* 'A' - 'J' *) -> k - 0x41 + 10
1302     | _ -> -1
1303   in
1304
1305   (* Display possible sort fields. *)
1306   let selected_index = ref 0 in
1307   List.iteri (
1308     fun i ord ->
1309       let selected = !sort_order = ord in
1310       if selected then selected_index := i;
1311       mvaddstr (domains_lineno+i) 0
1312         (sprintf "  %c %s %s %s"
1313            (key_of_int i) (if selected then "*" else " ")
1314            (printable_sort_order ord)
1315            (accelerator_key ord))
1316   ) all_sort_fields;
1317
1318   move message_lineno 0;
1319   refresh ();
1320   let k = getch () in
1321   if k >= 0 && k <> 32 && k <> Char.code 'q' && k <> 13 then (
1322     let new_order, loop =
1323       (* Redraw the display. *)
1324       if k = 12 (* ^L *) then None, true
1325       (* Make the UP and DOWN arrow keys do something useful. *)
1326       else if k = Key.up then (
1327         if !selected_index > 0 then
1328           Some (List.nth all_sort_fields (!selected_index-1)), true
1329         else
1330           None, true
1331       )
1332       else if k = Key.down then (
1333         if !selected_index < List.length all_sort_fields - 1 then
1334           Some (List.nth all_sort_fields (!selected_index+1)), true
1335         else
1336           None, true
1337       )
1338       (* Also understand the regular accelerator keys. *)
1339       else if k = Char.code 'M' then
1340         Some Memory, false
1341       else if k = Char.code 'P' then
1342         Some Processor, false
1343       else if k = Char.code 'T' then
1344         Some Time, false
1345       else if k = Char.code 'N' then
1346         Some DomainID, false
1347       else (
1348         (* It's one of the KEYs. *)
1349         let i = int_of_key k in
1350         if i >= 0 && i < List.length all_sort_fields then
1351           Some (List.nth all_sort_fields i), false
1352         else
1353           None, true
1354       ) in
1355
1356     (match new_order with
1357      | None -> ()
1358      | Some new_order ->
1359          sort_order := new_order;
1360          print_msg (sprintf "Sort order changed to: %s"
1361                       (printable_sort_order new_order));
1362          if not loop then sleep 1
1363     );
1364
1365     if loop then change_sort_order ()
1366   )
1367
1368 (* Note: We need to clear_pcpu_display_data every time
1369  * we _leave_ PCPUDisplay mode.
1370  *)
1371 and set_tasks_display () =              (* key 0 *)
1372   if !display_mode = PCPUDisplay then clear_pcpu_display_data ();
1373   display_mode := TaskDisplay
1374
1375 and toggle_pcpu_display () =            (* key 1 *)
1376   display_mode :=
1377     match !display_mode with
1378     | TaskDisplay | NetDisplay | BlockDisplay -> PCPUDisplay
1379     | PCPUDisplay -> clear_pcpu_display_data (); TaskDisplay
1380
1381 and toggle_net_display () =             (* key 2 *)
1382   display_mode :=
1383     match !display_mode with
1384     | PCPUDisplay -> clear_pcpu_display_data (); NetDisplay
1385     | TaskDisplay | BlockDisplay -> NetDisplay
1386     | NetDisplay -> TaskDisplay
1387
1388 and toggle_block_display () =           (* key 3 *)
1389   display_mode :=
1390     match !display_mode with
1391     | PCPUDisplay -> clear_pcpu_display_data (); BlockDisplay
1392     | TaskDisplay | NetDisplay -> BlockDisplay
1393     | BlockDisplay -> TaskDisplay
1394
1395 (* Write an init file. *)
1396 and write_init_file () =
1397   match !init_file with
1398   | NoInitFile -> ()                    (* Do nothing if --no-init-file *)
1399   | DefaultInitFile ->
1400       let home = try Sys.getenv "HOME" with Not_found -> "/" in
1401       let filename = home // ".virt-toprc" in
1402       _write_init_file filename
1403   | InitFile filename ->
1404       _write_init_file filename
1405
1406 and _write_init_file filename =
1407   try
1408     (* Create the new file as filename.new. *)
1409     let chan = open_out (filename ^ ".new") in
1410
1411     let time = Unix.gettimeofday () in
1412     let tm = Unix.localtime time in
1413     let printable_date_time =
1414       sprintf "%04d-%02d-%02d %02d:%02d:%02d"
1415         (tm.Unix.tm_year + 1900) (tm.Unix.tm_mon+1) tm.Unix.tm_mday
1416         tm.Unix.tm_hour tm.Unix.tm_min tm.Unix.tm_sec in
1417     let username =
1418       try
1419         let uid = Unix.geteuid () in
1420         (Unix.getpwuid uid).Unix.pw_name
1421       with
1422         Not_found -> "unknown" in
1423
1424     let fp = fprintf in
1425     let nl () = fp chan "\n" in
1426     fp chan "# .virt-toprc virt-top configuration file\n";
1427     fp chan "# generated on %s by %s\n" printable_date_time username;
1428     nl ();
1429     fp chan "display %s\n" (cli_of_display !display_mode);
1430     fp chan "delay %g\n" (float !delay /. 1000.);
1431     fp chan "hist-cpu %d\n" !historical_cpu_delay;
1432     if !iterations <> -1 then fp chan "iterations %d\n" !iterations;
1433     fp chan "sort %s\n" (cli_of_sort_order !sort_order);
1434     (match !uri with
1435      | None -> ()
1436      | Some uri -> fp chan "connect %s\n" uri
1437     );
1438     if !batch_mode = true then fp chan "batch true\n";
1439     if !secure_mode = true then fp chan "secure true\n";
1440     nl ();
1441     fp chan "# To send debug and error messages to a file, uncomment next line\n";
1442     fp chan "#debug virt-top.out\n";
1443     nl ();
1444     fp chan "# Enable CSV output to the named file\n";
1445     fp chan "#csv virt-top.csv\n";
1446     nl ();
1447     fp chan "# To protect this file from being overwritten, uncomment next line\n";
1448     fp chan "#overwrite-init-file false\n";
1449
1450     close_out chan;
1451
1452     (* If the file exists, rename it as filename.old. *)
1453     (try Unix.rename filename (filename ^ ".old")
1454      with Unix.Unix_error _ -> ());
1455
1456     (* Rename filename.new to filename. *)
1457     Unix.rename (filename ^ ".new") filename;
1458
1459     print_msg (sprintf "Wrote settings to %s" filename); sleep 2
1460   with
1461   | Sys_error err -> print_msg "Error: %s"; sleep 2
1462   | Unix.Unix_error (err, fn, str) ->
1463       print_msg (sprintf "Error: %s %s %s" (Unix.error_message err) fn str);
1464       sleep 2
1465
1466 and show_help (_, _, _, hostname,
1467                (libvirt_major, libvirt_minor, libvirt_release)) =
1468   clear ();
1469
1470   (* Get the screen/window size. *)
1471   let lines, cols = get_size () in
1472
1473   (* Banner at the top of the screen. *)
1474   let banner =
1475     sprintf "virt-top %s (libvirt %d.%d.%d) by Red Hat"
1476       Libvirt_version.version libvirt_major libvirt_minor libvirt_release in
1477   let banner = pad cols banner in
1478   attron A.reverse;
1479   mvaddstr 0 0 banner;
1480   attroff A.reverse;
1481
1482   (* Status. *)
1483   mvaddstr 1 0
1484     (sprintf "Delay: %.1f secs; Batch: %s; Secure: %s; Sort: %s"
1485        (float !delay /. 1000.)
1486        (if !batch_mode then "On" else "Off")
1487        (if !secure_mode then "On" else "Off")
1488        (printable_sort_order !sort_order));
1489   mvaddstr 2 0
1490     (sprintf "Connect: %s; Hostname: %s"
1491        (match !uri with None -> "default" | Some s -> s)
1492        hostname);
1493
1494   (* Misc keys on left. *)
1495   let banner = pad 38 "MAIN KEYS" in
1496   attron A.reverse;
1497   mvaddstr header_lineno 1 banner;
1498   attroff A.reverse;
1499
1500   let get_lineno =
1501     let lineno = ref domains_lineno in
1502     fun () -> let i = !lineno in incr lineno; i
1503   in
1504   let key keys description =
1505     let lineno = get_lineno () in
1506     move lineno 1; attron A.bold; addstr keys; attroff A.bold;
1507     move lineno 10; addstr description; ()
1508   in
1509   key "space ^L" "Update display";
1510   key "q"        "Quit";
1511   key "d s"      "Set update interval";
1512   key "h"        "Help";
1513
1514   (* Sort order. *)
1515   ignore (get_lineno ());
1516   let banner = pad 38 "SORTING" in
1517   attron A.reverse;
1518   mvaddstr (get_lineno ()) 1 banner;
1519   attroff A.reverse;
1520
1521   key "P" "Sort by %CPU";
1522   key "M" "Sort by %MEM";
1523   key "T" "Sort by TIME";
1524   key "N" "Sort by ID";
1525   key "F" "Select sort field";
1526
1527   (* Display modes on right. *)
1528   let banner = pad 39 "DISPLAY MODES" in
1529   attron A.reverse;
1530   mvaddstr header_lineno 40 banner;
1531   attroff A.reverse;
1532
1533   let get_lineno =
1534     let lineno = ref domains_lineno in
1535     fun () -> let i = !lineno in incr lineno; i
1536   in
1537   let key keys description =
1538     let lineno = get_lineno () in
1539     move lineno 40; attron A.bold; addstr keys; attroff A.bold;
1540     move lineno 49; addstr description; ()
1541   in
1542   key "0" "Domains display";
1543   key "1" "Toggle physical CPUs";
1544   key "2" "Toggle network interfaces";
1545   key "3" "Toggle block devices";
1546
1547   (* Update screen and wait for key press. *)
1548   mvaddstr (lines-1) 0
1549     "More help in virt-top(1) man page. Press any key to return.";
1550   refresh ();
1551   ignore (getch ())
1552
1553 and unknown_command k =
1554   print_msg "Unknown command - try 'h' for help";
1555   sleep 1