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