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 rd_mem_bytes : int64; (* Memory usage in bytes *)
406 rd_mem_percent: int64; (* Memory usage as percent of total *)
407 (* The following are since the last slice, or None if cannot be calc'd: *)
408 rd_block_rd_reqs : int64 option; (* Number of block device read rqs. *)
409 rd_block_wr_reqs : int64 option; (* Number of block device write rqs. *)
410 rd_block_rd_bytes : int64 option; (* Number of bytes block device read *)
411 rd_block_wr_bytes : int64 option; (* Number of bytes block device write *)
412 (* _info fields includes the number considering --block_in_bytes option *)
413 rd_block_rd_info : int64 option; (* Block device read info for user *)
414 rd_block_wr_info : int64 option; (* Block device read info for user *)
416 rd_net_rx_bytes : int64 option; (* Number of bytes received. *)
417 rd_net_tx_bytes : int64 option; (* Number of bytes transmitted. *)
421 let collect, clear_pcpu_display_data =
422 (* We cache the list of block devices and interfaces for each domain
423 * here, so we don't need to reparse the XML each time.
425 let devices = Hashtbl.create 13 in
427 (* Function to get the list of block devices, network interfaces for
428 * a particular domain. Get it from the devices cache, and if not
429 * there then parse the domain XML.
431 let get_devices id dom =
432 try Hashtbl.find devices id
434 let blkdevs, netifs = (!parse_device_xml) id dom in
435 Hashtbl.replace devices id (blkdevs, netifs);
439 (* We save the state of domains across redraws here, which allows us
440 * to deduce %CPU usage from the running total.
442 let last_info = Hashtbl.create 13 in
443 let last_time = ref (Unix.gettimeofday ()) in
445 (* Save vcpuinfo structures across redraws too (only for pCPU display). *)
446 let last_vcpu_info = Hashtbl.create 13 in
448 let clear_pcpu_display_data () =
449 (* Clear out vcpu_info used by PCPUDisplay display_mode
450 * when we switch back to TaskDisplay mode.
452 Hashtbl.clear last_vcpu_info
455 let collect (conn, _, _, _, _, node_info, _, _) =
456 (* Number of physical CPUs (some may be disabled). *)
457 let nr_pcpus = C.maxcpus_of_node_info node_info in
459 (* Get the current time. *)
460 let time = Unix.gettimeofday () in
461 let tm = Unix.localtime time in
463 sprintf "%02d:%02d:%02d" tm.Unix.tm_hour tm.Unix.tm_min tm.Unix.tm_sec in
465 (* What's the total CPU time elapsed since we were last called? (ns) *)
466 let total_cpu_per_pcpu = 1_000_000_000. *. (time -. !last_time) in
467 (* Avoid division by zero. *)
468 let total_cpu_per_pcpu =
469 if total_cpu_per_pcpu <= 0. then 1. else total_cpu_per_pcpu in
470 let total_cpu = float node_info.C.cpus *. total_cpu_per_pcpu in
472 (* Get the domains. Match up with their last_info (if any). *)
474 (* Active domains. *)
475 let n = C.num_of_domains conn in
477 if n > 0 then Array.to_list (C.list_domains conn n)
483 let dom = D.lookup_by_id conn id in
484 let name = D.get_name dom in
485 let blkdevs, netifs = get_devices id dom in
487 (* Get current CPU, block and network stats. *)
488 let info = D.get_info dom in
490 try List.map (fun dev -> dev, D.block_stats dom dev) blkdevs
492 | Libvirt.Not_supported "virDomainBlockStats"
493 | Libvirt.Virterror _ -> [] in
494 let interface_stats =
495 try List.map (fun dev -> dev, D.interface_stats dom dev) netifs
497 | Libvirt.Not_supported "virDomainInterfaceStats"
498 | Libvirt.Virterror _ -> [] in
500 let prev_info, prev_block_stats, prev_interface_stats =
502 let prev_info, prev_block_stats, prev_interface_stats =
503 Hashtbl.find last_info id in
504 Some prev_info, prev_block_stats, prev_interface_stats
505 with Not_found -> None, [], [] in
508 rd_domid = id; rd_dom = dom; rd_info = info;
509 rd_block_stats = block_stats;
510 rd_interface_stats = interface_stats;
511 rd_prev_info = prev_info;
512 rd_prev_block_stats = prev_block_stats;
513 rd_prev_interface_stats = prev_interface_stats;
514 rd_cpu_time = 0.; rd_percent_cpu = 0.;
515 rd_mem_bytes = 0L; rd_mem_percent = 0L;
516 rd_block_rd_reqs = None; rd_block_wr_reqs = None;
517 rd_block_rd_bytes = None; rd_block_wr_bytes = None;
518 rd_block_rd_info = None; rd_block_wr_info = None;
519 rd_net_rx_bytes = None; rd_net_tx_bytes = None;
522 Libvirt.Virterror _ -> None (* ignore transient error *)
525 (* Inactive domains. *)
528 let n = C.num_of_defined_domains conn in
530 if n > 0 then Array.to_list (C.list_defined_domains conn n)
532 List.map (fun name -> name, Inactive) names
534 (* Ignore transient errors, in particular errors from
535 * num_of_defined_domains if it cannot contact xend.
537 | Libvirt.Virterror _ -> [] in
539 doms @ doms_inactive in
541 (* Calculate the CPU time (ns) and %CPU used by each domain. *)
545 (* We have previous CPU info from which to calculate it? *)
546 | name, Active ({ rd_prev_info = Some prev_info } as rd) ->
548 Int64.to_float (rd.rd_info.D.cpu_time -^ prev_info.D.cpu_time) in
549 let percent_cpu = 100. *. cpu_time /. total_cpu in
550 let mem_usage = rd.rd_info.D.memory in
552 100L *^ rd.rd_info.D.memory /^ node_info.C.memory in
554 rd_cpu_time = cpu_time;
555 rd_percent_cpu = percent_cpu;
556 rd_mem_bytes = mem_usage;
557 rd_mem_percent = mem_percent} in
559 (* For all other domains we can't calculate it, so leave as 0 *)
563 (* Calculate the number of block device read/write requests across
564 * all block devices attached to a domain.
569 (* Do we have stats from the previous slice? *)
570 | name, Active ({ rd_prev_block_stats = ((_::_) as prev_block_stats) }
572 let block_stats = rd.rd_block_stats in (* stats now *)
574 (* Add all the devices together. Throw away device names. *)
575 let prev_block_stats =
576 sum_block_stats (List.map snd prev_block_stats) in
578 sum_block_stats (List.map snd block_stats) in
580 (* Calculate increase in read & write requests. *)
582 block_stats.D.rd_req -^ prev_block_stats.D.rd_req in
584 block_stats.D.wr_req -^ prev_block_stats.D.wr_req in
586 block_stats.D.rd_bytes -^ prev_block_stats.D.rd_bytes in
588 block_stats.D.wr_bytes -^ prev_block_stats.D.wr_bytes in
591 rd_block_rd_reqs = Some read_reqs;
592 rd_block_wr_reqs = Some write_reqs;
593 rd_block_rd_bytes = Some read_bytes;
594 rd_block_wr_bytes = Some write_bytes;
597 rd_block_rd_info = if !block_in_bytes then
598 rd.rd_block_rd_bytes else rd.rd_block_rd_reqs;
599 rd_block_wr_info = if !block_in_bytes then
600 rd.rd_block_wr_bytes else rd.rd_block_wr_reqs;
603 (* For all other domains we can't calculate it, so leave as None. *)
607 (* Calculate the same as above for network interfaces across
608 * all network interfaces attached to a domain.
613 (* Do we have stats from the previous slice? *)
614 | name, Active ({ rd_prev_interface_stats =
615 ((_::_) as prev_interface_stats) }
617 let interface_stats = rd.rd_interface_stats in (* stats now *)
619 (* Add all the devices together. Throw away device names. *)
620 let prev_interface_stats =
621 sum_interface_stats (List.map snd prev_interface_stats) in
622 let interface_stats =
623 sum_interface_stats (List.map snd interface_stats) in
625 (* Calculate increase in rx & tx bytes. *)
627 interface_stats.D.rx_bytes -^ prev_interface_stats.D.rx_bytes in
629 interface_stats.D.tx_bytes -^ prev_interface_stats.D.tx_bytes in
632 rd_net_rx_bytes = Some rx_bytes;
633 rd_net_tx_bytes = Some tx_bytes } in
635 (* For all other domains we can't calculate it, so leave as None. *)
639 (* Collect some extra information in PCPUDisplay display_mode. *)
641 if !display_mode = PCPUDisplay then (
642 (* Get the VCPU info and VCPU->PCPU mappings for active domains.
643 * Also cull some data we don't care about.
645 let doms = List.filter_map (
647 | (name, Active rd) ->
649 let domid = rd.rd_domid in
650 let maplen = C.cpumaplen nr_pcpus in
651 let maxinfo = rd.rd_info.D.nr_virt_cpu in
652 let nr_vcpus, vcpu_infos, cpumaps =
653 D.get_vcpus rd.rd_dom maxinfo maplen in
655 (* Got previous vcpu_infos for this domain? *)
656 let prev_vcpu_infos =
657 try Some (Hashtbl.find last_vcpu_info domid)
658 with Not_found -> None in
659 (* Update last_vcpu_info. *)
660 Hashtbl.replace last_vcpu_info domid vcpu_infos;
662 (match prev_vcpu_infos with
663 | Some prev_vcpu_infos
664 when Array.length prev_vcpu_infos = Array.length vcpu_infos ->
665 Some (domid, name, nr_vcpus, vcpu_infos, prev_vcpu_infos,
667 | _ -> None (* ignore missing / unequal length prev_vcpu_infos *)
670 Libvirt.Virterror _ -> None(* ignore transient libvirt errs *)
672 | (_, Inactive) -> None (* ignore inactive doms *)
674 let nr_doms = List.length doms in
676 (* Rearrange the data into a matrix. Major axis (down) is
677 * pCPUs. Minor axis (right) is domains. At each node we store:
678 * cpu_time (on this pCPU only, nanosecs),
679 * average? (if set, then cpu_time is an average because the
680 * vCPU is pinned to more than one pCPU)
681 * running? (if set, we were instantaneously running on this pCPU)
683 let empty_node = (0L, false, false) in
684 let pcpus = Array.make_matrix nr_pcpus nr_doms empty_node in
687 fun di (domid, name, nr_vcpus, vcpu_infos, prev_vcpu_infos,
689 (* Which pCPUs can this dom run on? *)
690 for v = 0 to nr_vcpus-1 do
691 let pcpu = vcpu_infos.(v).D.cpu in (* instantaneous pCPU *)
692 let nr_poss_pcpus = ref 0 in (* how many pcpus can it run on? *)
693 for p = 0 to nr_pcpus-1 do
694 (* vcpu v can reside on pcpu p *)
695 if C.cpu_usable cpumaps maplen v p then
698 let nr_poss_pcpus = Int64.of_int !nr_poss_pcpus in
699 for p = 0 to nr_pcpus-1 do
700 (* vcpu v can reside on pcpu p *)
701 if C.cpu_usable cpumaps maplen v p then
702 let vcpu_time_on_pcpu =
703 vcpu_infos.(v).D.vcpu_time
704 -^ prev_vcpu_infos.(v).D.vcpu_time in
705 let vcpu_time_on_pcpu =
706 vcpu_time_on_pcpu /^ nr_poss_pcpus in
708 (vcpu_time_on_pcpu, nr_poss_pcpus > 1L, p = pcpu)
713 (* Sum the CPU time used by each pCPU, for the %CPU column. *)
714 let pcpus_cpu_time = Array.map (
716 let cpu_time = ref 0L in
717 for di = 0 to Array.length row-1 do
718 let t, _, _ = row.(di) in
719 cpu_time := !cpu_time +^ t
721 Int64.to_float !cpu_time
724 Some (doms, pcpus, pcpus_cpu_time)
728 (* Calculate totals. *)
729 let totals = List.fold_left (
730 fun (count, running, blocked, paused, shutdown, shutoff,
731 crashed, active, inactive,
732 total_cpu_time, total_memory, total_domU_memory) ->
734 | (name, Active rd) ->
735 let test state orig =
736 if rd.rd_info.D.state = state then orig+1 else orig
738 let running = test D.InfoRunning running in
739 let blocked = test D.InfoBlocked blocked in
740 let paused = test D.InfoPaused paused in
741 let shutdown = test D.InfoShutdown shutdown in
742 let shutoff = test D.InfoShutoff shutoff in
743 let crashed = test D.InfoCrashed crashed in
745 let total_cpu_time = total_cpu_time +. rd.rd_cpu_time in
746 let total_memory = total_memory +^ rd.rd_info.D.memory in
747 let total_domU_memory = total_domU_memory +^
748 if rd.rd_domid > 0 then rd.rd_info.D.memory else 0L in
750 (count+1, running, blocked, paused, shutdown, shutoff,
751 crashed, active+1, inactive,
752 total_cpu_time, total_memory, total_domU_memory)
754 | (name, Inactive) -> (* inactive domain *)
755 (count+1, running, blocked, paused, shutdown, shutoff,
756 crashed, active, inactive+1,
757 total_cpu_time, total_memory, total_domU_memory)
758 ) (0,0,0,0,0,0,0,0,0, 0.,0L,0L) doms in
760 (* Update last_time, last_info. *)
762 Hashtbl.clear last_info;
766 let info = rd.rd_info, rd.rd_block_stats, rd.rd_interface_stats in
767 Hashtbl.add last_info rd.rd_domid info
772 time, printable_time,
773 nr_pcpus, total_cpu, total_cpu_per_pcpu,
778 collect, clear_pcpu_display_data
780 (* Redraw the display. *)
782 (* Keep a historical list of %CPU usages. *)
783 let historical_cpu = ref [] in
784 let historical_cpu_last_time = ref (Unix.gettimeofday ()) in
786 (_, _, _, _, _, node_info, _, _) (* setup *)
788 time, printable_time,
789 nr_pcpus, total_cpu, total_cpu_per_pcpu,
791 pcpu_display) (* state *) ->
794 (* Get the screen/window size. *)
795 let lines, cols = get_size () in
798 mvaddstr top_lineno 0 (sprintf "virt-top %s - " printable_time);
800 (* Basic node_info. *)
802 (sprintf "%s %d/%dCPU %dMHz %LdMB "
803 node_info.C.model node_info.C.cpus nr_pcpus node_info.C.mhz
804 (node_info.C.memory /^ 1024L));
805 (* Save the cursor position for when we come to draw the
806 * historical CPU times (down in this function).
808 let stdscr = stdscr () in
809 let historical_cursor = getyx stdscr in
811 (match !display_mode with
812 | TaskDisplay -> (*---------- Showing domains ----------*)
813 (* Sort domains on current sort_order. *)
816 match !sort_order with
818 (fun _ -> 0) (* fallthrough to default name compare *)
821 | Active rd1, Active rd2 ->
822 compare rd2.rd_percent_cpu rd1.rd_percent_cpu
823 | Active _, Inactive -> -1
824 | Inactive, Active _ -> 1
825 | Inactive, Inactive -> 0)
828 | Active { rd_info = info1 }, Active { rd_info = info2 } ->
829 compare info2.D.memory info1.D.memory
830 | Active _, Inactive -> -1
831 | Inactive, Active _ -> 1
832 | Inactive, Inactive -> 0)
835 | Active { rd_info = info1 }, Active { rd_info = info2 } ->
836 compare info2.D.cpu_time info1.D.cpu_time
837 | Active _, Inactive -> -1
838 | Inactive, Active _ -> 1
839 | Inactive, Inactive -> 0)
842 | Active { rd_domid = id1 }, Active { rd_domid = id2 } ->
844 | Active _, Inactive -> -1
845 | Inactive, Active _ -> 1
846 | Inactive, Inactive -> 0)
849 | Active { rd_net_rx_bytes = r1 }, Active { rd_net_rx_bytes = r2 } ->
851 | Active _, Inactive -> -1
852 | Inactive, Active _ -> 1
853 | Inactive, Inactive -> 0)
856 | Active { rd_net_tx_bytes = r1 }, Active { rd_net_tx_bytes = r2 } ->
858 | Active _, Inactive -> -1
859 | Inactive, Active _ -> 1
860 | Inactive, Inactive -> 0)
863 | Active { rd_block_rd_reqs = r1 }, Active { rd_block_rd_reqs = r2 } ->
865 | Active _, Inactive -> -1
866 | Inactive, Active _ -> 1
867 | Inactive, Inactive -> 0)
870 | Active { rd_block_wr_reqs = r1 }, Active { rd_block_wr_reqs = r2 } ->
872 | Active _, Inactive -> -1
873 | Inactive, Active _ -> 1
874 | Inactive, Inactive -> 0)
876 let cmp (name1, dom1) (name2, dom2) =
877 let r = cmp (dom1, dom2) in
879 else compare name1 name2
881 List.sort ~cmp doms in
885 let header_string = if !block_in_bytes
886 then " ID S RDBY WRBY RXBY TXBY %CPU %MEM TIME NAME"
887 else " ID S RDRQ WRRQ RXBY TXBY %CPU %MEM TIME NAME"
889 mvaddstr header_lineno 0
890 (pad cols header_string);
893 let rec loop lineno = function
895 | (name, Active rd) :: doms ->
896 if lineno < lines then (
897 let state = show_state rd.rd_info.D.state in
898 let rd_req = Show.int64_option rd.rd_block_rd_info in
899 let wr_req = Show.int64_option rd.rd_block_wr_info in
900 let rx_bytes = Show.int64_option rd.rd_net_rx_bytes in
901 let tx_bytes = Show.int64_option rd.rd_net_tx_bytes in
902 let percent_cpu = Show.percent rd.rd_percent_cpu in
903 let percent_mem = Int64.to_float rd.rd_mem_percent in
904 let percent_mem = Show.percent percent_mem in
905 let time = Show.time rd.rd_info.D.cpu_time in
907 let line = sprintf "%5d %c %s %s %s %s %s %s %s %s"
908 rd.rd_domid state rd_req wr_req rx_bytes tx_bytes
909 percent_cpu percent_mem time name in
910 let line = pad cols line in
911 mvaddstr lineno 0 line;
914 | (name, Inactive) :: doms -> (* inactive domain *)
915 if lineno < lines then (
920 let line = pad cols line in
921 mvaddstr lineno 0 line;
925 loop domains_lineno doms
927 | PCPUDisplay -> (*---------- Showing physical CPUs ----------*)
928 let doms, pcpus, pcpus_cpu_time =
929 match pcpu_display with
931 | None -> failwith "internal error: no pcpu_display data" in
933 (* Display the pCPUs. *)
937 fun (_, name, _, _, _, _, _) ->
938 let len = String.length name in
939 let width = max (len+1) 7 in
944 mvaddstr header_lineno 0 (pad cols ("PHYCPU %CPU " ^ dom_names));
949 mvaddstr (p+domains_lineno) 0 (sprintf "%4d " p);
950 let cpu_time = pcpus_cpu_time.(p) in (* ns used on this CPU *)
951 let percent_cpu = 100. *. cpu_time /. total_cpu_per_pcpu in
952 addstr (Show.percent percent_cpu);
956 fun di (domid, name, _, _, _, _, _) ->
957 let t, is_average, is_running = pcpus.(p).(di) in
958 let len = String.length name in
959 let width = max (len+1) 7 in
963 let t = Int64.to_float t in
964 let percent = 100. *. t /. total_cpu_per_pcpu in
965 sprintf "%s%c%c " (Show.percent percent)
966 (if is_average then '=' else ' ')
967 (if is_running then '#' else ' ')
969 addstr (pad width str);
974 | NetDisplay -> (*---------- Showing network interfaces ----------*)
975 (* Only care about active domains. *)
976 let doms = List.filter_map (
978 | (name, Active rd) -> Some (name, rd)
979 | (_, Inactive) -> None
982 (* For each domain we have a list of network interfaces seen
983 * this slice, and seen in the previous slice, which we now
984 * match up to get a list of (domain, interface) for which
985 * we have current & previous knowledge. (And ignore the rest).
993 (* Have prev slice stats for this device? *)
995 List.assoc dev rd.rd_prev_interface_stats in
996 Some (dev, name, rd, stats, prev_stats)
997 with Not_found -> None
998 ) rd.rd_interface_stats
1001 (* Finally we have a list of:
1002 * device name, domain name, rd_* stuff, curr stats, prev stats.
1004 let devs : (string * string * rd_active *
1005 D.interface_stats * D.interface_stats) list =
1006 List.flatten devs in
1008 (* Difference curr slice & prev slice. *)
1009 let devs = List.map (
1010 fun (dev, name, rd, curr, prev) ->
1011 dev, name, rd, diff_interface_stats curr prev
1014 (* Sort by current sort order, but map some of the standard
1015 * sort orders into ones which makes sense here.
1019 match !sort_order with
1021 (fun _ -> 0) (* fallthrough to default name compare *)
1023 (fun (_, { rd_domid = id1 }, _, { rd_domid = id2 }) ->
1025 | Processor | Memory | Time | BlockRdRq | BlockWrRq
1026 (* fallthrough to RXBY comparison. *)
1028 (fun ({ D.rx_bytes = b1 }, _, { D.rx_bytes = b2 }, _) ->
1031 (fun ({ D.tx_bytes = b1 }, _, { D.tx_bytes = b2 }, _) ->
1034 let cmp (dev1, name1, rd1, stats1) (dev2, name2, rd2, stats2) =
1035 let r = cmp (stats1, rd1, stats2, rd2) in
1037 else compare (dev1, name1) (dev2, name2)
1039 List.sort ~cmp devs in
1041 (* Print the header for network devices. *)
1043 mvaddstr header_lineno 0
1044 (pad cols " ID S RXBY TXBY RXPK TXPK DOMAIN INTERFACE");
1047 (* Print domains and devices. *)
1048 let rec loop lineno = function
1050 | (dev, name, rd, stats) :: devs ->
1051 if lineno < lines then (
1052 let state = show_state rd.rd_info.D.state in
1054 if stats.D.rx_bytes >= 0L
1055 then Show.int64 stats.D.rx_bytes
1058 if stats.D.tx_bytes >= 0L
1059 then Show.int64 stats.D.tx_bytes
1062 if stats.D.rx_packets >= 0L
1063 then Show.int64 stats.D.rx_packets
1066 if stats.D.tx_packets >= 0L
1067 then Show.int64 stats.D.tx_packets
1070 let line = sprintf "%5d %c %s %s %s %s %-12s %s"
1073 rx_packets tx_packets
1074 (pad 12 name) dev in
1075 let line = pad cols line in
1076 mvaddstr lineno 0 line;
1077 loop (lineno+1) devs
1080 loop domains_lineno devs
1082 | BlockDisplay -> (*---------- Showing block devices ----------*)
1083 (* Only care about active domains. *)
1084 let doms = List.filter_map (
1086 | (name, Active rd) -> Some (name, rd)
1087 | (_, Inactive) -> None
1090 (* For each domain we have a list of block devices seen
1091 * this slice, and seen in the previous slice, which we now
1092 * match up to get a list of (domain, device) for which
1093 * we have current & previous knowledge. (And ignore the rest).
1101 (* Have prev slice stats for this device? *)
1103 List.assoc dev rd.rd_prev_block_stats in
1104 Some (dev, name, rd, stats, prev_stats)
1105 with Not_found -> None
1109 (* Finally we have a list of:
1110 * device name, domain name, rd_* stuff, curr stats, prev stats.
1112 let devs : (string * string * rd_active *
1113 D.block_stats * D.block_stats) list =
1114 List.flatten devs in
1116 (* Difference curr slice & prev slice. *)
1117 let devs = List.map (
1118 fun (dev, name, rd, curr, prev) ->
1119 dev, name, rd, diff_block_stats curr prev
1122 (* Sort by current sort order, but map some of the standard
1123 * sort orders into ones which makes sense here.
1127 match !sort_order with
1129 (fun _ -> 0) (* fallthrough to default name compare *)
1131 (fun (_, { rd_domid = id1 }, _, { rd_domid = id2 }) ->
1133 | Processor | Memory | Time | NetRX | NetTX
1134 (* fallthrough to RDRQ comparison. *)
1136 (fun ({ D.rd_req = b1 }, _, { D.rd_req = b2 }, _) ->
1139 (fun ({ D.wr_req = b1 }, _, { D.wr_req = b2 }, _) ->
1142 let cmp (dev1, name1, rd1, stats1) (dev2, name2, rd2, stats2) =
1143 let r = cmp (stats1, rd1, stats2, rd2) in
1145 else compare (dev1, name1) (dev2, name2)
1147 List.sort ~cmp devs in
1149 (* Print the header for block devices. *)
1151 mvaddstr header_lineno 0
1152 (pad cols " ID S RDBY WRBY RDRQ WRRQ DOMAIN DEVICE");
1155 (* Print domains and devices. *)
1156 let rec loop lineno = function
1158 | (dev, name, rd, stats) :: devs ->
1159 if lineno < lines then (
1160 let state = show_state rd.rd_info.D.state in
1162 if stats.D.rd_bytes >= 0L
1163 then Show.int64 stats.D.rd_bytes
1166 if stats.D.wr_bytes >= 0L
1167 then Show.int64 stats.D.wr_bytes
1170 if stats.D.rd_req >= 0L
1171 then Show.int64 stats.D.rd_req
1174 if stats.D.wr_req >= 0L
1175 then Show.int64 stats.D.wr_req
1178 let line = sprintf "%5d %c %s %s %s %s %-12s %s"
1182 (pad 12 name) dev in
1183 let line = pad cols line in
1184 mvaddstr lineno 0 line;
1185 loop (lineno+1) devs
1188 loop domains_lineno devs
1189 ); (* end of display_mode conditional section *)
1191 let (count, running, blocked, paused, shutdown, shutoff,
1192 crashed, active, inactive,
1193 total_cpu_time, total_memory, total_domU_memory) = totals in
1195 mvaddstr summary_lineno 0
1197 (f_"%d domains, %d active, %d running, %d sleeping, %d paused, %d inactive D:%d O:%d X:%d")
1198 count active running blocked paused inactive shutdown shutoff crashed);
1200 (* Total %CPU used, and memory summary. *)
1201 let percent_cpu = 100. *. total_cpu_time /. total_cpu in
1202 mvaddstr (summary_lineno+1) 0
1204 (f_"CPU: %2.1f%% Mem: %Ld MB (%Ld MB by guests)")
1205 percent_cpu (total_memory /^ 1024L) (total_domU_memory /^ 1024L));
1207 (* Time to grab another historical %CPU for the list? *)
1208 if time >= !historical_cpu_last_time +. float !historical_cpu_delay
1210 historical_cpu := percent_cpu :: List.take 10 !historical_cpu;
1211 historical_cpu_last_time := time
1214 (* Display historical CPU time. *)
1216 let y, x = historical_cursor in
1217 let maxwidth = cols - x in
1220 (List.map (sprintf "%2.1f%%") !historical_cpu) in
1221 let line = pad maxwidth line in
1225 move message_lineno 0; (* Park cursor in message area, as with top. *)
1226 refresh () (* Refresh the display. *)
1228 (* Write CSV header row. *)
1229 let write_csv_header () =
1231 [ "Hostname"; "Time"; "Arch"; "Physical CPUs";
1232 "Count"; "Running"; "Blocked"; "Paused"; "Shutdown";
1233 "Shutoff"; "Crashed"; "Active"; "Inactive";
1235 "Total hardware memory (KB)";
1236 "Total memory (KB)"; "Total guest memory (KB)";
1237 "Total CPU time (ns)" ] @
1238 (* These fields are repeated for each domain: *)
1239 [ "Domain ID"; "Domain name"; ] @
1240 (if !csv_cpu then [ "CPU (ns)"; "%CPU"; ] else []) @
1241 (if !csv_block && not !block_in_bytes
1242 then [ "Block RDRQ"; "Block WRRQ"; ] else []) @
1243 (if !csv_block && !block_in_bytes
1244 then [ "Block RDBY"; "Block WRBY"; ] else []) @
1245 (if !csv_net then [ "Net RXBY"; "Net TXBY" ] else [])
1248 (* Write summary data to CSV file. *)
1250 (_, _, _, _, _, node_info, hostname, _) (* setup *)
1253 nr_pcpus, total_cpu, _,
1257 (* The totals / summary fields. *)
1258 let (count, running, blocked, paused, shutdown, shutoff,
1259 crashed, active, inactive,
1260 total_cpu_time, total_memory, total_domU_memory) = totals in
1262 let percent_cpu = 100. *. total_cpu_time /. total_cpu in
1264 let summary_fields = [
1265 hostname; printable_time; node_info.C.model; string_of_int nr_pcpus;
1266 string_of_int count; string_of_int running; string_of_int blocked;
1267 string_of_int paused; string_of_int shutdown; string_of_int shutoff;
1268 string_of_int crashed; string_of_int active; string_of_int inactive;
1269 sprintf "%2.1f" percent_cpu;
1270 Int64.to_string node_info.C.memory;
1271 Int64.to_string total_memory; Int64.to_string total_domU_memory;
1272 Int64.to_string (Int64.of_float total_cpu_time)
1277 * Sort them by ID so that the list of relatively stable. Ignore
1280 let doms = List.filter_map (
1282 | _, Inactive -> None (* Ignore inactive domains. *)
1283 | name, Active rd -> Some (name, rd)
1285 let cmp (_, { rd_domid = rd_domid1 }) (_, { rd_domid = rd_domid2 }) =
1286 compare rd_domid1 rd_domid2
1288 let doms = List.sort ~cmp doms in
1290 let string_of_int64_option = Option.map_default Int64.to_string "" in
1292 let domain_fields = List.map (
1293 fun (domname, rd) ->
1294 [ string_of_int rd.rd_domid; domname ] @
1296 string_of_float rd.rd_cpu_time; string_of_float rd.rd_percent_cpu
1298 (if !csv_block then [
1299 string_of_int64_option rd.rd_block_rd_info;
1300 string_of_int64_option rd.rd_block_wr_info;
1303 string_of_int64_option rd.rd_net_rx_bytes;
1304 string_of_int64_option rd.rd_net_tx_bytes;
1307 let domain_fields = List.flatten domain_fields in
1309 (!csv_write) (summary_fields @ domain_fields)
1312 (_, _, _, _, _, node_info, hostname, _) (* setup *)
1315 nr_pcpus, total_cpu, _,
1319 (* Header for this iteration *)
1320 printf "virt-top time %s Host %s %s %d/%dCPU %dMHz %LdMB \n"
1321 printable_time hostname node_info.C.model node_info.C.cpus nr_pcpus
1322 node_info.C.mhz (node_info.C.memory /^ 1024L);
1323 (* dump domain information one by one *)
1324 let rd, wr = if !block_in_bytes then "RDBY", "WRBY" else "RDRQ", "WRRQ"
1326 printf " ID S %s %s RXBY TXBY %%CPU %%MEM TIME NAME\n" rd wr;
1332 | Active {rd_domid = id1 }, Active {rd_domid = id2} ->
1334 | Active _, Inactive -> -1
1335 | Inactive, Active _ -> 1
1336 | Inactive, Inactive -> 0)
1338 let cmp (name1, dom1) (name2, dom2) = compare(dom1, dom2) in
1339 List.sort ~cmp doms in
1341 let dump_domain = fun name rd
1343 let state = show_state rd.rd_info.D.state in
1344 let rd_req = if rd.rd_block_rd_info = None then " 0"
1345 else Show.int64_option rd.rd_block_rd_info in
1346 let wr_req = if rd.rd_block_wr_info = None then " 0"
1347 else Show.int64_option rd.rd_block_wr_info in
1348 let rx_bytes = if rd.rd_net_rx_bytes = None then " 0"
1349 else Show.int64_option rd.rd_net_rx_bytes in
1350 let tx_bytes = if rd.rd_net_tx_bytes = None then " 0"
1351 else Show.int64_option rd.rd_net_tx_bytes in
1352 let percent_cpu = Show.percent rd.rd_percent_cpu in
1353 let percent_mem = Int64.to_float rd.rd_mem_percent in
1354 let percent_mem = Show.percent percent_mem in
1355 let time = Show.time rd.rd_info.D.cpu_time in
1356 printf "%5d %c %s %s %s %s %s %s %s %s\n"
1357 rd.rd_domid state rd_req wr_req rx_bytes tx_bytes
1358 percent_cpu percent_mem time name;
1363 | name, Active dom -> dump_domain name dom
1364 | name, Inactive -> ()
1369 let rec main_loop ((_, batch_mode, script_mode, csv_enabled, stream_mode, _, _, _)
1371 if csv_enabled then write_csv_header ();
1374 let state = collect setup in (* Collect stats. *)
1375 (* Redraw display. *)
1376 if not script_mode && not stream_mode then redraw setup state;
1377 if csv_enabled then append_csv setup state; (* Update CSV file. *)
1378 if stream_mode then dump_stdout setup state; (* dump to stdout *)
1380 (* Clear up unused virDomainPtr objects. *)
1383 (* Max iterations? *)
1384 if !iterations >= 0 then (
1386 if !iterations = 0 then quit := true
1389 (* End time? We might need to adjust the precise delay down if
1390 * the delay would be longer than the end time (RHBZ#637964). Note
1391 * 'delay' is in milliseconds.
1394 match !end_time with
1396 (* No --end-time option, so use the current delay. *)
1399 let (_, time, _, _, _, _, _, _) = state in
1400 let delay_secs = float !delay /. 1000. in
1401 if end_time <= time +. delay_secs then (
1403 let delay = int_of_float (1000. *. (end_time -. time)) in
1404 if delay >= 0 then delay else 0
1407 (*eprintf "adjusted delay = %d\n%!" delay;*)
1409 (* Get next key. This does the sleep. *)
1410 if not batch_mode && not script_mode && not stream_mode then
1411 get_key_press setup delay
1413 (* Batch mode, script mode, stream mode. We didn't call
1414 * get_key_press, so we didn't sleep. Sleep now, unless we are
1417 if not !quit || !end_time <> None then
1422 and get_key_press setup delay =
1423 (* Read the next key, waiting up to 'delay' milliseconds. *)
1426 timeout (-1); (* Reset to blocking mode. *)
1428 if k >= 0 && k <> 32 (* ' ' *) && k <> 12 (* ^L *) && k <> Key.resize
1430 if k = Char.code 'q' then quit := true
1431 else if k = Char.code 'h' then show_help setup
1432 else if k = Char.code 's' || k = Char.code 'd' then change_delay ()
1433 else if k = Char.code 'M' then sort_order := Memory
1434 else if k = Char.code 'P' then sort_order := Processor
1435 else if k = Char.code 'T' then sort_order := Time
1436 else if k = Char.code 'N' then sort_order := DomainID
1437 else if k = Char.code 'F' then change_sort_order ()
1438 else if k = Char.code '0' then set_tasks_display ()
1439 else if k = Char.code '1' then toggle_pcpu_display ()
1440 else if k = Char.code '2' then toggle_net_display ()
1441 else if k = Char.code '3' then toggle_block_display ()
1442 else if k = Char.code 'W' then write_init_file ()
1443 else if k = Char.code 'B' then toggle_block_in_bytes_mode ()
1444 else unknown_command k
1447 and change_delay () =
1449 (sprintf (f_"Change delay from %.1f to: ") (float !delay /. 1000.));
1450 let str = get_string 16 in
1451 (* Try to parse the number. *)
1454 let newdelay = float_of_string str in
1455 if newdelay <= 0. then (
1456 print_msg (s_"Delay must be > 0"); true
1458 delay := int_of_float (newdelay *. 1000.); false
1461 Failure "float_of_string" ->
1462 print_msg (s_"Not a valid number"); true in
1464 sleep (if error then 2 else 1)
1466 and change_sort_order () =
1468 let lines, cols = get_size () in
1470 mvaddstr top_lineno 0 (s_"Set sort order for main display");
1471 mvaddstr summary_lineno 0 (s_"Type key or use up and down cursor keys.");
1474 mvaddstr header_lineno 0 (pad cols "KEY Sort field");
1477 let accelerator_key = function
1478 | Memory -> "(key: M)"
1479 | Processor -> "(key: P)"
1480 | Time -> "(key: T)"
1481 | DomainID -> "(key: N)"
1482 | _ -> (* all others have to be changed from here *) ""
1485 let rec key_of_int = function
1486 | i when i < 10 -> Char.chr (i + Char.code '0')
1487 | i when i < 20 -> Char.chr (i + Char.code 'a')
1489 and int_of_key = function
1490 | k when k >= 0x30 && k <= 0x39 (* '0' - '9' *) -> k - 0x30
1491 | k when k >= 0x61 && k <= 0x7a (* 'a' - 'j' *) -> k - 0x61 + 10
1492 | k when k >= 0x41 && k <= 0x6a (* 'A' - 'J' *) -> k - 0x41 + 10
1496 (* Display possible sort fields. *)
1497 let selected_index = ref 0 in
1500 let selected = !sort_order = ord in
1501 if selected then selected_index := i;
1502 mvaddstr (domains_lineno+i) 0
1503 (sprintf " %c %s %s %s"
1504 (key_of_int i) (if selected then "*" else " ")
1505 (printable_sort_order ord)
1506 (accelerator_key ord))
1509 move message_lineno 0;
1512 if k >= 0 && k <> 32 && k <> Char.code 'q' && k <> 13 then (
1513 let new_order, loop =
1514 (* Redraw the display. *)
1515 if k = 12 (* ^L *) then None, true
1516 (* Make the UP and DOWN arrow keys do something useful. *)
1517 else if k = Key.up then (
1518 if !selected_index > 0 then
1519 Some (List.nth all_sort_fields (!selected_index-1)), true
1523 else if k = Key.down then (
1524 if !selected_index < List.length all_sort_fields - 1 then
1525 Some (List.nth all_sort_fields (!selected_index+1)), true
1529 (* Also understand the regular accelerator keys. *)
1530 else if k = Char.code 'M' then
1532 else if k = Char.code 'P' then
1533 Some Processor, false
1534 else if k = Char.code 'T' then
1536 else if k = Char.code 'N' then
1537 Some DomainID, false
1539 (* It's one of the KEYs. *)
1540 let i = int_of_key k in
1541 if i >= 0 && i < List.length all_sort_fields then
1542 Some (List.nth all_sort_fields i), false
1547 (match new_order with
1550 sort_order := new_order;
1551 print_msg (sprintf "Sort order changed to: %s"
1552 (printable_sort_order new_order));
1559 if loop then change_sort_order ()
1562 (* Note: We need to clear_pcpu_display_data every time
1563 * we _leave_ PCPUDisplay mode.
1565 and set_tasks_display () = (* key 0 *)
1566 if !display_mode = PCPUDisplay then clear_pcpu_display_data ();
1567 display_mode := TaskDisplay
1569 and toggle_pcpu_display () = (* key 1 *)
1571 match !display_mode with
1572 | TaskDisplay | NetDisplay | BlockDisplay -> PCPUDisplay
1573 | PCPUDisplay -> clear_pcpu_display_data (); TaskDisplay
1575 and toggle_net_display () = (* key 2 *)
1577 match !display_mode with
1578 | PCPUDisplay -> clear_pcpu_display_data (); NetDisplay
1579 | TaskDisplay | BlockDisplay -> NetDisplay
1580 | NetDisplay -> TaskDisplay
1582 and toggle_block_display () = (* key 3 *)
1584 match !display_mode with
1585 | PCPUDisplay -> clear_pcpu_display_data (); BlockDisplay
1586 | TaskDisplay | NetDisplay -> BlockDisplay
1587 | BlockDisplay -> TaskDisplay
1589 and toggle_block_in_bytes_mode () = (* key B *)
1591 match !block_in_bytes with
1595 (* Write an init file. *)
1596 and write_init_file () =
1597 match !init_file with
1598 | NoInitFile -> () (* Do nothing if --no-init-file *)
1599 | DefaultInitFile ->
1600 let home = try Sys.getenv "HOME" with Not_found -> "/" in
1601 let filename = home // rcfile in
1602 _write_init_file filename
1603 | InitFile filename ->
1604 _write_init_file filename
1606 and _write_init_file filename =
1608 (* Create the new file as filename.new. *)
1609 let chan = open_out (filename ^ ".new") in
1611 let time = Unix.gettimeofday () in
1612 let tm = Unix.localtime time in
1613 let printable_date_time =
1614 sprintf "%04d-%02d-%02d %02d:%02d:%02d"
1615 (tm.Unix.tm_year + 1900) (tm.Unix.tm_mon+1) tm.Unix.tm_mday
1616 tm.Unix.tm_hour tm.Unix.tm_min tm.Unix.tm_sec in
1619 let uid = Unix.geteuid () in
1620 (Unix.getpwuid uid).Unix.pw_name
1622 Not_found -> "unknown" in
1625 let nl () = fp chan "\n" in
1626 let () = fp chan (f_"# %s virt-top configuration file\n") rcfile in
1627 let () = fp chan (f_"# generated on %s by %s\n") printable_date_time username in
1629 fp chan "display %s\n" (cli_of_display !display_mode);
1630 fp chan "delay %g\n" (float !delay /. 1000.);
1631 fp chan "hist-cpu %d\n" !historical_cpu_delay;
1632 if !iterations <> -1 then fp chan "iterations %d\n" !iterations;
1633 fp chan "sort %s\n" (cli_of_sort_order !sort_order);
1636 | Some uri -> fp chan "connect %s\n" uri
1638 if !batch_mode = true then fp chan "batch true\n";
1639 if !secure_mode = true then fp chan "secure true\n";
1641 output_string chan (s_"# To send debug and error messages to a file, uncomment next line\n");
1642 fp chan "#debug virt-top.out\n";
1644 output_string chan (s_"# Enable CSV output to the named file\n");
1645 fp chan "#csv virt-top.csv\n";
1647 output_string chan (s_"# To protect this file from being overwritten, uncomment next line\n");
1648 fp chan "#overwrite-init-file false\n";
1652 (* If the file exists, rename it as filename.old. *)
1653 (try Unix.rename filename (filename ^ ".old")
1654 with Unix.Unix_error _ -> ());
1656 (* Rename filename.new to filename. *)
1657 Unix.rename (filename ^ ".new") filename;
1659 print_msg (sprintf (f_"Wrote settings to %s") filename);
1664 print_msg (s_"Error" ^ ": " ^ err);
1666 | Unix.Unix_error (err, fn, str) ->
1667 print_msg (s_"Error" ^ ": " ^
1668 (Unix.error_message err) ^ " " ^ fn ^ " " ^ str);
1672 and show_help (_, _, _, _, _, _, hostname,
1673 (libvirt_major, libvirt_minor, libvirt_release)) =
1676 (* Get the screen/window size. *)
1677 let lines, cols = get_size () in
1679 (* Banner at the top of the screen. *)
1681 sprintf (f_"virt-top %s ocaml-libvirt %s libvirt %d.%d.%d by Red Hat")
1682 Virt_top_version.version
1683 Libvirt_version.version
1684 libvirt_major libvirt_minor libvirt_release in
1685 let banner = pad cols banner in
1687 mvaddstr 0 0 banner;
1693 (f_"Delay: %.1f secs; Batch: %s; Secure: %s; Sort: %s")
1694 (float !delay /. 1000.)
1695 (if !batch_mode then s_"On" else s_"Off")
1696 (if !secure_mode then s_"On" else s_"Off")
1697 (printable_sort_order !sort_order));
1700 (f_"Connect: %s; Hostname: %s")
1701 (match !uri with None -> s_"default" | Some s -> s)
1704 (* Misc keys on left. *)
1705 let banner = pad 38 (s_"MAIN KEYS") in
1707 mvaddstr header_lineno 1 banner;
1711 let lineno = ref domains_lineno in
1712 fun () -> let i = !lineno in incr lineno; i
1714 let key keys description =
1715 let lineno = get_lineno () in
1716 move lineno 1; attron A.bold; addstr keys; attroff A.bold;
1717 move lineno 10; addstr description
1719 key "space ^L" (s_"Update display");
1721 key "d s" (s_"Set update interval");
1723 key "B" (s_"toggle block info req/bytes");
1726 ignore (get_lineno ());
1727 let banner = pad 38 (s_"SORTING") in
1729 mvaddstr (get_lineno ()) 1 banner;
1732 key "P" (s_"Sort by %CPU");
1733 key "M" (s_"Sort by %MEM");
1734 key "T" (s_"Sort by TIME");
1735 key "N" (s_"Sort by ID");
1736 key "F" (s_"Select sort field");
1738 (* Display modes on right. *)
1739 let banner = pad 39 (s_"DISPLAY MODES") in
1741 mvaddstr header_lineno 40 banner;
1745 let lineno = ref domains_lineno in
1746 fun () -> let i = !lineno in incr lineno; i
1748 let key keys description =
1749 let lineno = get_lineno () in
1750 move lineno 40; attron A.bold; addstr keys; attroff A.bold;
1751 move lineno 49; addstr description
1753 key "0" (s_"Domains display");
1754 key "1" (s_"Toggle physical CPUs");
1755 key "2" (s_"Toggle network interfaces");
1756 key "3" (s_"Toggle block devices");
1758 (* Update screen and wait for key press. *)
1759 mvaddstr (lines-1) 0
1760 (s_"More help in virt-top(1) man page. Press any key to return.");
1764 and unknown_command k =
1765 print_msg (s_"Unknown command - try 'h' for help");