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