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