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