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
135 (* Tuple of never-changing data returned by start_up function. *)
137 Libvirt.ro C.t * bool * bool * bool * bool * C.node_info * string *
140 (* Function to read command line arguments and go into curses mode. *)
142 (* Read command line arguments. *)
143 let rec set_delay newdelay =
144 if newdelay <= 0. then
145 failwith (s_"-d: cannot set a negative delay");
146 delay := int_of_float (newdelay *. 1000.)
147 and set_uri = function "" -> uri := None | u -> uri := Some u
148 and set_sort order = sort_order := sort_order_of_cli order
149 and set_pcpu_mode () = display_mode := PCPUDisplay
150 and set_net_mode () = display_mode := NetDisplay
151 and set_block_mode () = display_mode := BlockDisplay
152 and set_csv filename =
153 (!csv_start) filename;
155 and no_init_file () = init_file := NoInitFile
156 and set_init_file filename = init_file := InitFile filename
157 and set_end_time time = end_time := Some ((!parse_date_time) time)
158 and display_version () =
159 printf "virt-top %s ocaml-libvirt %s\n"
160 Virt_top_version.version Libvirt_version.version;
163 let argspec = Arg.align [
164 "-1", Arg.Unit set_pcpu_mode,
165 " " ^ s_"Start by displaying pCPUs (default: tasks)";
166 "-2", Arg.Unit set_net_mode,
167 " " ^ s_"Start by displaying network interfaces";
168 "-3", Arg.Unit set_block_mode,
169 " " ^ s_"Start by displaying block devices";
170 "-b", Arg.Set batch_mode,
171 " " ^ s_"Batch mode";
172 "-c", Arg.String set_uri,
173 "uri " ^ s_"Connect to URI (default: Xen)";
174 "--connect", Arg.String set_uri,
175 "uri " ^ s_"Connect to URI (default: Xen)";
176 "--csv", Arg.String set_csv,
177 "file " ^ s_"Log statistics to CSV file";
178 "--no-csv-cpu", Arg.Clear csv_cpu,
179 " " ^ s_"Disable CPU stats in CSV";
180 "--no-csv-block", Arg.Clear csv_block,
181 " " ^ s_"Disable block device stats in CSV";
182 "--no-csv-net", Arg.Clear csv_net,
183 " " ^ s_"Disable net stats in CSV";
184 "-d", Arg.Float set_delay,
185 "delay " ^ s_"Delay time interval (seconds)";
186 "--debug", Arg.Set_string debug_file,
187 "file " ^ s_"Send debug messages to file";
188 "--end-time", Arg.String set_end_time,
189 "time " ^ s_"Exit at given time";
190 "--hist-cpu", Arg.Set_int historical_cpu_delay,
191 "secs " ^ s_"Historical CPU delay";
192 "--init-file", Arg.String set_init_file,
193 "file " ^ s_"Set name of init file";
194 "--no-init-file", Arg.Unit no_init_file,
195 " " ^ s_"Do not read init file";
196 "-n", Arg.Set_int iterations,
197 "iterations " ^ s_"Number of iterations to run";
198 "-o", Arg.String set_sort,
199 "sort " ^ sprintf (f_"Set sort order (%s)") "cpu|mem|time|id|name";
200 "-s", Arg.Set secure_mode,
201 " " ^ s_"Secure (\"kiosk\") mode";
202 "--script", Arg.Set script_mode,
203 " " ^ s_"Run from a script (no user interface)";
204 "--stream", Arg.Set stream_mode,
205 " " ^ s_"dump output to stdout (no userinterface)";
206 "--version", Arg.Unit display_version,
207 " " ^ s_"Display version number and exit";
210 raise (Arg.Bad (sprintf (f_"%s: unknown parameter") str)) in
211 let usage_msg = s_"virt-top : a 'top'-like utility for virtualization
217 Arg.parse argspec anon_fun usage_msg;
219 (* Read the init file. *)
220 let try_to_read_init_file filename =
221 let config = read_config_file filename in
224 | _, "display", mode -> display_mode := display_of_cli mode
225 | _, "delay", secs -> set_delay (float_of_string secs)
226 | _, "hist-cpu", secs -> historical_cpu_delay := int_of_string secs
227 | _, "iterations", n -> iterations := int_of_string n
228 | _, "sort", order -> set_sort order
229 | _, "connect", uri -> set_uri uri
230 | _, "debug", filename -> debug_file := filename
231 | _, "csv", filename -> set_csv filename
232 | _, "csv-cpu", b -> csv_cpu := bool_of_string b
233 | _, "csv-block", b -> csv_block := bool_of_string b
234 | _, "csv-net", b -> csv_net := bool_of_string b
235 | _, "batch", b -> batch_mode := bool_of_string b
236 | _, "secure", b -> secure_mode := bool_of_string b
237 | _, "script", b -> script_mode := bool_of_string b
238 | _, "stream", b -> stream_mode := bool_of_string b
239 | _, "end-time", t -> set_end_time t
240 | _, "overwrite-init-file", "false" -> no_init_file ()
242 eprintf (f_"%s:%d: configuration item ``%s'' ignored\n%!")
246 (match !init_file with
249 let home = try Sys.getenv "HOME" with Not_found -> "/" in
250 let filename = home // rcfile in
251 try_to_read_init_file filename
252 | InitFile filename ->
253 try_to_read_init_file filename
256 (* Connect to the hypervisor before going into curses mode, since
257 * this is the most likely thing to fail.
261 try C.connect_readonly ?name ()
263 Libvirt.Virterror err ->
264 prerr_endline (Libvirt.Virterror.to_string err);
265 (* If non-root and no explicit connection URI, print a warning. *)
266 if Unix.geteuid () <> 0 && name = None then (
267 print_endline (s_"NB: If you want to monitor a local Xen hypervisor, you usually need to be root");
271 (* Get the node_info. This never changes, right? So we get it just once. *)
272 let node_info = C.get_node_info conn in
274 (* Hostname and libvirt library version also don't change. *)
276 try C.get_hostname conn
278 (* qemu:/// and other URIs didn't support virConnectGetHostname until
279 * libvirt 0.3.3. Before that they'd throw a virterror. *)
280 | Libvirt.Virterror _
281 | Libvirt.Not_supported "virConnectGetHostname" -> "unknown" in
283 let libvirt_version =
284 let v, _ = Libvirt.get_version () in
285 v / 1_000_000, (v / 1_000) mod 1_000, v mod 1_000 in
287 (* Open debug file if specified.
288 * NB: Do this just before jumping into curses mode.
290 (match !debug_file with
291 | "" -> (* No debug file specified, send stderr to /dev/null unless
292 * we're in script mode.
294 if not !script_mode && not !stream_mode then (
295 let fd = Unix.openfile "/dev/null" [Unix.O_WRONLY] 0o644 in
296 Unix.dup2 fd Unix.stderr;
299 | filename -> (* Send stderr to the named file. *)
301 Unix.openfile filename [Unix.O_WRONLY;Unix.O_CREAT;Unix.O_TRUNC]
303 Unix.dup2 fd Unix.stderr;
307 (* Curses voodoo (see ncurses(3)). *)
308 if not !script_mode && not !stream_mode then (
313 let stdscr = stdscr () in
314 ignore (intrflush stdscr false);
315 ignore (keypad stdscr true);
319 (* This tuple of static information is called 'setup' in other parts
320 * of this program, and is passed to other functions such as redraw and
321 * main_loop. See virt_top_main.ml.
324 !batch_mode, !script_mode, !csv_enabled, !stream_mode, (* immutable modes *)
325 node_info, hostname, libvirt_version (* info that doesn't change *)
328 (* Show a domain state (the 'S' column). *)
329 let show_state = function
330 | D.InfoNoState -> '?'
331 | D.InfoRunning -> 'R'
332 | D.InfoBlocked -> 'S'
333 | D.InfoPaused -> 'P'
334 | D.InfoShutdown -> 'D'
335 | D.InfoShutoff -> 'O'
336 | D.InfoCrashed -> 'X'
338 (* Sleep in seconds. *)
339 let sleep = Unix.sleep
341 (* Sleep in milliseconds. *)
343 ignore (Unix.select [] [] [] (float n /. 1000.))
345 (* The curses getstr/getnstr functions are just weird.
346 * This helper function also enables echo temporarily.
348 let get_string maxlen =
350 let str = String.create maxlen in
351 let ok = getstr str in (* Safe because binding calls getnstr. *)
355 (* Chop at first '\0'. *)
357 let i = String.index str '\000' in
360 Not_found -> str (* it is full maxlen bytes *)
365 let summary_lineno = 1 (* this takes 2 lines *)
366 let message_lineno = 3
367 let header_lineno = 4
368 let domains_lineno = 5
370 (* Easier to use versions of curses functions addstr, mvaddstr, etc. *)
371 let move y x = ignore (move y x)
372 let refresh () = ignore (refresh ())
373 let addch c = ignore (addch (int_of_char c))
374 let addstr s = ignore (addstr s)
375 let mvaddstr y x s = ignore (mvaddstr y x s)
377 (* Print in the "message area". *)
378 let clear_msg () = move message_lineno 0; clrtoeol ()
379 let print_msg str = clear_msg (); mvaddstr message_lineno 0 str
381 (* Intermediate "domain + stats" structure that we use to collect
382 * everything we know about a domain within the collect function.
384 type rd_domain = Inactive | Active of rd_active
386 rd_domid : int; (* Domain ID. *)
387 rd_dom : [`R] D.t; (* Domain object. *)
388 rd_info : D.info; (* Domain CPU info now. *)
389 rd_block_stats : (string * D.block_stats) list;
390 (* Domain block stats now. *)
391 rd_interface_stats : (string * D.interface_stats) list;
392 (* Domain net stats now. *)
393 rd_prev_info : D.info option; (* Domain CPU info previously. *)
394 rd_prev_block_stats : (string * D.block_stats) list;
395 (* Domain block stats prev. *)
396 rd_prev_interface_stats : (string * D.interface_stats) list;
397 (* Domain interface stats prev. *)
398 (* The following are since the last slice, or 0 if cannot be calculated: *)
399 rd_cpu_time : float; (* CPU time used in nanoseconds. *)
400 rd_percent_cpu : float; (* CPU time as percent of total. *)
401 (* The following are since the last slice, or None if cannot be calc'd: *)
402 rd_block_rd_reqs : int64 option; (* Number of block device read rqs. *)
403 rd_block_wr_reqs : int64 option; (* Number of block device write rqs. *)
404 rd_net_rx_bytes : int64 option; (* Number of bytes received. *)
405 rd_net_tx_bytes : int64 option; (* Number of bytes transmitted. *)
409 let collect, clear_pcpu_display_data =
410 (* We cache the list of block devices and interfaces for each domain
411 * here, so we don't need to reparse the XML each time.
413 let devices = Hashtbl.create 13 in
415 (* Function to get the list of block devices, network interfaces for
416 * a particular domain. Get it from the devices cache, and if not
417 * there then parse the domain XML.
419 let get_devices id dom =
420 try Hashtbl.find devices id
422 let blkdevs, netifs = (!parse_device_xml) id dom in
423 Hashtbl.replace devices id (blkdevs, netifs);
427 (* We save the state of domains across redraws here, which allows us
428 * to deduce %CPU usage from the running total.
430 let last_info = Hashtbl.create 13 in
431 let last_time = ref (Unix.gettimeofday ()) in
433 (* Save vcpuinfo structures across redraws too (only for pCPU display). *)
434 let last_vcpu_info = Hashtbl.create 13 in
436 let clear_pcpu_display_data () =
437 (* Clear out vcpu_info used by PCPUDisplay display_mode
438 * when we switch back to TaskDisplay mode.
440 Hashtbl.clear last_vcpu_info
443 let collect (conn, _, _, _, _, node_info, _, _) =
444 (* Number of physical CPUs (some may be disabled). *)
445 let nr_pcpus = C.maxcpus_of_node_info node_info in
447 (* Get the current time. *)
448 let time = Unix.gettimeofday () in
449 let tm = Unix.localtime time in
451 sprintf "%02d:%02d:%02d" tm.Unix.tm_hour tm.Unix.tm_min tm.Unix.tm_sec in
453 (* What's the total CPU time elapsed since we were last called? (ns) *)
454 let total_cpu_per_pcpu = 1_000_000_000. *. (time -. !last_time) in
455 (* Avoid division by zero. *)
456 let total_cpu_per_pcpu =
457 if total_cpu_per_pcpu <= 0. then 1. else total_cpu_per_pcpu in
458 let total_cpu = float node_info.C.cpus *. total_cpu_per_pcpu in
460 (* Get the domains. Match up with their last_info (if any). *)
462 (* Active domains. *)
463 let n = C.num_of_domains conn in
465 if n > 0 then Array.to_list (C.list_domains conn n)
471 let dom = D.lookup_by_id conn id in
472 let name = D.get_name dom in
473 let blkdevs, netifs = get_devices id dom in
475 (* Get current CPU, block and network stats. *)
476 let info = D.get_info dom in
478 try List.map (fun dev -> dev, D.block_stats dom dev) blkdevs
480 | Libvirt.Not_supported "virDomainBlockStats"
481 | Libvirt.Virterror _ -> [] in
482 let interface_stats =
483 try List.map (fun dev -> dev, D.interface_stats dom dev) netifs
485 | Libvirt.Not_supported "virDomainInterfaceStats"
486 | Libvirt.Virterror _ -> [] in
488 let prev_info, prev_block_stats, prev_interface_stats =
490 let prev_info, prev_block_stats, prev_interface_stats =
491 Hashtbl.find last_info id in
492 Some prev_info, prev_block_stats, prev_interface_stats
493 with Not_found -> None, [], [] in
496 rd_domid = id; rd_dom = dom; rd_info = info;
497 rd_block_stats = block_stats;
498 rd_interface_stats = interface_stats;
499 rd_prev_info = prev_info;
500 rd_prev_block_stats = prev_block_stats;
501 rd_prev_interface_stats = prev_interface_stats;
502 rd_cpu_time = 0.; rd_percent_cpu = 0.;
503 rd_block_rd_reqs = None; rd_block_wr_reqs = None;
504 rd_net_rx_bytes = None; rd_net_tx_bytes = None;
507 Libvirt.Virterror _ -> None (* ignore transient error *)
510 (* Inactive domains. *)
513 let n = C.num_of_defined_domains conn in
515 if n > 0 then Array.to_list (C.list_defined_domains conn n)
517 List.map (fun name -> name, Inactive) names
519 (* Ignore transient errors, in particular errors from
520 * num_of_defined_domains if it cannot contact xend.
522 | Libvirt.Virterror _ -> [] in
524 doms @ doms_inactive in
526 (* Calculate the CPU time (ns) and %CPU used by each domain. *)
530 (* We have previous CPU info from which to calculate it? *)
531 | name, Active ({ rd_prev_info = Some prev_info } as rd) ->
533 Int64.to_float (rd.rd_info.D.cpu_time -^ prev_info.D.cpu_time) in
534 let percent_cpu = 100. *. cpu_time /. total_cpu in
536 rd_cpu_time = cpu_time;
537 rd_percent_cpu = percent_cpu } in
539 (* For all other domains we can't calculate it, so leave as 0 *)
543 (* Calculate the number of block device read/write requests across
544 * all block devices attached to a domain.
549 (* Do we have stats from the previous slice? *)
550 | name, Active ({ rd_prev_block_stats = ((_::_) as prev_block_stats) }
552 let block_stats = rd.rd_block_stats in (* stats now *)
554 (* Add all the devices together. Throw away device names. *)
555 let prev_block_stats =
556 sum_block_stats (List.map snd prev_block_stats) in
558 sum_block_stats (List.map snd block_stats) in
560 (* Calculate increase in read & write requests. *)
562 block_stats.D.rd_req -^ prev_block_stats.D.rd_req in
564 block_stats.D.wr_req -^ prev_block_stats.D.wr_req in
567 rd_block_rd_reqs = Some read_reqs;
568 rd_block_wr_reqs = Some write_reqs } in
570 (* For all other domains we can't calculate it, so leave as None. *)
574 (* Calculate the same as above for network interfaces across
575 * all network interfaces attached to a domain.
580 (* Do we have stats from the previous slice? *)
581 | name, Active ({ rd_prev_interface_stats =
582 ((_::_) as prev_interface_stats) }
584 let interface_stats = rd.rd_interface_stats in (* stats now *)
586 (* Add all the devices together. Throw away device names. *)
587 let prev_interface_stats =
588 sum_interface_stats (List.map snd prev_interface_stats) in
589 let interface_stats =
590 sum_interface_stats (List.map snd interface_stats) in
592 (* Calculate increase in rx & tx bytes. *)
594 interface_stats.D.rx_bytes -^ prev_interface_stats.D.rx_bytes in
596 interface_stats.D.tx_bytes -^ prev_interface_stats.D.tx_bytes in
599 rd_net_rx_bytes = Some rx_bytes;
600 rd_net_tx_bytes = Some tx_bytes } in
602 (* For all other domains we can't calculate it, so leave as None. *)
606 (* Collect some extra information in PCPUDisplay display_mode. *)
608 if !display_mode = PCPUDisplay then (
609 (* Get the VCPU info and VCPU->PCPU mappings for active domains.
610 * Also cull some data we don't care about.
612 let doms = List.filter_map (
614 | (name, Active rd) ->
616 let domid = rd.rd_domid in
617 let maplen = C.cpumaplen nr_pcpus in
618 let maxinfo = rd.rd_info.D.nr_virt_cpu in
619 let nr_vcpus, vcpu_infos, cpumaps =
620 D.get_vcpus rd.rd_dom maxinfo maplen in
622 (* Got previous vcpu_infos for this domain? *)
623 let prev_vcpu_infos =
624 try Some (Hashtbl.find last_vcpu_info domid)
625 with Not_found -> None in
626 (* Update last_vcpu_info. *)
627 Hashtbl.replace last_vcpu_info domid vcpu_infos;
629 (match prev_vcpu_infos with
630 | Some prev_vcpu_infos
631 when Array.length prev_vcpu_infos = Array.length vcpu_infos ->
632 Some (domid, name, nr_vcpus, vcpu_infos, prev_vcpu_infos,
634 | _ -> None (* ignore missing / unequal length prev_vcpu_infos *)
637 Libvirt.Virterror _ -> None(* ignore transient libvirt errs *)
639 | (_, Inactive) -> None (* ignore inactive doms *)
641 let nr_doms = List.length doms in
643 (* Rearrange the data into a matrix. Major axis (down) is
644 * pCPUs. Minor axis (right) is domains. At each node we store:
645 * cpu_time (on this pCPU only, nanosecs),
646 * average? (if set, then cpu_time is an average because the
647 * vCPU is pinned to more than one pCPU)
648 * running? (if set, we were instantaneously running on this pCPU)
650 let empty_node = (0L, false, false) in
651 let pcpus = Array.make_matrix nr_pcpus nr_doms empty_node in
654 fun di (domid, name, nr_vcpus, vcpu_infos, prev_vcpu_infos,
656 (* Which pCPUs can this dom run on? *)
657 for v = 0 to nr_vcpus-1 do
658 let pcpu = vcpu_infos.(v).D.cpu in (* instantaneous pCPU *)
659 let nr_poss_pcpus = ref 0 in (* how many pcpus can it run on? *)
660 for p = 0 to nr_pcpus-1 do
661 (* vcpu v can reside on pcpu p *)
662 if C.cpu_usable cpumaps maplen v p then
665 let nr_poss_pcpus = Int64.of_int !nr_poss_pcpus in
666 for p = 0 to nr_pcpus-1 do
667 (* vcpu v can reside on pcpu p *)
668 if C.cpu_usable cpumaps maplen v p then
669 let vcpu_time_on_pcpu =
670 vcpu_infos.(v).D.vcpu_time
671 -^ prev_vcpu_infos.(v).D.vcpu_time in
672 let vcpu_time_on_pcpu =
673 vcpu_time_on_pcpu /^ nr_poss_pcpus in
675 (vcpu_time_on_pcpu, nr_poss_pcpus > 1L, p = pcpu)
680 (* Sum the CPU time used by each pCPU, for the %CPU column. *)
681 let pcpus_cpu_time = Array.map (
683 let cpu_time = ref 0L in
684 for di = 0 to Array.length row-1 do
685 let t, _, _ = row.(di) in
686 cpu_time := !cpu_time +^ t
688 Int64.to_float !cpu_time
691 Some (doms, pcpus, pcpus_cpu_time)
695 (* Calculate totals. *)
696 let totals = List.fold_left (
697 fun (count, running, blocked, paused, shutdown, shutoff,
698 crashed, active, inactive,
699 total_cpu_time, total_memory, total_domU_memory) ->
701 | (name, Active rd) ->
702 let test state orig =
703 if rd.rd_info.D.state = state then orig+1 else orig
705 let running = test D.InfoRunning running in
706 let blocked = test D.InfoBlocked blocked in
707 let paused = test D.InfoPaused paused in
708 let shutdown = test D.InfoShutdown shutdown in
709 let shutoff = test D.InfoShutoff shutoff in
710 let crashed = test D.InfoCrashed crashed in
712 let total_cpu_time = total_cpu_time +. rd.rd_cpu_time in
713 let total_memory = total_memory +^ rd.rd_info.D.memory in
714 let total_domU_memory = total_domU_memory +^
715 if rd.rd_domid > 0 then rd.rd_info.D.memory else 0L in
717 (count+1, running, blocked, paused, shutdown, shutoff,
718 crashed, active+1, inactive,
719 total_cpu_time, total_memory, total_domU_memory)
721 | (name, Inactive) -> (* inactive domain *)
722 (count+1, running, blocked, paused, shutdown, shutoff,
723 crashed, active, inactive+1,
724 total_cpu_time, total_memory, total_domU_memory)
725 ) (0,0,0,0,0,0,0,0,0, 0.,0L,0L) doms in
727 (* Update last_time, last_info. *)
729 Hashtbl.clear last_info;
733 let info = rd.rd_info, rd.rd_block_stats, rd.rd_interface_stats in
734 Hashtbl.add last_info rd.rd_domid info
739 time, printable_time,
740 nr_pcpus, total_cpu, total_cpu_per_pcpu,
745 collect, clear_pcpu_display_data
747 (* Redraw the display. *)
749 (* Keep a historical list of %CPU usages. *)
750 let historical_cpu = ref [] in
751 let historical_cpu_last_time = ref (Unix.gettimeofday ()) in
753 (_, _, _, _, _, node_info, _, _) (* setup *)
755 time, printable_time,
756 nr_pcpus, total_cpu, total_cpu_per_pcpu,
758 pcpu_display) (* state *) ->
761 (* Get the screen/window size. *)
762 let lines, cols = get_size () in
765 mvaddstr top_lineno 0 (sprintf "virt-top %s - " printable_time);
767 (* Basic node_info. *)
769 (sprintf "%s %d/%dCPU %dMHz %LdMB "
770 node_info.C.model node_info.C.cpus nr_pcpus node_info.C.mhz
771 (node_info.C.memory /^ 1024L));
772 (* Save the cursor position for when we come to draw the
773 * historical CPU times (down in this function).
775 let stdscr = stdscr () in
776 let historical_cursor = getyx stdscr in
778 (match !display_mode with
779 | TaskDisplay -> (*---------- Showing domains ----------*)
780 (* Sort domains on current sort_order. *)
783 match !sort_order with
785 (fun _ -> 0) (* fallthrough to default name compare *)
788 | Active rd1, Active rd2 ->
789 compare rd2.rd_percent_cpu rd1.rd_percent_cpu
790 | Active _, Inactive -> -1
791 | Inactive, Active _ -> 1
792 | Inactive, Inactive -> 0)
795 | Active { rd_info = info1 }, Active { rd_info = info2 } ->
796 compare info2.D.memory info1.D.memory
797 | Active _, Inactive -> -1
798 | Inactive, Active _ -> 1
799 | Inactive, Inactive -> 0)
802 | Active { rd_info = info1 }, Active { rd_info = info2 } ->
803 compare info2.D.cpu_time info1.D.cpu_time
804 | Active _, Inactive -> -1
805 | Inactive, Active _ -> 1
806 | Inactive, Inactive -> 0)
809 | Active { rd_domid = id1 }, Active { rd_domid = id2 } ->
811 | Active _, Inactive -> -1
812 | Inactive, Active _ -> 1
813 | Inactive, Inactive -> 0)
816 | Active { rd_net_rx_bytes = r1 }, Active { rd_net_rx_bytes = r2 } ->
818 | Active _, Inactive -> -1
819 | Inactive, Active _ -> 1
820 | Inactive, Inactive -> 0)
823 | Active { rd_net_tx_bytes = r1 }, Active { rd_net_tx_bytes = r2 } ->
825 | Active _, Inactive -> -1
826 | Inactive, Active _ -> 1
827 | Inactive, Inactive -> 0)
830 | Active { rd_block_rd_reqs = r1 }, Active { rd_block_rd_reqs = r2 } ->
832 | Active _, Inactive -> -1
833 | Inactive, Active _ -> 1
834 | Inactive, Inactive -> 0)
837 | Active { rd_block_wr_reqs = r1 }, Active { rd_block_wr_reqs = r2 } ->
839 | Active _, Inactive -> -1
840 | Inactive, Active _ -> 1
841 | Inactive, Inactive -> 0)
843 let cmp (name1, dom1) (name2, dom2) =
844 let r = cmp (dom1, dom2) in
846 else compare name1 name2
848 List.sort ~cmp doms in
852 mvaddstr header_lineno 0
853 (pad cols " ID S RDRQ WRRQ RXBY TXBY %CPU %MEM TIME NAME");
856 let rec loop lineno = function
858 | (name, Active rd) :: doms ->
859 if lineno < lines then (
860 let state = show_state rd.rd_info.D.state in
861 let rd_req = Show.int64_option rd.rd_block_rd_reqs in
862 let wr_req = Show.int64_option rd.rd_block_wr_reqs in
863 let rx_bytes = Show.int64_option rd.rd_net_rx_bytes in
864 let tx_bytes = Show.int64_option rd.rd_net_tx_bytes in
865 let percent_cpu = Show.percent rd.rd_percent_cpu in
867 100L *^ rd.rd_info.D.memory /^ node_info.C.memory in
868 let percent_mem = Int64.to_float percent_mem in
869 let percent_mem = Show.percent percent_mem in
870 let time = Show.time rd.rd_info.D.cpu_time in
872 let line = sprintf "%5d %c %s %s %s %s %s %s %s %s"
873 rd.rd_domid state rd_req wr_req rx_bytes tx_bytes
874 percent_cpu percent_mem time name in
875 let line = pad cols line in
876 mvaddstr lineno 0 line;
879 | (name, Inactive) :: doms -> (* inactive domain *)
880 if lineno < lines then (
885 let line = pad cols line in
886 mvaddstr lineno 0 line;
890 loop domains_lineno doms
892 | PCPUDisplay -> (*---------- Showing physical CPUs ----------*)
893 let doms, pcpus, pcpus_cpu_time =
894 match pcpu_display with
896 | None -> failwith "internal error: no pcpu_display data" in
898 (* Display the pCPUs. *)
902 fun (_, name, _, _, _, _, _) ->
903 let len = String.length name in
904 let width = max (len+1) 7 in
909 mvaddstr header_lineno 0 (pad cols ("PHYCPU %CPU " ^ dom_names));
914 mvaddstr (p+domains_lineno) 0 (sprintf "%4d " p);
915 let cpu_time = pcpus_cpu_time.(p) in (* ns used on this CPU *)
916 let percent_cpu = 100. *. cpu_time /. total_cpu_per_pcpu in
917 addstr (Show.percent percent_cpu);
921 fun di (domid, name, _, _, _, _, _) ->
922 let t, is_average, is_running = pcpus.(p).(di) in
923 let len = String.length name in
924 let width = max (len+1) 7 in
928 let t = Int64.to_float t in
929 let percent = 100. *. t /. total_cpu_per_pcpu in
930 sprintf "%s%c%c " (Show.percent percent)
931 (if is_average then '=' else ' ')
932 (if is_running then '#' else ' ')
934 addstr (pad width str);
939 | NetDisplay -> (*---------- Showing network interfaces ----------*)
940 (* Only care about active domains. *)
941 let doms = List.filter_map (
943 | (name, Active rd) -> Some (name, rd)
944 | (_, Inactive) -> None
947 (* For each domain we have a list of network interfaces seen
948 * this slice, and seen in the previous slice, which we now
949 * match up to get a list of (domain, interface) for which
950 * we have current & previous knowledge. (And ignore the rest).
958 (* Have prev slice stats for this device? *)
960 List.assoc dev rd.rd_prev_interface_stats in
961 Some (dev, name, rd, stats, prev_stats)
962 with Not_found -> None
963 ) rd.rd_interface_stats
966 (* Finally we have a list of:
967 * device name, domain name, rd_* stuff, curr stats, prev stats.
969 let devs : (string * string * rd_active *
970 D.interface_stats * D.interface_stats) list =
973 (* Difference curr slice & prev slice. *)
974 let devs = List.map (
975 fun (dev, name, rd, curr, prev) ->
976 dev, name, rd, diff_interface_stats curr prev
979 (* Sort by current sort order, but map some of the standard
980 * sort orders into ones which makes sense here.
984 match !sort_order with
986 (fun _ -> 0) (* fallthrough to default name compare *)
988 (fun (_, { rd_domid = id1 }, _, { rd_domid = id2 }) ->
990 | Processor | Memory | Time | BlockRdRq | BlockWrRq
991 (* fallthrough to RXBY comparison. *)
993 (fun ({ D.rx_bytes = b1 }, _, { D.rx_bytes = b2 }, _) ->
996 (fun ({ D.tx_bytes = b1 }, _, { D.tx_bytes = b2 }, _) ->
999 let cmp (dev1, name1, rd1, stats1) (dev2, name2, rd2, stats2) =
1000 let r = cmp (stats1, rd1, stats2, rd2) in
1002 else compare (dev1, name1) (dev2, name2)
1004 List.sort ~cmp devs in
1006 (* Print the header for network devices. *)
1008 mvaddstr header_lineno 0
1009 (pad cols " ID S RXBY TXBY RXPK TXPK DOMAIN INTERFACE");
1012 (* Print domains and devices. *)
1013 let rec loop lineno = function
1015 | (dev, name, rd, stats) :: devs ->
1016 if lineno < lines then (
1017 let state = show_state rd.rd_info.D.state in
1019 if stats.D.rx_bytes >= 0L
1020 then Show.int64 stats.D.rx_bytes
1023 if stats.D.tx_bytes >= 0L
1024 then Show.int64 stats.D.tx_bytes
1027 if stats.D.rx_packets >= 0L
1028 then Show.int64 stats.D.rx_packets
1031 if stats.D.tx_packets >= 0L
1032 then Show.int64 stats.D.tx_packets
1035 let line = sprintf "%5d %c %s %s %s %s %-12s %s"
1038 rx_packets tx_packets
1039 (pad 12 name) dev in
1040 let line = pad cols line in
1041 mvaddstr lineno 0 line;
1042 loop (lineno+1) devs
1045 loop domains_lineno devs
1047 | BlockDisplay -> (*---------- Showing block devices ----------*)
1048 (* Only care about active domains. *)
1049 let doms = List.filter_map (
1051 | (name, Active rd) -> Some (name, rd)
1052 | (_, Inactive) -> None
1055 (* For each domain we have a list of block devices seen
1056 * this slice, and seen in the previous slice, which we now
1057 * match up to get a list of (domain, device) for which
1058 * we have current & previous knowledge. (And ignore the rest).
1066 (* Have prev slice stats for this device? *)
1068 List.assoc dev rd.rd_prev_block_stats in
1069 Some (dev, name, rd, stats, prev_stats)
1070 with Not_found -> None
1074 (* Finally we have a list of:
1075 * device name, domain name, rd_* stuff, curr stats, prev stats.
1077 let devs : (string * string * rd_active *
1078 D.block_stats * D.block_stats) list =
1079 List.flatten devs in
1081 (* Difference curr slice & prev slice. *)
1082 let devs = List.map (
1083 fun (dev, name, rd, curr, prev) ->
1084 dev, name, rd, diff_block_stats curr prev
1087 (* Sort by current sort order, but map some of the standard
1088 * sort orders into ones which makes sense here.
1092 match !sort_order with
1094 (fun _ -> 0) (* fallthrough to default name compare *)
1096 (fun (_, { rd_domid = id1 }, _, { rd_domid = id2 }) ->
1098 | Processor | Memory | Time | NetRX | NetTX
1099 (* fallthrough to RDRQ comparison. *)
1101 (fun ({ D.rd_req = b1 }, _, { D.rd_req = b2 }, _) ->
1104 (fun ({ D.wr_req = b1 }, _, { D.wr_req = b2 }, _) ->
1107 let cmp (dev1, name1, rd1, stats1) (dev2, name2, rd2, stats2) =
1108 let r = cmp (stats1, rd1, stats2, rd2) in
1110 else compare (dev1, name1) (dev2, name2)
1112 List.sort ~cmp devs in
1114 (* Print the header for block devices. *)
1116 mvaddstr header_lineno 0
1117 (pad cols " ID S RDBY WRBY RDRQ WRRQ DOMAIN DEVICE");
1120 (* Print domains and devices. *)
1121 let rec loop lineno = function
1123 | (dev, name, rd, stats) :: devs ->
1124 if lineno < lines then (
1125 let state = show_state rd.rd_info.D.state in
1127 if stats.D.rd_bytes >= 0L
1128 then Show.int64 stats.D.rd_bytes
1131 if stats.D.wr_bytes >= 0L
1132 then Show.int64 stats.D.wr_bytes
1135 if stats.D.rd_req >= 0L
1136 then Show.int64 stats.D.rd_req
1139 if stats.D.wr_req >= 0L
1140 then Show.int64 stats.D.wr_req
1143 let line = sprintf "%5d %c %s %s %s %s %-12s %s"
1147 (pad 12 name) dev in
1148 let line = pad cols line in
1149 mvaddstr lineno 0 line;
1150 loop (lineno+1) devs
1153 loop domains_lineno devs
1154 ); (* end of display_mode conditional section *)
1156 let (count, running, blocked, paused, shutdown, shutoff,
1157 crashed, active, inactive,
1158 total_cpu_time, total_memory, total_domU_memory) = totals in
1160 mvaddstr summary_lineno 0
1162 (f_"%d domains, %d active, %d running, %d sleeping, %d paused, %d inactive D:%d O:%d X:%d")
1163 count active running blocked paused inactive shutdown shutoff crashed);
1165 (* Total %CPU used, and memory summary. *)
1166 let percent_cpu = 100. *. total_cpu_time /. total_cpu in
1167 mvaddstr (summary_lineno+1) 0
1169 (f_"CPU: %2.1f%% Mem: %Ld MB (%Ld MB by guests)")
1170 percent_cpu (total_memory /^ 1024L) (total_domU_memory /^ 1024L));
1172 (* Time to grab another historical %CPU for the list? *)
1173 if time >= !historical_cpu_last_time +. float !historical_cpu_delay
1175 historical_cpu := percent_cpu :: List.take 10 !historical_cpu;
1176 historical_cpu_last_time := time
1179 (* Display historical CPU time. *)
1181 let y, x = historical_cursor in
1182 let maxwidth = cols - x in
1185 (List.map (sprintf "%2.1f%%") !historical_cpu) in
1186 let line = pad maxwidth line in
1190 move message_lineno 0; (* Park cursor in message area, as with top. *)
1191 refresh () (* Refresh the display. *)
1193 (* Write CSV header row. *)
1194 let write_csv_header () =
1196 [ "Hostname"; "Time"; "Arch"; "Physical CPUs";
1197 "Count"; "Running"; "Blocked"; "Paused"; "Shutdown";
1198 "Shutoff"; "Crashed"; "Active"; "Inactive";
1200 "Total hardware memory (KB)";
1201 "Total memory (KB)"; "Total guest memory (KB)";
1202 "Total CPU time (ns)" ] @
1203 (* These fields are repeated for each domain: *)
1204 [ "Domain ID"; "Domain name"; ] @
1205 (if !csv_cpu then [ "CPU (ns)"; "%CPU"; ] else []) @
1206 (if !csv_block then [ "Block RDRQ"; "Block WRRQ"; ] else []) @
1207 (if !csv_net then [ "Net RXBY"; "Net TXBY" ] else [])
1210 (* Write summary data to CSV file. *)
1212 (_, _, _, _, _, node_info, hostname, _) (* setup *)
1215 nr_pcpus, total_cpu, _,
1219 (* The totals / summary fields. *)
1220 let (count, running, blocked, paused, shutdown, shutoff,
1221 crashed, active, inactive,
1222 total_cpu_time, total_memory, total_domU_memory) = totals in
1224 let percent_cpu = 100. *. total_cpu_time /. total_cpu in
1226 let summary_fields = [
1227 hostname; printable_time; node_info.C.model; string_of_int nr_pcpus;
1228 string_of_int count; string_of_int running; string_of_int blocked;
1229 string_of_int paused; string_of_int shutdown; string_of_int shutoff;
1230 string_of_int crashed; string_of_int active; string_of_int inactive;
1231 sprintf "%2.1f" percent_cpu;
1232 Int64.to_string node_info.C.memory;
1233 Int64.to_string total_memory; Int64.to_string total_domU_memory;
1234 Int64.to_string (Int64.of_float total_cpu_time)
1239 * Sort them by ID so that the list of relatively stable. Ignore
1242 let doms = List.filter_map (
1244 | _, Inactive -> None (* Ignore inactive domains. *)
1245 | name, Active rd -> Some (name, rd)
1247 let cmp (_, { rd_domid = rd_domid1 }) (_, { rd_domid = rd_domid2 }) =
1248 compare rd_domid1 rd_domid2
1250 let doms = List.sort ~cmp doms in
1252 let string_of_int64_option = Option.map_default Int64.to_string "" in
1254 let domain_fields = List.map (
1255 fun (domname, rd) ->
1256 [ string_of_int rd.rd_domid; domname ] @
1258 string_of_float rd.rd_cpu_time; string_of_float rd.rd_percent_cpu
1260 (if !csv_block then [
1261 string_of_int64_option rd.rd_block_rd_reqs;
1262 string_of_int64_option rd.rd_block_wr_reqs;
1265 string_of_int64_option rd.rd_net_rx_bytes;
1266 string_of_int64_option rd.rd_net_tx_bytes;
1269 let domain_fields = List.flatten domain_fields in
1271 (!csv_write) (summary_fields @ domain_fields)
1274 (_, _, _, _, _, node_info, hostname, _) (* setup *)
1277 nr_pcpus, total_cpu, _,
1281 (* Header for this iteration *)
1282 printf "virt-top time %s Host %s %s %d/%dCPU %dMHz %LdMB \n"
1283 printable_time hostname node_info.C.model node_info.C.cpus nr_pcpus
1284 node_info.C.mhz (node_info.C.memory /^ 1024L);
1285 (* dump domain information one by one *)
1286 printf " ID S RDRQ WRRQ RXBY TXBY %%CPU %%MEM TIME NAME\n";
1291 | Active {rd_domid = id1 }, Active {rd_domid = id2} ->
1293 | Active _, Inactive -> -1
1294 | Inactive, Active _ -> 1
1295 | Inactive, Inactive -> 0)
1297 let cmp (name1, dom1) (name2, dom2) = compare(dom1, dom2) in
1298 List.sort ~cmp doms in
1300 let dump_domain = fun name rd
1302 let state = show_state rd.rd_info.D.state in
1303 let rd_req = if rd.rd_block_rd_reqs = None then " 0"
1304 else Show.int64_option rd.rd_block_rd_reqs in
1305 let wr_req = if rd.rd_block_wr_reqs = None then " 0"
1306 else Show.int64_option rd.rd_block_wr_reqs in
1307 let rx_bytes = if rd.rd_net_rx_bytes = None then " 0"
1308 else Show.int64_option rd.rd_net_rx_bytes in
1309 let tx_bytes = if rd.rd_net_tx_bytes = None then " 0"
1310 else Show.int64_option rd.rd_net_tx_bytes in
1311 let percent_cpu = Show.percent rd.rd_percent_cpu in
1313 100L *^ rd.rd_info.D.memory /^ node_info.C.memory in
1314 let percent_mem = Int64.to_float percent_mem in
1315 let percent_mem = Show.percent percent_mem in
1316 let time = Show.time rd.rd_info.D.cpu_time in
1317 printf "%5d %c %s %s %s %s %s %s %s %s\n"
1318 rd.rd_domid state rd_req wr_req rx_bytes tx_bytes
1319 percent_cpu percent_mem time name;
1324 | name, Active dom -> dump_domain name dom
1325 | name, Inactive -> ()
1330 let rec main_loop ((_, batch_mode, script_mode, csv_enabled, stream_mode, _, _, _)
1332 if csv_enabled then write_csv_header ();
1335 let state = collect setup in (* Collect stats. *)
1336 (* Redraw display. *)
1337 if not script_mode && not stream_mode then redraw setup state;
1338 if csv_enabled then append_csv setup state; (* Update CSV file. *)
1339 if stream_mode then dump_stdout setup state; (* dump to stdout *)
1341 (* Clear up unused virDomainPtr objects. *)
1344 (* Max iterations? *)
1345 if !iterations >= 0 then (
1347 if !iterations = 0 then quit := true
1350 (* End time? We might need to adjust the precise delay down if
1351 * the delay would be longer than the end time (RHBZ#637964). Note
1352 * 'delay' is in milliseconds.
1355 match !end_time with
1357 (* No --end-time option, so use the current delay. *)
1360 let (_, time, _, _, _, _, _, _) = state in
1361 let delay_secs = float !delay /. 1000. in
1362 if end_time <= time +. delay_secs then (
1364 let delay = int_of_float (1000. *. (end_time -. time)) in
1365 if delay >= 0 then delay else 0
1368 (*eprintf "adjusted delay = %d\n%!" delay;*)
1370 (* Get next key. This does the sleep. *)
1371 if not batch_mode && not script_mode && not stream_mode then
1372 get_key_press setup delay
1374 (* Batch mode, script mode, stream mode. We didn't call
1375 * get_key_press, so we didn't sleep. Sleep now, unless we are
1378 if not !quit || !end_time <> None then
1383 and get_key_press setup delay =
1384 (* Read the next key, waiting up to 'delay' milliseconds. *)
1387 timeout (-1); (* Reset to blocking mode. *)
1389 if k >= 0 && k <> 32 (* ' ' *) && k <> 12 (* ^L *) && k <> Key.resize
1391 if k = Char.code 'q' then quit := true
1392 else if k = Char.code 'h' then show_help setup
1393 else if k = Char.code 's' || k = Char.code 'd' then change_delay ()
1394 else if k = Char.code 'M' then sort_order := Memory
1395 else if k = Char.code 'P' then sort_order := Processor
1396 else if k = Char.code 'T' then sort_order := Time
1397 else if k = Char.code 'N' then sort_order := DomainID
1398 else if k = Char.code 'F' then change_sort_order ()
1399 else if k = Char.code '0' then set_tasks_display ()
1400 else if k = Char.code '1' then toggle_pcpu_display ()
1401 else if k = Char.code '2' then toggle_net_display ()
1402 else if k = Char.code '3' then toggle_block_display ()
1403 else if k = Char.code 'W' then write_init_file ()
1404 else unknown_command k
1407 and change_delay () =
1409 (sprintf (f_"Change delay from %.1f to: ") (float !delay /. 1000.));
1410 let str = get_string 16 in
1411 (* Try to parse the number. *)
1414 let newdelay = float_of_string str in
1415 if newdelay <= 0. then (
1416 print_msg (s_"Delay must be > 0"); true
1418 delay := int_of_float (newdelay *. 1000.); false
1421 Failure "float_of_string" ->
1422 print_msg (s_"Not a valid number"); true in
1424 sleep (if error then 2 else 1)
1426 and change_sort_order () =
1428 let lines, cols = get_size () in
1430 mvaddstr top_lineno 0 (s_"Set sort order for main display");
1431 mvaddstr summary_lineno 0 (s_"Type key or use up and down cursor keys.");
1434 mvaddstr header_lineno 0 (pad cols "KEY Sort field");
1437 let accelerator_key = function
1438 | Memory -> "(key: M)"
1439 | Processor -> "(key: P)"
1440 | Time -> "(key: T)"
1441 | DomainID -> "(key: N)"
1442 | _ -> (* all others have to be changed from here *) ""
1445 let rec key_of_int = function
1446 | i when i < 10 -> Char.chr (i + Char.code '0')
1447 | i when i < 20 -> Char.chr (i + Char.code 'a')
1449 and int_of_key = function
1450 | k when k >= 0x30 && k <= 0x39 (* '0' - '9' *) -> k - 0x30
1451 | k when k >= 0x61 && k <= 0x7a (* 'a' - 'j' *) -> k - 0x61 + 10
1452 | k when k >= 0x41 && k <= 0x6a (* 'A' - 'J' *) -> k - 0x41 + 10
1456 (* Display possible sort fields. *)
1457 let selected_index = ref 0 in
1460 let selected = !sort_order = ord in
1461 if selected then selected_index := i;
1462 mvaddstr (domains_lineno+i) 0
1463 (sprintf " %c %s %s %s"
1464 (key_of_int i) (if selected then "*" else " ")
1465 (printable_sort_order ord)
1466 (accelerator_key ord))
1469 move message_lineno 0;
1472 if k >= 0 && k <> 32 && k <> Char.code 'q' && k <> 13 then (
1473 let new_order, loop =
1474 (* Redraw the display. *)
1475 if k = 12 (* ^L *) then None, true
1476 (* Make the UP and DOWN arrow keys do something useful. *)
1477 else if k = Key.up then (
1478 if !selected_index > 0 then
1479 Some (List.nth all_sort_fields (!selected_index-1)), true
1483 else if k = Key.down then (
1484 if !selected_index < List.length all_sort_fields - 1 then
1485 Some (List.nth all_sort_fields (!selected_index+1)), true
1489 (* Also understand the regular accelerator keys. *)
1490 else if k = Char.code 'M' then
1492 else if k = Char.code 'P' then
1493 Some Processor, false
1494 else if k = Char.code 'T' then
1496 else if k = Char.code 'N' then
1497 Some DomainID, false
1499 (* It's one of the KEYs. *)
1500 let i = int_of_key k in
1501 if i >= 0 && i < List.length all_sort_fields then
1502 Some (List.nth all_sort_fields i), false
1507 (match new_order with
1510 sort_order := new_order;
1511 print_msg (sprintf "Sort order changed to: %s"
1512 (printable_sort_order new_order));
1519 if loop then change_sort_order ()
1522 (* Note: We need to clear_pcpu_display_data every time
1523 * we _leave_ PCPUDisplay mode.
1525 and set_tasks_display () = (* key 0 *)
1526 if !display_mode = PCPUDisplay then clear_pcpu_display_data ();
1527 display_mode := TaskDisplay
1529 and toggle_pcpu_display () = (* key 1 *)
1531 match !display_mode with
1532 | TaskDisplay | NetDisplay | BlockDisplay -> PCPUDisplay
1533 | PCPUDisplay -> clear_pcpu_display_data (); TaskDisplay
1535 and toggle_net_display () = (* key 2 *)
1537 match !display_mode with
1538 | PCPUDisplay -> clear_pcpu_display_data (); NetDisplay
1539 | TaskDisplay | BlockDisplay -> NetDisplay
1540 | NetDisplay -> TaskDisplay
1542 and toggle_block_display () = (* key 3 *)
1544 match !display_mode with
1545 | PCPUDisplay -> clear_pcpu_display_data (); BlockDisplay
1546 | TaskDisplay | NetDisplay -> BlockDisplay
1547 | BlockDisplay -> TaskDisplay
1549 (* Write an init file. *)
1550 and write_init_file () =
1551 match !init_file with
1552 | NoInitFile -> () (* Do nothing if --no-init-file *)
1553 | DefaultInitFile ->
1554 let home = try Sys.getenv "HOME" with Not_found -> "/" in
1555 let filename = home // rcfile in
1556 _write_init_file filename
1557 | InitFile filename ->
1558 _write_init_file filename
1560 and _write_init_file filename =
1562 (* Create the new file as filename.new. *)
1563 let chan = open_out (filename ^ ".new") in
1565 let time = Unix.gettimeofday () in
1566 let tm = Unix.localtime time in
1567 let printable_date_time =
1568 sprintf "%04d-%02d-%02d %02d:%02d:%02d"
1569 (tm.Unix.tm_year + 1900) (tm.Unix.tm_mon+1) tm.Unix.tm_mday
1570 tm.Unix.tm_hour tm.Unix.tm_min tm.Unix.tm_sec in
1573 let uid = Unix.geteuid () in
1574 (Unix.getpwuid uid).Unix.pw_name
1576 Not_found -> "unknown" in
1579 let nl () = fp chan "\n" in
1580 let () = fp chan (f_"# %s virt-top configuration file\n") rcfile in
1581 let () = fp chan (f_"# generated on %s by %s\n") printable_date_time username in
1583 fp chan "display %s\n" (cli_of_display !display_mode);
1584 fp chan "delay %g\n" (float !delay /. 1000.);
1585 fp chan "hist-cpu %d\n" !historical_cpu_delay;
1586 if !iterations <> -1 then fp chan "iterations %d\n" !iterations;
1587 fp chan "sort %s\n" (cli_of_sort_order !sort_order);
1590 | Some uri -> fp chan "connect %s\n" uri
1592 if !batch_mode = true then fp chan "batch true\n";
1593 if !secure_mode = true then fp chan "secure true\n";
1595 output_string chan (s_"# To send debug and error messages to a file, uncomment next line\n");
1596 fp chan "#debug virt-top.out\n";
1598 output_string chan (s_"# Enable CSV output to the named file\n");
1599 fp chan "#csv virt-top.csv\n";
1601 output_string chan (s_"# To protect this file from being overwritten, uncomment next line\n");
1602 fp chan "#overwrite-init-file false\n";
1606 (* If the file exists, rename it as filename.old. *)
1607 (try Unix.rename filename (filename ^ ".old")
1608 with Unix.Unix_error _ -> ());
1610 (* Rename filename.new to filename. *)
1611 Unix.rename (filename ^ ".new") filename;
1613 print_msg (sprintf (f_"Wrote settings to %s") filename);
1618 print_msg (s_"Error" ^ ": " ^ err);
1620 | Unix.Unix_error (err, fn, str) ->
1621 print_msg (s_"Error" ^ ": " ^
1622 (Unix.error_message err) ^ " " ^ fn ^ " " ^ str);
1626 and show_help (_, _, _, _, _, _, hostname,
1627 (libvirt_major, libvirt_minor, libvirt_release)) =
1630 (* Get the screen/window size. *)
1631 let lines, cols = get_size () in
1633 (* Banner at the top of the screen. *)
1635 sprintf (f_"virt-top %s ocaml-libvirt %s libvirt %d.%d.%d by Red Hat")
1636 Virt_top_version.version
1637 Libvirt_version.version
1638 libvirt_major libvirt_minor libvirt_release in
1639 let banner = pad cols banner in
1641 mvaddstr 0 0 banner;
1647 (f_"Delay: %.1f secs; Batch: %s; Secure: %s; Sort: %s")
1648 (float !delay /. 1000.)
1649 (if !batch_mode then s_"On" else s_"Off")
1650 (if !secure_mode then s_"On" else s_"Off")
1651 (printable_sort_order !sort_order));
1654 (f_"Connect: %s; Hostname: %s")
1655 (match !uri with None -> s_"default" | Some s -> s)
1658 (* Misc keys on left. *)
1659 let banner = pad 38 (s_"MAIN KEYS") in
1661 mvaddstr header_lineno 1 banner;
1665 let lineno = ref domains_lineno in
1666 fun () -> let i = !lineno in incr lineno; i
1668 let key keys description =
1669 let lineno = get_lineno () in
1670 move lineno 1; attron A.bold; addstr keys; attroff A.bold;
1671 move lineno 10; addstr description
1673 key "space ^L" (s_"Update display");
1675 key "d s" (s_"Set update interval");
1679 ignore (get_lineno ());
1680 let banner = pad 38 (s_"SORTING") in
1682 mvaddstr (get_lineno ()) 1 banner;
1685 key "P" (s_"Sort by %CPU");
1686 key "M" (s_"Sort by %MEM");
1687 key "T" (s_"Sort by TIME");
1688 key "N" (s_"Sort by ID");
1689 key "F" (s_"Select sort field");
1691 (* Display modes on right. *)
1692 let banner = pad 39 (s_"DISPLAY MODES") in
1694 mvaddstr header_lineno 40 banner;
1698 let lineno = ref domains_lineno in
1699 fun () -> let i = !lineno in incr lineno; i
1701 let key keys description =
1702 let lineno = get_lineno () in
1703 move lineno 40; attron A.bold; addstr keys; attroff A.bold;
1704 move lineno 49; addstr description
1706 key "0" (s_"Domains display");
1707 key "1" (s_"Toggle physical CPUs");
1708 key "2" (s_"Toggle network interfaces");
1709 key "3" (s_"Toggle block devices");
1711 (* Update screen and wait for key press. *)
1712 mvaddstr (lines-1) 0
1713 (s_"More help in virt-top(1) man page. Press any key to return.");
1717 and unknown_command k =
1718 print_msg (s_"Unknown command - try 'h' for help");