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