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)
256 (* Show a percentage in 4 chars. *)
257 let show_percent percent =
258 if percent <= 0. then " 0.0"
259 else if percent <= 9.9 then sprintf " %1.1f" percent
260 else if percent <= 99.9 then sprintf "%2.1f" percent
263 (* Show an int64 option in 4 chars. *)
264 let rec show_int64_option = function
266 | Some n -> show_int64 n
267 (* Show an int64 in 4 chars. *)
268 and show_int64 = function
269 | n when n < 0L -> "-!!!"
270 | n when n <= 9999L ->
272 | n when n /^ 1024L <= 999L ->
273 sprintf "%3LdK" (n /^ 1024L)
274 | n when n /^ 1_048_576L <= 999L ->
275 sprintf "%3LdM" (n /^ 1_048_576L)
276 | n when n /^ 1_073_741_824L <= 999L ->
277 sprintf "%3LdG" (n /^ 1_073_741_824L)
280 (* Format the total time (may be large!) in 9 chars. *)
282 let secs_in_ns = 1_000_000_000L in
283 let mins_in_ns = 60_000_000_000L in
284 let hours_in_ns = 3_600_000_000_000L in
286 let hours = ns /^ hours_in_ns in
287 let ns = ns -^ (hours *^ hours_in_ns) in
288 let mins = ns /^ mins_in_ns in
289 let ns = ns -^ (mins *^ mins_in_ns) in
290 let secs = ns /^ secs_in_ns in
291 let ns = ns -^ (secs *^ secs_in_ns) in
292 let pennies = ns /^ 10_000_000L in
295 sprintf "%3Ld:%02Ld.%02Ld" (hours *^ 60L +^ mins) secs pennies
296 else if hours <= 999L then
297 sprintf "%3Ld:%02Ld:%02Ld" hours mins secs
299 let days = hours /^ 24L in
300 let hours = hours -^ (days *^ 24L) in
301 sprintf "%3Ldd%02Ld:%02Ld" days hours mins
304 (* Show a domain state (the 'S' column). *)
305 let show_state = function
306 | D.InfoNoState -> '?'
307 | D.InfoRunning -> 'R'
308 | D.InfoBlocked -> 'S'
309 | D.InfoPaused -> 'P'
310 | D.InfoShutdown -> 'D'
311 | D.InfoShutoff -> 'O'
312 | D.InfoCrashed -> 'X'
314 (* Sum Domain.block_stats structures together. Missing fields
315 * get forced to 0. Empty list returns all 0.
317 let zero_block_stats =
318 { D.rd_req = 0L; rd_bytes = 0L; wr_req = 0L; wr_bytes = 0L; errs = 0L }
319 let add_block_stats bs1 bs2 =
320 let add f1 f2 = if f1 >= 0L && f2 >= 0L then f1 +^ f2 else 0L in
321 { D.rd_req = add bs1.D.rd_req bs2.D.rd_req;
322 rd_bytes = add bs1.D.rd_bytes bs2.D.rd_bytes;
323 wr_req = add bs1.D.wr_req bs2.D.wr_req;
324 wr_bytes = add bs1.D.wr_bytes bs2.D.wr_bytes;
325 errs = add bs1.D.errs bs2.D.errs }
326 let sum_block_stats =
327 List.fold_left add_block_stats zero_block_stats
329 (* Get the difference between two block_stats structures. Missing data
330 * forces the difference to -1.
332 let diff_block_stats curr prev =
333 let sub f1 f2 = if f1 >= 0L && f2 >= 0L then f1 -^ f2 else -1L in
334 { D.rd_req = sub curr.D.rd_req prev.D.rd_req;
335 rd_bytes = sub curr.D.rd_bytes prev.D.rd_bytes;
336 wr_req = sub curr.D.wr_req prev.D.wr_req;
337 wr_bytes = sub curr.D.wr_bytes prev.D.wr_bytes;
338 errs = sub curr.D.errs prev.D.errs }
340 (* Sum Domain.interface_stats structures together. Missing fields
341 * get forced to 0. Empty list returns all 0.
343 let zero_interface_stats =
344 { D.rx_bytes = 0L; rx_packets = 0L; rx_errs = 0L; rx_drop = 0L;
345 tx_bytes = 0L; tx_packets = 0L; tx_errs = 0L; tx_drop = 0L }
346 let add_interface_stats is1 is2 =
347 let add f1 f2 = if f1 >= 0L && f2 >= 0L then f1 +^ f2 else 0L in
348 { D.rx_bytes = add is1.D.rx_bytes is2.D.rx_bytes;
349 rx_packets = add is1.D.rx_packets is2.D.rx_packets;
350 rx_errs = add is1.D.rx_errs is2.D.rx_errs;
351 rx_drop = add is1.D.rx_drop is2.D.rx_drop;
352 tx_bytes = add is1.D.tx_bytes is2.D.tx_bytes;
353 tx_packets = add is1.D.tx_packets is2.D.tx_packets;
354 tx_errs = add is1.D.tx_errs is2.D.tx_errs;
355 tx_drop = add is1.D.tx_drop is2.D.tx_drop }
356 let sum_interface_stats =
357 List.fold_left add_interface_stats zero_interface_stats
359 (* Get the difference between two interface_stats structures.
360 * Missing data forces the difference to -1.
362 let diff_interface_stats curr prev =
363 let sub f1 f2 = if f1 >= 0L && f2 >= 0L then f1 -^ f2 else -1L in
364 { D.rx_bytes = sub curr.D.rx_bytes prev.D.rx_bytes;
365 rx_packets = sub curr.D.rx_packets prev.D.rx_packets;
366 rx_errs = sub curr.D.rx_errs prev.D.rx_errs;
367 rx_drop = sub curr.D.rx_drop prev.D.rx_drop;
368 tx_bytes = sub curr.D.tx_bytes prev.D.tx_bytes;
369 tx_packets = sub curr.D.tx_packets prev.D.tx_packets;
370 tx_errs = sub curr.D.tx_errs prev.D.tx_errs;
371 tx_drop = sub curr.D.tx_drop prev.D.tx_drop }
373 (* Update the display and sleep for given number of seconds. *)
374 let sleep n = refresh (); Unix.sleep n
376 (* The curses getstr/getnstr functions are just weird.
377 * This helper function also enables echo temporarily.
379 let get_string maxlen =
381 let str = String.create maxlen in
382 let ok = getstr str in (* Safe because binding calls getnstr. *)
386 (* Chop at first '\0'. *)
388 let i = String.index str '\000' in
391 Not_found -> str (* it is full maxlen bytes *)
394 (* Pad a string to the full width with spaces. If too long, truncate. *)
396 let n = String.length str in
397 if n = width then str
398 else if n > width then String.sub str 0 width
399 else (* if n < width then *) str ^ String.make (width-n) ' '
403 let summary_lineno = 1 (* this takes 2 lines *)
404 let message_lineno = 3
405 let header_lineno = 4
406 let domains_lineno = 5
408 (* Print in the "message area". *)
409 let clear_msg () = move message_lineno 0; clrtoeol ()
410 let print_msg str = clear_msg (); mvaddstr message_lineno 0 str; ()
412 (* Write CSV header row. *)
413 let write_csv_header () =
414 (!csv_write) [ "Hostname"; "Time"; "Arch"; "Physical CPUs";
415 "Count"; "Running"; "Blocked"; "Paused"; "Shutdown";
416 "Shutoff"; "Crashed"; "Active"; "Inactive";
417 "%CPU"; "Total memory KB"; "Total guest memory KB";
418 "Total CPU time ns" ]
420 (* Intermediate "domain + stats" structure that we use to collect
421 * everything we know about a domain within the collect function.
423 type rd_domain = Inactive | Active of rd_active
425 rd_domid : int; (* Domain ID. *)
426 rd_dom : [`R] D.t; (* Domain object. *)
427 rd_info : D.info; (* Domain CPU info now. *)
428 rd_block_stats : (string * D.block_stats) list;
429 (* Domain block stats now. *)
430 rd_interface_stats : (string * D.interface_stats) list;
431 (* Domain net stats now. *)
432 rd_prev_info : D.info option; (* Domain CPU info previously. *)
433 rd_prev_block_stats : (string * D.block_stats) list;
434 (* Domain block stats prev. *)
435 rd_prev_interface_stats : (string * D.interface_stats) list;
436 (* Domain interface stats prev. *)
437 (* The following are since the last slice, or 0 if cannot be calculated: *)
438 rd_cpu_time : float; (* CPU time used in nanoseconds. *)
439 rd_percent_cpu : float; (* CPU time as percent of total. *)
440 (* The following are since the last slice, or None if cannot be calc'd: *)
441 rd_block_rd_reqs : int64 option; (* Number of block device read rqs. *)
442 rd_block_wr_reqs : int64 option; (* Number of block device write rqs. *)
443 rd_net_rx_bytes : int64 option; (* Number of bytes received. *)
444 rd_net_tx_bytes : int64 option; (* Number of bytes transmitted. *)
448 let collect, clear_pcpu_display_data =
449 (* We cache the list of block devices and interfaces for each domain
450 * here, so we don't need to reparse the XML each time.
452 let devices = Hashtbl.create 13 in
454 (* Function to get the list of block devices, network interfaces for
455 * a particular domain. Get it from the devices cache, and if not
456 * there then parse the domain XML.
458 let get_devices id dom =
459 try Hashtbl.find devices id
461 let blkdevs, netifs = (!parse_device_xml) id dom in
462 Hashtbl.replace devices id (blkdevs, netifs);
466 (* We save the state of domains across redraws here, which allows us
467 * to deduce %CPU usage from the running total.
469 let last_info = Hashtbl.create 13 in
470 let last_time = ref (Unix.gettimeofday ()) in
472 (* Save vcpuinfo structures across redraws too (only for pCPU display). *)
473 let last_vcpu_info = Hashtbl.create 13 in
475 let clear_pcpu_display_data () =
476 (* Clear out vcpu_info used by PCPUDisplay display_mode
477 * when we switch back to TaskDisplay mode.
479 Hashtbl.clear last_vcpu_info
482 let collect (conn, _, _, _, node_info, _, _) =
483 (* Number of physical CPUs (some may be disabled). *)
484 let nr_pcpus = C.maxcpus_of_node_info node_info in
486 (* Get the current time. *)
487 let time = Unix.gettimeofday () in
488 let tm = Unix.localtime time in
490 sprintf "%02d:%02d:%02d" tm.Unix.tm_hour tm.Unix.tm_min tm.Unix.tm_sec in
491 mvaddstr top_lineno 0 ("virt-top " ^ printable_time ^ " - ");
493 (* What's the total CPU time elapsed since we were last called? (ns) *)
494 let total_cpu_per_pcpu = 1_000_000_000. *. (time -. !last_time) in
495 (* Avoid division by zero. *)
496 let total_cpu_per_pcpu =
497 if total_cpu_per_pcpu <= 0. then 1. else total_cpu_per_pcpu in
498 let total_cpu = float node_info.C.cpus *. total_cpu_per_pcpu in
500 (* Get the domains. Match up with their last_info (if any). *)
502 (* Active domains. *)
503 let n = C.num_of_domains conn in
505 if n > 0 then Array.to_list (C.list_domains conn n)
511 let dom = D.lookup_by_id conn id in
512 let name = D.get_name dom in
513 let blkdevs, netifs = get_devices id dom in
515 (* Get current CPU, block and network stats. *)
516 let info = D.get_info dom in
518 try List.map (fun dev -> dev, D.block_stats dom dev) blkdevs
520 | Invalid_argument "virDomainBlockStats not supported"
521 | Libvirt.Virterror _ -> [] in
522 let interface_stats =
523 try List.map (fun dev -> dev, D.interface_stats dom dev) netifs
525 | Invalid_argument "virDomainInterfaceStats not supported"
526 | Libvirt.Virterror _ -> [] in
528 let prev_info, prev_block_stats, prev_interface_stats =
530 let prev_info, prev_block_stats, prev_interface_stats =
531 Hashtbl.find last_info id in
532 Some prev_info, prev_block_stats, prev_interface_stats
533 with Not_found -> None, [], [] in
536 rd_domid = id; rd_dom = dom; rd_info = info;
537 rd_block_stats = block_stats;
538 rd_interface_stats = interface_stats;
539 rd_prev_info = prev_info;
540 rd_prev_block_stats = prev_block_stats;
541 rd_prev_interface_stats = prev_interface_stats;
542 rd_cpu_time = 0.; rd_percent_cpu = 0.;
543 rd_block_rd_reqs = None; rd_block_wr_reqs = None;
544 rd_net_rx_bytes = None; rd_net_tx_bytes = None;
547 Libvirt.Virterror _ -> None (* ignore transient error *)
550 (* Inactive domains. *)
553 let n = C.num_of_defined_domains conn in
555 if n > 0 then Array.to_list (C.list_defined_domains conn n)
557 List.map (fun name -> name, Inactive) names
559 (* Ignore transient errors, in particular errors from
560 * num_of_defined_domains if it cannot contact xend.
562 | Libvirt.Virterror _ -> [] in
564 doms @ doms_inactive in
566 (* Calculate the CPU time (ns) and %CPU used by each domain. *)
570 (* We have previous CPU info from which to calculate it? *)
571 | name, Active ({ rd_prev_info = Some prev_info } as rd) ->
573 Int64.to_float (rd.rd_info.D.cpu_time -^ prev_info.D.cpu_time) in
574 let percent_cpu = 100. *. cpu_time /. total_cpu in
576 rd_cpu_time = cpu_time;
577 rd_percent_cpu = percent_cpu } in
579 (* For all other domains we can't calculate it, so leave as 0 *)
583 (* Calculate the number of block device read/write requests across
584 * all block devices attached to a domain.
589 (* Do we have stats from the previous slice? *)
590 | name, Active ({ rd_prev_block_stats = ((_::_) as prev_block_stats) }
592 let block_stats = rd.rd_block_stats in (* stats now *)
594 (* Add all the devices together. Throw away device names. *)
595 let prev_block_stats =
596 sum_block_stats (List.map snd prev_block_stats) in
598 sum_block_stats (List.map snd block_stats) in
600 (* Calculate increase in read & write requests. *)
602 block_stats.D.rd_req -^ prev_block_stats.D.rd_req in
604 block_stats.D.wr_req -^ prev_block_stats.D.wr_req in
607 rd_block_rd_reqs = Some read_reqs;
608 rd_block_wr_reqs = Some write_reqs } in
610 (* For all other domains we can't calculate it, so leave as None. *)
614 (* Calculate the same as above for network interfaces across
615 * all network interfaces attached to a domain.
620 (* Do we have stats from the previous slice? *)
621 | name, Active ({ rd_prev_interface_stats =
622 ((_::_) as prev_interface_stats) }
624 let interface_stats = rd.rd_interface_stats in (* stats now *)
626 (* Add all the devices together. Throw away device names. *)
627 let prev_interface_stats =
628 sum_interface_stats (List.map snd prev_interface_stats) in
629 let interface_stats =
630 sum_interface_stats (List.map snd interface_stats) in
632 (* Calculate increase in rx & tx bytes. *)
634 interface_stats.D.rx_bytes -^ prev_interface_stats.D.rx_bytes in
636 interface_stats.D.tx_bytes -^ prev_interface_stats.D.tx_bytes in
639 rd_net_rx_bytes = Some rx_bytes;
640 rd_net_tx_bytes = Some tx_bytes } in
642 (* For all other domains we can't calculate it, so leave as None. *)
646 (* Collect some extra information in PCPUDisplay display_mode. *)
648 if !display_mode = PCPUDisplay then (
649 (* Get the VCPU info and VCPU->PCPU mappings for active domains.
650 * Also cull some data we don't care about.
652 let doms = List.filter_map (
654 | (name, Active rd) ->
656 let domid = rd.rd_domid in
657 let maplen = C.cpumaplen nr_pcpus in
658 let maxinfo = rd.rd_info.D.nr_virt_cpu in
659 let nr_vcpus, vcpu_infos, cpumaps =
660 D.get_vcpus rd.rd_dom maxinfo maplen in
662 (* Got previous vcpu_infos for this domain? *)
663 let prev_vcpu_infos =
664 try Some (Hashtbl.find last_vcpu_info domid)
665 with Not_found -> None in
666 (* Update last_vcpu_info. *)
667 Hashtbl.replace last_vcpu_info domid vcpu_infos;
669 (match prev_vcpu_infos with
670 | Some prev_vcpu_infos
671 when Array.length prev_vcpu_infos = Array.length vcpu_infos ->
672 Some (domid, name, nr_vcpus, vcpu_infos, prev_vcpu_infos,
674 | _ -> None (* ignore missing / unequal length prev_vcpu_infos *)
677 Libvirt.Virterror _ -> None(* ignore transient libvirt errs *)
679 | (_, Inactive) -> None (* ignore inactive doms *)
681 let nr_doms = List.length doms in
683 (* Rearrange the data into a matrix. Major axis (down) is
684 * pCPUs. Minor axis (right) is domains. At each node we store:
685 * cpu_time (on this pCPU only, nanosecs),
686 * average? (if set, then cpu_time is an average because the
687 * vCPU is pinned to more than one pCPU)
688 * running? (if set, we were instantaneously running on this pCPU)
690 let empty_node = (0L, false, false) in
691 let pcpus = Array.make_matrix nr_pcpus nr_doms empty_node in
694 fun di (domid, name, nr_vcpus, vcpu_infos, prev_vcpu_infos,
696 (* Which pCPUs can this dom run on? *)
697 for v = 0 to nr_vcpus-1 do
698 let pcpu = vcpu_infos.(v).D.cpu in (* instantaneous pCPU *)
699 let nr_poss_pcpus = ref 0 in (* how many pcpus can it run on? *)
700 for p = 0 to nr_pcpus-1 do
701 (* vcpu v can reside on pcpu p *)
702 if C.cpu_usable cpumaps maplen v p then
705 let nr_poss_pcpus = Int64.of_int !nr_poss_pcpus in
706 for p = 0 to nr_pcpus-1 do
707 (* vcpu v can reside on pcpu p *)
708 if C.cpu_usable cpumaps maplen v p then
709 let vcpu_time_on_pcpu =
710 vcpu_infos.(v).D.vcpu_time
711 -^ prev_vcpu_infos.(v).D.vcpu_time in
712 let vcpu_time_on_pcpu =
713 vcpu_time_on_pcpu /^ nr_poss_pcpus in
715 (vcpu_time_on_pcpu, nr_poss_pcpus > 1L, p = pcpu)
720 (* Sum the CPU time used by each pCPU, for the %CPU column. *)
721 let pcpus_cpu_time = Array.map (
723 let cpu_time = ref 0L in
724 for di = 0 to Array.length row-1 do
725 let t, _, _ = row.(di) in
726 cpu_time := !cpu_time +^ t
728 Int64.to_float !cpu_time
731 Some (doms, pcpus, pcpus_cpu_time)
735 (* Calculate totals. *)
736 let totals = List.fold_left (
737 fun (count, running, blocked, paused, shutdown, shutoff,
738 crashed, active, inactive,
739 total_cpu_time, total_memory, total_domU_memory) ->
741 | (name, Active rd) ->
742 let test state orig =
743 if rd.rd_info.D.state = state then orig+1 else orig
745 let running = test D.InfoRunning running in
746 let blocked = test D.InfoBlocked blocked in
747 let paused = test D.InfoPaused paused in
748 let shutdown = test D.InfoShutdown shutdown in
749 let shutoff = test D.InfoShutoff shutoff in
750 let crashed = test D.InfoCrashed crashed in
752 let total_cpu_time = total_cpu_time +. rd.rd_cpu_time in
753 let total_memory = total_memory +^ rd.rd_info.D.memory in
754 let total_domU_memory = total_domU_memory +^
755 if rd.rd_domid > 0 then rd.rd_info.D.memory else 0L in
757 (count+1, running, blocked, paused, shutdown, shutoff,
758 crashed, active+1, inactive,
759 total_cpu_time, total_memory, total_domU_memory)
761 | (name, Inactive) -> (* inactive domain *)
762 (count+1, running, blocked, paused, shutdown, shutoff,
763 crashed, active, inactive+1,
764 total_cpu_time, total_memory, total_domU_memory)
765 ) (0,0,0,0,0,0,0,0,0, 0.,0L,0L) doms in
767 (* Update last_time, last_info. *)
769 Hashtbl.clear last_info;
773 let info = rd.rd_info, rd.rd_block_stats, rd.rd_interface_stats in
774 Hashtbl.add last_info rd.rd_domid info
779 time, printable_time,
780 nr_pcpus, total_cpu, total_cpu_per_pcpu,
785 collect, clear_pcpu_display_data
787 (* Redraw the display. *)
789 (* Keep a historical list of %CPU usages. *)
790 let historical_cpu = ref [] in
791 let historical_cpu_last_time = ref (Unix.gettimeofday ()) in
793 (_, _, _, _, node_info, _, _) (* setup *)
795 time, printable_time,
796 nr_pcpus, total_cpu, total_cpu_per_pcpu,
798 pcpu_display) (* state *) ->
801 (* Get the screen/window size. *)
802 let lines, cols = get_size () in
804 (* Basic node_info. *)
805 addstr (sprintf "%s %d/%dCPU %dMHz %LdMB "
806 node_info.C.model node_info.C.cpus nr_pcpus node_info.C.mhz
807 (node_info.C.memory /^ 1024L));
808 (* Save the cursor position for when we come to draw the
809 * historical CPU times (down in this function).
811 let stdscr = stdscr () in
812 let historical_cursor = getyx stdscr in
814 (match !display_mode with
815 | TaskDisplay -> (*---------- Showing domains ----------*)
816 (* Sort domains on current sort_order. *)
819 match !sort_order with
821 (fun _ -> 0) (* fallthrough to default name compare *)
824 | Active rd1, Active rd2 ->
825 compare rd2.rd_percent_cpu rd1.rd_percent_cpu
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.memory info1.D.memory
833 | Active _, Inactive -> -1
834 | Inactive, Active _ -> 1
835 | Inactive, Inactive -> 0)
838 | Active { rd_info = info1 }, Active { rd_info = info2 } ->
839 compare info2.D.cpu_time info1.D.cpu_time
840 | Active _, Inactive -> -1
841 | Inactive, Active _ -> 1
842 | Inactive, Inactive -> 0)
845 | Active { rd_domid = id1 }, Active { rd_domid = id2 } ->
847 | Active _, Inactive -> -1
848 | Inactive, Active _ -> 1
849 | Inactive, Inactive -> 0)
852 | Active { rd_net_rx_bytes = r1 }, Active { rd_net_rx_bytes = r2 } ->
854 | Active _, Inactive -> -1
855 | Inactive, Active _ -> 1
856 | Inactive, Inactive -> 0)
859 | Active { rd_net_tx_bytes = r1 }, Active { rd_net_tx_bytes = r2 } ->
861 | Active _, Inactive -> -1
862 | Inactive, Active _ -> 1
863 | Inactive, Inactive -> 0)
866 | Active { rd_block_rd_reqs = r1 }, Active { rd_block_rd_reqs = r2 } ->
868 | Active _, Inactive -> -1
869 | Inactive, Active _ -> 1
870 | Inactive, Inactive -> 0)
873 | Active { rd_block_wr_reqs = r1 }, Active { rd_block_wr_reqs = r2 } ->
875 | Active _, Inactive -> -1
876 | Inactive, Active _ -> 1
877 | Inactive, Inactive -> 0)
879 let cmp (name1, dom1) (name2, dom2) =
880 let r = cmp (dom1, dom2) in
882 else compare name1 name2
884 List.sort ~cmp doms in
888 mvaddstr header_lineno 0
889 (pad cols " ID S RDRQ WRRQ RXBY TXBY %CPU %MEM TIME NAME");
892 let rec loop lineno = function
894 | (name, Active rd) :: doms ->
895 if lineno < lines then (
896 let state = show_state rd.rd_info.D.state in
897 let rd_req = show_int64_option rd.rd_block_rd_reqs in
898 let wr_req = show_int64_option rd.rd_block_wr_reqs in
899 let rx_bytes = show_int64_option rd.rd_net_rx_bytes in
900 let tx_bytes = show_int64_option rd.rd_net_tx_bytes in
901 let percent_cpu = show_percent rd.rd_percent_cpu in
903 100L *^ rd.rd_info.D.memory /^ node_info.C.memory in
904 let percent_mem = Int64.to_float percent_mem in
905 let percent_mem = show_percent percent_mem in
906 let time = show_time rd.rd_info.D.cpu_time in
908 let line = sprintf "%5d %c %s %s %s %s %s %s %s %s"
909 rd.rd_domid state rd_req wr_req rx_bytes tx_bytes
910 percent_cpu percent_mem time name in
911 let line = pad cols line in
912 mvaddstr lineno 0 line;
915 | (name, Inactive) :: doms -> (* inactive domain *)
916 if lineno < lines then (
921 let line = pad cols line in
922 mvaddstr lineno 0 line;
926 loop domains_lineno doms
928 | PCPUDisplay -> (*---------- Showing physical CPUs ----------*)
929 let doms, pcpus, pcpus_cpu_time =
930 match pcpu_display with
932 | None -> failwith "internal error: no pcpu_display data" in
934 (* Display the pCPUs. *)
938 fun (_, name, _, _, _, _, _) ->
939 let len = String.length name in
940 let width = max (len+1) 7 in
945 mvaddstr header_lineno 0 (pad cols ("PHYCPU %CPU " ^ dom_names));
950 mvaddstr (p+domains_lineno) 0 (sprintf "%4d " p);
951 let cpu_time = pcpus_cpu_time.(p) in (* ns used on this CPU *)
952 let percent_cpu = 100. *. cpu_time /. total_cpu_per_pcpu in
953 addstr (show_percent percent_cpu);
957 fun di (domid, name, _, _, _, _, _) ->
958 let t, is_average, is_running = pcpus.(p).(di) in
959 let len = String.length name in
960 let width = max (len+1) 7 in
964 let t = Int64.to_float t in
965 let percent = 100. *. t /. total_cpu_per_pcpu in
966 sprintf "%s%c%c " (show_percent percent)
967 (if is_average then '=' else ' ')
968 (if is_running then '#' else ' ')
970 addstr (pad width str);
975 | NetDisplay -> (*---------- Showing network interfaces ----------*)
976 (* Only care about active domains. *)
977 let doms = List.filter_map (
979 | (name, Active rd) -> Some (name, rd)
980 | (_, Inactive) -> None
983 (* For each domain we have a list of network interfaces seen
984 * this slice, and seen in the previous slice, which we now
985 * match up to get a list of (domain, interface) for which
986 * we have current & previous knowledge. (And ignore the rest).
994 (* Have prev slice stats for this device? *)
996 List.assoc dev rd.rd_prev_interface_stats in
997 Some (dev, name, rd, stats, prev_stats)
998 with Not_found -> None
999 ) rd.rd_interface_stats
1002 (* Finally we have a list of:
1003 * device name, domain name, rd_* stuff, curr stats, prev stats.
1005 let devs : (string * string * rd_active *
1006 D.interface_stats * D.interface_stats) list =
1007 List.flatten devs in
1009 (* Difference curr slice & prev slice. *)
1010 let devs = List.map (
1011 fun (dev, name, rd, curr, prev) ->
1012 dev, name, rd, diff_interface_stats curr prev
1015 (* Sort by current sort order, but map some of the standard
1016 * sort orders into ones which makes sense here.
1020 match !sort_order with
1022 (fun _ -> 0) (* fallthrough to default name compare *)
1024 (fun (_, { rd_domid = id1 }, _, { rd_domid = id2 }) ->
1026 | Processor | Memory | Time | BlockRdRq | BlockWrRq
1027 (* fallthrough to RXBY comparison. *)
1029 (fun ({ D.rx_bytes = b1 }, _, { D.rx_bytes = b2 }, _) ->
1032 (fun ({ D.tx_bytes = b1 }, _, { D.tx_bytes = b2 }, _) ->
1035 let cmp (dev1, name1, rd1, stats1) (dev2, name2, rd2, stats2) =
1036 let r = cmp (stats1, rd1, stats2, rd2) in
1038 else compare (dev1, name1) (dev2, name2)
1040 List.sort ~cmp devs in
1042 (* Print the header for network devices. *)
1044 mvaddstr header_lineno 0
1045 (pad cols " ID S RXBY TXBY RXPK TXPK DOMAIN INTERFACE");
1048 (* Print domains and devices. *)
1049 let rec loop lineno = function
1051 | (dev, name, rd, stats) :: devs ->
1052 if lineno < lines then (
1053 let state = show_state rd.rd_info.D.state in
1055 if stats.D.rx_bytes >= 0L
1056 then show_int64 stats.D.rx_bytes
1059 if stats.D.tx_bytes >= 0L
1060 then show_int64 stats.D.tx_bytes
1063 if stats.D.rx_packets >= 0L
1064 then show_int64 stats.D.rx_packets
1067 if stats.D.tx_packets >= 0L
1068 then show_int64 stats.D.tx_packets
1071 let line = sprintf "%5d %c %s %s %s %s %-12s %s"
1074 rx_packets tx_packets
1075 (pad 12 name) dev in
1076 let line = pad cols line in
1077 mvaddstr lineno 0 line;
1078 loop (lineno+1) devs
1081 loop domains_lineno devs
1083 | BlockDisplay -> (*---------- Showing block devices ----------*)
1084 (* Only care about active domains. *)
1085 let doms = List.filter_map (
1087 | (name, Active rd) -> Some (name, rd)
1088 | (_, Inactive) -> None
1091 (* For each domain we have a list of block devices seen
1092 * this slice, and seen in the previous slice, which we now
1093 * match up to get a list of (domain, device) for which
1094 * we have current & previous knowledge. (And ignore the rest).
1102 (* Have prev slice stats for this device? *)
1104 List.assoc dev rd.rd_prev_block_stats in
1105 Some (dev, name, rd, stats, prev_stats)
1106 with Not_found -> None
1110 (* Finally we have a list of:
1111 * device name, domain name, rd_* stuff, curr stats, prev stats.
1113 let devs : (string * string * rd_active *
1114 D.block_stats * D.block_stats) list =
1115 List.flatten devs in
1117 (* Difference curr slice & prev slice. *)
1118 let devs = List.map (
1119 fun (dev, name, rd, curr, prev) ->
1120 dev, name, rd, diff_block_stats curr prev
1123 (* Sort by current sort order, but map some of the standard
1124 * sort orders into ones which makes sense here.
1128 match !sort_order with
1130 (fun _ -> 0) (* fallthrough to default name compare *)
1132 (fun (_, { rd_domid = id1 }, _, { rd_domid = id2 }) ->
1134 | Processor | Memory | Time | NetRX | NetTX
1135 (* fallthrough to RDRQ comparison. *)
1137 (fun ({ D.rd_req = b1 }, _, { D.rd_req = b2 }, _) ->
1140 (fun ({ D.wr_req = b1 }, _, { D.wr_req = b2 }, _) ->
1143 let cmp (dev1, name1, rd1, stats1) (dev2, name2, rd2, stats2) =
1144 let r = cmp (stats1, rd1, stats2, rd2) in
1146 else compare (dev1, name1) (dev2, name2)
1148 List.sort ~cmp devs in
1150 (* Print the header for block devices. *)
1152 mvaddstr header_lineno 0
1153 (pad cols " ID S RDBY WRBY RDRQ WRRQ DOMAIN DEVICE");
1156 (* Print domains and devices. *)
1157 let rec loop lineno = function
1159 | (dev, name, rd, stats) :: devs ->
1160 if lineno < lines then (
1161 let state = show_state rd.rd_info.D.state in
1163 if stats.D.rd_bytes >= 0L
1164 then show_int64 stats.D.rd_bytes
1167 if stats.D.wr_bytes >= 0L
1168 then show_int64 stats.D.wr_bytes
1171 if stats.D.rd_req >= 0L
1172 then show_int64 stats.D.rd_req
1175 if stats.D.wr_req >= 0L
1176 then show_int64 stats.D.wr_req
1179 let line = sprintf "%5d %c %s %s %s %s %-12s %s"
1183 (pad 12 name) dev in
1184 let line = pad cols line in
1185 mvaddstr lineno 0 line;
1186 loop (lineno+1) devs
1189 loop domains_lineno devs
1190 ); (* end of display_mode conditional section *)
1192 let (count, running, blocked, paused, shutdown, shutoff,
1193 crashed, active, inactive,
1194 total_cpu_time, total_memory, total_domU_memory) = totals in
1196 mvaddstr summary_lineno 0
1197 (sprintf "%d domains, %d active, %d running, %d sleeping, %d paused, %d inactive D:%d O:%d X:%d"
1198 count active running blocked paused inactive shutdown shutoff
1201 (* Total %CPU used, and memory summary. *)
1202 let percent_cpu = 100. *. total_cpu_time /. total_cpu in
1203 mvaddstr (summary_lineno+1) 0
1204 (sprintf "CPU: %2.1f%% Mem: %Ld MB (%Ld MB by guests)"
1205 percent_cpu (total_memory /^ 1024L) (total_domU_memory /^ 1024L));
1207 (* Time to grab another historical %CPU for the list? *)
1208 if time >= !historical_cpu_last_time +. float !historical_cpu_delay
1210 historical_cpu := percent_cpu :: List.take 10 !historical_cpu;
1211 historical_cpu_last_time := time
1214 (* Display historical CPU time. *)
1216 let x, y = historical_cursor in (* Yes, it's a bug in ocaml-curses *)
1217 let maxwidth = cols - x in
1220 (List.map (sprintf "%2.1f%%") !historical_cpu) in
1221 let line = pad maxwidth line in
1225 move message_lineno 0; (* Park cursor in message area, as with top. *)
1226 refresh (); (* Refresh the display. *)
1229 (* Write summary data to CSV file. See also write_csv_header (). *)
1231 (_, _, _, _, node_info, hostname, _) (* setup *)
1234 nr_pcpus, total_cpu, _,
1237 let (count, running, blocked, paused, shutdown, shutoff,
1238 crashed, active, inactive,
1239 total_cpu_time, total_memory, total_domU_memory) = totals in
1241 let percent_cpu = 100. *. total_cpu_time /. total_cpu in
1244 hostname; printable_time; node_info.C.model; string_of_int nr_pcpus;
1245 string_of_int count; string_of_int running; string_of_int blocked;
1246 string_of_int paused; string_of_int shutdown; string_of_int shutoff;
1247 string_of_int crashed; string_of_int active; string_of_int inactive;
1248 sprintf "%2.1f" percent_cpu;
1249 Int64.to_string total_memory; Int64.to_string total_domU_memory;
1250 Int64.to_string (Int64.of_float total_cpu_time)
1254 let rec main_loop ((_, batch_mode, script_mode, csv_enabled, _, _, _)
1256 if csv_enabled then write_csv_header ();
1259 let state = collect setup in (* Collect stats. *)
1260 if not script_mode then redraw setup state; (* Redraw display. *)
1261 if csv_enabled then append_csv setup state; (* Update CSV file. *)
1263 (* Clear up unused virDomainPtr objects. *)
1266 if not batch_mode && not script_mode then
1268 else (* Batch mode or script mode - just sleep, ignore keys. *)
1269 Unix.sleep (!delay / 1000);
1271 (* Max iterations? *)
1272 if !iterations >= 0 then (
1274 if !iterations = 0 then quit := true
1278 and get_key_press setup =
1279 (* Read the next key, waiting up to !delay milliseconds. *)
1282 timeout (-1); (* Reset to blocking mode. *)
1284 if k >= 0 && k <> 32 (* ' ' *) && k <> 12 (* ^L *) && k <> Key.resize
1286 if k = Char.code 'q' then quit := true
1287 else if k = Char.code 'h' then show_help setup
1288 else if k = Char.code 's' || k = Char.code 'd' then change_delay ()
1289 else if k = Char.code 'M' then sort_order := Memory
1290 else if k = Char.code 'P' then sort_order := Processor
1291 else if k = Char.code 'T' then sort_order := Time
1292 else if k = Char.code 'N' then sort_order := DomainID
1293 else if k = Char.code 'F' then change_sort_order ()
1294 else if k = Char.code '0' then set_tasks_display ()
1295 else if k = Char.code '1' then toggle_pcpu_display ()
1296 else if k = Char.code '2' then toggle_net_display ()
1297 else if k = Char.code '3' then toggle_block_display ()
1298 else if k = Char.code 'W' then write_init_file ()
1299 else unknown_command k
1302 and change_delay () =
1303 print_msg (sprintf "Change delay from %.1f to: " (float !delay /. 1000.));
1304 let str = get_string 16 in
1305 (* Try to parse the number. *)
1308 let newdelay = float_of_string str in
1309 if newdelay <= 0. then (
1310 print_msg "Delay must be > 0"; true
1312 delay := int_of_float (newdelay *. 1000.); false
1315 Failure "float_of_string" ->
1316 print_msg "Not a valid number"; true in
1317 sleep (if error then 2 else 1)
1319 and change_sort_order () =
1321 let lines, cols = get_size () in
1323 mvaddstr top_lineno 0 "Set sort order for main display";
1324 mvaddstr summary_lineno 0 "Type key or use up and down cursor keys.";
1327 mvaddstr header_lineno 0 (pad cols "KEY Sort field");
1330 let accelerator_key = function
1331 | Memory -> "(key: M)"
1332 | Processor -> "(key: P)"
1333 | Time -> "(key: T)"
1334 | DomainID -> "(key: N)"
1335 | _ -> (* all others have to be changed from here *) ""
1338 let rec key_of_int = function
1339 | i when i < 10 -> Char.chr (i + Char.code '0')
1340 | i when i < 20 -> Char.chr (i + Char.code 'a')
1342 and int_of_key = function
1343 | k when k >= 0x30 && k <= 0x39 (* '0' - '9' *) -> k - 0x30
1344 | k when k >= 0x61 && k <= 0x7a (* 'a' - 'j' *) -> k - 0x61 + 10
1345 | k when k >= 0x41 && k <= 0x6a (* 'A' - 'J' *) -> k - 0x41 + 10
1349 (* Display possible sort fields. *)
1350 let selected_index = ref 0 in
1353 let selected = !sort_order = ord in
1354 if selected then selected_index := i;
1355 mvaddstr (domains_lineno+i) 0
1356 (sprintf " %c %s %s %s"
1357 (key_of_int i) (if selected then "*" else " ")
1358 (printable_sort_order ord)
1359 (accelerator_key ord))
1362 move message_lineno 0;
1365 if k >= 0 && k <> 32 && k <> Char.code 'q' && k <> 13 then (
1366 let new_order, loop =
1367 (* Redraw the display. *)
1368 if k = 12 (* ^L *) then None, true
1369 (* Make the UP and DOWN arrow keys do something useful. *)
1370 else if k = Key.up then (
1371 if !selected_index > 0 then
1372 Some (List.nth all_sort_fields (!selected_index-1)), true
1376 else if k = Key.down then (
1377 if !selected_index < List.length all_sort_fields - 1 then
1378 Some (List.nth all_sort_fields (!selected_index+1)), true
1382 (* Also understand the regular accelerator keys. *)
1383 else if k = Char.code 'M' then
1385 else if k = Char.code 'P' then
1386 Some Processor, false
1387 else if k = Char.code 'T' then
1389 else if k = Char.code 'N' then
1390 Some DomainID, false
1392 (* It's one of the KEYs. *)
1393 let i = int_of_key k in
1394 if i >= 0 && i < List.length all_sort_fields then
1395 Some (List.nth all_sort_fields i), false
1400 (match new_order with
1403 sort_order := new_order;
1404 print_msg (sprintf "Sort order changed to: %s"
1405 (printable_sort_order new_order));
1406 if not loop then sleep 1
1409 if loop then change_sort_order ()
1412 (* Note: We need to clear_pcpu_display_data every time
1413 * we _leave_ PCPUDisplay mode.
1415 and set_tasks_display () = (* key 0 *)
1416 if !display_mode = PCPUDisplay then clear_pcpu_display_data ();
1417 display_mode := TaskDisplay
1419 and toggle_pcpu_display () = (* key 1 *)
1421 match !display_mode with
1422 | TaskDisplay | NetDisplay | BlockDisplay -> PCPUDisplay
1423 | PCPUDisplay -> clear_pcpu_display_data (); TaskDisplay
1425 and toggle_net_display () = (* key 2 *)
1427 match !display_mode with
1428 | PCPUDisplay -> clear_pcpu_display_data (); NetDisplay
1429 | TaskDisplay | BlockDisplay -> NetDisplay
1430 | NetDisplay -> TaskDisplay
1432 and toggle_block_display () = (* key 3 *)
1434 match !display_mode with
1435 | PCPUDisplay -> clear_pcpu_display_data (); BlockDisplay
1436 | TaskDisplay | NetDisplay -> BlockDisplay
1437 | BlockDisplay -> TaskDisplay
1439 (* Write an init file. *)
1440 and write_init_file () =
1441 match !init_file with
1442 | NoInitFile -> () (* Do nothing if --no-init-file *)
1443 | DefaultInitFile ->
1444 let home = try Sys.getenv "HOME" with Not_found -> "/" in
1445 let filename = home // ".virt-toprc" in
1446 _write_init_file filename
1447 | InitFile filename ->
1448 _write_init_file filename
1450 and _write_init_file filename =
1452 (* Create the new file as filename.new. *)
1453 let chan = open_out (filename ^ ".new") in
1455 let time = Unix.gettimeofday () in
1456 let tm = Unix.localtime time in
1457 let printable_date_time =
1458 sprintf "%04d-%02d-%02d %02d:%02d:%02d"
1459 (tm.Unix.tm_year + 1900) (tm.Unix.tm_mon+1) tm.Unix.tm_mday
1460 tm.Unix.tm_hour tm.Unix.tm_min tm.Unix.tm_sec in
1463 let uid = Unix.geteuid () in
1464 (Unix.getpwuid uid).Unix.pw_name
1466 Not_found -> "unknown" in
1469 let nl () = fp chan "\n" in
1470 fp chan "# .virt-toprc virt-top configuration file\n";
1471 fp chan "# generated on %s by %s\n" printable_date_time username;
1473 fp chan "display %s\n" (cli_of_display !display_mode);
1474 fp chan "delay %g\n" (float !delay /. 1000.);
1475 fp chan "hist-cpu %d\n" !historical_cpu_delay;
1476 if !iterations <> -1 then fp chan "iterations %d\n" !iterations;
1477 fp chan "sort %s\n" (cli_of_sort_order !sort_order);
1480 | Some uri -> fp chan "connect %s\n" uri
1482 if !batch_mode = true then fp chan "batch true\n";
1483 if !secure_mode = true then fp chan "secure true\n";
1485 fp chan "# To send debug and error messages to a file, uncomment next line\n";
1486 fp chan "#debug virt-top.out\n";
1488 fp chan "# Enable CSV output to the named file\n";
1489 fp chan "#csv virt-top.csv\n";
1491 fp chan "# To protect this file from being overwritten, uncomment next line\n";
1492 fp chan "#overwrite-init-file false\n";
1496 (* If the file exists, rename it as filename.old. *)
1497 (try Unix.rename filename (filename ^ ".old")
1498 with Unix.Unix_error _ -> ());
1500 (* Rename filename.new to filename. *)
1501 Unix.rename (filename ^ ".new") filename;
1503 print_msg (sprintf "Wrote settings to %s" filename); sleep 2
1505 | Sys_error err -> print_msg "Error: %s"; sleep 2
1506 | Unix.Unix_error (err, fn, str) ->
1507 print_msg (sprintf "Error: %s %s %s" (Unix.error_message err) fn str);
1510 and show_help (_, _, _, _, _, hostname,
1511 (libvirt_major, libvirt_minor, libvirt_release)) =
1514 (* Get the screen/window size. *)
1515 let lines, cols = get_size () in
1517 (* Banner at the top of the screen. *)
1519 sprintf "virt-top %s (libvirt %d.%d.%d) by Red Hat"
1520 Libvirt_version.version libvirt_major libvirt_minor libvirt_release in
1521 let banner = pad cols banner in
1523 mvaddstr 0 0 banner;
1528 (sprintf "Delay: %.1f secs; Batch: %s; Secure: %s; Sort: %s"
1529 (float !delay /. 1000.)
1530 (if !batch_mode then "On" else "Off")
1531 (if !secure_mode then "On" else "Off")
1532 (printable_sort_order !sort_order));
1534 (sprintf "Connect: %s; Hostname: %s"
1535 (match !uri with None -> "default" | Some s -> s)
1538 (* Misc keys on left. *)
1539 let banner = pad 38 "MAIN KEYS" in
1541 mvaddstr header_lineno 1 banner;
1545 let lineno = ref domains_lineno in
1546 fun () -> let i = !lineno in incr lineno; i
1548 let key keys description =
1549 let lineno = get_lineno () in
1550 move lineno 1; attron A.bold; addstr keys; attroff A.bold;
1551 move lineno 10; addstr description; ()
1553 key "space ^L" "Update display";
1555 key "d s" "Set update interval";
1559 ignore (get_lineno ());
1560 let banner = pad 38 "SORTING" in
1562 mvaddstr (get_lineno ()) 1 banner;
1565 key "P" "Sort by %CPU";
1566 key "M" "Sort by %MEM";
1567 key "T" "Sort by TIME";
1568 key "N" "Sort by ID";
1569 key "F" "Select sort field";
1571 (* Display modes on right. *)
1572 let banner = pad 39 "DISPLAY MODES" in
1574 mvaddstr header_lineno 40 banner;
1578 let lineno = ref domains_lineno in
1579 fun () -> let i = !lineno in incr lineno; i
1581 let key keys description =
1582 let lineno = get_lineno () in
1583 move lineno 40; attron A.bold; addstr keys; attroff A.bold;
1584 move lineno 49; addstr description; ()
1586 key "0" "Domains display";
1587 key "1" "Toggle physical CPUs";
1588 key "2" "Toggle network interfaces";
1589 key "3" "Toggle block devices";
1591 (* Update screen and wait for key press. *)
1592 mvaddstr (lines-1) 0
1593 "More help in virt-top(1) man page. Press any key to return.";
1597 and unknown_command k =
1598 print_msg "Unknown command - try 'h' for help";