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