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