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