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