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