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