1 (* 'top'-like tool for libvirt domains.
2 (C) Copyright 2007-2009 Richard W.M. Jones, Red Hat Inc.
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.
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.
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.
24 open Virt_top_gettext.Gettext
27 module C = Libvirt.Connect
28 module D = Libvirt.Domain
29 module N = Libvirt.Network
31 let rcfile = ".virt-toprc"
33 (* Hook for XML support (see virt_top_xml.ml). *)
34 let parse_device_xml : (int -> [>`R] D.t -> string list * string list) ref =
39 (* Hooks for CSV support (see virt_top_csv.ml). *)
40 let csv_start : (string -> unit) ref =
42 fun _ -> failwith (s_"virt-top was compiled without support for CSV files")
44 let csv_write : (string list -> unit) ref =
49 (* Hook for calendar support (see virt_top_calendar.ml). *)
50 let parse_date_time : (string -> float) ref =
53 failwith (s_"virt-top was compiled without support for dates and times")
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
64 let printable_sort_order = function
65 | Processor -> s_"%CPU"
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
79 | "name" -> DomainName
80 | "netrx" -> NetRX | "nettx" -> NetTX
81 | "blockrdrq" -> BlockRdRq | "blockwrrq" -> BlockWrRq
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
90 | DomainName -> "name"
93 | BlockRdRq -> "blockrdrq"
94 | BlockWrRq -> "blockwrrq"
96 (* Current major display mode: TaskDisplay is the normal display. *)
97 type display = TaskDisplay | PCPUDisplay | BlockDisplay | NetDisplay
99 let display_of_cli = function
100 | "task" -> TaskDisplay
101 | "pcpu" -> PCPUDisplay
102 | "block" -> BlockDisplay
103 | "net" -> NetDisplay
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"
113 type init_file = NoInitFile | DefaultInitFile | InitFile of string
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
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 let stream_mode = ref false
134 let block_in_bytes = ref false
136 (* Tuple of never-changing data returned by start_up function. *)
138 Libvirt.ro C.t * bool * bool * bool * bool * C.node_info * string *
141 (* Function to read command line arguments and go into curses mode. *)
143 (* Read command line arguments. *)
144 let rec set_delay newdelay =
145 if newdelay <= 0. then
146 failwith (s_"-d: cannot set a negative delay");
147 delay := int_of_float (newdelay *. 1000.)
148 and set_uri = function "" -> uri := None | u -> uri := Some u
149 and set_sort order = sort_order := sort_order_of_cli order
150 and set_pcpu_mode () = display_mode := PCPUDisplay
151 and set_net_mode () = display_mode := NetDisplay
152 and set_block_mode () = display_mode := BlockDisplay
153 and set_csv filename =
154 (!csv_start) filename;
156 and no_init_file () = init_file := NoInitFile
157 and set_init_file filename = init_file := InitFile filename
158 and set_end_time time = end_time := Some ((!parse_date_time) time)
159 and display_version () =
160 printf "virt-top %s ocaml-libvirt %s\n"
161 Virt_top_version.version Libvirt_version.version;
164 let argspec = Arg.align [
165 "-1", Arg.Unit set_pcpu_mode,
166 " " ^ s_"Start by displaying pCPUs (default: tasks)";
167 "-2", Arg.Unit set_net_mode,
168 " " ^ s_"Start by displaying network interfaces";
169 "-3", Arg.Unit set_block_mode,
170 " " ^ s_"Start by displaying block devices";
171 "-b", Arg.Set batch_mode,
172 " " ^ s_"Batch mode";
173 "-c", Arg.String set_uri,
174 "uri " ^ s_"Connect to URI (default: Xen)";
175 "--connect", Arg.String set_uri,
176 "uri " ^ s_"Connect to URI (default: Xen)";
177 "--csv", Arg.String set_csv,
178 "file " ^ s_"Log statistics to CSV file";
179 "--no-csv-cpu", Arg.Clear csv_cpu,
180 " " ^ s_"Disable CPU stats in CSV";
181 "--no-csv-block", Arg.Clear csv_block,
182 " " ^ s_"Disable block device stats in CSV";
183 "--no-csv-net", Arg.Clear csv_net,
184 " " ^ s_"Disable net stats in CSV";
185 "-d", Arg.Float set_delay,
186 "delay " ^ s_"Delay time interval (seconds)";
187 "--debug", Arg.Set_string debug_file,
188 "file " ^ s_"Send debug messages to file";
189 "--end-time", Arg.String set_end_time,
190 "time " ^ s_"Exit at given time";
191 "--hist-cpu", Arg.Set_int historical_cpu_delay,
192 "secs " ^ s_"Historical CPU delay";
193 "--init-file", Arg.String set_init_file,
194 "file " ^ s_"Set name of init file";
195 "--no-init-file", Arg.Unit no_init_file,
196 " " ^ s_"Do not read init file";
197 "-n", Arg.Set_int iterations,
198 "iterations " ^ s_"Number of iterations to run";
199 "-o", Arg.String set_sort,
200 "sort " ^ sprintf (f_"Set sort order (%s)") "cpu|mem|time|id|name";
201 "-s", Arg.Set secure_mode,
202 " " ^ s_"Secure (\"kiosk\") mode";
203 "--script", Arg.Set script_mode,
204 " " ^ s_"Run from a script (no user interface)";
205 "--stream", Arg.Set stream_mode,
206 " " ^ s_"dump output to stdout (no userinterface)";
207 "--block-in-bytes", Arg.Set block_in_bytes,
208 " " ^ s_"show block device load in bytes rather than reqs";
209 "--version", Arg.Unit display_version,
210 " " ^ s_"Display version number and exit";
213 raise (Arg.Bad (sprintf (f_"%s: unknown parameter") str)) in
214 let usage_msg = s_"virt-top : a 'top'-like utility for virtualization
220 Arg.parse argspec anon_fun usage_msg;
222 (* Read the init file. *)
223 let try_to_read_init_file filename =
224 let config = read_config_file filename in
227 | _, "display", mode -> display_mode := display_of_cli mode
228 | _, "delay", secs -> set_delay (float_of_string secs)
229 | _, "hist-cpu", secs -> historical_cpu_delay := int_of_string secs
230 | _, "iterations", n -> iterations := int_of_string n
231 | _, "sort", order -> set_sort order
232 | _, "connect", uri -> set_uri uri
233 | _, "debug", filename -> debug_file := filename
234 | _, "csv", filename -> set_csv filename
235 | _, "csv-cpu", b -> csv_cpu := bool_of_string b
236 | _, "csv-block", b -> csv_block := bool_of_string b
237 | _, "csv-net", b -> csv_net := bool_of_string b
238 | _, "batch", b -> batch_mode := bool_of_string b
239 | _, "secure", b -> secure_mode := bool_of_string b
240 | _, "script", b -> script_mode := bool_of_string b
241 | _, "stream", b -> stream_mode := bool_of_string b
242 | _, "block-in-bytes", b -> block_in_bytes := bool_of_string b
243 | _, "end-time", t -> set_end_time t
244 | _, "overwrite-init-file", "false" -> no_init_file ()
246 eprintf (f_"%s:%d: configuration item ``%s'' ignored\n%!")
250 (match !init_file with
253 let home = try Sys.getenv "HOME" with Not_found -> "/" in
254 let filename = home // rcfile in
255 try_to_read_init_file filename
256 | InitFile filename ->
257 try_to_read_init_file filename
260 (* Connect to the hypervisor before going into curses mode, since
261 * this is the most likely thing to fail.
265 try C.connect_readonly ?name ()
267 Libvirt.Virterror err ->
268 prerr_endline (Libvirt.Virterror.to_string err);
269 (* If non-root and no explicit connection URI, print a warning. *)
270 if Unix.geteuid () <> 0 && name = None then (
271 print_endline (s_"NB: If you want to monitor a local Xen hypervisor, you usually need to be root");
275 (* Get the node_info. This never changes, right? So we get it just once. *)
276 let node_info = C.get_node_info conn in
278 (* Hostname and libvirt library version also don't change. *)
280 try C.get_hostname conn
282 (* qemu:/// and other URIs didn't support virConnectGetHostname until
283 * libvirt 0.3.3. Before that they'd throw a virterror. *)
284 | Libvirt.Virterror _
285 | Libvirt.Not_supported "virConnectGetHostname" -> "unknown" in
287 let libvirt_version =
288 let v, _ = Libvirt.get_version () in
289 v / 1_000_000, (v / 1_000) mod 1_000, v mod 1_000 in
291 (* Open debug file if specified.
292 * NB: Do this just before jumping into curses mode.
294 (match !debug_file with
295 | "" -> (* No debug file specified, send stderr to /dev/null unless
296 * we're in script mode.
298 if not !script_mode && not !stream_mode then (
299 let fd = Unix.openfile "/dev/null" [Unix.O_WRONLY] 0o644 in
300 Unix.dup2 fd Unix.stderr;
303 | filename -> (* Send stderr to the named file. *)
305 Unix.openfile filename [Unix.O_WRONLY;Unix.O_CREAT;Unix.O_TRUNC]
307 Unix.dup2 fd Unix.stderr;
311 (* Curses voodoo (see ncurses(3)). *)
312 if not !script_mode && not !stream_mode then (
317 let stdscr = stdscr () in
318 ignore (intrflush stdscr false);
319 ignore (keypad stdscr true);
323 (* This tuple of static information is called 'setup' in other parts
324 * of this program, and is passed to other functions such as redraw and
325 * main_loop. See virt_top_main.ml.
328 !batch_mode, !script_mode, !csv_enabled, !stream_mode, (* immutable modes *)
329 node_info, hostname, libvirt_version (* info that doesn't change *)
332 (* Show a domain state (the 'S' column). *)
333 let show_state = function
334 | D.InfoNoState -> '?'
335 | D.InfoRunning -> 'R'
336 | D.InfoBlocked -> 'S'
337 | D.InfoPaused -> 'P'
338 | D.InfoShutdown -> 'D'
339 | D.InfoShutoff -> 'O'
340 | D.InfoCrashed -> 'X'
342 (* Sleep in seconds. *)
343 let sleep = Unix.sleep
345 (* Sleep in milliseconds. *)
347 ignore (Unix.select [] [] [] (float n /. 1000.))
349 (* The curses getstr/getnstr functions are just weird.
350 * This helper function also enables echo temporarily.
352 let get_string maxlen =
354 let str = String.create maxlen in
355 let ok = getstr str in (* Safe because binding calls getnstr. *)
359 (* Chop at first '\0'. *)
361 let i = String.index str '\000' in
364 Not_found -> str (* it is full maxlen bytes *)
369 let summary_lineno = 1 (* this takes 2 lines *)
370 let message_lineno = 3
371 let header_lineno = 4
372 let domains_lineno = 5
374 (* Easier to use versions of curses functions addstr, mvaddstr, etc. *)
375 let move y x = ignore (move y x)
376 let refresh () = ignore (refresh ())
377 let addch c = ignore (addch (int_of_char c))
378 let addstr s = ignore (addstr s)
379 let mvaddstr y x s = ignore (mvaddstr y x s)
381 (* Print in the "message area". *)
382 let clear_msg () = move message_lineno 0; clrtoeol ()
383 let print_msg str = clear_msg (); mvaddstr message_lineno 0 str
385 (* Intermediate "domain + stats" structure that we use to collect
386 * everything we know about a domain within the collect function.
388 type rd_domain = Inactive | Active of rd_active
390 rd_domid : int; (* Domain ID. *)
391 rd_dom : [`R] D.t; (* Domain object. *)
392 rd_info : D.info; (* Domain CPU info now. *)
393 rd_block_stats : (string * D.block_stats) list;
394 (* Domain block stats now. *)
395 rd_interface_stats : (string * D.interface_stats) list;
396 (* Domain net stats now. *)
397 rd_prev_info : D.info option; (* Domain CPU info previously. *)
398 rd_prev_block_stats : (string * D.block_stats) list;
399 (* Domain block stats prev. *)
400 rd_prev_interface_stats : (string * D.interface_stats) list;
401 (* Domain interface stats prev. *)
402 (* The following are since the last slice, or 0 if cannot be calculated: *)
403 rd_cpu_time : float; (* CPU time used in nanoseconds. *)
404 rd_percent_cpu : float; (* CPU time as percent of total. *)
405 (* The following are since the last slice, or None if cannot be calc'd: *)
406 rd_block_rd_reqs : int64 option; (* Number of block device read rqs. *)
407 rd_block_wr_reqs : int64 option; (* Number of block device write rqs. *)
408 rd_block_rd_bytes : int64 option; (* Number of bytes block device read *)
409 rd_block_wr_bytes : int64 option; (* Number of bytes block device write *)
410 (* _info fields includes the number considering --block_in_bytes option *)
411 rd_block_rd_info : int64 option; (* Block device read info for user *)
412 rd_block_wr_info : int64 option; (* Block device read info for user *)
414 rd_net_rx_bytes : int64 option; (* Number of bytes received. *)
415 rd_net_tx_bytes : int64 option; (* Number of bytes transmitted. *)
419 let collect, clear_pcpu_display_data =
420 (* We cache the list of block devices and interfaces for each domain
421 * here, so we don't need to reparse the XML each time.
423 let devices = Hashtbl.create 13 in
425 (* Function to get the list of block devices, network interfaces for
426 * a particular domain. Get it from the devices cache, and if not
427 * there then parse the domain XML.
429 let get_devices id dom =
430 try Hashtbl.find devices id
432 let blkdevs, netifs = (!parse_device_xml) id dom in
433 Hashtbl.replace devices id (blkdevs, netifs);
437 (* We save the state of domains across redraws here, which allows us
438 * to deduce %CPU usage from the running total.
440 let last_info = Hashtbl.create 13 in
441 let last_time = ref (Unix.gettimeofday ()) in
443 (* Save vcpuinfo structures across redraws too (only for pCPU display). *)
444 let last_vcpu_info = Hashtbl.create 13 in
446 let clear_pcpu_display_data () =
447 (* Clear out vcpu_info used by PCPUDisplay display_mode
448 * when we switch back to TaskDisplay mode.
450 Hashtbl.clear last_vcpu_info
453 let collect (conn, _, _, _, _, node_info, _, _) =
454 (* Number of physical CPUs (some may be disabled). *)
455 let nr_pcpus = C.maxcpus_of_node_info node_info in
457 (* Get the current time. *)
458 let time = Unix.gettimeofday () in
459 let tm = Unix.localtime time in
461 sprintf "%02d:%02d:%02d" tm.Unix.tm_hour tm.Unix.tm_min tm.Unix.tm_sec in
463 (* What's the total CPU time elapsed since we were last called? (ns) *)
464 let total_cpu_per_pcpu = 1_000_000_000. *. (time -. !last_time) in
465 (* Avoid division by zero. *)
466 let total_cpu_per_pcpu =
467 if total_cpu_per_pcpu <= 0. then 1. else total_cpu_per_pcpu in
468 let total_cpu = float node_info.C.cpus *. total_cpu_per_pcpu in
470 (* Get the domains. Match up with their last_info (if any). *)
472 (* Active domains. *)
473 let n = C.num_of_domains conn in
475 if n > 0 then Array.to_list (C.list_domains conn n)
481 let dom = D.lookup_by_id conn id in
482 let name = D.get_name dom in
483 let blkdevs, netifs = get_devices id dom in
485 (* Get current CPU, block and network stats. *)
486 let info = D.get_info dom in
488 try List.map (fun dev -> dev, D.block_stats dom dev) blkdevs
490 | Libvirt.Not_supported "virDomainBlockStats"
491 | Libvirt.Virterror _ -> [] in
492 let interface_stats =
493 try List.map (fun dev -> dev, D.interface_stats dom dev) netifs
495 | Libvirt.Not_supported "virDomainInterfaceStats"
496 | Libvirt.Virterror _ -> [] in
498 let prev_info, prev_block_stats, prev_interface_stats =
500 let prev_info, prev_block_stats, prev_interface_stats =
501 Hashtbl.find last_info id in
502 Some prev_info, prev_block_stats, prev_interface_stats
503 with Not_found -> None, [], [] in
506 rd_domid = id; rd_dom = dom; rd_info = info;
507 rd_block_stats = block_stats;
508 rd_interface_stats = interface_stats;
509 rd_prev_info = prev_info;
510 rd_prev_block_stats = prev_block_stats;
511 rd_prev_interface_stats = prev_interface_stats;
512 rd_cpu_time = 0.; rd_percent_cpu = 0.;
513 rd_block_rd_reqs = None; rd_block_wr_reqs = None;
514 rd_block_rd_bytes = None; rd_block_wr_bytes = None;
515 rd_block_rd_info = None; rd_block_wr_info = None;
516 rd_net_rx_bytes = None; rd_net_tx_bytes = None;
519 Libvirt.Virterror _ -> None (* ignore transient error *)
522 (* Inactive domains. *)
525 let n = C.num_of_defined_domains conn in
527 if n > 0 then Array.to_list (C.list_defined_domains conn n)
529 List.map (fun name -> name, Inactive) names
531 (* Ignore transient errors, in particular errors from
532 * num_of_defined_domains if it cannot contact xend.
534 | Libvirt.Virterror _ -> [] in
536 doms @ doms_inactive in
538 (* Calculate the CPU time (ns) and %CPU used by each domain. *)
542 (* We have previous CPU info from which to calculate it? *)
543 | name, Active ({ rd_prev_info = Some prev_info } as rd) ->
545 Int64.to_float (rd.rd_info.D.cpu_time -^ prev_info.D.cpu_time) in
546 let percent_cpu = 100. *. cpu_time /. total_cpu in
548 rd_cpu_time = cpu_time;
549 rd_percent_cpu = percent_cpu } in
551 (* For all other domains we can't calculate it, so leave as 0 *)
555 (* Calculate the number of block device read/write requests across
556 * all block devices attached to a domain.
561 (* Do we have stats from the previous slice? *)
562 | name, Active ({ rd_prev_block_stats = ((_::_) as prev_block_stats) }
564 let block_stats = rd.rd_block_stats in (* stats now *)
566 (* Add all the devices together. Throw away device names. *)
567 let prev_block_stats =
568 sum_block_stats (List.map snd prev_block_stats) in
570 sum_block_stats (List.map snd block_stats) in
572 (* Calculate increase in read & write requests. *)
574 block_stats.D.rd_req -^ prev_block_stats.D.rd_req in
576 block_stats.D.wr_req -^ prev_block_stats.D.wr_req in
578 block_stats.D.rd_bytes -^ prev_block_stats.D.rd_bytes in
580 block_stats.D.wr_bytes -^ prev_block_stats.D.wr_bytes in
583 rd_block_rd_reqs = Some read_reqs;
584 rd_block_wr_reqs = Some write_reqs;
585 rd_block_rd_bytes = Some read_bytes;
586 rd_block_wr_bytes = Some write_bytes;
589 rd_block_rd_info = if !block_in_bytes then
590 rd.rd_block_rd_bytes else rd.rd_block_rd_reqs;
591 rd_block_wr_info = if !block_in_bytes then
592 rd.rd_block_wr_bytes else rd.rd_block_wr_reqs;
595 (* For all other domains we can't calculate it, so leave as None. *)
599 (* Calculate the same as above for network interfaces across
600 * all network interfaces attached to a domain.
605 (* Do we have stats from the previous slice? *)
606 | name, Active ({ rd_prev_interface_stats =
607 ((_::_) as prev_interface_stats) }
609 let interface_stats = rd.rd_interface_stats in (* stats now *)
611 (* Add all the devices together. Throw away device names. *)
612 let prev_interface_stats =
613 sum_interface_stats (List.map snd prev_interface_stats) in
614 let interface_stats =
615 sum_interface_stats (List.map snd interface_stats) in
617 (* Calculate increase in rx & tx bytes. *)
619 interface_stats.D.rx_bytes -^ prev_interface_stats.D.rx_bytes in
621 interface_stats.D.tx_bytes -^ prev_interface_stats.D.tx_bytes in
624 rd_net_rx_bytes = Some rx_bytes;
625 rd_net_tx_bytes = Some tx_bytes } in
627 (* For all other domains we can't calculate it, so leave as None. *)
631 (* Collect some extra information in PCPUDisplay display_mode. *)
633 if !display_mode = PCPUDisplay then (
634 (* Get the VCPU info and VCPU->PCPU mappings for active domains.
635 * Also cull some data we don't care about.
637 let doms = List.filter_map (
639 | (name, Active rd) ->
641 let domid = rd.rd_domid in
642 let maplen = C.cpumaplen nr_pcpus in
643 let maxinfo = rd.rd_info.D.nr_virt_cpu in
644 let nr_vcpus, vcpu_infos, cpumaps =
645 D.get_vcpus rd.rd_dom maxinfo maplen in
647 (* Got previous vcpu_infos for this domain? *)
648 let prev_vcpu_infos =
649 try Some (Hashtbl.find last_vcpu_info domid)
650 with Not_found -> None in
651 (* Update last_vcpu_info. *)
652 Hashtbl.replace last_vcpu_info domid vcpu_infos;
654 (match prev_vcpu_infos with
655 | Some prev_vcpu_infos
656 when Array.length prev_vcpu_infos = Array.length vcpu_infos ->
657 Some (domid, name, nr_vcpus, vcpu_infos, prev_vcpu_infos,
659 | _ -> None (* ignore missing / unequal length prev_vcpu_infos *)
662 Libvirt.Virterror _ -> None(* ignore transient libvirt errs *)
664 | (_, Inactive) -> None (* ignore inactive doms *)
666 let nr_doms = List.length doms in
668 (* Rearrange the data into a matrix. Major axis (down) is
669 * pCPUs. Minor axis (right) is domains. At each node we store:
670 * cpu_time (on this pCPU only, nanosecs),
671 * average? (if set, then cpu_time is an average because the
672 * vCPU is pinned to more than one pCPU)
673 * running? (if set, we were instantaneously running on this pCPU)
675 let empty_node = (0L, false, false) in
676 let pcpus = Array.make_matrix nr_pcpus nr_doms empty_node in
679 fun di (domid, name, nr_vcpus, vcpu_infos, prev_vcpu_infos,
681 (* Which pCPUs can this dom run on? *)
682 for v = 0 to nr_vcpus-1 do
683 let pcpu = vcpu_infos.(v).D.cpu in (* instantaneous pCPU *)
684 let nr_poss_pcpus = ref 0 in (* how many pcpus can it run on? *)
685 for p = 0 to nr_pcpus-1 do
686 (* vcpu v can reside on pcpu p *)
687 if C.cpu_usable cpumaps maplen v p then
690 let nr_poss_pcpus = Int64.of_int !nr_poss_pcpus in
691 for p = 0 to nr_pcpus-1 do
692 (* vcpu v can reside on pcpu p *)
693 if C.cpu_usable cpumaps maplen v p then
694 let vcpu_time_on_pcpu =
695 vcpu_infos.(v).D.vcpu_time
696 -^ prev_vcpu_infos.(v).D.vcpu_time in
697 let vcpu_time_on_pcpu =
698 vcpu_time_on_pcpu /^ nr_poss_pcpus in
700 (vcpu_time_on_pcpu, nr_poss_pcpus > 1L, p = pcpu)
705 (* Sum the CPU time used by each pCPU, for the %CPU column. *)
706 let pcpus_cpu_time = Array.map (
708 let cpu_time = ref 0L in
709 for di = 0 to Array.length row-1 do
710 let t, _, _ = row.(di) in
711 cpu_time := !cpu_time +^ t
713 Int64.to_float !cpu_time
716 Some (doms, pcpus, pcpus_cpu_time)
720 (* Calculate totals. *)
721 let totals = List.fold_left (
722 fun (count, running, blocked, paused, shutdown, shutoff,
723 crashed, active, inactive,
724 total_cpu_time, total_memory, total_domU_memory) ->
726 | (name, Active rd) ->
727 let test state orig =
728 if rd.rd_info.D.state = state then orig+1 else orig
730 let running = test D.InfoRunning running in
731 let blocked = test D.InfoBlocked blocked in
732 let paused = test D.InfoPaused paused in
733 let shutdown = test D.InfoShutdown shutdown in
734 let shutoff = test D.InfoShutoff shutoff in
735 let crashed = test D.InfoCrashed crashed in
737 let total_cpu_time = total_cpu_time +. rd.rd_cpu_time in
738 let total_memory = total_memory +^ rd.rd_info.D.memory in
739 let total_domU_memory = total_domU_memory +^
740 if rd.rd_domid > 0 then rd.rd_info.D.memory else 0L in
742 (count+1, running, blocked, paused, shutdown, shutoff,
743 crashed, active+1, inactive,
744 total_cpu_time, total_memory, total_domU_memory)
746 | (name, Inactive) -> (* inactive domain *)
747 (count+1, running, blocked, paused, shutdown, shutoff,
748 crashed, active, inactive+1,
749 total_cpu_time, total_memory, total_domU_memory)
750 ) (0,0,0,0,0,0,0,0,0, 0.,0L,0L) doms in
752 (* Update last_time, last_info. *)
754 Hashtbl.clear last_info;
758 let info = rd.rd_info, rd.rd_block_stats, rd.rd_interface_stats in
759 Hashtbl.add last_info rd.rd_domid info
764 time, printable_time,
765 nr_pcpus, total_cpu, total_cpu_per_pcpu,
770 collect, clear_pcpu_display_data
772 (* Redraw the display. *)
774 (* Keep a historical list of %CPU usages. *)
775 let historical_cpu = ref [] in
776 let historical_cpu_last_time = ref (Unix.gettimeofday ()) in
778 (_, _, _, _, _, node_info, _, _) (* setup *)
780 time, printable_time,
781 nr_pcpus, total_cpu, total_cpu_per_pcpu,
783 pcpu_display) (* state *) ->
786 (* Get the screen/window size. *)
787 let lines, cols = get_size () in
790 mvaddstr top_lineno 0 (sprintf "virt-top %s - " printable_time);
792 (* Basic node_info. *)
794 (sprintf "%s %d/%dCPU %dMHz %LdMB "
795 node_info.C.model node_info.C.cpus nr_pcpus node_info.C.mhz
796 (node_info.C.memory /^ 1024L));
797 (* Save the cursor position for when we come to draw the
798 * historical CPU times (down in this function).
800 let stdscr = stdscr () in
801 let historical_cursor = getyx stdscr in
803 (match !display_mode with
804 | TaskDisplay -> (*---------- Showing domains ----------*)
805 (* Sort domains on current sort_order. *)
808 match !sort_order with
810 (fun _ -> 0) (* fallthrough to default name compare *)
813 | Active rd1, Active rd2 ->
814 compare rd2.rd_percent_cpu rd1.rd_percent_cpu
815 | Active _, Inactive -> -1
816 | Inactive, Active _ -> 1
817 | Inactive, Inactive -> 0)
820 | Active { rd_info = info1 }, Active { rd_info = info2 } ->
821 compare info2.D.memory info1.D.memory
822 | Active _, Inactive -> -1
823 | Inactive, Active _ -> 1
824 | Inactive, Inactive -> 0)
827 | Active { rd_info = info1 }, Active { rd_info = info2 } ->
828 compare info2.D.cpu_time info1.D.cpu_time
829 | Active _, Inactive -> -1
830 | Inactive, Active _ -> 1
831 | Inactive, Inactive -> 0)
834 | Active { rd_domid = id1 }, Active { rd_domid = id2 } ->
836 | Active _, Inactive -> -1
837 | Inactive, Active _ -> 1
838 | Inactive, Inactive -> 0)
841 | Active { rd_net_rx_bytes = r1 }, Active { rd_net_rx_bytes = r2 } ->
843 | Active _, Inactive -> -1
844 | Inactive, Active _ -> 1
845 | Inactive, Inactive -> 0)
848 | Active { rd_net_tx_bytes = r1 }, Active { rd_net_tx_bytes = r2 } ->
850 | Active _, Inactive -> -1
851 | Inactive, Active _ -> 1
852 | Inactive, Inactive -> 0)
855 | Active { rd_block_rd_reqs = r1 }, Active { rd_block_rd_reqs = r2 } ->
857 | Active _, Inactive -> -1
858 | Inactive, Active _ -> 1
859 | Inactive, Inactive -> 0)
862 | Active { rd_block_wr_reqs = r1 }, Active { rd_block_wr_reqs = r2 } ->
864 | Active _, Inactive -> -1
865 | Inactive, Active _ -> 1
866 | Inactive, Inactive -> 0)
868 let cmp (name1, dom1) (name2, dom2) =
869 let r = cmp (dom1, dom2) in
871 else compare name1 name2
873 List.sort ~cmp doms in
877 let header_string = if !block_in_bytes
878 then " ID S RDBY WRBY RXBY TXBY %CPU %MEM TIME NAME"
879 else " ID S RDRQ WRRQ RXBY TXBY %CPU %MEM TIME NAME"
881 mvaddstr header_lineno 0
882 (pad cols header_string);
885 let rec loop lineno = function
887 | (name, Active rd) :: doms ->
888 if lineno < lines then (
889 let state = show_state rd.rd_info.D.state in
890 let rd_req = Show.int64_option rd.rd_block_rd_info in
891 let wr_req = Show.int64_option rd.rd_block_wr_info in
892 let rx_bytes = Show.int64_option rd.rd_net_rx_bytes in
893 let tx_bytes = Show.int64_option rd.rd_net_tx_bytes in
894 let percent_cpu = Show.percent rd.rd_percent_cpu in
896 100L *^ rd.rd_info.D.memory /^ node_info.C.memory in
897 let percent_mem = Int64.to_float percent_mem in
898 let percent_mem = Show.percent percent_mem in
899 let time = Show.time rd.rd_info.D.cpu_time in
901 let line = sprintf "%5d %c %s %s %s %s %s %s %s %s"
902 rd.rd_domid state rd_req wr_req rx_bytes tx_bytes
903 percent_cpu percent_mem time name in
904 let line = pad cols line in
905 mvaddstr lineno 0 line;
908 | (name, Inactive) :: doms -> (* inactive domain *)
909 if lineno < lines then (
914 let line = pad cols line in
915 mvaddstr lineno 0 line;
919 loop domains_lineno doms
921 | PCPUDisplay -> (*---------- Showing physical CPUs ----------*)
922 let doms, pcpus, pcpus_cpu_time =
923 match pcpu_display with
925 | None -> failwith "internal error: no pcpu_display data" in
927 (* Display the pCPUs. *)
931 fun (_, name, _, _, _, _, _) ->
932 let len = String.length name in
933 let width = max (len+1) 7 in
938 mvaddstr header_lineno 0 (pad cols ("PHYCPU %CPU " ^ dom_names));
943 mvaddstr (p+domains_lineno) 0 (sprintf "%4d " p);
944 let cpu_time = pcpus_cpu_time.(p) in (* ns used on this CPU *)
945 let percent_cpu = 100. *. cpu_time /. total_cpu_per_pcpu in
946 addstr (Show.percent percent_cpu);
950 fun di (domid, name, _, _, _, _, _) ->
951 let t, is_average, is_running = pcpus.(p).(di) in
952 let len = String.length name in
953 let width = max (len+1) 7 in
957 let t = Int64.to_float t in
958 let percent = 100. *. t /. total_cpu_per_pcpu in
959 sprintf "%s%c%c " (Show.percent percent)
960 (if is_average then '=' else ' ')
961 (if is_running then '#' else ' ')
963 addstr (pad width str);
968 | NetDisplay -> (*---------- Showing network interfaces ----------*)
969 (* Only care about active domains. *)
970 let doms = List.filter_map (
972 | (name, Active rd) -> Some (name, rd)
973 | (_, Inactive) -> None
976 (* For each domain we have a list of network interfaces seen
977 * this slice, and seen in the previous slice, which we now
978 * match up to get a list of (domain, interface) for which
979 * we have current & previous knowledge. (And ignore the rest).
987 (* Have prev slice stats for this device? *)
989 List.assoc dev rd.rd_prev_interface_stats in
990 Some (dev, name, rd, stats, prev_stats)
991 with Not_found -> None
992 ) rd.rd_interface_stats
995 (* Finally we have a list of:
996 * device name, domain name, rd_* stuff, curr stats, prev stats.
998 let devs : (string * string * rd_active *
999 D.interface_stats * D.interface_stats) list =
1000 List.flatten devs in
1002 (* Difference curr slice & prev slice. *)
1003 let devs = List.map (
1004 fun (dev, name, rd, curr, prev) ->
1005 dev, name, rd, diff_interface_stats curr prev
1008 (* Sort by current sort order, but map some of the standard
1009 * sort orders into ones which makes sense here.
1013 match !sort_order with
1015 (fun _ -> 0) (* fallthrough to default name compare *)
1017 (fun (_, { rd_domid = id1 }, _, { rd_domid = id2 }) ->
1019 | Processor | Memory | Time | BlockRdRq | BlockWrRq
1020 (* fallthrough to RXBY comparison. *)
1022 (fun ({ D.rx_bytes = b1 }, _, { D.rx_bytes = b2 }, _) ->
1025 (fun ({ D.tx_bytes = b1 }, _, { D.tx_bytes = b2 }, _) ->
1028 let cmp (dev1, name1, rd1, stats1) (dev2, name2, rd2, stats2) =
1029 let r = cmp (stats1, rd1, stats2, rd2) in
1031 else compare (dev1, name1) (dev2, name2)
1033 List.sort ~cmp devs in
1035 (* Print the header for network devices. *)
1037 mvaddstr header_lineno 0
1038 (pad cols " ID S RXBY TXBY RXPK TXPK DOMAIN INTERFACE");
1041 (* Print domains and devices. *)
1042 let rec loop lineno = function
1044 | (dev, name, rd, stats) :: devs ->
1045 if lineno < lines then (
1046 let state = show_state rd.rd_info.D.state in
1048 if stats.D.rx_bytes >= 0L
1049 then Show.int64 stats.D.rx_bytes
1052 if stats.D.tx_bytes >= 0L
1053 then Show.int64 stats.D.tx_bytes
1056 if stats.D.rx_packets >= 0L
1057 then Show.int64 stats.D.rx_packets
1060 if stats.D.tx_packets >= 0L
1061 then Show.int64 stats.D.tx_packets
1064 let line = sprintf "%5d %c %s %s %s %s %-12s %s"
1067 rx_packets tx_packets
1068 (pad 12 name) dev in
1069 let line = pad cols line in
1070 mvaddstr lineno 0 line;
1071 loop (lineno+1) devs
1074 loop domains_lineno devs
1076 | BlockDisplay -> (*---------- Showing block devices ----------*)
1077 (* Only care about active domains. *)
1078 let doms = List.filter_map (
1080 | (name, Active rd) -> Some (name, rd)
1081 | (_, Inactive) -> None
1084 (* For each domain we have a list of block devices seen
1085 * this slice, and seen in the previous slice, which we now
1086 * match up to get a list of (domain, device) for which
1087 * we have current & previous knowledge. (And ignore the rest).
1095 (* Have prev slice stats for this device? *)
1097 List.assoc dev rd.rd_prev_block_stats in
1098 Some (dev, name, rd, stats, prev_stats)
1099 with Not_found -> None
1103 (* Finally we have a list of:
1104 * device name, domain name, rd_* stuff, curr stats, prev stats.
1106 let devs : (string * string * rd_active *
1107 D.block_stats * D.block_stats) list =
1108 List.flatten devs in
1110 (* Difference curr slice & prev slice. *)
1111 let devs = List.map (
1112 fun (dev, name, rd, curr, prev) ->
1113 dev, name, rd, diff_block_stats curr prev
1116 (* Sort by current sort order, but map some of the standard
1117 * sort orders into ones which makes sense here.
1121 match !sort_order with
1123 (fun _ -> 0) (* fallthrough to default name compare *)
1125 (fun (_, { rd_domid = id1 }, _, { rd_domid = id2 }) ->
1127 | Processor | Memory | Time | NetRX | NetTX
1128 (* fallthrough to RDRQ comparison. *)
1130 (fun ({ D.rd_req = b1 }, _, { D.rd_req = b2 }, _) ->
1133 (fun ({ D.wr_req = b1 }, _, { D.wr_req = b2 }, _) ->
1136 let cmp (dev1, name1, rd1, stats1) (dev2, name2, rd2, stats2) =
1137 let r = cmp (stats1, rd1, stats2, rd2) in
1139 else compare (dev1, name1) (dev2, name2)
1141 List.sort ~cmp devs in
1143 (* Print the header for block devices. *)
1145 mvaddstr header_lineno 0
1146 (pad cols " ID S RDBY WRBY RDRQ WRRQ DOMAIN DEVICE");
1149 (* Print domains and devices. *)
1150 let rec loop lineno = function
1152 | (dev, name, rd, stats) :: devs ->
1153 if lineno < lines then (
1154 let state = show_state rd.rd_info.D.state in
1156 if stats.D.rd_bytes >= 0L
1157 then Show.int64 stats.D.rd_bytes
1160 if stats.D.wr_bytes >= 0L
1161 then Show.int64 stats.D.wr_bytes
1164 if stats.D.rd_req >= 0L
1165 then Show.int64 stats.D.rd_req
1168 if stats.D.wr_req >= 0L
1169 then Show.int64 stats.D.wr_req
1172 let line = sprintf "%5d %c %s %s %s %s %-12s %s"
1176 (pad 12 name) dev in
1177 let line = pad cols line in
1178 mvaddstr lineno 0 line;
1179 loop (lineno+1) devs
1182 loop domains_lineno devs
1183 ); (* end of display_mode conditional section *)
1185 let (count, running, blocked, paused, shutdown, shutoff,
1186 crashed, active, inactive,
1187 total_cpu_time, total_memory, total_domU_memory) = totals in
1189 mvaddstr summary_lineno 0
1191 (f_"%d domains, %d active, %d running, %d sleeping, %d paused, %d inactive D:%d O:%d X:%d")
1192 count active running blocked paused inactive shutdown shutoff crashed);
1194 (* Total %CPU used, and memory summary. *)
1195 let percent_cpu = 100. *. total_cpu_time /. total_cpu in
1196 mvaddstr (summary_lineno+1) 0
1198 (f_"CPU: %2.1f%% Mem: %Ld MB (%Ld MB by guests)")
1199 percent_cpu (total_memory /^ 1024L) (total_domU_memory /^ 1024L));
1201 (* Time to grab another historical %CPU for the list? *)
1202 if time >= !historical_cpu_last_time +. float !historical_cpu_delay
1204 historical_cpu := percent_cpu :: List.take 10 !historical_cpu;
1205 historical_cpu_last_time := time
1208 (* Display historical CPU time. *)
1210 let y, x = historical_cursor in
1211 let maxwidth = cols - x in
1214 (List.map (sprintf "%2.1f%%") !historical_cpu) in
1215 let line = pad maxwidth line in
1219 move message_lineno 0; (* Park cursor in message area, as with top. *)
1220 refresh () (* Refresh the display. *)
1222 (* Write CSV header row. *)
1223 let write_csv_header () =
1225 [ "Hostname"; "Time"; "Arch"; "Physical CPUs";
1226 "Count"; "Running"; "Blocked"; "Paused"; "Shutdown";
1227 "Shutoff"; "Crashed"; "Active"; "Inactive";
1229 "Total hardware memory (KB)";
1230 "Total memory (KB)"; "Total guest memory (KB)";
1231 "Total CPU time (ns)" ] @
1232 (* These fields are repeated for each domain: *)
1233 [ "Domain ID"; "Domain name"; ] @
1234 (if !csv_cpu then [ "CPU (ns)"; "%CPU"; ] else []) @
1235 (if !csv_block && not !block_in_bytes
1236 then [ "Block RDRQ"; "Block WRRQ"; ] else []) @
1237 (if !csv_block && !block_in_bytes
1238 then [ "Block RDBY"; "Block WRBY"; ] else []) @
1239 (if !csv_net then [ "Net RXBY"; "Net TXBY" ] else [])
1242 (* Write summary data to CSV file. *)
1244 (_, _, _, _, _, node_info, hostname, _) (* setup *)
1247 nr_pcpus, total_cpu, _,
1251 (* The totals / summary fields. *)
1252 let (count, running, blocked, paused, shutdown, shutoff,
1253 crashed, active, inactive,
1254 total_cpu_time, total_memory, total_domU_memory) = totals in
1256 let percent_cpu = 100. *. total_cpu_time /. total_cpu in
1258 let summary_fields = [
1259 hostname; printable_time; node_info.C.model; string_of_int nr_pcpus;
1260 string_of_int count; string_of_int running; string_of_int blocked;
1261 string_of_int paused; string_of_int shutdown; string_of_int shutoff;
1262 string_of_int crashed; string_of_int active; string_of_int inactive;
1263 sprintf "%2.1f" percent_cpu;
1264 Int64.to_string node_info.C.memory;
1265 Int64.to_string total_memory; Int64.to_string total_domU_memory;
1266 Int64.to_string (Int64.of_float total_cpu_time)
1271 * Sort them by ID so that the list of relatively stable. Ignore
1274 let doms = List.filter_map (
1276 | _, Inactive -> None (* Ignore inactive domains. *)
1277 | name, Active rd -> Some (name, rd)
1279 let cmp (_, { rd_domid = rd_domid1 }) (_, { rd_domid = rd_domid2 }) =
1280 compare rd_domid1 rd_domid2
1282 let doms = List.sort ~cmp doms in
1284 let string_of_int64_option = Option.map_default Int64.to_string "" in
1286 let domain_fields = List.map (
1287 fun (domname, rd) ->
1288 [ string_of_int rd.rd_domid; domname ] @
1290 string_of_float rd.rd_cpu_time; string_of_float rd.rd_percent_cpu
1292 (if !csv_block then [
1293 string_of_int64_option rd.rd_block_rd_info;
1294 string_of_int64_option rd.rd_block_wr_info;
1297 string_of_int64_option rd.rd_net_rx_bytes;
1298 string_of_int64_option rd.rd_net_tx_bytes;
1301 let domain_fields = List.flatten domain_fields in
1303 (!csv_write) (summary_fields @ domain_fields)
1306 (_, _, _, _, _, node_info, hostname, _) (* setup *)
1309 nr_pcpus, total_cpu, _,
1313 (* Header for this iteration *)
1314 printf "virt-top time %s Host %s %s %d/%dCPU %dMHz %LdMB \n"
1315 printable_time hostname node_info.C.model node_info.C.cpus nr_pcpus
1316 node_info.C.mhz (node_info.C.memory /^ 1024L);
1317 (* dump domain information one by one *)
1318 let rd, wr = if !block_in_bytes then "RDBY", "WRBY" else "RDRQ", "WRRQ"
1320 printf " ID S %s %s RXBY TXBY %%CPU %%MEM TIME NAME\n" rd wr;
1326 | Active {rd_domid = id1 }, Active {rd_domid = id2} ->
1328 | Active _, Inactive -> -1
1329 | Inactive, Active _ -> 1
1330 | Inactive, Inactive -> 0)
1332 let cmp (name1, dom1) (name2, dom2) = compare(dom1, dom2) in
1333 List.sort ~cmp doms in
1335 let dump_domain = fun name rd
1337 let state = show_state rd.rd_info.D.state in
1338 let rd_req = if rd.rd_block_rd_info = None then " 0"
1339 else Show.int64_option rd.rd_block_rd_info in
1340 let wr_req = if rd.rd_block_wr_info = None then " 0"
1341 else Show.int64_option rd.rd_block_wr_info in
1342 let rx_bytes = if rd.rd_net_rx_bytes = None then " 0"
1343 else Show.int64_option rd.rd_net_rx_bytes in
1344 let tx_bytes = if rd.rd_net_tx_bytes = None then " 0"
1345 else Show.int64_option rd.rd_net_tx_bytes in
1346 let percent_cpu = Show.percent rd.rd_percent_cpu in
1348 100L *^ rd.rd_info.D.memory /^ node_info.C.memory in
1349 let percent_mem = Int64.to_float percent_mem in
1350 let percent_mem = Show.percent percent_mem in
1351 let time = Show.time rd.rd_info.D.cpu_time in
1352 printf "%5d %c %s %s %s %s %s %s %s %s\n"
1353 rd.rd_domid state rd_req wr_req rx_bytes tx_bytes
1354 percent_cpu percent_mem time name;
1359 | name, Active dom -> dump_domain name dom
1360 | name, Inactive -> ()
1365 let rec main_loop ((_, batch_mode, script_mode, csv_enabled, stream_mode, _, _, _)
1367 if csv_enabled then write_csv_header ();
1370 let state = collect setup in (* Collect stats. *)
1371 (* Redraw display. *)
1372 if not script_mode && not stream_mode then redraw setup state;
1373 if csv_enabled then append_csv setup state; (* Update CSV file. *)
1374 if stream_mode then dump_stdout setup state; (* dump to stdout *)
1376 (* Clear up unused virDomainPtr objects. *)
1379 (* Max iterations? *)
1380 if !iterations >= 0 then (
1382 if !iterations = 0 then quit := true
1385 (* End time? We might need to adjust the precise delay down if
1386 * the delay would be longer than the end time (RHBZ#637964). Note
1387 * 'delay' is in milliseconds.
1390 match !end_time with
1392 (* No --end-time option, so use the current delay. *)
1395 let (_, time, _, _, _, _, _, _) = state in
1396 let delay_secs = float !delay /. 1000. in
1397 if end_time <= time +. delay_secs then (
1399 let delay = int_of_float (1000. *. (end_time -. time)) in
1400 if delay >= 0 then delay else 0
1403 (*eprintf "adjusted delay = %d\n%!" delay;*)
1405 (* Get next key. This does the sleep. *)
1406 if not batch_mode && not script_mode && not stream_mode then
1407 get_key_press setup delay
1409 (* Batch mode, script mode, stream mode. We didn't call
1410 * get_key_press, so we didn't sleep. Sleep now, unless we are
1413 if not !quit || !end_time <> None then
1418 and get_key_press setup delay =
1419 (* Read the next key, waiting up to 'delay' milliseconds. *)
1422 timeout (-1); (* Reset to blocking mode. *)
1424 if k >= 0 && k <> 32 (* ' ' *) && k <> 12 (* ^L *) && k <> Key.resize
1426 if k = Char.code 'q' then quit := true
1427 else if k = Char.code 'h' then show_help setup
1428 else if k = Char.code 's' || k = Char.code 'd' then change_delay ()
1429 else if k = Char.code 'M' then sort_order := Memory
1430 else if k = Char.code 'P' then sort_order := Processor
1431 else if k = Char.code 'T' then sort_order := Time
1432 else if k = Char.code 'N' then sort_order := DomainID
1433 else if k = Char.code 'F' then change_sort_order ()
1434 else if k = Char.code '0' then set_tasks_display ()
1435 else if k = Char.code '1' then toggle_pcpu_display ()
1436 else if k = Char.code '2' then toggle_net_display ()
1437 else if k = Char.code '3' then toggle_block_display ()
1438 else if k = Char.code 'W' then write_init_file ()
1439 else if k = Char.code 'B' then toggle_block_in_bytes_mode ()
1440 else unknown_command k
1443 and change_delay () =
1445 (sprintf (f_"Change delay from %.1f to: ") (float !delay /. 1000.));
1446 let str = get_string 16 in
1447 (* Try to parse the number. *)
1450 let newdelay = float_of_string str in
1451 if newdelay <= 0. then (
1452 print_msg (s_"Delay must be > 0"); true
1454 delay := int_of_float (newdelay *. 1000.); false
1457 Failure "float_of_string" ->
1458 print_msg (s_"Not a valid number"); true in
1460 sleep (if error then 2 else 1)
1462 and change_sort_order () =
1464 let lines, cols = get_size () in
1466 mvaddstr top_lineno 0 (s_"Set sort order for main display");
1467 mvaddstr summary_lineno 0 (s_"Type key or use up and down cursor keys.");
1470 mvaddstr header_lineno 0 (pad cols "KEY Sort field");
1473 let accelerator_key = function
1474 | Memory -> "(key: M)"
1475 | Processor -> "(key: P)"
1476 | Time -> "(key: T)"
1477 | DomainID -> "(key: N)"
1478 | _ -> (* all others have to be changed from here *) ""
1481 let rec key_of_int = function
1482 | i when i < 10 -> Char.chr (i + Char.code '0')
1483 | i when i < 20 -> Char.chr (i + Char.code 'a')
1485 and int_of_key = function
1486 | k when k >= 0x30 && k <= 0x39 (* '0' - '9' *) -> k - 0x30
1487 | k when k >= 0x61 && k <= 0x7a (* 'a' - 'j' *) -> k - 0x61 + 10
1488 | k when k >= 0x41 && k <= 0x6a (* 'A' - 'J' *) -> k - 0x41 + 10
1492 (* Display possible sort fields. *)
1493 let selected_index = ref 0 in
1496 let selected = !sort_order = ord in
1497 if selected then selected_index := i;
1498 mvaddstr (domains_lineno+i) 0
1499 (sprintf " %c %s %s %s"
1500 (key_of_int i) (if selected then "*" else " ")
1501 (printable_sort_order ord)
1502 (accelerator_key ord))
1505 move message_lineno 0;
1508 if k >= 0 && k <> 32 && k <> Char.code 'q' && k <> 13 then (
1509 let new_order, loop =
1510 (* Redraw the display. *)
1511 if k = 12 (* ^L *) then None, true
1512 (* Make the UP and DOWN arrow keys do something useful. *)
1513 else if k = Key.up then (
1514 if !selected_index > 0 then
1515 Some (List.nth all_sort_fields (!selected_index-1)), true
1519 else if k = Key.down then (
1520 if !selected_index < List.length all_sort_fields - 1 then
1521 Some (List.nth all_sort_fields (!selected_index+1)), true
1525 (* Also understand the regular accelerator keys. *)
1526 else if k = Char.code 'M' then
1528 else if k = Char.code 'P' then
1529 Some Processor, false
1530 else if k = Char.code 'T' then
1532 else if k = Char.code 'N' then
1533 Some DomainID, false
1535 (* It's one of the KEYs. *)
1536 let i = int_of_key k in
1537 if i >= 0 && i < List.length all_sort_fields then
1538 Some (List.nth all_sort_fields i), false
1543 (match new_order with
1546 sort_order := new_order;
1547 print_msg (sprintf "Sort order changed to: %s"
1548 (printable_sort_order new_order));
1555 if loop then change_sort_order ()
1558 (* Note: We need to clear_pcpu_display_data every time
1559 * we _leave_ PCPUDisplay mode.
1561 and set_tasks_display () = (* key 0 *)
1562 if !display_mode = PCPUDisplay then clear_pcpu_display_data ();
1563 display_mode := TaskDisplay
1565 and toggle_pcpu_display () = (* key 1 *)
1567 match !display_mode with
1568 | TaskDisplay | NetDisplay | BlockDisplay -> PCPUDisplay
1569 | PCPUDisplay -> clear_pcpu_display_data (); TaskDisplay
1571 and toggle_net_display () = (* key 2 *)
1573 match !display_mode with
1574 | PCPUDisplay -> clear_pcpu_display_data (); NetDisplay
1575 | TaskDisplay | BlockDisplay -> NetDisplay
1576 | NetDisplay -> TaskDisplay
1578 and toggle_block_display () = (* key 3 *)
1580 match !display_mode with
1581 | PCPUDisplay -> clear_pcpu_display_data (); BlockDisplay
1582 | TaskDisplay | NetDisplay -> BlockDisplay
1583 | BlockDisplay -> TaskDisplay
1585 and toggle_block_in_bytes_mode () = (* key B *)
1587 match !block_in_bytes with
1591 (* Write an init file. *)
1592 and write_init_file () =
1593 match !init_file with
1594 | NoInitFile -> () (* Do nothing if --no-init-file *)
1595 | DefaultInitFile ->
1596 let home = try Sys.getenv "HOME" with Not_found -> "/" in
1597 let filename = home // rcfile in
1598 _write_init_file filename
1599 | InitFile filename ->
1600 _write_init_file filename
1602 and _write_init_file filename =
1604 (* Create the new file as filename.new. *)
1605 let chan = open_out (filename ^ ".new") in
1607 let time = Unix.gettimeofday () in
1608 let tm = Unix.localtime time in
1609 let printable_date_time =
1610 sprintf "%04d-%02d-%02d %02d:%02d:%02d"
1611 (tm.Unix.tm_year + 1900) (tm.Unix.tm_mon+1) tm.Unix.tm_mday
1612 tm.Unix.tm_hour tm.Unix.tm_min tm.Unix.tm_sec in
1615 let uid = Unix.geteuid () in
1616 (Unix.getpwuid uid).Unix.pw_name
1618 Not_found -> "unknown" in
1621 let nl () = fp chan "\n" in
1622 let () = fp chan (f_"# %s virt-top configuration file\n") rcfile in
1623 let () = fp chan (f_"# generated on %s by %s\n") printable_date_time username in
1625 fp chan "display %s\n" (cli_of_display !display_mode);
1626 fp chan "delay %g\n" (float !delay /. 1000.);
1627 fp chan "hist-cpu %d\n" !historical_cpu_delay;
1628 if !iterations <> -1 then fp chan "iterations %d\n" !iterations;
1629 fp chan "sort %s\n" (cli_of_sort_order !sort_order);
1632 | Some uri -> fp chan "connect %s\n" uri
1634 if !batch_mode = true then fp chan "batch true\n";
1635 if !secure_mode = true then fp chan "secure true\n";
1637 output_string chan (s_"# To send debug and error messages to a file, uncomment next line\n");
1638 fp chan "#debug virt-top.out\n";
1640 output_string chan (s_"# Enable CSV output to the named file\n");
1641 fp chan "#csv virt-top.csv\n";
1643 output_string chan (s_"# To protect this file from being overwritten, uncomment next line\n");
1644 fp chan "#overwrite-init-file false\n";
1648 (* If the file exists, rename it as filename.old. *)
1649 (try Unix.rename filename (filename ^ ".old")
1650 with Unix.Unix_error _ -> ());
1652 (* Rename filename.new to filename. *)
1653 Unix.rename (filename ^ ".new") filename;
1655 print_msg (sprintf (f_"Wrote settings to %s") filename);
1660 print_msg (s_"Error" ^ ": " ^ err);
1662 | Unix.Unix_error (err, fn, str) ->
1663 print_msg (s_"Error" ^ ": " ^
1664 (Unix.error_message err) ^ " " ^ fn ^ " " ^ str);
1668 and show_help (_, _, _, _, _, _, hostname,
1669 (libvirt_major, libvirt_minor, libvirt_release)) =
1672 (* Get the screen/window size. *)
1673 let lines, cols = get_size () in
1675 (* Banner at the top of the screen. *)
1677 sprintf (f_"virt-top %s ocaml-libvirt %s libvirt %d.%d.%d by Red Hat")
1678 Virt_top_version.version
1679 Libvirt_version.version
1680 libvirt_major libvirt_minor libvirt_release in
1681 let banner = pad cols banner in
1683 mvaddstr 0 0 banner;
1689 (f_"Delay: %.1f secs; Batch: %s; Secure: %s; Sort: %s")
1690 (float !delay /. 1000.)
1691 (if !batch_mode then s_"On" else s_"Off")
1692 (if !secure_mode then s_"On" else s_"Off")
1693 (printable_sort_order !sort_order));
1696 (f_"Connect: %s; Hostname: %s")
1697 (match !uri with None -> s_"default" | Some s -> s)
1700 (* Misc keys on left. *)
1701 let banner = pad 38 (s_"MAIN KEYS") in
1703 mvaddstr header_lineno 1 banner;
1707 let lineno = ref domains_lineno in
1708 fun () -> let i = !lineno in incr lineno; i
1710 let key keys description =
1711 let lineno = get_lineno () in
1712 move lineno 1; attron A.bold; addstr keys; attroff A.bold;
1713 move lineno 10; addstr description
1715 key "space ^L" (s_"Update display");
1717 key "d s" (s_"Set update interval");
1719 key "B" (s_"toggle block info req/bytes");
1722 ignore (get_lineno ());
1723 let banner = pad 38 (s_"SORTING") in
1725 mvaddstr (get_lineno ()) 1 banner;
1728 key "P" (s_"Sort by %CPU");
1729 key "M" (s_"Sort by %MEM");
1730 key "T" (s_"Sort by TIME");
1731 key "N" (s_"Sort by ID");
1732 key "F" (s_"Select sort field");
1734 (* Display modes on right. *)
1735 let banner = pad 39 (s_"DISPLAY MODES") in
1737 mvaddstr header_lineno 40 banner;
1741 let lineno = ref domains_lineno in
1742 fun () -> let i = !lineno in incr lineno; i
1744 let key keys description =
1745 let lineno = get_lineno () in
1746 move lineno 40; attron A.bold; addstr keys; attroff A.bold;
1747 move lineno 49; addstr description
1749 key "0" (s_"Domains display");
1750 key "1" (s_"Toggle physical CPUs");
1751 key "2" (s_"Toggle network interfaces");
1752 key "3" (s_"Toggle block devices");
1754 (* Update screen and wait for key press. *)
1755 mvaddstr (lines-1) 0
1756 (s_"More help in virt-top(1) man page. Press any key to return.");
1760 and unknown_command k =
1761 print_msg (s_"Unknown command - try 'h' for help");