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