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