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