1 (* 'top'-like tool for libvirt domains.
10 module C = Libvirt.Connect
11 module D = Libvirt.Domain
12 module N = Libvirt.Network
14 (* Hook for XML support (see virt_top_xml.ml). *)
15 let parse_device_xml : (int -> [>`R] D.t -> string list * string list) ref =
20 (* Hooks for CSV support (see virt_top_csv.ml). *)
21 let csv_start : (string -> unit) ref =
23 fun _ -> failwith "virt-top was compiled without support for CSV"
25 let csv_write : (string list -> unit) ref =
30 (* Int64 operators for convenience. *)
33 let ( *^ ) = Int64.mul
38 | DomainID | DomainName | Processor | Memory | Time
39 | NetRX | NetTX | BlockRdRq | BlockWrRq
40 let all_sort_fields = [
41 DomainID; DomainName; Processor; Memory; Time;
42 NetRX; NetTX; BlockRdRq; BlockWrRq
44 let printable_sort_order = function
47 | Time -> "TIME (CPU time)"
48 | DomainID -> "Domain ID"
49 | DomainName -> "Domain name"
50 | NetRX -> "Net RX bytes"
51 | NetTX -> "Net TX bytes"
52 | BlockRdRq -> "Block read reqs"
53 | BlockWrRq -> "Block write reqs"
54 let sort_order_of_cli = function
55 | "cpu" | "processor" -> Processor
56 | "mem" | "memory" -> Memory
59 | "name" -> DomainName
60 | "netrx" -> NetRX | "nettx" -> NetTX
61 | "blockrdrq" -> BlockRdRq | "blockwrrq" -> BlockWrRq
62 | str -> failwith (str ^ ": sort order should be: cpu|mem|time|id|name|netrx|nettx|blockrdrq|blockwrrq")
63 let cli_of_sort_order = function
68 | DomainName -> "name"
71 | BlockRdRq -> "blockrdrq"
72 | BlockWrRq -> "blockwrrq"
74 (* Current major display mode: TaskDisplay is the normal display. *)
75 type display = TaskDisplay | PCPUDisplay | BlockDisplay | NetDisplay
77 let display_of_cli = function
78 | "task" -> TaskDisplay
79 | "pcpu" -> PCPUDisplay
80 | "block" -> BlockDisplay
82 | str -> failwith (str ^ ": display should be task|pcpu|block|net")
83 let cli_of_display = function
84 | TaskDisplay -> "task"
85 | PCPUDisplay -> "pcpu"
86 | BlockDisplay -> "block"
90 type init_file = NoInitFile | DefaultInitFile | InitFile of string
94 let delay = ref 3000 (* milliseconds *)
95 let historical_cpu_delay = ref 20 (* secs *)
96 let iterations = ref (-1)
97 let batch_mode = ref false
98 let secure_mode = ref false
99 let sort_order = ref Processor
100 let display_mode = ref TaskDisplay
102 let debug_file = ref ""
103 let csv_enabled = ref false
104 let csv_cpu = ref true
105 let csv_block = ref true
106 let csv_net = ref true
107 let init_file = ref DefaultInitFile
108 let script_mode = ref false
110 (* Function to read command line arguments and go into curses mode. *)
112 (* Read command line arguments. *)
113 let rec set_delay newdelay =
114 if newdelay <= 0. then
115 failwith "-d: cannot set a negative delay";
116 delay := int_of_float (newdelay *. 1000.)
117 and set_uri = function "" -> uri := None | u -> uri := Some u
118 and set_sort order = sort_order := sort_order_of_cli order
119 and set_pcpu_mode () = display_mode := PCPUDisplay
120 and set_net_mode () = display_mode := NetDisplay
121 and set_block_mode () = display_mode := BlockDisplay
122 and set_csv filename =
123 (!csv_start) filename;
125 and no_init_file () = init_file := NoInitFile
126 and set_init_file filename = init_file := InitFile filename
128 let argspec = Arg.align [
129 "-1", Arg.Unit set_pcpu_mode, " Start by displaying pCPUs (default: tasks)";
130 "-2", Arg.Unit set_net_mode, " Start by displaying network interfaces";
131 "-3", Arg.Unit set_block_mode, " Start by displaying block devices";
132 "-b", Arg.Set batch_mode, " Batch mode";
133 "-c", Arg.String set_uri, "uri Connect to URI (default: Xen)";
134 "--connect", Arg.String set_uri, "uri Connect to URI (default: Xen)";
135 "--csv", Arg.String set_csv, "file Log statistics to CSV file";
136 "--no-csv-cpu", Arg.Clear csv_cpu, " Disable CPU stats in CSV";
137 "--no-csv-block", Arg.Clear csv_block, " Disable block device stats in CSV";
138 "--no-csv-net", Arg.Clear csv_net, " Disable net stats in CSV";
139 "-d", Arg.Float set_delay, "delay Delay time interval (seconds)";
140 "--debug", Arg.Set_string debug_file, "file Send debug messages to file";
141 "--hist-cpu", Arg.Set_int historical_cpu_delay, "secs Historical CPU delay";
142 "--init-file", Arg.String set_init_file, "file Set name of init file";
143 "--no-init-file", Arg.Unit no_init_file, " Do not read init file";
144 "-n", Arg.Set_int iterations, "iterations Number of iterations to run";
145 "-o", Arg.String set_sort, "sort Set sort order (cpu|mem|time|id|name)";
146 "-s", Arg.Set secure_mode, " Secure (\"kiosk\") mode";
147 "--script", Arg.Set script_mode, " Run from a script (no user interface)";
149 let anon_fun str = raise (Arg.Bad (str ^ ": unknown parameter")) in
150 let usage_msg = "virt-top : a 'top'-like utility for virtualization
156 Arg.parse argspec anon_fun usage_msg;
158 (* Read the init file. *)
159 let try_to_read_init_file filename =
160 let config = read_config_file filename in
163 | _, "display", mode -> display_mode := display_of_cli mode
164 | _, "delay", secs -> set_delay (float_of_string secs)
165 | _, "hist-cpu", secs -> historical_cpu_delay := int_of_string secs
166 | _, "iterations", n -> iterations := int_of_string n
167 | _, "sort", order -> set_sort order
168 | _, "connect", uri -> set_uri uri
169 | _, "debug", filename -> debug_file := filename
170 | _, "csv", filename -> set_csv filename
171 | _, "csv-cpu", b -> csv_cpu := bool_of_string b
172 | _, "csv-block", b -> csv_block := bool_of_string b
173 | _, "csv-net", b -> csv_net := bool_of_string b
174 | _, "batch", b -> batch_mode := bool_of_string b
175 | _, "secure", b -> secure_mode := bool_of_string b
176 | _, "script", b -> script_mode := bool_of_string b
177 | _, "overwrite-init-file", "false" -> no_init_file ()
179 eprintf "%s:%d: configuration item ``%s'' ignored\n%!"
183 (match !init_file with
186 let home = try Sys.getenv "HOME" with Not_found -> "/" in
187 let filename = home // ".virt-toprc" in
188 try_to_read_init_file filename
189 | InitFile filename ->
190 try_to_read_init_file filename
193 (* Connect to the hypervisor before going into curses mode, since
194 * this is the most likely thing to fail.
198 try C.connect_readonly ?name ()
200 Libvirt.Virterror err ->
201 prerr_endline (Libvirt.Virterror.to_string err);
202 (* If non-root and no explicit connection URI, print a warning. *)
203 if Unix.geteuid () <> 0 && name = None then (
204 print_endline "NB: If you want to monitor a local Xen hypervisor, you usually need to be root";
208 (* Get the node_info. This never changes, right? So we get it just once. *)
209 let node_info = C.get_node_info conn in
211 (* Hostname and libvirt library version also don't change. *)
213 try C.get_hostname conn
215 (* qemu:/// and other URIs didn't support virConnectGetHostname until
216 * libvirt 0.3.3. Before that they'd throw a virterror. *)
217 | Libvirt.Virterror _
218 | Invalid_argument "virConnectGetHostname not supported" -> "unknown" in
220 let libvirt_version =
221 let v, _ = Libvirt.get_version () in
222 v / 1_000_000, (v / 1_000) mod 1_000, v mod 1_000 in
224 (* Open debug file if specified.
225 * NB: Do this just before jumping into curses mode.
227 (match !debug_file with
228 | "" -> (* No debug file specified, send stderr to /dev/null unless
229 * we're in script mode.
231 if not !script_mode then (
232 let fd = Unix.openfile "/dev/null" [Unix.O_WRONLY] 0o644 in
233 Unix.dup2 fd Unix.stderr;
236 | filename -> (* Send stderr to the named file. *)
238 Unix.openfile filename [Unix.O_WRONLY;Unix.O_CREAT;Unix.O_TRUNC]
240 Unix.dup2 fd Unix.stderr;
244 (* Curses voodoo (see ncurses(3)). *)
245 if not !script_mode then (
250 let stdscr = stdscr () in
251 intrflush stdscr false;
256 (* This tuple of static information is called 'setup' in other parts
257 * of this program, and is passed to other functions such as redraw and
258 * main_loop. See virt_top_main.ml.
261 !batch_mode, !script_mode, !csv_enabled, (* immutable modes *)
262 node_info, hostname, libvirt_version (* info that doesn't change *)
265 (* Show a percentage in 4 chars. *)
266 let show_percent percent =
267 if percent <= 0. then " 0.0"
268 else if percent <= 9.9 then sprintf " %1.1f" percent
269 else if percent <= 99.9 then sprintf "%2.1f" percent
272 (* Show an int64 option in 4 chars. *)
273 let rec show_int64_option = function
275 | Some n -> show_int64 n
276 (* Show an int64 in 4 chars. *)
277 and show_int64 = function
278 | n when n < 0L -> "-!!!"
279 | n when n <= 9999L ->
281 | n when n /^ 1024L <= 999L ->
282 sprintf "%3LdK" (n /^ 1024L)
283 | n when n /^ 1_048_576L <= 999L ->
284 sprintf "%3LdM" (n /^ 1_048_576L)
285 | n when n /^ 1_073_741_824L <= 999L ->
286 sprintf "%3LdG" (n /^ 1_073_741_824L)
289 (* Format the total time (may be large!) in 9 chars. *)
291 let secs_in_ns = 1_000_000_000L in
292 let mins_in_ns = 60_000_000_000L in
293 let hours_in_ns = 3_600_000_000_000L in
295 let hours = ns /^ hours_in_ns in
296 let ns = ns -^ (hours *^ hours_in_ns) in
297 let mins = ns /^ mins_in_ns in
298 let ns = ns -^ (mins *^ mins_in_ns) in
299 let secs = ns /^ secs_in_ns in
300 let ns = ns -^ (secs *^ secs_in_ns) in
301 let pennies = ns /^ 10_000_000L in
304 sprintf "%3Ld:%02Ld.%02Ld" (hours *^ 60L +^ mins) secs pennies
305 else if hours <= 999L then
306 sprintf "%3Ld:%02Ld:%02Ld" hours mins secs
308 let days = hours /^ 24L in
309 let hours = hours -^ (days *^ 24L) in
310 sprintf "%3Ldd%02Ld:%02Ld" days hours mins
313 (* Show a domain state (the 'S' column). *)
314 let show_state = function
315 | D.InfoNoState -> '?'
316 | D.InfoRunning -> 'R'
317 | D.InfoBlocked -> 'S'
318 | D.InfoPaused -> 'P'
319 | D.InfoShutdown -> 'D'
320 | D.InfoShutoff -> 'O'
321 | D.InfoCrashed -> 'X'
323 (* Sum Domain.block_stats structures together. Missing fields
324 * get forced to 0. Empty list returns all 0.
326 let zero_block_stats =
327 { D.rd_req = 0L; rd_bytes = 0L; wr_req = 0L; wr_bytes = 0L; errs = 0L }
328 let add_block_stats bs1 bs2 =
329 let add f1 f2 = if f1 >= 0L && f2 >= 0L then f1 +^ f2 else 0L in
330 { D.rd_req = add bs1.D.rd_req bs2.D.rd_req;
331 rd_bytes = add bs1.D.rd_bytes bs2.D.rd_bytes;
332 wr_req = add bs1.D.wr_req bs2.D.wr_req;
333 wr_bytes = add bs1.D.wr_bytes bs2.D.wr_bytes;
334 errs = add bs1.D.errs bs2.D.errs }
335 let sum_block_stats =
336 List.fold_left add_block_stats zero_block_stats
338 (* Get the difference between two block_stats structures. Missing data
339 * forces the difference to -1.
341 let diff_block_stats curr prev =
342 let sub f1 f2 = if f1 >= 0L && f2 >= 0L then f1 -^ f2 else -1L in
343 { D.rd_req = sub curr.D.rd_req prev.D.rd_req;
344 rd_bytes = sub curr.D.rd_bytes prev.D.rd_bytes;
345 wr_req = sub curr.D.wr_req prev.D.wr_req;
346 wr_bytes = sub curr.D.wr_bytes prev.D.wr_bytes;
347 errs = sub curr.D.errs prev.D.errs }
349 (* Sum Domain.interface_stats structures together. Missing fields
350 * get forced to 0. Empty list returns all 0.
352 let zero_interface_stats =
353 { D.rx_bytes = 0L; rx_packets = 0L; rx_errs = 0L; rx_drop = 0L;
354 tx_bytes = 0L; tx_packets = 0L; tx_errs = 0L; tx_drop = 0L }
355 let add_interface_stats is1 is2 =
356 let add f1 f2 = if f1 >= 0L && f2 >= 0L then f1 +^ f2 else 0L in
357 { D.rx_bytes = add is1.D.rx_bytes is2.D.rx_bytes;
358 rx_packets = add is1.D.rx_packets is2.D.rx_packets;
359 rx_errs = add is1.D.rx_errs is2.D.rx_errs;
360 rx_drop = add is1.D.rx_drop is2.D.rx_drop;
361 tx_bytes = add is1.D.tx_bytes is2.D.tx_bytes;
362 tx_packets = add is1.D.tx_packets is2.D.tx_packets;
363 tx_errs = add is1.D.tx_errs is2.D.tx_errs;
364 tx_drop = add is1.D.tx_drop is2.D.tx_drop }
365 let sum_interface_stats =
366 List.fold_left add_interface_stats zero_interface_stats
368 (* Get the difference between two interface_stats structures.
369 * Missing data forces the difference to -1.
371 let diff_interface_stats curr prev =
372 let sub f1 f2 = if f1 >= 0L && f2 >= 0L then f1 -^ f2 else -1L in
373 { D.rx_bytes = sub curr.D.rx_bytes prev.D.rx_bytes;
374 rx_packets = sub curr.D.rx_packets prev.D.rx_packets;
375 rx_errs = sub curr.D.rx_errs prev.D.rx_errs;
376 rx_drop = sub curr.D.rx_drop prev.D.rx_drop;
377 tx_bytes = sub curr.D.tx_bytes prev.D.tx_bytes;
378 tx_packets = sub curr.D.tx_packets prev.D.tx_packets;
379 tx_errs = sub curr.D.tx_errs prev.D.tx_errs;
380 tx_drop = sub curr.D.tx_drop prev.D.tx_drop }
382 (* Update the display and sleep for given number of seconds. *)
383 let sleep n = refresh (); Unix.sleep n
385 (* The curses getstr/getnstr functions are just weird.
386 * This helper function also enables echo temporarily.
388 let get_string maxlen =
390 let str = String.create maxlen in
391 let ok = getstr str in (* Safe because binding calls getnstr. *)
395 (* Chop at first '\0'. *)
397 let i = String.index str '\000' in
400 Not_found -> str (* it is full maxlen bytes *)
403 (* Pad a string to the full width with spaces. If too long, truncate. *)
405 let n = String.length str in
406 if n = width then str
407 else if n > width then String.sub str 0 width
408 else (* if n < width then *) str ^ String.make (width-n) ' '
412 let summary_lineno = 1 (* this takes 2 lines *)
413 let message_lineno = 3
414 let header_lineno = 4
415 let domains_lineno = 5
417 (* Print in the "message area". *)
418 let clear_msg () = move message_lineno 0; clrtoeol ()
419 let print_msg str = clear_msg (); mvaddstr message_lineno 0 str; ()
421 (* Intermediate "domain + stats" structure that we use to collect
422 * everything we know about a domain within the collect function.
424 type rd_domain = Inactive | Active of rd_active
426 rd_domid : int; (* Domain ID. *)
427 rd_dom : [`R] D.t; (* Domain object. *)
428 rd_info : D.info; (* Domain CPU info now. *)
429 rd_block_stats : (string * D.block_stats) list;
430 (* Domain block stats now. *)
431 rd_interface_stats : (string * D.interface_stats) list;
432 (* Domain net stats now. *)
433 rd_prev_info : D.info option; (* Domain CPU info previously. *)
434 rd_prev_block_stats : (string * D.block_stats) list;
435 (* Domain block stats prev. *)
436 rd_prev_interface_stats : (string * D.interface_stats) list;
437 (* Domain interface stats prev. *)
438 (* The following are since the last slice, or 0 if cannot be calculated: *)
439 rd_cpu_time : float; (* CPU time used in nanoseconds. *)
440 rd_percent_cpu : float; (* CPU time as percent of total. *)
441 (* The following are since the last slice, or None if cannot be calc'd: *)
442 rd_block_rd_reqs : int64 option; (* Number of block device read rqs. *)
443 rd_block_wr_reqs : int64 option; (* Number of block device write rqs. *)
444 rd_net_rx_bytes : int64 option; (* Number of bytes received. *)
445 rd_net_tx_bytes : int64 option; (* Number of bytes transmitted. *)
449 let collect, clear_pcpu_display_data =
450 (* We cache the list of block devices and interfaces for each domain
451 * here, so we don't need to reparse the XML each time.
453 let devices = Hashtbl.create 13 in
455 (* Function to get the list of block devices, network interfaces for
456 * a particular domain. Get it from the devices cache, and if not
457 * there then parse the domain XML.
459 let get_devices id dom =
460 try Hashtbl.find devices id
462 let blkdevs, netifs = (!parse_device_xml) id dom in
463 Hashtbl.replace devices id (blkdevs, netifs);
467 (* We save the state of domains across redraws here, which allows us
468 * to deduce %CPU usage from the running total.
470 let last_info = Hashtbl.create 13 in
471 let last_time = ref (Unix.gettimeofday ()) in
473 (* Save vcpuinfo structures across redraws too (only for pCPU display). *)
474 let last_vcpu_info = Hashtbl.create 13 in
476 let clear_pcpu_display_data () =
477 (* Clear out vcpu_info used by PCPUDisplay display_mode
478 * when we switch back to TaskDisplay mode.
480 Hashtbl.clear last_vcpu_info
483 let collect (conn, _, _, _, node_info, _, _) =
484 (* Number of physical CPUs (some may be disabled). *)
485 let nr_pcpus = C.maxcpus_of_node_info node_info in
487 (* Get the current time. *)
488 let time = Unix.gettimeofday () in
489 let tm = Unix.localtime time in
491 sprintf "%02d:%02d:%02d" tm.Unix.tm_hour tm.Unix.tm_min tm.Unix.tm_sec in
492 mvaddstr top_lineno 0 ("virt-top " ^ printable_time ^ " - ");
494 (* What's the total CPU time elapsed since we were last called? (ns) *)
495 let total_cpu_per_pcpu = 1_000_000_000. *. (time -. !last_time) in
496 (* Avoid division by zero. *)
497 let total_cpu_per_pcpu =
498 if total_cpu_per_pcpu <= 0. then 1. else total_cpu_per_pcpu in
499 let total_cpu = float node_info.C.cpus *. total_cpu_per_pcpu in
501 (* Get the domains. Match up with their last_info (if any). *)
503 (* Active domains. *)
504 let n = C.num_of_domains conn in
506 if n > 0 then Array.to_list (C.list_domains conn n)
512 let dom = D.lookup_by_id conn id in
513 let name = D.get_name dom in
514 let blkdevs, netifs = get_devices id dom in
516 (* Get current CPU, block and network stats. *)
517 let info = D.get_info dom in
519 try List.map (fun dev -> dev, D.block_stats dom dev) blkdevs
521 | Invalid_argument "virDomainBlockStats not supported"
522 | Libvirt.Virterror _ -> [] in
523 let interface_stats =
524 try List.map (fun dev -> dev, D.interface_stats dom dev) netifs
526 | Invalid_argument "virDomainInterfaceStats not supported"
527 | Libvirt.Virterror _ -> [] in
529 let prev_info, prev_block_stats, prev_interface_stats =
531 let prev_info, prev_block_stats, prev_interface_stats =
532 Hashtbl.find last_info id in
533 Some prev_info, prev_block_stats, prev_interface_stats
534 with Not_found -> None, [], [] in
537 rd_domid = id; rd_dom = dom; rd_info = info;
538 rd_block_stats = block_stats;
539 rd_interface_stats = interface_stats;
540 rd_prev_info = prev_info;
541 rd_prev_block_stats = prev_block_stats;
542 rd_prev_interface_stats = prev_interface_stats;
543 rd_cpu_time = 0.; rd_percent_cpu = 0.;
544 rd_block_rd_reqs = None; rd_block_wr_reqs = None;
545 rd_net_rx_bytes = None; rd_net_tx_bytes = None;
548 Libvirt.Virterror _ -> None (* ignore transient error *)
551 (* Inactive domains. *)
554 let n = C.num_of_defined_domains conn in
556 if n > 0 then Array.to_list (C.list_defined_domains conn n)
558 List.map (fun name -> name, Inactive) names
560 (* Ignore transient errors, in particular errors from
561 * num_of_defined_domains if it cannot contact xend.
563 | Libvirt.Virterror _ -> [] in
565 doms @ doms_inactive in
567 (* Calculate the CPU time (ns) and %CPU used by each domain. *)
571 (* We have previous CPU info from which to calculate it? *)
572 | name, Active ({ rd_prev_info = Some prev_info } as rd) ->
574 Int64.to_float (rd.rd_info.D.cpu_time -^ prev_info.D.cpu_time) in
575 let percent_cpu = 100. *. cpu_time /. total_cpu in
577 rd_cpu_time = cpu_time;
578 rd_percent_cpu = percent_cpu } in
580 (* For all other domains we can't calculate it, so leave as 0 *)
584 (* Calculate the number of block device read/write requests across
585 * all block devices attached to a domain.
590 (* Do we have stats from the previous slice? *)
591 | name, Active ({ rd_prev_block_stats = ((_::_) as prev_block_stats) }
593 let block_stats = rd.rd_block_stats in (* stats now *)
595 (* Add all the devices together. Throw away device names. *)
596 let prev_block_stats =
597 sum_block_stats (List.map snd prev_block_stats) in
599 sum_block_stats (List.map snd block_stats) in
601 (* Calculate increase in read & write requests. *)
603 block_stats.D.rd_req -^ prev_block_stats.D.rd_req in
605 block_stats.D.wr_req -^ prev_block_stats.D.wr_req in
608 rd_block_rd_reqs = Some read_reqs;
609 rd_block_wr_reqs = Some write_reqs } in
611 (* For all other domains we can't calculate it, so leave as None. *)
615 (* Calculate the same as above for network interfaces across
616 * all network interfaces attached to a domain.
621 (* Do we have stats from the previous slice? *)
622 | name, Active ({ rd_prev_interface_stats =
623 ((_::_) as prev_interface_stats) }
625 let interface_stats = rd.rd_interface_stats in (* stats now *)
627 (* Add all the devices together. Throw away device names. *)
628 let prev_interface_stats =
629 sum_interface_stats (List.map snd prev_interface_stats) in
630 let interface_stats =
631 sum_interface_stats (List.map snd interface_stats) in
633 (* Calculate increase in rx & tx bytes. *)
635 interface_stats.D.rx_bytes -^ prev_interface_stats.D.rx_bytes in
637 interface_stats.D.tx_bytes -^ prev_interface_stats.D.tx_bytes in
640 rd_net_rx_bytes = Some rx_bytes;
641 rd_net_tx_bytes = Some tx_bytes } in
643 (* For all other domains we can't calculate it, so leave as None. *)
647 (* Collect some extra information in PCPUDisplay display_mode. *)
649 if !display_mode = PCPUDisplay then (
650 (* Get the VCPU info and VCPU->PCPU mappings for active domains.
651 * Also cull some data we don't care about.
653 let doms = List.filter_map (
655 | (name, Active rd) ->
657 let domid = rd.rd_domid in
658 let maplen = C.cpumaplen nr_pcpus in
659 let maxinfo = rd.rd_info.D.nr_virt_cpu in
660 let nr_vcpus, vcpu_infos, cpumaps =
661 D.get_vcpus rd.rd_dom maxinfo maplen in
663 (* Got previous vcpu_infos for this domain? *)
664 let prev_vcpu_infos =
665 try Some (Hashtbl.find last_vcpu_info domid)
666 with Not_found -> None in
667 (* Update last_vcpu_info. *)
668 Hashtbl.replace last_vcpu_info domid vcpu_infos;
670 (match prev_vcpu_infos with
671 | Some prev_vcpu_infos
672 when Array.length prev_vcpu_infos = Array.length vcpu_infos ->
673 Some (domid, name, nr_vcpus, vcpu_infos, prev_vcpu_infos,
675 | _ -> None (* ignore missing / unequal length prev_vcpu_infos *)
678 Libvirt.Virterror _ -> None(* ignore transient libvirt errs *)
680 | (_, Inactive) -> None (* ignore inactive doms *)
682 let nr_doms = List.length doms in
684 (* Rearrange the data into a matrix. Major axis (down) is
685 * pCPUs. Minor axis (right) is domains. At each node we store:
686 * cpu_time (on this pCPU only, nanosecs),
687 * average? (if set, then cpu_time is an average because the
688 * vCPU is pinned to more than one pCPU)
689 * running? (if set, we were instantaneously running on this pCPU)
691 let empty_node = (0L, false, false) in
692 let pcpus = Array.make_matrix nr_pcpus nr_doms empty_node in
695 fun di (domid, name, nr_vcpus, vcpu_infos, prev_vcpu_infos,
697 (* Which pCPUs can this dom run on? *)
698 for v = 0 to nr_vcpus-1 do
699 let pcpu = vcpu_infos.(v).D.cpu in (* instantaneous pCPU *)
700 let nr_poss_pcpus = ref 0 in (* how many pcpus can it run on? *)
701 for p = 0 to nr_pcpus-1 do
702 (* vcpu v can reside on pcpu p *)
703 if C.cpu_usable cpumaps maplen v p then
706 let nr_poss_pcpus = Int64.of_int !nr_poss_pcpus in
707 for p = 0 to nr_pcpus-1 do
708 (* vcpu v can reside on pcpu p *)
709 if C.cpu_usable cpumaps maplen v p then
710 let vcpu_time_on_pcpu =
711 vcpu_infos.(v).D.vcpu_time
712 -^ prev_vcpu_infos.(v).D.vcpu_time in
713 let vcpu_time_on_pcpu =
714 vcpu_time_on_pcpu /^ nr_poss_pcpus in
716 (vcpu_time_on_pcpu, nr_poss_pcpus > 1L, p = pcpu)
721 (* Sum the CPU time used by each pCPU, for the %CPU column. *)
722 let pcpus_cpu_time = Array.map (
724 let cpu_time = ref 0L in
725 for di = 0 to Array.length row-1 do
726 let t, _, _ = row.(di) in
727 cpu_time := !cpu_time +^ t
729 Int64.to_float !cpu_time
732 Some (doms, pcpus, pcpus_cpu_time)
736 (* Calculate totals. *)
737 let totals = List.fold_left (
738 fun (count, running, blocked, paused, shutdown, shutoff,
739 crashed, active, inactive,
740 total_cpu_time, total_memory, total_domU_memory) ->
742 | (name, Active rd) ->
743 let test state orig =
744 if rd.rd_info.D.state = state then orig+1 else orig
746 let running = test D.InfoRunning running in
747 let blocked = test D.InfoBlocked blocked in
748 let paused = test D.InfoPaused paused in
749 let shutdown = test D.InfoShutdown shutdown in
750 let shutoff = test D.InfoShutoff shutoff in
751 let crashed = test D.InfoCrashed crashed in
753 let total_cpu_time = total_cpu_time +. rd.rd_cpu_time in
754 let total_memory = total_memory +^ rd.rd_info.D.memory in
755 let total_domU_memory = total_domU_memory +^
756 if rd.rd_domid > 0 then rd.rd_info.D.memory else 0L in
758 (count+1, running, blocked, paused, shutdown, shutoff,
759 crashed, active+1, inactive,
760 total_cpu_time, total_memory, total_domU_memory)
762 | (name, Inactive) -> (* inactive domain *)
763 (count+1, running, blocked, paused, shutdown, shutoff,
764 crashed, active, inactive+1,
765 total_cpu_time, total_memory, total_domU_memory)
766 ) (0,0,0,0,0,0,0,0,0, 0.,0L,0L) doms in
768 (* Update last_time, last_info. *)
770 Hashtbl.clear last_info;
774 let info = rd.rd_info, rd.rd_block_stats, rd.rd_interface_stats in
775 Hashtbl.add last_info rd.rd_domid info
780 time, printable_time,
781 nr_pcpus, total_cpu, total_cpu_per_pcpu,
786 collect, clear_pcpu_display_data
788 (* Redraw the display. *)
790 (* Keep a historical list of %CPU usages. *)
791 let historical_cpu = ref [] in
792 let historical_cpu_last_time = ref (Unix.gettimeofday ()) in
794 (_, _, _, _, node_info, _, _) (* setup *)
796 time, printable_time,
797 nr_pcpus, total_cpu, total_cpu_per_pcpu,
799 pcpu_display) (* state *) ->
802 (* Get the screen/window size. *)
803 let lines, cols = get_size () in
805 (* Basic node_info. *)
806 addstr (sprintf "%s %d/%dCPU %dMHz %LdMB "
807 node_info.C.model node_info.C.cpus nr_pcpus node_info.C.mhz
808 (node_info.C.memory /^ 1024L));
809 (* Save the cursor position for when we come to draw the
810 * historical CPU times (down in this function).
812 let stdscr = stdscr () in
813 let historical_cursor = getyx stdscr in
815 (match !display_mode with
816 | TaskDisplay -> (*---------- Showing domains ----------*)
817 (* Sort domains on current sort_order. *)
820 match !sort_order with
822 (fun _ -> 0) (* fallthrough to default name compare *)
825 | Active rd1, Active rd2 ->
826 compare rd2.rd_percent_cpu rd1.rd_percent_cpu
827 | Active _, Inactive -> -1
828 | Inactive, Active _ -> 1
829 | Inactive, Inactive -> 0)
832 | Active { rd_info = info1 }, Active { rd_info = info2 } ->
833 compare info2.D.memory info1.D.memory
834 | Active _, Inactive -> -1
835 | Inactive, Active _ -> 1
836 | Inactive, Inactive -> 0)
839 | Active { rd_info = info1 }, Active { rd_info = info2 } ->
840 compare info2.D.cpu_time info1.D.cpu_time
841 | Active _, Inactive -> -1
842 | Inactive, Active _ -> 1
843 | Inactive, Inactive -> 0)
846 | Active { rd_domid = id1 }, Active { rd_domid = id2 } ->
848 | Active _, Inactive -> -1
849 | Inactive, Active _ -> 1
850 | Inactive, Inactive -> 0)
853 | Active { rd_net_rx_bytes = r1 }, Active { rd_net_rx_bytes = r2 } ->
855 | Active _, Inactive -> -1
856 | Inactive, Active _ -> 1
857 | Inactive, Inactive -> 0)
860 | Active { rd_net_tx_bytes = r1 }, Active { rd_net_tx_bytes = r2 } ->
862 | Active _, Inactive -> -1
863 | Inactive, Active _ -> 1
864 | Inactive, Inactive -> 0)
867 | Active { rd_block_rd_reqs = r1 }, Active { rd_block_rd_reqs = r2 } ->
869 | Active _, Inactive -> -1
870 | Inactive, Active _ -> 1
871 | Inactive, Inactive -> 0)
874 | Active { rd_block_wr_reqs = r1 }, Active { rd_block_wr_reqs = r2 } ->
876 | Active _, Inactive -> -1
877 | Inactive, Active _ -> 1
878 | Inactive, Inactive -> 0)
880 let cmp (name1, dom1) (name2, dom2) =
881 let r = cmp (dom1, dom2) in
883 else compare name1 name2
885 List.sort ~cmp doms in
889 mvaddstr header_lineno 0
890 (pad cols " ID S RDRQ WRRQ RXBY TXBY %CPU %MEM TIME NAME");
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_reqs in
899 let wr_req = show_int64_option rd.rd_block_wr_reqs 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
904 100L *^ rd.rd_info.D.memory /^ node_info.C.memory in
905 let percent_mem = Int64.to_float percent_mem in
906 let percent_mem = show_percent percent_mem in
907 let time = show_time rd.rd_info.D.cpu_time in
909 let line = sprintf "%5d %c %s %s %s %s %s %s %s %s"
910 rd.rd_domid state rd_req wr_req rx_bytes tx_bytes
911 percent_cpu percent_mem time name in
912 let line = pad cols line in
913 mvaddstr lineno 0 line;
916 | (name, Inactive) :: doms -> (* inactive domain *)
917 if lineno < lines then (
922 let line = pad cols line in
923 mvaddstr lineno 0 line;
927 loop domains_lineno doms
929 | PCPUDisplay -> (*---------- Showing physical CPUs ----------*)
930 let doms, pcpus, pcpus_cpu_time =
931 match pcpu_display with
933 | None -> failwith "internal error: no pcpu_display data" in
935 (* Display the pCPUs. *)
939 fun (_, name, _, _, _, _, _) ->
940 let len = String.length name in
941 let width = max (len+1) 7 in
946 mvaddstr header_lineno 0 (pad cols ("PHYCPU %CPU " ^ dom_names));
951 mvaddstr (p+domains_lineno) 0 (sprintf "%4d " p);
952 let cpu_time = pcpus_cpu_time.(p) in (* ns used on this CPU *)
953 let percent_cpu = 100. *. cpu_time /. total_cpu_per_pcpu in
954 addstr (show_percent percent_cpu);
958 fun di (domid, name, _, _, _, _, _) ->
959 let t, is_average, is_running = pcpus.(p).(di) in
960 let len = String.length name in
961 let width = max (len+1) 7 in
965 let t = Int64.to_float t in
966 let percent = 100. *. t /. total_cpu_per_pcpu in
967 sprintf "%s%c%c " (show_percent percent)
968 (if is_average then '=' else ' ')
969 (if is_running then '#' else ' ')
971 addstr (pad width str);
976 | NetDisplay -> (*---------- Showing network interfaces ----------*)
977 (* Only care about active domains. *)
978 let doms = List.filter_map (
980 | (name, Active rd) -> Some (name, rd)
981 | (_, Inactive) -> None
984 (* For each domain we have a list of network interfaces seen
985 * this slice, and seen in the previous slice, which we now
986 * match up to get a list of (domain, interface) for which
987 * we have current & previous knowledge. (And ignore the rest).
995 (* Have prev slice stats for this device? *)
997 List.assoc dev rd.rd_prev_interface_stats in
998 Some (dev, name, rd, stats, prev_stats)
999 with Not_found -> None
1000 ) rd.rd_interface_stats
1003 (* Finally we have a list of:
1004 * device name, domain name, rd_* stuff, curr stats, prev stats.
1006 let devs : (string * string * rd_active *
1007 D.interface_stats * D.interface_stats) list =
1008 List.flatten devs in
1010 (* Difference curr slice & prev slice. *)
1011 let devs = List.map (
1012 fun (dev, name, rd, curr, prev) ->
1013 dev, name, rd, diff_interface_stats curr prev
1016 (* Sort by current sort order, but map some of the standard
1017 * sort orders into ones which makes sense here.
1021 match !sort_order with
1023 (fun _ -> 0) (* fallthrough to default name compare *)
1025 (fun (_, { rd_domid = id1 }, _, { rd_domid = id2 }) ->
1027 | Processor | Memory | Time | BlockRdRq | BlockWrRq
1028 (* fallthrough to RXBY comparison. *)
1030 (fun ({ D.rx_bytes = b1 }, _, { D.rx_bytes = b2 }, _) ->
1033 (fun ({ D.tx_bytes = b1 }, _, { D.tx_bytes = b2 }, _) ->
1036 let cmp (dev1, name1, rd1, stats1) (dev2, name2, rd2, stats2) =
1037 let r = cmp (stats1, rd1, stats2, rd2) in
1039 else compare (dev1, name1) (dev2, name2)
1041 List.sort ~cmp devs in
1043 (* Print the header for network devices. *)
1045 mvaddstr header_lineno 0
1046 (pad cols " ID S RXBY TXBY RXPK TXPK DOMAIN INTERFACE");
1049 (* Print domains and devices. *)
1050 let rec loop lineno = function
1052 | (dev, name, rd, stats) :: devs ->
1053 if lineno < lines then (
1054 let state = show_state rd.rd_info.D.state in
1056 if stats.D.rx_bytes >= 0L
1057 then show_int64 stats.D.rx_bytes
1060 if stats.D.tx_bytes >= 0L
1061 then show_int64 stats.D.tx_bytes
1064 if stats.D.rx_packets >= 0L
1065 then show_int64 stats.D.rx_packets
1068 if stats.D.tx_packets >= 0L
1069 then show_int64 stats.D.tx_packets
1072 let line = sprintf "%5d %c %s %s %s %s %-12s %s"
1075 rx_packets tx_packets
1076 (pad 12 name) dev in
1077 let line = pad cols line in
1078 mvaddstr lineno 0 line;
1079 loop (lineno+1) devs
1082 loop domains_lineno devs
1084 | BlockDisplay -> (*---------- Showing block devices ----------*)
1085 (* Only care about active domains. *)
1086 let doms = List.filter_map (
1088 | (name, Active rd) -> Some (name, rd)
1089 | (_, Inactive) -> None
1092 (* For each domain we have a list of block devices seen
1093 * this slice, and seen in the previous slice, which we now
1094 * match up to get a list of (domain, device) for which
1095 * we have current & previous knowledge. (And ignore the rest).
1103 (* Have prev slice stats for this device? *)
1105 List.assoc dev rd.rd_prev_block_stats in
1106 Some (dev, name, rd, stats, prev_stats)
1107 with Not_found -> None
1111 (* Finally we have a list of:
1112 * device name, domain name, rd_* stuff, curr stats, prev stats.
1114 let devs : (string * string * rd_active *
1115 D.block_stats * D.block_stats) list =
1116 List.flatten devs in
1118 (* Difference curr slice & prev slice. *)
1119 let devs = List.map (
1120 fun (dev, name, rd, curr, prev) ->
1121 dev, name, rd, diff_block_stats curr prev
1124 (* Sort by current sort order, but map some of the standard
1125 * sort orders into ones which makes sense here.
1129 match !sort_order with
1131 (fun _ -> 0) (* fallthrough to default name compare *)
1133 (fun (_, { rd_domid = id1 }, _, { rd_domid = id2 }) ->
1135 | Processor | Memory | Time | NetRX | NetTX
1136 (* fallthrough to RDRQ comparison. *)
1138 (fun ({ D.rd_req = b1 }, _, { D.rd_req = b2 }, _) ->
1141 (fun ({ D.wr_req = b1 }, _, { D.wr_req = b2 }, _) ->
1144 let cmp (dev1, name1, rd1, stats1) (dev2, name2, rd2, stats2) =
1145 let r = cmp (stats1, rd1, stats2, rd2) in
1147 else compare (dev1, name1) (dev2, name2)
1149 List.sort ~cmp devs in
1151 (* Print the header for block devices. *)
1153 mvaddstr header_lineno 0
1154 (pad cols " ID S RDBY WRBY RDRQ WRRQ DOMAIN DEVICE");
1157 (* Print domains and devices. *)
1158 let rec loop lineno = function
1160 | (dev, name, rd, stats) :: devs ->
1161 if lineno < lines then (
1162 let state = show_state rd.rd_info.D.state in
1164 if stats.D.rd_bytes >= 0L
1165 then show_int64 stats.D.rd_bytes
1168 if stats.D.wr_bytes >= 0L
1169 then show_int64 stats.D.wr_bytes
1172 if stats.D.rd_req >= 0L
1173 then show_int64 stats.D.rd_req
1176 if stats.D.wr_req >= 0L
1177 then show_int64 stats.D.wr_req
1180 let line = sprintf "%5d %c %s %s %s %s %-12s %s"
1184 (pad 12 name) dev in
1185 let line = pad cols line in
1186 mvaddstr lineno 0 line;
1187 loop (lineno+1) devs
1190 loop domains_lineno devs
1191 ); (* end of display_mode conditional section *)
1193 let (count, running, blocked, paused, shutdown, shutoff,
1194 crashed, active, inactive,
1195 total_cpu_time, total_memory, total_domU_memory) = totals in
1197 mvaddstr summary_lineno 0
1198 (sprintf "%d domains, %d active, %d running, %d sleeping, %d paused, %d inactive D:%d O:%d X:%d"
1199 count active running blocked paused inactive shutdown shutoff
1202 (* Total %CPU used, and memory summary. *)
1203 let percent_cpu = 100. *. total_cpu_time /. total_cpu in
1204 mvaddstr (summary_lineno+1) 0
1205 (sprintf "CPU: %2.1f%% Mem: %Ld MB (%Ld MB by guests)"
1206 percent_cpu (total_memory /^ 1024L) (total_domU_memory /^ 1024L));
1208 (* Time to grab another historical %CPU for the list? *)
1209 if time >= !historical_cpu_last_time +. float !historical_cpu_delay
1211 historical_cpu := percent_cpu :: List.take 10 !historical_cpu;
1212 historical_cpu_last_time := time
1215 (* Display historical CPU time. *)
1217 let x, y = historical_cursor in (* Yes, it's a bug in ocaml-curses *)
1218 let maxwidth = cols - x in
1221 (List.map (sprintf "%2.1f%%") !historical_cpu) in
1222 let line = pad maxwidth line in
1226 move message_lineno 0; (* Park cursor in message area, as with top. *)
1227 refresh (); (* Refresh the display. *)
1230 (* Write CSV header row. *)
1231 let write_csv_header () =
1233 [ "Hostname"; "Time"; "Arch"; "Physical CPUs";
1234 "Count"; "Running"; "Blocked"; "Paused"; "Shutdown";
1235 "Shutoff"; "Crashed"; "Active"; "Inactive";
1236 "%CPU"; "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 then [ "Block RDRQ"; "Block WRRQ"; ] else []) @
1242 (if !csv_net then [ "Net RXBY"; "Net TXBY" ] else [])
1245 (* Write summary data to CSV file. *)
1247 (_, _, _, _, node_info, hostname, _) (* setup *)
1250 nr_pcpus, total_cpu, _,
1254 (* The totals / summary fields. *)
1255 let (count, running, blocked, paused, shutdown, shutoff,
1256 crashed, active, inactive,
1257 total_cpu_time, total_memory, total_domU_memory) = totals in
1259 let percent_cpu = 100. *. total_cpu_time /. total_cpu in
1261 let summary_fields = [
1262 hostname; printable_time; node_info.C.model; string_of_int nr_pcpus;
1263 string_of_int count; string_of_int running; string_of_int blocked;
1264 string_of_int paused; string_of_int shutdown; string_of_int shutoff;
1265 string_of_int crashed; string_of_int active; string_of_int inactive;
1266 sprintf "%2.1f" percent_cpu;
1267 Int64.to_string total_memory; Int64.to_string total_domU_memory;
1268 Int64.to_string (Int64.of_float total_cpu_time)
1273 * Sort them by ID so that the list of relatively stable. Ignore
1276 let doms = List.filter_map (
1278 | _, Inactive -> None (* Ignore inactive domains. *)
1279 | name, Active rd -> Some (name, rd)
1281 let cmp (_, { rd_domid = rd_domid1 }) (_, { rd_domid = rd_domid2 }) =
1282 compare rd_domid1 rd_domid2
1284 let doms = List.sort ~cmp doms in
1286 let string_of_int64_option = Option.map_default Int64.to_string "" in
1288 let domain_fields = List.map (
1289 fun (domname, rd) ->
1290 [ string_of_int rd.rd_domid; domname ] @
1292 string_of_float rd.rd_cpu_time; string_of_float rd.rd_percent_cpu
1294 (if !csv_block then [
1295 string_of_int64_option rd.rd_block_rd_reqs;
1296 string_of_int64_option rd.rd_block_wr_reqs;
1299 string_of_int64_option rd.rd_net_rx_bytes;
1300 string_of_int64_option rd.rd_net_tx_bytes;
1303 let domain_fields = List.flatten domain_fields in
1305 (!csv_write) (summary_fields @ domain_fields)
1308 let rec main_loop ((_, batch_mode, script_mode, csv_enabled, _, _, _)
1310 if csv_enabled then write_csv_header ();
1313 let state = collect setup in (* Collect stats. *)
1314 if not script_mode then redraw setup state; (* Redraw display. *)
1315 if csv_enabled then append_csv setup state; (* Update CSV file. *)
1317 (* Clear up unused virDomainPtr objects. *)
1320 if not batch_mode && not script_mode then
1322 else (* Batch mode or script mode - just sleep, ignore keys. *)
1323 Unix.sleep (!delay / 1000);
1325 (* Max iterations? *)
1326 if !iterations >= 0 then (
1328 if !iterations = 0 then quit := true
1332 and get_key_press setup =
1333 (* Read the next key, waiting up to !delay milliseconds. *)
1336 timeout (-1); (* Reset to blocking mode. *)
1338 if k >= 0 && k <> 32 (* ' ' *) && k <> 12 (* ^L *) && k <> Key.resize
1340 if k = Char.code 'q' then quit := true
1341 else if k = Char.code 'h' then show_help setup
1342 else if k = Char.code 's' || k = Char.code 'd' then change_delay ()
1343 else if k = Char.code 'M' then sort_order := Memory
1344 else if k = Char.code 'P' then sort_order := Processor
1345 else if k = Char.code 'T' then sort_order := Time
1346 else if k = Char.code 'N' then sort_order := DomainID
1347 else if k = Char.code 'F' then change_sort_order ()
1348 else if k = Char.code '0' then set_tasks_display ()
1349 else if k = Char.code '1' then toggle_pcpu_display ()
1350 else if k = Char.code '2' then toggle_net_display ()
1351 else if k = Char.code '3' then toggle_block_display ()
1352 else if k = Char.code 'W' then write_init_file ()
1353 else unknown_command k
1356 and change_delay () =
1357 print_msg (sprintf "Change delay from %.1f to: " (float !delay /. 1000.));
1358 let str = get_string 16 in
1359 (* Try to parse the number. *)
1362 let newdelay = float_of_string str in
1363 if newdelay <= 0. then (
1364 print_msg "Delay must be > 0"; true
1366 delay := int_of_float (newdelay *. 1000.); false
1369 Failure "float_of_string" ->
1370 print_msg "Not a valid number"; true in
1371 sleep (if error then 2 else 1)
1373 and change_sort_order () =
1375 let lines, cols = get_size () in
1377 mvaddstr top_lineno 0 "Set sort order for main display";
1378 mvaddstr summary_lineno 0 "Type key or use up and down cursor keys.";
1381 mvaddstr header_lineno 0 (pad cols "KEY Sort field");
1384 let accelerator_key = function
1385 | Memory -> "(key: M)"
1386 | Processor -> "(key: P)"
1387 | Time -> "(key: T)"
1388 | DomainID -> "(key: N)"
1389 | _ -> (* all others have to be changed from here *) ""
1392 let rec key_of_int = function
1393 | i when i < 10 -> Char.chr (i + Char.code '0')
1394 | i when i < 20 -> Char.chr (i + Char.code 'a')
1396 and int_of_key = function
1397 | k when k >= 0x30 && k <= 0x39 (* '0' - '9' *) -> k - 0x30
1398 | k when k >= 0x61 && k <= 0x7a (* 'a' - 'j' *) -> k - 0x61 + 10
1399 | k when k >= 0x41 && k <= 0x6a (* 'A' - 'J' *) -> k - 0x41 + 10
1403 (* Display possible sort fields. *)
1404 let selected_index = ref 0 in
1407 let selected = !sort_order = ord in
1408 if selected then selected_index := i;
1409 mvaddstr (domains_lineno+i) 0
1410 (sprintf " %c %s %s %s"
1411 (key_of_int i) (if selected then "*" else " ")
1412 (printable_sort_order ord)
1413 (accelerator_key ord))
1416 move message_lineno 0;
1419 if k >= 0 && k <> 32 && k <> Char.code 'q' && k <> 13 then (
1420 let new_order, loop =
1421 (* Redraw the display. *)
1422 if k = 12 (* ^L *) then None, true
1423 (* Make the UP and DOWN arrow keys do something useful. *)
1424 else if k = Key.up then (
1425 if !selected_index > 0 then
1426 Some (List.nth all_sort_fields (!selected_index-1)), true
1430 else if k = Key.down then (
1431 if !selected_index < List.length all_sort_fields - 1 then
1432 Some (List.nth all_sort_fields (!selected_index+1)), true
1436 (* Also understand the regular accelerator keys. *)
1437 else if k = Char.code 'M' then
1439 else if k = Char.code 'P' then
1440 Some Processor, false
1441 else if k = Char.code 'T' then
1443 else if k = Char.code 'N' then
1444 Some DomainID, false
1446 (* It's one of the KEYs. *)
1447 let i = int_of_key k in
1448 if i >= 0 && i < List.length all_sort_fields then
1449 Some (List.nth all_sort_fields i), false
1454 (match new_order with
1457 sort_order := new_order;
1458 print_msg (sprintf "Sort order changed to: %s"
1459 (printable_sort_order new_order));
1460 if not loop then sleep 1
1463 if loop then change_sort_order ()
1466 (* Note: We need to clear_pcpu_display_data every time
1467 * we _leave_ PCPUDisplay mode.
1469 and set_tasks_display () = (* key 0 *)
1470 if !display_mode = PCPUDisplay then clear_pcpu_display_data ();
1471 display_mode := TaskDisplay
1473 and toggle_pcpu_display () = (* key 1 *)
1475 match !display_mode with
1476 | TaskDisplay | NetDisplay | BlockDisplay -> PCPUDisplay
1477 | PCPUDisplay -> clear_pcpu_display_data (); TaskDisplay
1479 and toggle_net_display () = (* key 2 *)
1481 match !display_mode with
1482 | PCPUDisplay -> clear_pcpu_display_data (); NetDisplay
1483 | TaskDisplay | BlockDisplay -> NetDisplay
1484 | NetDisplay -> TaskDisplay
1486 and toggle_block_display () = (* key 3 *)
1488 match !display_mode with
1489 | PCPUDisplay -> clear_pcpu_display_data (); BlockDisplay
1490 | TaskDisplay | NetDisplay -> BlockDisplay
1491 | BlockDisplay -> TaskDisplay
1493 (* Write an init file. *)
1494 and write_init_file () =
1495 match !init_file with
1496 | NoInitFile -> () (* Do nothing if --no-init-file *)
1497 | DefaultInitFile ->
1498 let home = try Sys.getenv "HOME" with Not_found -> "/" in
1499 let filename = home // ".virt-toprc" in
1500 _write_init_file filename
1501 | InitFile filename ->
1502 _write_init_file filename
1504 and _write_init_file filename =
1506 (* Create the new file as filename.new. *)
1507 let chan = open_out (filename ^ ".new") in
1509 let time = Unix.gettimeofday () in
1510 let tm = Unix.localtime time in
1511 let printable_date_time =
1512 sprintf "%04d-%02d-%02d %02d:%02d:%02d"
1513 (tm.Unix.tm_year + 1900) (tm.Unix.tm_mon+1) tm.Unix.tm_mday
1514 tm.Unix.tm_hour tm.Unix.tm_min tm.Unix.tm_sec in
1517 let uid = Unix.geteuid () in
1518 (Unix.getpwuid uid).Unix.pw_name
1520 Not_found -> "unknown" in
1523 let nl () = fp chan "\n" in
1524 fp chan "# .virt-toprc virt-top configuration file\n";
1525 fp chan "# generated on %s by %s\n" printable_date_time username;
1527 fp chan "display %s\n" (cli_of_display !display_mode);
1528 fp chan "delay %g\n" (float !delay /. 1000.);
1529 fp chan "hist-cpu %d\n" !historical_cpu_delay;
1530 if !iterations <> -1 then fp chan "iterations %d\n" !iterations;
1531 fp chan "sort %s\n" (cli_of_sort_order !sort_order);
1534 | Some uri -> fp chan "connect %s\n" uri
1536 if !batch_mode = true then fp chan "batch true\n";
1537 if !secure_mode = true then fp chan "secure true\n";
1539 fp chan "# To send debug and error messages to a file, uncomment next line\n";
1540 fp chan "#debug virt-top.out\n";
1542 fp chan "# Enable CSV output to the named file\n";
1543 fp chan "#csv virt-top.csv\n";
1545 fp chan "# To protect this file from being overwritten, uncomment next line\n";
1546 fp chan "#overwrite-init-file false\n";
1550 (* If the file exists, rename it as filename.old. *)
1551 (try Unix.rename filename (filename ^ ".old")
1552 with Unix.Unix_error _ -> ());
1554 (* Rename filename.new to filename. *)
1555 Unix.rename (filename ^ ".new") filename;
1557 print_msg (sprintf "Wrote settings to %s" filename); sleep 2
1559 | Sys_error err -> print_msg "Error: %s"; sleep 2
1560 | Unix.Unix_error (err, fn, str) ->
1561 print_msg (sprintf "Error: %s %s %s" (Unix.error_message err) fn str);
1564 and show_help (_, _, _, _, _, hostname,
1565 (libvirt_major, libvirt_minor, libvirt_release)) =
1568 (* Get the screen/window size. *)
1569 let lines, cols = get_size () in
1571 (* Banner at the top of the screen. *)
1573 sprintf "virt-top %s (libvirt %d.%d.%d) by Red Hat"
1574 Libvirt_version.version libvirt_major libvirt_minor libvirt_release in
1575 let banner = pad cols banner in
1577 mvaddstr 0 0 banner;
1582 (sprintf "Delay: %.1f secs; Batch: %s; Secure: %s; Sort: %s"
1583 (float !delay /. 1000.)
1584 (if !batch_mode then "On" else "Off")
1585 (if !secure_mode then "On" else "Off")
1586 (printable_sort_order !sort_order));
1588 (sprintf "Connect: %s; Hostname: %s"
1589 (match !uri with None -> "default" | Some s -> s)
1592 (* Misc keys on left. *)
1593 let banner = pad 38 "MAIN KEYS" in
1595 mvaddstr header_lineno 1 banner;
1599 let lineno = ref domains_lineno in
1600 fun () -> let i = !lineno in incr lineno; i
1602 let key keys description =
1603 let lineno = get_lineno () in
1604 move lineno 1; attron A.bold; addstr keys; attroff A.bold;
1605 move lineno 10; addstr description; ()
1607 key "space ^L" "Update display";
1609 key "d s" "Set update interval";
1613 ignore (get_lineno ());
1614 let banner = pad 38 "SORTING" in
1616 mvaddstr (get_lineno ()) 1 banner;
1619 key "P" "Sort by %CPU";
1620 key "M" "Sort by %MEM";
1621 key "T" "Sort by TIME";
1622 key "N" "Sort by ID";
1623 key "F" "Select sort field";
1625 (* Display modes on right. *)
1626 let banner = pad 39 "DISPLAY MODES" in
1628 mvaddstr header_lineno 40 banner;
1632 let lineno = ref domains_lineno in
1633 fun () -> let i = !lineno in incr lineno; i
1635 let key keys description =
1636 let lineno = get_lineno () in
1637 move lineno 40; attron A.bold; addstr keys; attroff A.bold;
1638 move lineno 49; addstr description; ()
1640 key "0" "Domains display";
1641 key "1" "Toggle physical CPUs";
1642 key "2" "Toggle network interfaces";
1643 key "3" "Toggle block devices";
1645 (* Update screen and wait for key press. *)
1646 mvaddstr (lines-1) 0
1647 "More help in virt-top(1) man page. Press any key to return.";
1651 and unknown_command k =
1652 print_msg "Unknown command - try 'h' for help";