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