1 (* 'top'-like tool for libvirt domains.
2 * $Id: virt_top.ml,v 1.5 2007/08/30 13:52:40 rjones Exp $
11 module C = Libvirt.Connect
12 module D = Libvirt.Domain
13 module N = Libvirt.Network
15 (* Hook for XML support (see virt_top_xml.ml). *)
16 let parse_device_xml : (int -> [>`R] D.t -> string list * string list) ref =
21 (* Hooks for CSV support (see virt_top_csv.ml). *)
22 let csv_start : (string -> unit) ref =
24 fun _ -> failwith "virt-top was compiled without support for CSV"
26 let csv_write : (string list -> unit) ref =
31 (* Int64 operators for convenience. *)
34 let ( *^ ) = Int64.mul
39 | DomainID | DomainName | Processor | Memory | Time
40 | NetRX | NetTX | BlockRdRq | BlockWrRq
41 let all_sort_fields = [
42 DomainID; DomainName; Processor; Memory; Time;
43 NetRX; NetTX; BlockRdRq; BlockWrRq
45 let printable_sort_order = function
48 | Time -> "TIME (CPU time)"
49 | DomainID -> "Domain ID"
50 | DomainName -> "Domain name"
51 | NetRX -> "Net RX bytes"
52 | NetTX -> "Net TX bytes"
53 | BlockRdRq -> "Block read reqs"
54 | BlockWrRq -> "Block write reqs"
55 let sort_order_of_cli = function
56 | "cpu" | "processor" -> Processor
57 | "mem" | "memory" -> Memory
60 | "name" -> DomainName
61 | "netrx" -> NetRX | "nettx" -> NetTX
62 | "blockrdrq" -> BlockRdRq | "blockwrrq" -> BlockWrRq
63 | str -> failwith (str ^ ": sort order should be: cpu|mem|time|id|name|netrx|nettx|blockrdrq|blockwrrq")
64 let cli_of_sort_order = function
69 | DomainName -> "name"
72 | BlockRdRq -> "blockrdrq"
73 | BlockWrRq -> "blockwrrq"
75 (* Current major display mode: TaskDisplay is the normal display. *)
76 type display = TaskDisplay | PCPUDisplay | BlockDisplay | NetDisplay
78 let display_of_cli = function
79 | "task" -> TaskDisplay
80 | "pcpu" -> PCPUDisplay
81 | "block" -> BlockDisplay
83 | str -> failwith (str ^ ": display should be task|pcpu|block|net")
84 let cli_of_display = function
85 | TaskDisplay -> "task"
86 | PCPUDisplay -> "pcpu"
87 | BlockDisplay -> "block"
91 type init_file = NoInitFile | DefaultInitFile | InitFile of string
95 let delay = ref 3000 (* milliseconds *)
96 let historical_cpu_delay = ref 20 (* secs *)
97 let iterations = ref (-1)
98 let batch_mode = ref false
99 let secure_mode = ref false
100 let sort_order = ref Processor
101 let display_mode = ref TaskDisplay
103 let debug_file = ref ""
104 let csv_enabled = ref false
105 let init_file = ref DefaultInitFile
106 let script_mode = ref false
108 (* Function to read command line arguments and go into curses mode. *)
110 (* Read command line arguments. *)
111 let rec set_delay newdelay =
112 if newdelay <= 0. then
113 failwith "-d: cannot set a negative delay";
114 delay := int_of_float (newdelay *. 1000.)
115 and set_uri = function "" -> uri := None | u -> uri := Some u
116 and set_sort order = sort_order := sort_order_of_cli order
117 and set_pcpu_mode () = display_mode := PCPUDisplay
118 and set_net_mode () = display_mode := NetDisplay
119 and set_block_mode () = display_mode := BlockDisplay
120 and set_csv filename =
121 (!csv_start) filename;
123 and no_init_file () = init_file := NoInitFile
124 and set_init_file filename = init_file := InitFile filename
126 let argspec = Arg.align [
127 "-1", Arg.Unit set_pcpu_mode, " Start by displaying pCPUs (default: tasks)";
128 "-2", Arg.Unit set_net_mode, " Start by displaying network interfaces";
129 "-3", Arg.Unit set_block_mode, " Start by displaying block devices";
130 "-b", Arg.Set batch_mode, " Batch mode";
131 "-c", Arg.String set_uri, "uri Connect to URI (default: Xen)";
132 "--connect", Arg.String set_uri, "uri Connect to URI (default: Xen)";
133 "--csv", Arg.String set_csv, "file Log statistics to CSV file";
134 "-d", Arg.Float set_delay, "delay Delay time interval (seconds)";
135 "--debug", Arg.Set_string debug_file, "file Send debug messages to file";
136 "--hist-cpu", Arg.Set_int historical_cpu_delay, "secs Historical CPU delay";
137 "--init-file", Arg.String set_init_file, "file Set name of init file";
138 "--no-init-file", Arg.Unit no_init_file, " Do not read init file";
139 "-n", Arg.Set_int iterations, "iterations Number of iterations to run";
140 "-o", Arg.String set_sort, "sort Set sort order (cpu|mem|time|id|name)";
141 "-s", Arg.Set secure_mode, " Secure (\"kiosk\") mode";
142 "--script", Arg.Set script_mode, " Run from a script (no user interface)";
144 let anon_fun str = raise (Arg.Bad (str ^ ": unknown parameter")) in
145 let usage_msg = "virt-top : a 'top'-like utility for virtualization
151 Arg.parse argspec anon_fun usage_msg;
153 (* Read the init file. *)
154 let try_to_read_init_file filename =
155 let config = read_config_file filename in
158 | _, "display", mode -> display_mode := display_of_cli mode
159 | _, "delay", secs -> set_delay (float_of_string secs)
160 | _, "hist-cpu", secs -> historical_cpu_delay := int_of_string secs
161 | _, "iterations", n -> iterations := int_of_string n
162 | _, "sort", order -> set_sort order
163 | _, "connect", uri -> set_uri uri
164 | _, "debug", filename -> debug_file := filename
165 | _, "csv", filename -> set_csv filename
166 | _, "batch", b -> batch_mode := bool_of_string b
167 | _, "secure", b -> secure_mode := bool_of_string b
168 | _, "script", b -> script_mode := bool_of_string b
169 | _, "overwrite-init-file", "false" -> no_init_file ()
171 eprintf "%s:%d: configuration item ``%s'' ignored\n%!"
175 (match !init_file with
178 let home = try Sys.getenv "HOME" with Not_found -> "/" in
179 let filename = home // ".virt-toprc" in
180 try_to_read_init_file filename
181 | InitFile filename ->
182 try_to_read_init_file filename
185 (* Connect to the hypervisor before going into curses mode, since
186 * this is the most likely thing to fail.
190 try C.connect_readonly ?name ()
192 Libvirt.Virterror err ->
193 prerr_endline (Libvirt.Virterror.to_string err);
194 (* If non-root and no explicit connection URI, print a warning. *)
195 if Unix.geteuid () <> 0 && name = None then (
196 print_endline "NB: If you want to monitor a local Xen hypervisor, you usually need to be root";
200 (* Get the node_info. This never changes, right? So we get it just once. *)
201 let node_info = C.get_node_info conn in
203 (* Hostname and libvirt library version also don't change. *)
205 try C.get_hostname conn
207 (* qemu:/// and other URIs didn't support virConnectGetHostname until
208 * libvirt 0.3.3. Before that they'd throw a virterror. *)
209 | Libvirt.Virterror _
210 | Invalid_argument "virConnectGetHostname not supported" -> "unknown" in
212 let libvirt_version =
213 let v, _ = Libvirt.get_version () in
214 v / 1_000_000, (v / 1_000) mod 1_000, v mod 1_000 in
216 (* Open debug file if specified.
217 * NB: Do this just before jumping into curses mode.
219 (match !debug_file with
220 | "" -> (* No debug file specified, send stderr to /dev/null unless
221 * we're in script mode.
223 if not !script_mode then (
224 let fd = Unix.openfile "/dev/null" [Unix.O_WRONLY] 0o644 in
225 Unix.dup2 fd Unix.stderr;
228 | filename -> (* Send stderr to the named file. *)
230 Unix.openfile filename [Unix.O_WRONLY;Unix.O_CREAT;Unix.O_TRUNC]
232 Unix.dup2 fd Unix.stderr;
236 (* Curses voodoo (see ncurses(3)). *)
237 if not !script_mode then (
242 let stdscr = stdscr () in
243 intrflush stdscr false;
248 (* This tuple of static information is called 'setup' in other parts
249 * of this program, and is passed to other functions such as redraw and
250 * main_loop. See virt_top_main.ml.
253 !batch_mode, !script_mode, !csv_enabled, (* immutable modes *)
254 node_info, hostname, libvirt_version (* info that doesn't change *)
257 (* Show a percentage in 4 chars. *)
258 let show_percent percent =
259 if percent <= 0. then " 0.0"
260 else if percent <= 9.9 then sprintf " %1.1f" percent
261 else if percent <= 99.9 then sprintf "%2.1f" percent
264 (* Show an int64 option in 4 chars. *)
265 let rec show_int64_option = function
267 | Some n -> show_int64 n
268 (* Show an int64 in 4 chars. *)
269 and show_int64 = function
270 | n when n < 0L -> "-!!!"
271 | n when n <= 9999L ->
273 | n when n /^ 1024L <= 999L ->
274 sprintf "%3LdK" (n /^ 1024L)
275 | n when n /^ 1_048_576L <= 999L ->
276 sprintf "%3LdM" (n /^ 1_048_576L)
277 | n when n /^ 1_073_741_824L <= 999L ->
278 sprintf "%3LdG" (n /^ 1_073_741_824L)
281 (* Format the total time (may be large!) in 9 chars. *)
283 let secs_in_ns = 1_000_000_000L in
284 let mins_in_ns = 60_000_000_000L in
285 let hours_in_ns = 3_600_000_000_000L in
287 let hours = ns /^ hours_in_ns in
288 let ns = ns -^ (hours *^ hours_in_ns) in
289 let mins = ns /^ mins_in_ns in
290 let ns = ns -^ (mins *^ mins_in_ns) in
291 let secs = ns /^ secs_in_ns in
292 let ns = ns -^ (secs *^ secs_in_ns) in
293 let pennies = ns /^ 10_000_000L in
296 sprintf "%3Ld:%02Ld.%02Ld" (hours *^ 60L +^ mins) secs pennies
297 else if hours <= 999L then
298 sprintf "%3Ld:%02Ld:%02Ld" hours mins secs
300 let days = hours /^ 24L in
301 let hours = hours -^ (days *^ 24L) in
302 sprintf "%3Ldd%02Ld:%02Ld" days hours mins
305 (* Show a domain state (the 'S' column). *)
306 let show_state = function
307 | D.InfoNoState -> '?'
308 | D.InfoRunning -> 'R'
309 | D.InfoBlocked -> 'S'
310 | D.InfoPaused -> 'P'
311 | D.InfoShutdown -> 'D'
312 | D.InfoShutoff -> 'O'
313 | D.InfoCrashed -> 'X'
315 (* Sum Domain.block_stats structures together. Missing fields
316 * get forced to 0. Empty list returns all 0.
318 let zero_block_stats =
319 { D.rd_req = 0L; rd_bytes = 0L; wr_req = 0L; wr_bytes = 0L; errs = 0L }
320 let add_block_stats bs1 bs2 =
321 let add f1 f2 = if f1 >= 0L && f2 >= 0L then f1 +^ f2 else 0L in
322 { D.rd_req = add bs1.D.rd_req bs2.D.rd_req;
323 rd_bytes = add bs1.D.rd_bytes bs2.D.rd_bytes;
324 wr_req = add bs1.D.wr_req bs2.D.wr_req;
325 wr_bytes = add bs1.D.wr_bytes bs2.D.wr_bytes;
326 errs = add bs1.D.errs bs2.D.errs }
327 let sum_block_stats =
328 List.fold_left add_block_stats zero_block_stats
330 (* Get the difference between two block_stats structures. Missing data
331 * forces the difference to -1.
333 let diff_block_stats curr prev =
334 let sub f1 f2 = if f1 >= 0L && f2 >= 0L then f1 -^ f2 else -1L in
335 { D.rd_req = sub curr.D.rd_req prev.D.rd_req;
336 rd_bytes = sub curr.D.rd_bytes prev.D.rd_bytes;
337 wr_req = sub curr.D.wr_req prev.D.wr_req;
338 wr_bytes = sub curr.D.wr_bytes prev.D.wr_bytes;
339 errs = sub curr.D.errs prev.D.errs }
341 (* Sum Domain.interface_stats structures together. Missing fields
342 * get forced to 0. Empty list returns all 0.
344 let zero_interface_stats =
345 { D.rx_bytes = 0L; rx_packets = 0L; rx_errs = 0L; rx_drop = 0L;
346 tx_bytes = 0L; tx_packets = 0L; tx_errs = 0L; tx_drop = 0L }
347 let add_interface_stats is1 is2 =
348 let add f1 f2 = if f1 >= 0L && f2 >= 0L then f1 +^ f2 else 0L in
349 { D.rx_bytes = add is1.D.rx_bytes is2.D.rx_bytes;
350 rx_packets = add is1.D.rx_packets is2.D.rx_packets;
351 rx_errs = add is1.D.rx_errs is2.D.rx_errs;
352 rx_drop = add is1.D.rx_drop is2.D.rx_drop;
353 tx_bytes = add is1.D.tx_bytes is2.D.tx_bytes;
354 tx_packets = add is1.D.tx_packets is2.D.tx_packets;
355 tx_errs = add is1.D.tx_errs is2.D.tx_errs;
356 tx_drop = add is1.D.tx_drop is2.D.tx_drop }
357 let sum_interface_stats =
358 List.fold_left add_interface_stats zero_interface_stats
360 (* Get the difference between two interface_stats structures.
361 * Missing data forces the difference to -1.
363 let diff_interface_stats curr prev =
364 let sub f1 f2 = if f1 >= 0L && f2 >= 0L then f1 -^ f2 else -1L in
365 { D.rx_bytes = sub curr.D.rx_bytes prev.D.rx_bytes;
366 rx_packets = sub curr.D.rx_packets prev.D.rx_packets;
367 rx_errs = sub curr.D.rx_errs prev.D.rx_errs;
368 rx_drop = sub curr.D.rx_drop prev.D.rx_drop;
369 tx_bytes = sub curr.D.tx_bytes prev.D.tx_bytes;
370 tx_packets = sub curr.D.tx_packets prev.D.tx_packets;
371 tx_errs = sub curr.D.tx_errs prev.D.tx_errs;
372 tx_drop = sub curr.D.tx_drop prev.D.tx_drop }
374 (* Update the display and sleep for given number of seconds. *)
375 let sleep n = refresh (); Unix.sleep n
377 (* The curses getstr/getnstr functions are just weird.
378 * This helper function also enables echo temporarily.
380 let get_string maxlen =
382 let str = String.create maxlen in
383 let ok = getstr str in (* Safe because binding calls getnstr. *)
387 (* Chop at first '\0'. *)
389 let i = String.index str '\000' in
392 Not_found -> str (* it is full maxlen bytes *)
395 (* Pad a string to the full width with spaces. If too long, truncate. *)
397 let n = String.length str in
398 if n = width then str
399 else if n > width then String.sub str 0 width
400 else (* if n < width then *) str ^ String.make (width-n) ' '
404 let summary_lineno = 1 (* this takes 2 lines *)
405 let message_lineno = 3
406 let header_lineno = 4
407 let domains_lineno = 5
409 (* Print in the "message area". *)
410 let clear_msg () = move message_lineno 0; clrtoeol ()
411 let print_msg str = clear_msg (); mvaddstr message_lineno 0 str; ()
413 (* Intermediate "domain + stats" structure that we use to collect
414 * everything we know about a domain within the collect function.
416 type rd_domain = Inactive | Active of rd_active
418 rd_domid : int; (* Domain ID. *)
419 rd_dom : [`R] D.t; (* Domain object. *)
420 rd_info : D.info; (* Domain CPU info now. *)
421 rd_block_stats : (string * D.block_stats) list;
422 (* Domain block stats now. *)
423 rd_interface_stats : (string * D.interface_stats) list;
424 (* Domain net stats now. *)
425 rd_prev_info : D.info option; (* Domain CPU info previously. *)
426 rd_prev_block_stats : (string * D.block_stats) list;
427 (* Domain block stats prev. *)
428 rd_prev_interface_stats : (string * D.interface_stats) list;
429 (* Domain interface stats prev. *)
430 (* The following are since the last slice, or 0 if cannot be calculated: *)
431 rd_cpu_time : float; (* CPU time used in nanoseconds. *)
432 rd_percent_cpu : float; (* CPU time as percent of total. *)
433 (* The following are since the last slice, or None if cannot be calc'd: *)
434 rd_block_rd_reqs : int64 option; (* Number of block device read rqs. *)
435 rd_block_wr_reqs : int64 option; (* Number of block device write rqs. *)
436 rd_net_rx_bytes : int64 option; (* Number of bytes received. *)
437 rd_net_tx_bytes : int64 option; (* Number of bytes transmitted. *)
441 let collect, clear_pcpu_display_data =
442 (* We cache the list of block devices and interfaces for each domain
443 * here, so we don't need to reparse the XML each time.
445 let devices = Hashtbl.create 13 in
447 (* Function to get the list of block devices, network interfaces for
448 * a particular domain. Get it from the devices cache, and if not
449 * there then parse the domain XML.
451 let get_devices id dom =
452 try Hashtbl.find devices id
454 let blkdevs, netifs = (!parse_device_xml) id dom in
455 Hashtbl.replace devices id (blkdevs, netifs);
459 (* We save the state of domains across redraws here, which allows us
460 * to deduce %CPU usage from the running total.
462 let last_info = Hashtbl.create 13 in
463 let last_time = ref (Unix.gettimeofday ()) in
465 (* Save vcpuinfo structures across redraws too (only for pCPU display). *)
466 let last_vcpu_info = Hashtbl.create 13 in
468 let clear_pcpu_display_data () =
469 (* Clear out vcpu_info used by PCPUDisplay display_mode
470 * when we switch back to TaskDisplay mode.
472 Hashtbl.clear last_vcpu_info
475 let collect (conn, _, _, _, node_info, _, _) =
476 (* Number of physical CPUs (some may be disabled). *)
477 let nr_pcpus = C.maxcpus_of_node_info node_info in
479 (* Get the current time. *)
480 let time = Unix.gettimeofday () in
481 let tm = Unix.localtime time in
483 sprintf "%02d:%02d:%02d" tm.Unix.tm_hour tm.Unix.tm_min tm.Unix.tm_sec in
484 mvaddstr top_lineno 0 ("virt-top " ^ printable_time ^ " - ");
486 (* What's the total CPU time elapsed since we were last called? (ns) *)
487 let total_cpu_per_pcpu = 1_000_000_000. *. (time -. !last_time) in
488 (* Avoid division by zero. *)
489 let total_cpu_per_pcpu =
490 if total_cpu_per_pcpu <= 0. then 1. else total_cpu_per_pcpu in
491 let total_cpu = float node_info.C.cpus *. total_cpu_per_pcpu in
493 (* Get the domains. Match up with their last_info (if any). *)
495 (* Active domains. *)
496 let n = C.num_of_domains conn in
498 if n > 0 then Array.to_list (C.list_domains conn n)
504 let dom = D.lookup_by_id conn id in
505 let name = D.get_name dom in
506 let blkdevs, netifs = get_devices id dom in
508 (* Get current CPU, block and network stats. *)
509 let info = D.get_info dom in
511 try List.map (fun dev -> dev, D.block_stats dom dev) blkdevs
513 | Invalid_argument "virDomainBlockStats not supported"
514 | Libvirt.Virterror _ -> [] in
515 let interface_stats =
516 try List.map (fun dev -> dev, D.interface_stats dom dev) netifs
518 | Invalid_argument "virDomainInterfaceStats not supported"
519 | Libvirt.Virterror _ -> [] in
521 let prev_info, prev_block_stats, prev_interface_stats =
523 let prev_info, prev_block_stats, prev_interface_stats =
524 Hashtbl.find last_info id in
525 Some prev_info, prev_block_stats, prev_interface_stats
526 with Not_found -> None, [], [] in
529 rd_domid = id; rd_dom = dom; rd_info = info;
530 rd_block_stats = block_stats;
531 rd_interface_stats = interface_stats;
532 rd_prev_info = prev_info;
533 rd_prev_block_stats = prev_block_stats;
534 rd_prev_interface_stats = prev_interface_stats;
535 rd_cpu_time = 0.; rd_percent_cpu = 0.;
536 rd_block_rd_reqs = None; rd_block_wr_reqs = None;
537 rd_net_rx_bytes = None; rd_net_tx_bytes = None;
540 Libvirt.Virterror _ -> None (* ignore transient error *)
543 (* Inactive domains. *)
546 let n = C.num_of_defined_domains conn in
548 if n > 0 then Array.to_list (C.list_defined_domains conn n)
550 List.map (fun name -> name, Inactive) names
552 (* Ignore transient errors, in particular errors from
553 * num_of_defined_domains if it cannot contact xend.
555 | Libvirt.Virterror _ -> [] in
557 doms @ doms_inactive in
559 (* Calculate the CPU time (ns) and %CPU used by each domain. *)
563 (* We have previous CPU info from which to calculate it? *)
564 | name, Active ({ rd_prev_info = Some prev_info } as rd) ->
566 Int64.to_float (rd.rd_info.D.cpu_time -^ prev_info.D.cpu_time) in
567 let percent_cpu = 100. *. cpu_time /. total_cpu in
569 rd_cpu_time = cpu_time;
570 rd_percent_cpu = percent_cpu } in
572 (* For all other domains we can't calculate it, so leave as 0 *)
576 (* Calculate the number of block device read/write requests across
577 * all block devices attached to a domain.
582 (* Do we have stats from the previous slice? *)
583 | name, Active ({ rd_prev_block_stats = ((_::_) as prev_block_stats) }
585 let block_stats = rd.rd_block_stats in (* stats now *)
587 (* Add all the devices together. Throw away device names. *)
588 let prev_block_stats =
589 sum_block_stats (List.map snd prev_block_stats) in
591 sum_block_stats (List.map snd block_stats) in
593 (* Calculate increase in read & write requests. *)
595 block_stats.D.rd_req -^ prev_block_stats.D.rd_req in
597 block_stats.D.wr_req -^ prev_block_stats.D.wr_req in
600 rd_block_rd_reqs = Some read_reqs;
601 rd_block_wr_reqs = Some write_reqs } in
603 (* For all other domains we can't calculate it, so leave as None. *)
607 (* Calculate the same as above for network interfaces across
608 * all network interfaces attached to a domain.
613 (* Do we have stats from the previous slice? *)
614 | name, Active ({ rd_prev_interface_stats =
615 ((_::_) as prev_interface_stats) }
617 let interface_stats = rd.rd_interface_stats in (* stats now *)
619 (* Add all the devices together. Throw away device names. *)
620 let prev_interface_stats =
621 sum_interface_stats (List.map snd prev_interface_stats) in
622 let interface_stats =
623 sum_interface_stats (List.map snd interface_stats) in
625 (* Calculate increase in rx & tx bytes. *)
627 interface_stats.D.rx_bytes -^ prev_interface_stats.D.rx_bytes in
629 interface_stats.D.tx_bytes -^ prev_interface_stats.D.tx_bytes in
632 rd_net_rx_bytes = Some rx_bytes;
633 rd_net_tx_bytes = Some tx_bytes } in
635 (* For all other domains we can't calculate it, so leave as None. *)
639 (* Collect some extra information in PCPUDisplay display_mode. *)
641 if !display_mode = PCPUDisplay then (
642 (* Get the VCPU info and VCPU->PCPU mappings for active domains.
643 * Also cull some data we don't care about.
645 let doms = List.filter_map (
647 | (name, Active rd) ->
649 let domid = rd.rd_domid in
650 let maplen = C.cpumaplen nr_pcpus in
651 let maxinfo = rd.rd_info.D.nr_virt_cpu in
652 let nr_vcpus, vcpu_infos, cpumaps =
653 D.get_vcpus rd.rd_dom maxinfo maplen in
655 (* Got previous vcpu_infos for this domain? *)
656 let prev_vcpu_infos =
657 try Some (Hashtbl.find last_vcpu_info domid)
658 with Not_found -> None in
659 (* Update last_vcpu_info. *)
660 Hashtbl.replace last_vcpu_info domid vcpu_infos;
662 (match prev_vcpu_infos with
663 | Some prev_vcpu_infos
664 when Array.length prev_vcpu_infos = Array.length vcpu_infos ->
665 Some (domid, name, nr_vcpus, vcpu_infos, prev_vcpu_infos,
667 | _ -> None (* ignore missing / unequal length prev_vcpu_infos *)
670 Libvirt.Virterror _ -> None(* ignore transient libvirt errs *)
672 | (_, Inactive) -> None (* ignore inactive doms *)
674 let nr_doms = List.length doms in
676 (* Rearrange the data into a matrix. Major axis (down) is
677 * pCPUs. Minor axis (right) is domains. At each node we store:
678 * cpu_time (on this pCPU only, nanosecs),
679 * average? (if set, then cpu_time is an average because the
680 * vCPU is pinned to more than one pCPU)
681 * running? (if set, we were instantaneously running on this pCPU)
683 let empty_node = (0L, false, false) in
684 let pcpus = Array.make_matrix nr_pcpus nr_doms empty_node in
687 fun di (domid, name, nr_vcpus, vcpu_infos, prev_vcpu_infos,
689 (* Which pCPUs can this dom run on? *)
690 for v = 0 to nr_vcpus-1 do
691 let pcpu = vcpu_infos.(v).D.cpu in (* instantaneous pCPU *)
692 let nr_poss_pcpus = ref 0 in (* how many pcpus can it run on? *)
693 for p = 0 to nr_pcpus-1 do
694 (* vcpu v can reside on pcpu p *)
695 if C.cpu_usable cpumaps maplen v p then
698 let nr_poss_pcpus = Int64.of_int !nr_poss_pcpus in
699 for p = 0 to nr_pcpus-1 do
700 (* vcpu v can reside on pcpu p *)
701 if C.cpu_usable cpumaps maplen v p then
702 let vcpu_time_on_pcpu =
703 vcpu_infos.(v).D.vcpu_time
704 -^ prev_vcpu_infos.(v).D.vcpu_time in
705 let vcpu_time_on_pcpu =
706 vcpu_time_on_pcpu /^ nr_poss_pcpus in
708 (vcpu_time_on_pcpu, nr_poss_pcpus > 1L, p = pcpu)
713 (* Sum the CPU time used by each pCPU, for the %CPU column. *)
714 let pcpus_cpu_time = Array.map (
716 let cpu_time = ref 0L in
717 for di = 0 to Array.length row-1 do
718 let t, _, _ = row.(di) in
719 cpu_time := !cpu_time +^ t
721 Int64.to_float !cpu_time
724 Some (doms, pcpus, pcpus_cpu_time)
728 (* Calculate totals. *)
729 let totals = List.fold_left (
730 fun (count, running, blocked, paused, shutdown, shutoff,
731 crashed, active, inactive,
732 total_cpu_time, total_memory, total_domU_memory) ->
734 | (name, Active rd) ->
735 let test state orig =
736 if rd.rd_info.D.state = state then orig+1 else orig
738 let running = test D.InfoRunning running in
739 let blocked = test D.InfoBlocked blocked in
740 let paused = test D.InfoPaused paused in
741 let shutdown = test D.InfoShutdown shutdown in
742 let shutoff = test D.InfoShutoff shutoff in
743 let crashed = test D.InfoCrashed crashed in
745 let total_cpu_time = total_cpu_time +. rd.rd_cpu_time in
746 let total_memory = total_memory +^ rd.rd_info.D.memory in
747 let total_domU_memory = total_domU_memory +^
748 if rd.rd_domid > 0 then rd.rd_info.D.memory else 0L in
750 (count+1, running, blocked, paused, shutdown, shutoff,
751 crashed, active+1, inactive,
752 total_cpu_time, total_memory, total_domU_memory)
754 | (name, Inactive) -> (* inactive domain *)
755 (count+1, running, blocked, paused, shutdown, shutoff,
756 crashed, active, inactive+1,
757 total_cpu_time, total_memory, total_domU_memory)
758 ) (0,0,0,0,0,0,0,0,0, 0.,0L,0L) doms in
760 (* Update last_time, last_info. *)
762 Hashtbl.clear last_info;
766 let info = rd.rd_info, rd.rd_block_stats, rd.rd_interface_stats in
767 Hashtbl.add last_info rd.rd_domid info
772 time, printable_time,
773 nr_pcpus, total_cpu, total_cpu_per_pcpu,
778 collect, clear_pcpu_display_data
780 (* Redraw the display. *)
782 (* Keep a historical list of %CPU usages. *)
783 let historical_cpu = ref [] in
784 let historical_cpu_last_time = ref (Unix.gettimeofday ()) in
786 (_, _, _, _, node_info, _, _) (* setup *)
788 time, printable_time,
789 nr_pcpus, total_cpu, total_cpu_per_pcpu,
791 pcpu_display) (* state *) ->
794 (* Get the screen/window size. *)
795 let lines, cols = get_size () in
797 (* Basic node_info. *)
798 addstr (sprintf "%s %d/%dCPU %dMHz %LdMB "
799 node_info.C.model node_info.C.cpus nr_pcpus node_info.C.mhz
800 (node_info.C.memory /^ 1024L));
801 (* Save the cursor position for when we come to draw the
802 * historical CPU times (down in this function).
804 let stdscr = stdscr () in
805 let historical_cursor = getyx stdscr in
807 (match !display_mode with
808 | TaskDisplay -> (*---------- Showing domains ----------*)
809 (* Sort domains on current sort_order. *)
812 match !sort_order with
814 (fun _ -> 0) (* fallthrough to default name compare *)
817 | Active rd1, Active rd2 ->
818 compare rd2.rd_percent_cpu rd1.rd_percent_cpu
819 | Active _, Inactive -> -1
820 | Inactive, Active _ -> 1
821 | Inactive, Inactive -> 0)
824 | Active { rd_info = info1 }, Active { rd_info = info2 } ->
825 compare info2.D.memory info1.D.memory
826 | Active _, Inactive -> -1
827 | Inactive, Active _ -> 1
828 | Inactive, Inactive -> 0)
831 | Active { rd_info = info1 }, Active { rd_info = info2 } ->
832 compare info2.D.cpu_time info1.D.cpu_time
833 | Active _, Inactive -> -1
834 | Inactive, Active _ -> 1
835 | Inactive, Inactive -> 0)
838 | Active { rd_domid = id1 }, Active { rd_domid = id2 } ->
840 | Active _, Inactive -> -1
841 | Inactive, Active _ -> 1
842 | Inactive, Inactive -> 0)
845 | Active { rd_net_rx_bytes = r1 }, Active { rd_net_rx_bytes = r2 } ->
847 | Active _, Inactive -> -1
848 | Inactive, Active _ -> 1
849 | Inactive, Inactive -> 0)
852 | Active { rd_net_tx_bytes = r1 }, Active { rd_net_tx_bytes = r2 } ->
854 | Active _, Inactive -> -1
855 | Inactive, Active _ -> 1
856 | Inactive, Inactive -> 0)
859 | Active { rd_block_rd_reqs = r1 }, Active { rd_block_rd_reqs = r2 } ->
861 | Active _, Inactive -> -1
862 | Inactive, Active _ -> 1
863 | Inactive, Inactive -> 0)
866 | Active { rd_block_wr_reqs = r1 }, Active { rd_block_wr_reqs = r2 } ->
868 | Active _, Inactive -> -1
869 | Inactive, Active _ -> 1
870 | Inactive, Inactive -> 0)
872 let cmp (name1, dom1) (name2, dom2) =
873 let r = cmp (dom1, dom2) in
875 else compare name1 name2
877 List.sort ~cmp doms in
881 mvaddstr header_lineno 0
882 (pad cols " ID S RDRQ WRRQ RXBY TXBY %CPU %MEM TIME NAME");
885 let rec loop lineno = function
887 | (name, Active rd) :: doms ->
888 if lineno < lines then (
889 let state = show_state rd.rd_info.D.state in
890 let rd_req = show_int64_option rd.rd_block_rd_reqs in
891 let wr_req = show_int64_option rd.rd_block_wr_reqs in
892 let rx_bytes = show_int64_option rd.rd_net_rx_bytes in
893 let tx_bytes = show_int64_option rd.rd_net_tx_bytes in
894 let percent_cpu = show_percent rd.rd_percent_cpu in
896 100L *^ rd.rd_info.D.memory /^ node_info.C.memory in
897 let percent_mem = Int64.to_float percent_mem in
898 let percent_mem = show_percent percent_mem in
899 let time = show_time rd.rd_info.D.cpu_time in
901 let line = sprintf "%5d %c %s %s %s %s %s %s %s %s"
902 rd.rd_domid state rd_req wr_req rx_bytes tx_bytes
903 percent_cpu percent_mem time name in
904 let line = pad cols line in
905 mvaddstr lineno 0 line;
908 | (name, Inactive) :: doms -> (* inactive domain *)
909 if lineno < lines then (
914 let line = pad cols line in
915 mvaddstr lineno 0 line;
919 loop domains_lineno doms
921 | PCPUDisplay -> (*---------- Showing physical CPUs ----------*)
922 let doms, pcpus, pcpus_cpu_time =
923 match pcpu_display with
925 | None -> failwith "internal error: no pcpu_display data" in
927 (* Display the pCPUs. *)
931 fun (_, name, _, _, _, _, _) ->
932 let len = String.length name in
933 let width = max (len+1) 7 in
938 mvaddstr header_lineno 0 (pad cols ("PHYCPU %CPU " ^ dom_names));
943 mvaddstr (p+domains_lineno) 0 (sprintf "%4d " p);
944 let cpu_time = pcpus_cpu_time.(p) in (* ns used on this CPU *)
945 let percent_cpu = 100. *. cpu_time /. total_cpu_per_pcpu in
946 addstr (show_percent percent_cpu);
950 fun di (domid, name, _, _, _, _, _) ->
951 let t, is_average, is_running = pcpus.(p).(di) in
952 let len = String.length name in
953 let width = max (len+1) 7 in
957 let t = Int64.to_float t in
958 let percent = 100. *. t /. total_cpu_per_pcpu in
959 sprintf "%s%c%c " (show_percent percent)
960 (if is_average then '=' else ' ')
961 (if is_running then '#' else ' ')
963 addstr (pad width str);
968 | NetDisplay -> (*---------- Showing network interfaces ----------*)
969 (* Only care about active domains. *)
970 let doms = List.filter_map (
972 | (name, Active rd) -> Some (name, rd)
973 | (_, Inactive) -> None
976 (* For each domain we have a list of network interfaces seen
977 * this slice, and seen in the previous slice, which we now
978 * match up to get a list of (domain, interface) for which
979 * we have current & previous knowledge. (And ignore the rest).
987 (* Have prev slice stats for this device? *)
989 List.assoc dev rd.rd_prev_interface_stats in
990 Some (dev, name, rd, stats, prev_stats)
991 with Not_found -> None
992 ) rd.rd_interface_stats
995 (* Finally we have a list of:
996 * device name, domain name, rd_* stuff, curr stats, prev stats.
998 let devs : (string * string * rd_active *
999 D.interface_stats * D.interface_stats) list =
1000 List.flatten devs in
1002 (* Difference curr slice & prev slice. *)
1003 let devs = List.map (
1004 fun (dev, name, rd, curr, prev) ->
1005 dev, name, rd, diff_interface_stats curr prev
1008 (* Sort by current sort order, but map some of the standard
1009 * sort orders into ones which makes sense here.
1013 match !sort_order with
1015 (fun _ -> 0) (* fallthrough to default name compare *)
1017 (fun (_, { rd_domid = id1 }, _, { rd_domid = id2 }) ->
1019 | Processor | Memory | Time | BlockRdRq | BlockWrRq
1020 (* fallthrough to RXBY comparison. *)
1022 (fun ({ D.rx_bytes = b1 }, _, { D.rx_bytes = b2 }, _) ->
1025 (fun ({ D.tx_bytes = b1 }, _, { D.tx_bytes = b2 }, _) ->
1028 let cmp (dev1, name1, rd1, stats1) (dev2, name2, rd2, stats2) =
1029 let r = cmp (stats1, rd1, stats2, rd2) in
1031 else compare (dev1, name1) (dev2, name2)
1033 List.sort ~cmp devs in
1035 (* Print the header for network devices. *)
1037 mvaddstr header_lineno 0
1038 (pad cols " ID S RXBY TXBY RXPK TXPK DOMAIN INTERFACE");
1041 (* Print domains and devices. *)
1042 let rec loop lineno = function
1044 | (dev, name, rd, stats) :: devs ->
1045 if lineno < lines then (
1046 let state = show_state rd.rd_info.D.state in
1048 if stats.D.rx_bytes >= 0L
1049 then show_int64 stats.D.rx_bytes
1052 if stats.D.tx_bytes >= 0L
1053 then show_int64 stats.D.tx_bytes
1056 if stats.D.rx_packets >= 0L
1057 then show_int64 stats.D.rx_packets
1060 if stats.D.tx_packets >= 0L
1061 then show_int64 stats.D.tx_packets
1064 let line = sprintf "%5d %c %s %s %s %s %-12s %s"
1067 rx_packets tx_packets
1068 (pad 12 name) dev in
1069 let line = pad cols line in
1070 mvaddstr lineno 0 line;
1071 loop (lineno+1) devs
1074 loop domains_lineno devs
1076 | BlockDisplay -> (*---------- Showing block devices ----------*)
1077 (* Only care about active domains. *)
1078 let doms = List.filter_map (
1080 | (name, Active rd) -> Some (name, rd)
1081 | (_, Inactive) -> None
1084 (* For each domain we have a list of block devices seen
1085 * this slice, and seen in the previous slice, which we now
1086 * match up to get a list of (domain, device) for which
1087 * we have current & previous knowledge. (And ignore the rest).
1095 (* Have prev slice stats for this device? *)
1097 List.assoc dev rd.rd_prev_block_stats in
1098 Some (dev, name, rd, stats, prev_stats)
1099 with Not_found -> None
1103 (* Finally we have a list of:
1104 * device name, domain name, rd_* stuff, curr stats, prev stats.
1106 let devs : (string * string * rd_active *
1107 D.block_stats * D.block_stats) list =
1108 List.flatten devs in
1110 (* Difference curr slice & prev slice. *)
1111 let devs = List.map (
1112 fun (dev, name, rd, curr, prev) ->
1113 dev, name, rd, diff_block_stats curr prev
1116 (* Sort by current sort order, but map some of the standard
1117 * sort orders into ones which makes sense here.
1121 match !sort_order with
1123 (fun _ -> 0) (* fallthrough to default name compare *)
1125 (fun (_, { rd_domid = id1 }, _, { rd_domid = id2 }) ->
1127 | Processor | Memory | Time | NetRX | NetTX
1128 (* fallthrough to RDRQ comparison. *)
1130 (fun ({ D.rd_req = b1 }, _, { D.rd_req = b2 }, _) ->
1133 (fun ({ D.wr_req = b1 }, _, { D.wr_req = b2 }, _) ->
1136 let cmp (dev1, name1, rd1, stats1) (dev2, name2, rd2, stats2) =
1137 let r = cmp (stats1, rd1, stats2, rd2) in
1139 else compare (dev1, name1) (dev2, name2)
1141 List.sort ~cmp devs in
1143 (* Print the header for block devices. *)
1145 mvaddstr header_lineno 0
1146 (pad cols " ID S RDBY WRBY RDRQ WRRQ DOMAIN DEVICE");
1149 (* Print domains and devices. *)
1150 let rec loop lineno = function
1152 | (dev, name, rd, stats) :: devs ->
1153 if lineno < lines then (
1154 let state = show_state rd.rd_info.D.state in
1156 if stats.D.rd_bytes >= 0L
1157 then show_int64 stats.D.rd_bytes
1160 if stats.D.wr_bytes >= 0L
1161 then show_int64 stats.D.wr_bytes
1164 if stats.D.rd_req >= 0L
1165 then show_int64 stats.D.rd_req
1168 if stats.D.wr_req >= 0L
1169 then show_int64 stats.D.wr_req
1172 let line = sprintf "%5d %c %s %s %s %s %-12s %s"
1176 (pad 12 name) dev in
1177 let line = pad cols line in
1178 mvaddstr lineno 0 line;
1179 loop (lineno+1) devs
1182 loop domains_lineno devs
1183 ); (* end of display_mode conditional section *)
1185 let (count, running, blocked, paused, shutdown, shutoff,
1186 crashed, active, inactive,
1187 total_cpu_time, total_memory, total_domU_memory) = totals in
1189 mvaddstr summary_lineno 0
1190 (sprintf "%d domains, %d active, %d running, %d sleeping, %d paused, %d inactive D:%d O:%d X:%d"
1191 count active running blocked paused inactive shutdown shutoff
1194 (* Total %CPU used, and memory summary. *)
1195 let percent_cpu = 100. *. total_cpu_time /. total_cpu in
1196 mvaddstr (summary_lineno+1) 0
1197 (sprintf "CPU: %2.1f%% Mem: %Ld MB (%Ld MB by guests)"
1198 percent_cpu (total_memory /^ 1024L) (total_domU_memory /^ 1024L));
1200 (* Time to grab another historical %CPU for the list? *)
1201 if time >= !historical_cpu_last_time +. float !historical_cpu_delay
1203 historical_cpu := percent_cpu :: List.take 10 !historical_cpu;
1204 historical_cpu_last_time := time
1207 (* Display historical CPU time. *)
1209 let x, y = historical_cursor in (* Yes, it's a bug in ocaml-curses *)
1210 let maxwidth = cols - x in
1213 (List.map (sprintf "%2.1f%%") !historical_cpu) in
1214 let line = pad maxwidth line in
1218 move message_lineno 0; (* Park cursor in message area, as with top. *)
1219 refresh (); (* Refresh the display. *)
1222 (* Write CSV header row. *)
1223 let write_csv_header () =
1225 [ "Hostname"; "Time"; "Arch"; "Physical CPUs";
1226 "Count"; "Running"; "Blocked"; "Paused"; "Shutdown";
1227 "Shutoff"; "Crashed"; "Active"; "Inactive";
1228 "%CPU"; "Total memory (KB)"; "Total guest memory (KB)";
1229 "Total CPU time (ns)";
1230 (* These fields are repeated for each domain: *)
1231 "Domain ID"; "Domain name";
1233 "Block RDRQ"; "Block WRRQ";
1234 "Net RXBY"; "Net TXBY" ]
1236 (* Write summary data to CSV file. *)
1238 (_, _, _, _, node_info, hostname, _) (* setup *)
1241 nr_pcpus, total_cpu, _,
1245 (* The totals / summary fields. *)
1246 let (count, running, blocked, paused, shutdown, shutoff,
1247 crashed, active, inactive,
1248 total_cpu_time, total_memory, total_domU_memory) = totals in
1250 let percent_cpu = 100. *. total_cpu_time /. total_cpu in
1252 let summary_fields = [
1253 hostname; printable_time; node_info.C.model; string_of_int nr_pcpus;
1254 string_of_int count; string_of_int running; string_of_int blocked;
1255 string_of_int paused; string_of_int shutdown; string_of_int shutoff;
1256 string_of_int crashed; string_of_int active; string_of_int inactive;
1257 sprintf "%2.1f" percent_cpu;
1258 Int64.to_string total_memory; Int64.to_string total_domU_memory;
1259 Int64.to_string (Int64.of_float total_cpu_time)
1264 * Sort them by ID so that the list of relatively stable. Ignore
1267 let doms = List.filter_map (
1269 | _, Inactive -> None (* Ignore inactive domains. *)
1270 | name, Active rd -> Some (name, rd)
1272 let cmp (_, { rd_domid = rd_domid1 }) (_, { rd_domid = rd_domid2 }) =
1273 compare rd_domid1 rd_domid2
1275 let doms = List.sort ~cmp doms in
1277 let string_of_int64_option = Option.map_default Int64.to_string "" in
1279 let domain_fields = List.map (
1280 fun (domname, rd) ->
1281 [ string_of_int rd.rd_domid; domname;
1282 string_of_float rd.rd_cpu_time; string_of_float rd.rd_percent_cpu;
1283 string_of_int64_option rd.rd_block_rd_reqs;
1284 string_of_int64_option rd.rd_block_wr_reqs;
1285 string_of_int64_option rd.rd_net_rx_bytes;
1286 string_of_int64_option rd.rd_net_tx_bytes; ]
1288 let domain_fields = List.flatten domain_fields in
1290 (!csv_write) (summary_fields @ domain_fields)
1293 let rec main_loop ((_, batch_mode, script_mode, csv_enabled, _, _, _)
1295 if csv_enabled then write_csv_header ();
1298 let state = collect setup in (* Collect stats. *)
1299 if not script_mode then redraw setup state; (* Redraw display. *)
1300 if csv_enabled then append_csv setup state; (* Update CSV file. *)
1302 (* Clear up unused virDomainPtr objects. *)
1305 if not batch_mode && not script_mode then
1307 else (* Batch mode or script mode - just sleep, ignore keys. *)
1308 Unix.sleep (!delay / 1000);
1310 (* Max iterations? *)
1311 if !iterations >= 0 then (
1313 if !iterations = 0 then quit := true
1317 and get_key_press setup =
1318 (* Read the next key, waiting up to !delay milliseconds. *)
1321 timeout (-1); (* Reset to blocking mode. *)
1323 if k >= 0 && k <> 32 (* ' ' *) && k <> 12 (* ^L *) && k <> Key.resize
1325 if k = Char.code 'q' then quit := true
1326 else if k = Char.code 'h' then show_help setup
1327 else if k = Char.code 's' || k = Char.code 'd' then change_delay ()
1328 else if k = Char.code 'M' then sort_order := Memory
1329 else if k = Char.code 'P' then sort_order := Processor
1330 else if k = Char.code 'T' then sort_order := Time
1331 else if k = Char.code 'N' then sort_order := DomainID
1332 else if k = Char.code 'F' then change_sort_order ()
1333 else if k = Char.code '0' then set_tasks_display ()
1334 else if k = Char.code '1' then toggle_pcpu_display ()
1335 else if k = Char.code '2' then toggle_net_display ()
1336 else if k = Char.code '3' then toggle_block_display ()
1337 else if k = Char.code 'W' then write_init_file ()
1338 else unknown_command k
1341 and change_delay () =
1342 print_msg (sprintf "Change delay from %.1f to: " (float !delay /. 1000.));
1343 let str = get_string 16 in
1344 (* Try to parse the number. *)
1347 let newdelay = float_of_string str in
1348 if newdelay <= 0. then (
1349 print_msg "Delay must be > 0"; true
1351 delay := int_of_float (newdelay *. 1000.); false
1354 Failure "float_of_string" ->
1355 print_msg "Not a valid number"; true in
1356 sleep (if error then 2 else 1)
1358 and change_sort_order () =
1360 let lines, cols = get_size () in
1362 mvaddstr top_lineno 0 "Set sort order for main display";
1363 mvaddstr summary_lineno 0 "Type key or use up and down cursor keys.";
1366 mvaddstr header_lineno 0 (pad cols "KEY Sort field");
1369 let accelerator_key = function
1370 | Memory -> "(key: M)"
1371 | Processor -> "(key: P)"
1372 | Time -> "(key: T)"
1373 | DomainID -> "(key: N)"
1374 | _ -> (* all others have to be changed from here *) ""
1377 let rec key_of_int = function
1378 | i when i < 10 -> Char.chr (i + Char.code '0')
1379 | i when i < 20 -> Char.chr (i + Char.code 'a')
1381 and int_of_key = function
1382 | k when k >= 0x30 && k <= 0x39 (* '0' - '9' *) -> k - 0x30
1383 | k when k >= 0x61 && k <= 0x7a (* 'a' - 'j' *) -> k - 0x61 + 10
1384 | k when k >= 0x41 && k <= 0x6a (* 'A' - 'J' *) -> k - 0x41 + 10
1388 (* Display possible sort fields. *)
1389 let selected_index = ref 0 in
1392 let selected = !sort_order = ord in
1393 if selected then selected_index := i;
1394 mvaddstr (domains_lineno+i) 0
1395 (sprintf " %c %s %s %s"
1396 (key_of_int i) (if selected then "*" else " ")
1397 (printable_sort_order ord)
1398 (accelerator_key ord))
1401 move message_lineno 0;
1404 if k >= 0 && k <> 32 && k <> Char.code 'q' && k <> 13 then (
1405 let new_order, loop =
1406 (* Redraw the display. *)
1407 if k = 12 (* ^L *) then None, true
1408 (* Make the UP and DOWN arrow keys do something useful. *)
1409 else if k = Key.up then (
1410 if !selected_index > 0 then
1411 Some (List.nth all_sort_fields (!selected_index-1)), true
1415 else if k = Key.down then (
1416 if !selected_index < List.length all_sort_fields - 1 then
1417 Some (List.nth all_sort_fields (!selected_index+1)), true
1421 (* Also understand the regular accelerator keys. *)
1422 else if k = Char.code 'M' then
1424 else if k = Char.code 'P' then
1425 Some Processor, false
1426 else if k = Char.code 'T' then
1428 else if k = Char.code 'N' then
1429 Some DomainID, false
1431 (* It's one of the KEYs. *)
1432 let i = int_of_key k in
1433 if i >= 0 && i < List.length all_sort_fields then
1434 Some (List.nth all_sort_fields i), false
1439 (match new_order with
1442 sort_order := new_order;
1443 print_msg (sprintf "Sort order changed to: %s"
1444 (printable_sort_order new_order));
1445 if not loop then sleep 1
1448 if loop then change_sort_order ()
1451 (* Note: We need to clear_pcpu_display_data every time
1452 * we _leave_ PCPUDisplay mode.
1454 and set_tasks_display () = (* key 0 *)
1455 if !display_mode = PCPUDisplay then clear_pcpu_display_data ();
1456 display_mode := TaskDisplay
1458 and toggle_pcpu_display () = (* key 1 *)
1460 match !display_mode with
1461 | TaskDisplay | NetDisplay | BlockDisplay -> PCPUDisplay
1462 | PCPUDisplay -> clear_pcpu_display_data (); TaskDisplay
1464 and toggle_net_display () = (* key 2 *)
1466 match !display_mode with
1467 | PCPUDisplay -> clear_pcpu_display_data (); NetDisplay
1468 | TaskDisplay | BlockDisplay -> NetDisplay
1469 | NetDisplay -> TaskDisplay
1471 and toggle_block_display () = (* key 3 *)
1473 match !display_mode with
1474 | PCPUDisplay -> clear_pcpu_display_data (); BlockDisplay
1475 | TaskDisplay | NetDisplay -> BlockDisplay
1476 | BlockDisplay -> TaskDisplay
1478 (* Write an init file. *)
1479 and write_init_file () =
1480 match !init_file with
1481 | NoInitFile -> () (* Do nothing if --no-init-file *)
1482 | DefaultInitFile ->
1483 let home = try Sys.getenv "HOME" with Not_found -> "/" in
1484 let filename = home // ".virt-toprc" in
1485 _write_init_file filename
1486 | InitFile filename ->
1487 _write_init_file filename
1489 and _write_init_file filename =
1491 (* Create the new file as filename.new. *)
1492 let chan = open_out (filename ^ ".new") in
1494 let time = Unix.gettimeofday () in
1495 let tm = Unix.localtime time in
1496 let printable_date_time =
1497 sprintf "%04d-%02d-%02d %02d:%02d:%02d"
1498 (tm.Unix.tm_year + 1900) (tm.Unix.tm_mon+1) tm.Unix.tm_mday
1499 tm.Unix.tm_hour tm.Unix.tm_min tm.Unix.tm_sec in
1502 let uid = Unix.geteuid () in
1503 (Unix.getpwuid uid).Unix.pw_name
1505 Not_found -> "unknown" in
1508 let nl () = fp chan "\n" in
1509 fp chan "# .virt-toprc virt-top configuration file\n";
1510 fp chan "# generated on %s by %s\n" printable_date_time username;
1512 fp chan "display %s\n" (cli_of_display !display_mode);
1513 fp chan "delay %g\n" (float !delay /. 1000.);
1514 fp chan "hist-cpu %d\n" !historical_cpu_delay;
1515 if !iterations <> -1 then fp chan "iterations %d\n" !iterations;
1516 fp chan "sort %s\n" (cli_of_sort_order !sort_order);
1519 | Some uri -> fp chan "connect %s\n" uri
1521 if !batch_mode = true then fp chan "batch true\n";
1522 if !secure_mode = true then fp chan "secure true\n";
1524 fp chan "# To send debug and error messages to a file, uncomment next line\n";
1525 fp chan "#debug virt-top.out\n";
1527 fp chan "# Enable CSV output to the named file\n";
1528 fp chan "#csv virt-top.csv\n";
1530 fp chan "# To protect this file from being overwritten, uncomment next line\n";
1531 fp chan "#overwrite-init-file false\n";
1535 (* If the file exists, rename it as filename.old. *)
1536 (try Unix.rename filename (filename ^ ".old")
1537 with Unix.Unix_error _ -> ());
1539 (* Rename filename.new to filename. *)
1540 Unix.rename (filename ^ ".new") filename;
1542 print_msg (sprintf "Wrote settings to %s" filename); sleep 2
1544 | Sys_error err -> print_msg "Error: %s"; sleep 2
1545 | Unix.Unix_error (err, fn, str) ->
1546 print_msg (sprintf "Error: %s %s %s" (Unix.error_message err) fn str);
1549 and show_help (_, _, _, _, _, hostname,
1550 (libvirt_major, libvirt_minor, libvirt_release)) =
1553 (* Get the screen/window size. *)
1554 let lines, cols = get_size () in
1556 (* Banner at the top of the screen. *)
1558 sprintf "virt-top %s (libvirt %d.%d.%d) by Red Hat"
1559 Libvirt_version.version libvirt_major libvirt_minor libvirt_release in
1560 let banner = pad cols banner in
1562 mvaddstr 0 0 banner;
1567 (sprintf "Delay: %.1f secs; Batch: %s; Secure: %s; Sort: %s"
1568 (float !delay /. 1000.)
1569 (if !batch_mode then "On" else "Off")
1570 (if !secure_mode then "On" else "Off")
1571 (printable_sort_order !sort_order));
1573 (sprintf "Connect: %s; Hostname: %s"
1574 (match !uri with None -> "default" | Some s -> s)
1577 (* Misc keys on left. *)
1578 let banner = pad 38 "MAIN KEYS" in
1580 mvaddstr header_lineno 1 banner;
1584 let lineno = ref domains_lineno in
1585 fun () -> let i = !lineno in incr lineno; i
1587 let key keys description =
1588 let lineno = get_lineno () in
1589 move lineno 1; attron A.bold; addstr keys; attroff A.bold;
1590 move lineno 10; addstr description; ()
1592 key "space ^L" "Update display";
1594 key "d s" "Set update interval";
1598 ignore (get_lineno ());
1599 let banner = pad 38 "SORTING" in
1601 mvaddstr (get_lineno ()) 1 banner;
1604 key "P" "Sort by %CPU";
1605 key "M" "Sort by %MEM";
1606 key "T" "Sort by TIME";
1607 key "N" "Sort by ID";
1608 key "F" "Select sort field";
1610 (* Display modes on right. *)
1611 let banner = pad 39 "DISPLAY MODES" in
1613 mvaddstr header_lineno 40 banner;
1617 let lineno = ref domains_lineno in
1618 fun () -> let i = !lineno in incr lineno; i
1620 let key keys description =
1621 let lineno = get_lineno () in
1622 move lineno 40; attron A.bold; addstr keys; attroff A.bold;
1623 move lineno 49; addstr description; ()
1625 key "0" "Domains display";
1626 key "1" "Toggle physical CPUs";
1627 key "2" "Toggle network interfaces";
1628 key "3" "Toggle block devices";
1630 (* Update screen and wait for key press. *)
1631 mvaddstr (lines-1) 0
1632 "More help in virt-top(1) man page. Press any key to return.";
1636 and unknown_command k =
1637 print_msg "Unknown command - try 'h' for help";