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