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