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