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