1 (* 'top'-like tool for libvirt domains.
2 (C) Copyright 2007 Richard W.M. Jones, Red Hat Inc.
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
26 module C = Libvirt.Connect
27 module D = Libvirt.Domain
28 module N = Libvirt.Network
30 (* Hook for XML support (see virt_top_xml.ml). *)
31 let parse_device_xml : (int -> [>`R] D.t -> string list * string list) ref =
36 (* Hooks for CSV support (see virt_top_csv.ml). *)
37 let csv_start : (string -> unit) ref =
39 fun _ -> failwith "virt-top was compiled without support for CSV files"
41 let csv_write : (string list -> unit) ref =
46 (* Hook for calendar support (see virt_top_calendar.ml). *)
47 let parse_date_time : (string -> float) ref =
50 failwith "virt-top was compiled without support for dates and times"
55 | DomainID | DomainName | Processor | Memory | Time
56 | NetRX | NetTX | BlockRdRq | BlockWrRq
57 let all_sort_fields = [
58 DomainID; DomainName; Processor; Memory; Time;
59 NetRX; NetTX; BlockRdRq; BlockWrRq
61 let printable_sort_order = function
64 | Time -> "TIME (CPU time)"
65 | DomainID -> "Domain ID"
66 | DomainName -> "Domain name"
67 | NetRX -> "Net RX bytes"
68 | NetTX -> "Net TX bytes"
69 | BlockRdRq -> "Block read reqs"
70 | BlockWrRq -> "Block write reqs"
71 let sort_order_of_cli = function
72 | "cpu" | "processor" -> Processor
73 | "mem" | "memory" -> Memory
76 | "name" -> DomainName
77 | "netrx" -> NetRX | "nettx" -> NetTX
78 | "blockrdrq" -> BlockRdRq | "blockwrrq" -> BlockWrRq
79 | str -> failwith (str ^ ": sort order should be: cpu|mem|time|id|name|netrx|nettx|blockrdrq|blockwrrq")
80 let cli_of_sort_order = function
85 | DomainName -> "name"
88 | BlockRdRq -> "blockrdrq"
89 | BlockWrRq -> "blockwrrq"
91 (* Current major display mode: TaskDisplay is the normal display. *)
92 type display = TaskDisplay | PCPUDisplay | BlockDisplay | NetDisplay
94 let display_of_cli = function
95 | "task" -> TaskDisplay
96 | "pcpu" -> PCPUDisplay
97 | "block" -> BlockDisplay
99 | str -> failwith (str ^ ": display should be task|pcpu|block|net")
100 let cli_of_display = function
101 | TaskDisplay -> "task"
102 | PCPUDisplay -> "pcpu"
103 | BlockDisplay -> "block"
104 | NetDisplay -> "net"
107 type init_file = NoInitFile | DefaultInitFile | InitFile of string
111 let delay = ref 3000 (* milliseconds *)
112 let historical_cpu_delay = ref 20 (* secs *)
113 let iterations = ref (-1)
114 let end_time = ref None
115 let batch_mode = ref false
116 let secure_mode = ref false
117 let sort_order = ref Processor
118 let display_mode = ref TaskDisplay
120 let debug_file = ref ""
121 let csv_enabled = ref false
122 let csv_cpu = ref true
123 let csv_block = ref true
124 let csv_net = ref true
125 let init_file = ref DefaultInitFile
126 let script_mode = ref false
128 (* Tuple of never-changing data returned by start_up function. *)
130 Libvirt.ro C.t * bool * bool * bool * C.node_info * string *
133 (* Function to read command line arguments and go into curses mode. *)
135 (* Read command line arguments. *)
136 let rec set_delay newdelay =
137 if newdelay <= 0. then
138 failwith "-d: cannot set a negative delay";
139 delay := int_of_float (newdelay *. 1000.)
140 and set_uri = function "" -> uri := None | u -> uri := Some u
141 and set_sort order = sort_order := sort_order_of_cli order
142 and set_pcpu_mode () = display_mode := PCPUDisplay
143 and set_net_mode () = display_mode := NetDisplay
144 and set_block_mode () = display_mode := BlockDisplay
145 and set_csv filename =
146 (!csv_start) filename;
148 and no_init_file () = init_file := NoInitFile
149 and set_init_file filename = init_file := InitFile filename
150 and set_end_time time = end_time := Some ((!parse_date_time) time)
152 let argspec = Arg.align [
153 "-1", Arg.Unit set_pcpu_mode, " Start by displaying pCPUs (default: tasks)";
154 "-2", Arg.Unit set_net_mode, " Start by displaying network interfaces";
155 "-3", Arg.Unit set_block_mode, " Start by displaying block devices";
156 "-b", Arg.Set batch_mode, " Batch mode";
157 "-c", Arg.String set_uri, "uri Connect to URI (default: Xen)";
158 "--connect", Arg.String set_uri, "uri Connect to URI (default: Xen)";
159 "--csv", Arg.String set_csv, "file Log statistics to CSV file";
160 "--no-csv-cpu", Arg.Clear csv_cpu, " Disable CPU stats in CSV";
161 "--no-csv-block", Arg.Clear csv_block, " Disable block device stats in CSV";
162 "--no-csv-net", Arg.Clear csv_net, " Disable net stats in CSV";
163 "-d", Arg.Float set_delay, "delay Delay time interval (seconds)";
164 "--debug", Arg.Set_string debug_file, "file Send debug messages to file";
165 "--end-time", Arg.String set_end_time, "time Exit at given time";
166 "--hist-cpu", Arg.Set_int historical_cpu_delay, "secs Historical CPU delay";
167 "--init-file", Arg.String set_init_file, "file Set name of init file";
168 "--no-init-file", Arg.Unit no_init_file, " Do not read init file";
169 "-n", Arg.Set_int iterations, "iterations Number of iterations to run";
170 "-o", Arg.String set_sort, "sort Set sort order (cpu|mem|time|id|name)";
171 "-s", Arg.Set secure_mode, " Secure (\"kiosk\") mode";
172 "--script", Arg.Set script_mode, " Run from a script (no user interface)";
174 let anon_fun str = raise (Arg.Bad (str ^ ": unknown parameter")) in
175 let usage_msg = "virt-top : a 'top'-like utility for virtualization
181 Arg.parse argspec anon_fun usage_msg;
183 (* Read the init file. *)
184 let try_to_read_init_file filename =
185 let config = read_config_file filename in
188 | _, "display", mode -> display_mode := display_of_cli mode
189 | _, "delay", secs -> set_delay (float_of_string secs)
190 | _, "hist-cpu", secs -> historical_cpu_delay := int_of_string secs
191 | _, "iterations", n -> iterations := int_of_string n
192 | _, "sort", order -> set_sort order
193 | _, "connect", uri -> set_uri uri
194 | _, "debug", filename -> debug_file := filename
195 | _, "csv", filename -> set_csv filename
196 | _, "csv-cpu", b -> csv_cpu := bool_of_string b
197 | _, "csv-block", b -> csv_block := bool_of_string b
198 | _, "csv-net", b -> csv_net := bool_of_string b
199 | _, "batch", b -> batch_mode := bool_of_string b
200 | _, "secure", b -> secure_mode := bool_of_string b
201 | _, "script", b -> script_mode := bool_of_string b
202 | _, "end-time", t -> set_end_time t
203 | _, "overwrite-init-file", "false" -> no_init_file ()
205 eprintf "%s:%d: configuration item ``%s'' ignored\n%!"
209 (match !init_file with
212 let home = try Sys.getenv "HOME" with Not_found -> "/" in
213 let filename = home // ".virt-toprc" in
214 try_to_read_init_file filename
215 | InitFile filename ->
216 try_to_read_init_file filename
219 (* Connect to the hypervisor before going into curses mode, since
220 * this is the most likely thing to fail.
224 try C.connect_readonly ?name ()
226 Libvirt.Virterror err ->
227 prerr_endline (Libvirt.Virterror.to_string err);
228 (* If non-root and no explicit connection URI, print a warning. *)
229 if Unix.geteuid () <> 0 && name = None then (
230 print_endline "NB: If you want to monitor a local Xen hypervisor, you usually need to be root";
234 (* Get the node_info. This never changes, right? So we get it just once. *)
235 let node_info = C.get_node_info conn in
237 (* Hostname and libvirt library version also don't change. *)
239 try C.get_hostname conn
241 (* qemu:/// and other URIs didn't support virConnectGetHostname until
242 * libvirt 0.3.3. Before that they'd throw a virterror. *)
243 | Libvirt.Virterror _
244 | Libvirt.Not_supported "virConnectGetHostname" -> "unknown" in
246 let libvirt_version =
247 let v, _ = Libvirt.get_version () in
248 v / 1_000_000, (v / 1_000) mod 1_000, v mod 1_000 in
250 (* Open debug file if specified.
251 * NB: Do this just before jumping into curses mode.
253 (match !debug_file with
254 | "" -> (* No debug file specified, send stderr to /dev/null unless
255 * we're in script mode.
257 if not !script_mode then (
258 let fd = Unix.openfile "/dev/null" [Unix.O_WRONLY] 0o644 in
259 Unix.dup2 fd Unix.stderr;
262 | filename -> (* Send stderr to the named file. *)
264 Unix.openfile filename [Unix.O_WRONLY;Unix.O_CREAT;Unix.O_TRUNC]
266 Unix.dup2 fd Unix.stderr;
270 (* Curses voodoo (see ncurses(3)). *)
271 if not !script_mode then (
276 let stdscr = stdscr () in
277 intrflush stdscr false;
282 (* This tuple of static information is called 'setup' in other parts
283 * of this program, and is passed to other functions such as redraw and
284 * main_loop. See virt_top_main.ml.
287 !batch_mode, !script_mode, !csv_enabled, (* immutable modes *)
288 node_info, hostname, libvirt_version (* info that doesn't change *)
291 (* Show a domain state (the 'S' column). *)
292 let show_state = function
293 | D.InfoNoState -> '?'
294 | D.InfoRunning -> 'R'
295 | D.InfoBlocked -> 'S'
296 | D.InfoPaused -> 'P'
297 | D.InfoShutdown -> 'D'
298 | D.InfoShutoff -> 'O'
299 | D.InfoCrashed -> 'X'
301 (* Sleep in seconds. *)
302 let sleep = Unix.sleep
304 (* Sleep in milliseconds. *)
306 ignore (Unix.select [] [] [] (float n /. 1000.))
308 (* The curses getstr/getnstr functions are just weird.
309 * This helper function also enables echo temporarily.
311 let get_string maxlen =
313 let str = String.create maxlen in
314 let ok = getstr str in (* Safe because binding calls getnstr. *)
318 (* Chop at first '\0'. *)
320 let i = String.index str '\000' in
323 Not_found -> str (* it is full maxlen bytes *)
328 let summary_lineno = 1 (* this takes 2 lines *)
329 let message_lineno = 3
330 let header_lineno = 4
331 let domains_lineno = 5
333 (* Print in the "message area". *)
334 let clear_msg () = move message_lineno 0; clrtoeol ()
335 let print_msg str = clear_msg (); mvaddstr message_lineno 0 str; ()
337 (* Intermediate "domain + stats" structure that we use to collect
338 * everything we know about a domain within the collect function.
340 type rd_domain = Inactive | Active of rd_active
342 rd_domid : int; (* Domain ID. *)
343 rd_dom : [`R] D.t; (* Domain object. *)
344 rd_info : D.info; (* Domain CPU info now. *)
345 rd_block_stats : (string * D.block_stats) list;
346 (* Domain block stats now. *)
347 rd_interface_stats : (string * D.interface_stats) list;
348 (* Domain net stats now. *)
349 rd_prev_info : D.info option; (* Domain CPU info previously. *)
350 rd_prev_block_stats : (string * D.block_stats) list;
351 (* Domain block stats prev. *)
352 rd_prev_interface_stats : (string * D.interface_stats) list;
353 (* Domain interface stats prev. *)
354 (* The following are since the last slice, or 0 if cannot be calculated: *)
355 rd_cpu_time : float; (* CPU time used in nanoseconds. *)
356 rd_percent_cpu : float; (* CPU time as percent of total. *)
357 (* The following are since the last slice, or None if cannot be calc'd: *)
358 rd_block_rd_reqs : int64 option; (* Number of block device read rqs. *)
359 rd_block_wr_reqs : int64 option; (* Number of block device write rqs. *)
360 rd_net_rx_bytes : int64 option; (* Number of bytes received. *)
361 rd_net_tx_bytes : int64 option; (* Number of bytes transmitted. *)
365 let collect, clear_pcpu_display_data =
366 (* We cache the list of block devices and interfaces for each domain
367 * here, so we don't need to reparse the XML each time.
369 let devices = Hashtbl.create 13 in
371 (* Function to get the list of block devices, network interfaces for
372 * a particular domain. Get it from the devices cache, and if not
373 * there then parse the domain XML.
375 let get_devices id dom =
376 try Hashtbl.find devices id
378 let blkdevs, netifs = (!parse_device_xml) id dom in
379 Hashtbl.replace devices id (blkdevs, netifs);
383 (* We save the state of domains across redraws here, which allows us
384 * to deduce %CPU usage from the running total.
386 let last_info = Hashtbl.create 13 in
387 let last_time = ref (Unix.gettimeofday ()) in
389 (* Save vcpuinfo structures across redraws too (only for pCPU display). *)
390 let last_vcpu_info = Hashtbl.create 13 in
392 let clear_pcpu_display_data () =
393 (* Clear out vcpu_info used by PCPUDisplay display_mode
394 * when we switch back to TaskDisplay mode.
396 Hashtbl.clear last_vcpu_info
399 let collect (conn, _, _, _, node_info, _, _) =
400 (* Number of physical CPUs (some may be disabled). *)
401 let nr_pcpus = C.maxcpus_of_node_info node_info in
403 (* Get the current time. *)
404 let time = Unix.gettimeofday () in
405 let tm = Unix.localtime time in
407 sprintf "%02d:%02d:%02d" tm.Unix.tm_hour tm.Unix.tm_min tm.Unix.tm_sec in
409 (* What's the total CPU time elapsed since we were last called? (ns) *)
410 let total_cpu_per_pcpu = 1_000_000_000. *. (time -. !last_time) in
411 (* Avoid division by zero. *)
412 let total_cpu_per_pcpu =
413 if total_cpu_per_pcpu <= 0. then 1. else total_cpu_per_pcpu in
414 let total_cpu = float node_info.C.cpus *. total_cpu_per_pcpu in
416 (* Get the domains. Match up with their last_info (if any). *)
418 (* Active domains. *)
419 let n = C.num_of_domains conn in
421 if n > 0 then Array.to_list (C.list_domains conn n)
427 let dom = D.lookup_by_id conn id in
428 let name = D.get_name dom in
429 let blkdevs, netifs = get_devices id dom in
431 (* Get current CPU, block and network stats. *)
432 let info = D.get_info dom in
434 try List.map (fun dev -> dev, D.block_stats dom dev) blkdevs
436 | Libvirt.Not_supported "virDomainBlockStats"
437 | Libvirt.Virterror _ -> [] in
438 let interface_stats =
439 try List.map (fun dev -> dev, D.interface_stats dom dev) netifs
441 | Libvirt.Not_supported "virDomainInterfaceStats"
442 | Libvirt.Virterror _ -> [] in
444 let prev_info, prev_block_stats, prev_interface_stats =
446 let prev_info, prev_block_stats, prev_interface_stats =
447 Hashtbl.find last_info id in
448 Some prev_info, prev_block_stats, prev_interface_stats
449 with Not_found -> None, [], [] in
452 rd_domid = id; rd_dom = dom; rd_info = info;
453 rd_block_stats = block_stats;
454 rd_interface_stats = interface_stats;
455 rd_prev_info = prev_info;
456 rd_prev_block_stats = prev_block_stats;
457 rd_prev_interface_stats = prev_interface_stats;
458 rd_cpu_time = 0.; rd_percent_cpu = 0.;
459 rd_block_rd_reqs = None; rd_block_wr_reqs = None;
460 rd_net_rx_bytes = None; rd_net_tx_bytes = None;
463 Libvirt.Virterror _ -> None (* ignore transient error *)
466 (* Inactive domains. *)
469 let n = C.num_of_defined_domains conn in
471 if n > 0 then Array.to_list (C.list_defined_domains conn n)
473 List.map (fun name -> name, Inactive) names
475 (* Ignore transient errors, in particular errors from
476 * num_of_defined_domains if it cannot contact xend.
478 | Libvirt.Virterror _ -> [] in
480 doms @ doms_inactive in
482 (* Calculate the CPU time (ns) and %CPU used by each domain. *)
486 (* We have previous CPU info from which to calculate it? *)
487 | name, Active ({ rd_prev_info = Some prev_info } as rd) ->
489 Int64.to_float (rd.rd_info.D.cpu_time -^ prev_info.D.cpu_time) in
490 let percent_cpu = 100. *. cpu_time /. total_cpu in
492 rd_cpu_time = cpu_time;
493 rd_percent_cpu = percent_cpu } in
495 (* For all other domains we can't calculate it, so leave as 0 *)
499 (* Calculate the number of block device read/write requests across
500 * all block devices attached to a domain.
505 (* Do we have stats from the previous slice? *)
506 | name, Active ({ rd_prev_block_stats = ((_::_) as prev_block_stats) }
508 let block_stats = rd.rd_block_stats in (* stats now *)
510 (* Add all the devices together. Throw away device names. *)
511 let prev_block_stats =
512 sum_block_stats (List.map snd prev_block_stats) in
514 sum_block_stats (List.map snd block_stats) in
516 (* Calculate increase in read & write requests. *)
518 block_stats.D.rd_req -^ prev_block_stats.D.rd_req in
520 block_stats.D.wr_req -^ prev_block_stats.D.wr_req in
523 rd_block_rd_reqs = Some read_reqs;
524 rd_block_wr_reqs = Some write_reqs } in
526 (* For all other domains we can't calculate it, so leave as None. *)
530 (* Calculate the same as above for network interfaces across
531 * all network interfaces attached to a domain.
536 (* Do we have stats from the previous slice? *)
537 | name, Active ({ rd_prev_interface_stats =
538 ((_::_) as prev_interface_stats) }
540 let interface_stats = rd.rd_interface_stats in (* stats now *)
542 (* Add all the devices together. Throw away device names. *)
543 let prev_interface_stats =
544 sum_interface_stats (List.map snd prev_interface_stats) in
545 let interface_stats =
546 sum_interface_stats (List.map snd interface_stats) in
548 (* Calculate increase in rx & tx bytes. *)
550 interface_stats.D.rx_bytes -^ prev_interface_stats.D.rx_bytes in
552 interface_stats.D.tx_bytes -^ prev_interface_stats.D.tx_bytes in
555 rd_net_rx_bytes = Some rx_bytes;
556 rd_net_tx_bytes = Some tx_bytes } in
558 (* For all other domains we can't calculate it, so leave as None. *)
562 (* Collect some extra information in PCPUDisplay display_mode. *)
564 if !display_mode = PCPUDisplay then (
565 (* Get the VCPU info and VCPU->PCPU mappings for active domains.
566 * Also cull some data we don't care about.
568 let doms = List.filter_map (
570 | (name, Active rd) ->
572 let domid = rd.rd_domid in
573 let maplen = C.cpumaplen nr_pcpus in
574 let maxinfo = rd.rd_info.D.nr_virt_cpu in
575 let nr_vcpus, vcpu_infos, cpumaps =
576 D.get_vcpus rd.rd_dom maxinfo maplen in
578 (* Got previous vcpu_infos for this domain? *)
579 let prev_vcpu_infos =
580 try Some (Hashtbl.find last_vcpu_info domid)
581 with Not_found -> None in
582 (* Update last_vcpu_info. *)
583 Hashtbl.replace last_vcpu_info domid vcpu_infos;
585 (match prev_vcpu_infos with
586 | Some prev_vcpu_infos
587 when Array.length prev_vcpu_infos = Array.length vcpu_infos ->
588 Some (domid, name, nr_vcpus, vcpu_infos, prev_vcpu_infos,
590 | _ -> None (* ignore missing / unequal length prev_vcpu_infos *)
593 Libvirt.Virterror _ -> None(* ignore transient libvirt errs *)
595 | (_, Inactive) -> None (* ignore inactive doms *)
597 let nr_doms = List.length doms in
599 (* Rearrange the data into a matrix. Major axis (down) is
600 * pCPUs. Minor axis (right) is domains. At each node we store:
601 * cpu_time (on this pCPU only, nanosecs),
602 * average? (if set, then cpu_time is an average because the
603 * vCPU is pinned to more than one pCPU)
604 * running? (if set, we were instantaneously running on this pCPU)
606 let empty_node = (0L, false, false) in
607 let pcpus = Array.make_matrix nr_pcpus nr_doms empty_node in
610 fun di (domid, name, nr_vcpus, vcpu_infos, prev_vcpu_infos,
612 (* Which pCPUs can this dom run on? *)
613 for v = 0 to nr_vcpus-1 do
614 let pcpu = vcpu_infos.(v).D.cpu in (* instantaneous pCPU *)
615 let nr_poss_pcpus = ref 0 in (* how many pcpus can it run on? *)
616 for p = 0 to nr_pcpus-1 do
617 (* vcpu v can reside on pcpu p *)
618 if C.cpu_usable cpumaps maplen v p then
621 let nr_poss_pcpus = Int64.of_int !nr_poss_pcpus in
622 for p = 0 to nr_pcpus-1 do
623 (* vcpu v can reside on pcpu p *)
624 if C.cpu_usable cpumaps maplen v p then
625 let vcpu_time_on_pcpu =
626 vcpu_infos.(v).D.vcpu_time
627 -^ prev_vcpu_infos.(v).D.vcpu_time in
628 let vcpu_time_on_pcpu =
629 vcpu_time_on_pcpu /^ nr_poss_pcpus in
631 (vcpu_time_on_pcpu, nr_poss_pcpus > 1L, p = pcpu)
636 (* Sum the CPU time used by each pCPU, for the %CPU column. *)
637 let pcpus_cpu_time = Array.map (
639 let cpu_time = ref 0L in
640 for di = 0 to Array.length row-1 do
641 let t, _, _ = row.(di) in
642 cpu_time := !cpu_time +^ t
644 Int64.to_float !cpu_time
647 Some (doms, pcpus, pcpus_cpu_time)
651 (* Calculate totals. *)
652 let totals = List.fold_left (
653 fun (count, running, blocked, paused, shutdown, shutoff,
654 crashed, active, inactive,
655 total_cpu_time, total_memory, total_domU_memory) ->
657 | (name, Active rd) ->
658 let test state orig =
659 if rd.rd_info.D.state = state then orig+1 else orig
661 let running = test D.InfoRunning running in
662 let blocked = test D.InfoBlocked blocked in
663 let paused = test D.InfoPaused paused in
664 let shutdown = test D.InfoShutdown shutdown in
665 let shutoff = test D.InfoShutoff shutoff in
666 let crashed = test D.InfoCrashed crashed in
668 let total_cpu_time = total_cpu_time +. rd.rd_cpu_time in
669 let total_memory = total_memory +^ rd.rd_info.D.memory in
670 let total_domU_memory = total_domU_memory +^
671 if rd.rd_domid > 0 then rd.rd_info.D.memory else 0L in
673 (count+1, running, blocked, paused, shutdown, shutoff,
674 crashed, active+1, inactive,
675 total_cpu_time, total_memory, total_domU_memory)
677 | (name, Inactive) -> (* inactive domain *)
678 (count+1, running, blocked, paused, shutdown, shutoff,
679 crashed, active, inactive+1,
680 total_cpu_time, total_memory, total_domU_memory)
681 ) (0,0,0,0,0,0,0,0,0, 0.,0L,0L) doms in
683 (* Update last_time, last_info. *)
685 Hashtbl.clear last_info;
689 let info = rd.rd_info, rd.rd_block_stats, rd.rd_interface_stats in
690 Hashtbl.add last_info rd.rd_domid info
695 time, printable_time,
696 nr_pcpus, total_cpu, total_cpu_per_pcpu,
701 collect, clear_pcpu_display_data
703 (* Redraw the display. *)
705 (* Keep a historical list of %CPU usages. *)
706 let historical_cpu = ref [] in
707 let historical_cpu_last_time = ref (Unix.gettimeofday ()) in
709 (_, _, _, _, node_info, _, _) (* setup *)
711 time, printable_time,
712 nr_pcpus, total_cpu, total_cpu_per_pcpu,
714 pcpu_display) (* state *) ->
717 (* Get the screen/window size. *)
718 let lines, cols = get_size () in
721 mvaddstr top_lineno 0 ("virt-top " ^ printable_time ^ " - ");
723 (* Basic node_info. *)
724 addstr (sprintf "%s %d/%dCPU %dMHz %LdMB "
725 node_info.C.model node_info.C.cpus nr_pcpus node_info.C.mhz
726 (node_info.C.memory /^ 1024L));
727 (* Save the cursor position for when we come to draw the
728 * historical CPU times (down in this function).
730 let stdscr = stdscr () in
731 let historical_cursor = getyx stdscr in
733 (match !display_mode with
734 | TaskDisplay -> (*---------- Showing domains ----------*)
735 (* Sort domains on current sort_order. *)
738 match !sort_order with
740 (fun _ -> 0) (* fallthrough to default name compare *)
743 | Active rd1, Active rd2 ->
744 compare rd2.rd_percent_cpu rd1.rd_percent_cpu
745 | Active _, Inactive -> -1
746 | Inactive, Active _ -> 1
747 | Inactive, Inactive -> 0)
750 | Active { rd_info = info1 }, Active { rd_info = info2 } ->
751 compare info2.D.memory info1.D.memory
752 | Active _, Inactive -> -1
753 | Inactive, Active _ -> 1
754 | Inactive, Inactive -> 0)
757 | Active { rd_info = info1 }, Active { rd_info = info2 } ->
758 compare info2.D.cpu_time info1.D.cpu_time
759 | Active _, Inactive -> -1
760 | Inactive, Active _ -> 1
761 | Inactive, Inactive -> 0)
764 | Active { rd_domid = id1 }, Active { rd_domid = id2 } ->
766 | Active _, Inactive -> -1
767 | Inactive, Active _ -> 1
768 | Inactive, Inactive -> 0)
771 | Active { rd_net_rx_bytes = r1 }, Active { rd_net_rx_bytes = r2 } ->
773 | Active _, Inactive -> -1
774 | Inactive, Active _ -> 1
775 | Inactive, Inactive -> 0)
778 | Active { rd_net_tx_bytes = r1 }, Active { rd_net_tx_bytes = r2 } ->
780 | Active _, Inactive -> -1
781 | Inactive, Active _ -> 1
782 | Inactive, Inactive -> 0)
785 | Active { rd_block_rd_reqs = r1 }, Active { rd_block_rd_reqs = r2 } ->
787 | Active _, Inactive -> -1
788 | Inactive, Active _ -> 1
789 | Inactive, Inactive -> 0)
792 | Active { rd_block_wr_reqs = r1 }, Active { rd_block_wr_reqs = r2 } ->
794 | Active _, Inactive -> -1
795 | Inactive, Active _ -> 1
796 | Inactive, Inactive -> 0)
798 let cmp (name1, dom1) (name2, dom2) =
799 let r = cmp (dom1, dom2) in
801 else compare name1 name2
803 List.sort ~cmp doms in
807 mvaddstr header_lineno 0
808 (pad cols " ID S RDRQ WRRQ RXBY TXBY %CPU %MEM TIME NAME");
811 let rec loop lineno = function
813 | (name, Active rd) :: doms ->
814 if lineno < lines then (
815 let state = show_state rd.rd_info.D.state in
816 let rd_req = Show.int64_option rd.rd_block_rd_reqs in
817 let wr_req = Show.int64_option rd.rd_block_wr_reqs in
818 let rx_bytes = Show.int64_option rd.rd_net_rx_bytes in
819 let tx_bytes = Show.int64_option rd.rd_net_tx_bytes in
820 let percent_cpu = Show.percent rd.rd_percent_cpu in
822 100L *^ rd.rd_info.D.memory /^ node_info.C.memory in
823 let percent_mem = Int64.to_float percent_mem in
824 let percent_mem = Show.percent percent_mem in
825 let time = Show.time rd.rd_info.D.cpu_time in
827 let line = sprintf "%5d %c %s %s %s %s %s %s %s %s"
828 rd.rd_domid state rd_req wr_req rx_bytes tx_bytes
829 percent_cpu percent_mem time name in
830 let line = pad cols line in
831 mvaddstr lineno 0 line;
834 | (name, Inactive) :: doms -> (* inactive domain *)
835 if lineno < lines then (
840 let line = pad cols line in
841 mvaddstr lineno 0 line;
845 loop domains_lineno doms
847 | PCPUDisplay -> (*---------- Showing physical CPUs ----------*)
848 let doms, pcpus, pcpus_cpu_time =
849 match pcpu_display with
851 | None -> failwith "internal error: no pcpu_display data" in
853 (* Display the pCPUs. *)
857 fun (_, name, _, _, _, _, _) ->
858 let len = String.length name in
859 let width = max (len+1) 7 in
864 mvaddstr header_lineno 0 (pad cols ("PHYCPU %CPU " ^ dom_names));
869 mvaddstr (p+domains_lineno) 0 (sprintf "%4d " p);
870 let cpu_time = pcpus_cpu_time.(p) in (* ns used on this CPU *)
871 let percent_cpu = 100. *. cpu_time /. total_cpu_per_pcpu in
872 addstr (Show.percent percent_cpu);
876 fun di (domid, name, _, _, _, _, _) ->
877 let t, is_average, is_running = pcpus.(p).(di) in
878 let len = String.length name in
879 let width = max (len+1) 7 in
883 let t = Int64.to_float t in
884 let percent = 100. *. t /. total_cpu_per_pcpu in
885 sprintf "%s%c%c " (Show.percent percent)
886 (if is_average then '=' else ' ')
887 (if is_running then '#' else ' ')
889 addstr (pad width str);
894 | NetDisplay -> (*---------- Showing network interfaces ----------*)
895 (* Only care about active domains. *)
896 let doms = List.filter_map (
898 | (name, Active rd) -> Some (name, rd)
899 | (_, Inactive) -> None
902 (* For each domain we have a list of network interfaces seen
903 * this slice, and seen in the previous slice, which we now
904 * match up to get a list of (domain, interface) for which
905 * we have current & previous knowledge. (And ignore the rest).
913 (* Have prev slice stats for this device? *)
915 List.assoc dev rd.rd_prev_interface_stats in
916 Some (dev, name, rd, stats, prev_stats)
917 with Not_found -> None
918 ) rd.rd_interface_stats
921 (* Finally we have a list of:
922 * device name, domain name, rd_* stuff, curr stats, prev stats.
924 let devs : (string * string * rd_active *
925 D.interface_stats * D.interface_stats) list =
928 (* Difference curr slice & prev slice. *)
929 let devs = List.map (
930 fun (dev, name, rd, curr, prev) ->
931 dev, name, rd, diff_interface_stats curr prev
934 (* Sort by current sort order, but map some of the standard
935 * sort orders into ones which makes sense here.
939 match !sort_order with
941 (fun _ -> 0) (* fallthrough to default name compare *)
943 (fun (_, { rd_domid = id1 }, _, { rd_domid = id2 }) ->
945 | Processor | Memory | Time | BlockRdRq | BlockWrRq
946 (* fallthrough to RXBY comparison. *)
948 (fun ({ D.rx_bytes = b1 }, _, { D.rx_bytes = b2 }, _) ->
951 (fun ({ D.tx_bytes = b1 }, _, { D.tx_bytes = b2 }, _) ->
954 let cmp (dev1, name1, rd1, stats1) (dev2, name2, rd2, stats2) =
955 let r = cmp (stats1, rd1, stats2, rd2) in
957 else compare (dev1, name1) (dev2, name2)
959 List.sort ~cmp devs in
961 (* Print the header for network devices. *)
963 mvaddstr header_lineno 0
964 (pad cols " ID S RXBY TXBY RXPK TXPK DOMAIN INTERFACE");
967 (* Print domains and devices. *)
968 let rec loop lineno = function
970 | (dev, name, rd, stats) :: devs ->
971 if lineno < lines then (
972 let state = show_state rd.rd_info.D.state in
974 if stats.D.rx_bytes >= 0L
975 then Show.int64 stats.D.rx_bytes
978 if stats.D.tx_bytes >= 0L
979 then Show.int64 stats.D.tx_bytes
982 if stats.D.rx_packets >= 0L
983 then Show.int64 stats.D.rx_packets
986 if stats.D.tx_packets >= 0L
987 then Show.int64 stats.D.tx_packets
990 let line = sprintf "%5d %c %s %s %s %s %-12s %s"
993 rx_packets tx_packets
995 let line = pad cols line in
996 mvaddstr lineno 0 line;
1000 loop domains_lineno devs
1002 | BlockDisplay -> (*---------- Showing block devices ----------*)
1003 (* Only care about active domains. *)
1004 let doms = List.filter_map (
1006 | (name, Active rd) -> Some (name, rd)
1007 | (_, Inactive) -> None
1010 (* For each domain we have a list of block devices seen
1011 * this slice, and seen in the previous slice, which we now
1012 * match up to get a list of (domain, device) for which
1013 * we have current & previous knowledge. (And ignore the rest).
1021 (* Have prev slice stats for this device? *)
1023 List.assoc dev rd.rd_prev_block_stats in
1024 Some (dev, name, rd, stats, prev_stats)
1025 with Not_found -> None
1029 (* Finally we have a list of:
1030 * device name, domain name, rd_* stuff, curr stats, prev stats.
1032 let devs : (string * string * rd_active *
1033 D.block_stats * D.block_stats) list =
1034 List.flatten devs in
1036 (* Difference curr slice & prev slice. *)
1037 let devs = List.map (
1038 fun (dev, name, rd, curr, prev) ->
1039 dev, name, rd, diff_block_stats curr prev
1042 (* Sort by current sort order, but map some of the standard
1043 * sort orders into ones which makes sense here.
1047 match !sort_order with
1049 (fun _ -> 0) (* fallthrough to default name compare *)
1051 (fun (_, { rd_domid = id1 }, _, { rd_domid = id2 }) ->
1053 | Processor | Memory | Time | NetRX | NetTX
1054 (* fallthrough to RDRQ comparison. *)
1056 (fun ({ D.rd_req = b1 }, _, { D.rd_req = b2 }, _) ->
1059 (fun ({ D.wr_req = b1 }, _, { D.wr_req = b2 }, _) ->
1062 let cmp (dev1, name1, rd1, stats1) (dev2, name2, rd2, stats2) =
1063 let r = cmp (stats1, rd1, stats2, rd2) in
1065 else compare (dev1, name1) (dev2, name2)
1067 List.sort ~cmp devs in
1069 (* Print the header for block devices. *)
1071 mvaddstr header_lineno 0
1072 (pad cols " ID S RDBY WRBY RDRQ WRRQ DOMAIN DEVICE");
1075 (* Print domains and devices. *)
1076 let rec loop lineno = function
1078 | (dev, name, rd, stats) :: devs ->
1079 if lineno < lines then (
1080 let state = show_state rd.rd_info.D.state in
1082 if stats.D.rd_bytes >= 0L
1083 then Show.int64 stats.D.rd_bytes
1086 if stats.D.wr_bytes >= 0L
1087 then Show.int64 stats.D.wr_bytes
1090 if stats.D.rd_req >= 0L
1091 then Show.int64 stats.D.rd_req
1094 if stats.D.wr_req >= 0L
1095 then Show.int64 stats.D.wr_req
1098 let line = sprintf "%5d %c %s %s %s %s %-12s %s"
1102 (pad 12 name) dev in
1103 let line = pad cols line in
1104 mvaddstr lineno 0 line;
1105 loop (lineno+1) devs
1108 loop domains_lineno devs
1109 ); (* end of display_mode conditional section *)
1111 let (count, running, blocked, paused, shutdown, shutoff,
1112 crashed, active, inactive,
1113 total_cpu_time, total_memory, total_domU_memory) = totals in
1115 mvaddstr summary_lineno 0
1116 (sprintf "%d domains, %d active, %d running, %d sleeping, %d paused, %d inactive D:%d O:%d X:%d"
1117 count active running blocked paused inactive shutdown shutoff
1120 (* Total %CPU used, and memory summary. *)
1121 let percent_cpu = 100. *. total_cpu_time /. total_cpu in
1122 mvaddstr (summary_lineno+1) 0
1123 (sprintf "CPU: %2.1f%% Mem: %Ld MB (%Ld MB by guests)"
1124 percent_cpu (total_memory /^ 1024L) (total_domU_memory /^ 1024L));
1126 (* Time to grab another historical %CPU for the list? *)
1127 if time >= !historical_cpu_last_time +. float !historical_cpu_delay
1129 historical_cpu := percent_cpu :: List.take 10 !historical_cpu;
1130 historical_cpu_last_time := time
1133 (* Display historical CPU time. *)
1135 let x, y = historical_cursor in (* Yes, it's a bug in ocaml-curses *)
1136 let maxwidth = cols - x in
1139 (List.map (sprintf "%2.1f%%") !historical_cpu) in
1140 let line = pad maxwidth line in
1144 move message_lineno 0; (* Park cursor in message area, as with top. *)
1145 refresh (); (* Refresh the display. *)
1148 (* Write CSV header row. *)
1149 let write_csv_header () =
1151 [ "Hostname"; "Time"; "Arch"; "Physical CPUs";
1152 "Count"; "Running"; "Blocked"; "Paused"; "Shutdown";
1153 "Shutoff"; "Crashed"; "Active"; "Inactive";
1154 "%CPU"; "Total memory (KB)"; "Total guest memory (KB)";
1155 "Total CPU time (ns)" ] @
1156 (* These fields are repeated for each domain: *)
1157 [ "Domain ID"; "Domain name"; ] @
1158 (if !csv_cpu then [ "CPU (ns)"; "%CPU"; ] else []) @
1159 (if !csv_block then [ "Block RDRQ"; "Block WRRQ"; ] else []) @
1160 (if !csv_net then [ "Net RXBY"; "Net TXBY" ] else [])
1163 (* Write summary data to CSV file. *)
1165 (_, _, _, _, node_info, hostname, _) (* setup *)
1168 nr_pcpus, total_cpu, _,
1172 (* The totals / summary fields. *)
1173 let (count, running, blocked, paused, shutdown, shutoff,
1174 crashed, active, inactive,
1175 total_cpu_time, total_memory, total_domU_memory) = totals in
1177 let percent_cpu = 100. *. total_cpu_time /. total_cpu in
1179 let summary_fields = [
1180 hostname; printable_time; node_info.C.model; string_of_int nr_pcpus;
1181 string_of_int count; string_of_int running; string_of_int blocked;
1182 string_of_int paused; string_of_int shutdown; string_of_int shutoff;
1183 string_of_int crashed; string_of_int active; string_of_int inactive;
1184 sprintf "%2.1f" percent_cpu;
1185 Int64.to_string total_memory; Int64.to_string total_domU_memory;
1186 Int64.to_string (Int64.of_float total_cpu_time)
1191 * Sort them by ID so that the list of relatively stable. Ignore
1194 let doms = List.filter_map (
1196 | _, Inactive -> None (* Ignore inactive domains. *)
1197 | name, Active rd -> Some (name, rd)
1199 let cmp (_, { rd_domid = rd_domid1 }) (_, { rd_domid = rd_domid2 }) =
1200 compare rd_domid1 rd_domid2
1202 let doms = List.sort ~cmp doms in
1204 let string_of_int64_option = Option.map_default Int64.to_string "" in
1206 let domain_fields = List.map (
1207 fun (domname, rd) ->
1208 [ string_of_int rd.rd_domid; domname ] @
1210 string_of_float rd.rd_cpu_time; string_of_float rd.rd_percent_cpu
1212 (if !csv_block then [
1213 string_of_int64_option rd.rd_block_rd_reqs;
1214 string_of_int64_option rd.rd_block_wr_reqs;
1217 string_of_int64_option rd.rd_net_rx_bytes;
1218 string_of_int64_option rd.rd_net_tx_bytes;
1221 let domain_fields = List.flatten domain_fields in
1223 (!csv_write) (summary_fields @ domain_fields)
1226 let rec main_loop ((_, batch_mode, script_mode, csv_enabled, _, _, _)
1228 if csv_enabled then write_csv_header ();
1231 let state = collect setup in (* Collect stats. *)
1232 if not script_mode then redraw setup state; (* Redraw display. *)
1233 if csv_enabled then append_csv setup state; (* Update CSV file. *)
1235 (* Clear up unused virDomainPtr objects. *)
1238 (* Get next key. This does the sleep. *)
1239 if not batch_mode && not script_mode then
1240 get_key_press setup;
1242 (* Max iterations? *)
1243 if !iterations >= 0 then (
1245 if !iterations = 0 then quit := true
1249 (match !end_time with
1252 let (_, time, _, _, _, _, _, _) = state in
1253 let delay_secs = float !delay /. 1000. in
1254 if end_time <= time +. delay_secs then quit := true
1257 (* Batch mode or script mode. We didn't call get_key_press above, so
1258 * we didn't sleep. Sleep now, unless we are about to quit.
1260 if batch_mode || script_mode then
1265 and get_key_press setup =
1266 (* Read the next key, waiting up to !delay milliseconds. *)
1269 timeout (-1); (* Reset to blocking mode. *)
1271 if k >= 0 && k <> 32 (* ' ' *) && k <> 12 (* ^L *) && k <> Key.resize
1273 if k = Char.code 'q' then quit := true
1274 else if k = Char.code 'h' then show_help setup
1275 else if k = Char.code 's' || k = Char.code 'd' then change_delay ()
1276 else if k = Char.code 'M' then sort_order := Memory
1277 else if k = Char.code 'P' then sort_order := Processor
1278 else if k = Char.code 'T' then sort_order := Time
1279 else if k = Char.code 'N' then sort_order := DomainID
1280 else if k = Char.code 'F' then change_sort_order ()
1281 else if k = Char.code '0' then set_tasks_display ()
1282 else if k = Char.code '1' then toggle_pcpu_display ()
1283 else if k = Char.code '2' then toggle_net_display ()
1284 else if k = Char.code '3' then toggle_block_display ()
1285 else if k = Char.code 'W' then write_init_file ()
1286 else unknown_command k
1289 and change_delay () =
1290 print_msg (sprintf "Change delay from %.1f to: " (float !delay /. 1000.));
1291 let str = get_string 16 in
1292 (* Try to parse the number. *)
1295 let newdelay = float_of_string str in
1296 if newdelay <= 0. then (
1297 print_msg "Delay must be > 0"; true
1299 delay := int_of_float (newdelay *. 1000.); false
1302 Failure "float_of_string" ->
1303 print_msg "Not a valid number"; true in
1305 sleep (if error then 2 else 1)
1307 and change_sort_order () =
1309 let lines, cols = get_size () in
1311 mvaddstr top_lineno 0 "Set sort order for main display";
1312 mvaddstr summary_lineno 0 "Type key or use up and down cursor keys.";
1315 mvaddstr header_lineno 0 (pad cols "KEY Sort field");
1318 let accelerator_key = function
1319 | Memory -> "(key: M)"
1320 | Processor -> "(key: P)"
1321 | Time -> "(key: T)"
1322 | DomainID -> "(key: N)"
1323 | _ -> (* all others have to be changed from here *) ""
1326 let rec key_of_int = function
1327 | i when i < 10 -> Char.chr (i + Char.code '0')
1328 | i when i < 20 -> Char.chr (i + Char.code 'a')
1330 and int_of_key = function
1331 | k when k >= 0x30 && k <= 0x39 (* '0' - '9' *) -> k - 0x30
1332 | k when k >= 0x61 && k <= 0x7a (* 'a' - 'j' *) -> k - 0x61 + 10
1333 | k when k >= 0x41 && k <= 0x6a (* 'A' - 'J' *) -> k - 0x41 + 10
1337 (* Display possible sort fields. *)
1338 let selected_index = ref 0 in
1341 let selected = !sort_order = ord in
1342 if selected then selected_index := i;
1343 mvaddstr (domains_lineno+i) 0
1344 (sprintf " %c %s %s %s"
1345 (key_of_int i) (if selected then "*" else " ")
1346 (printable_sort_order ord)
1347 (accelerator_key ord))
1350 move message_lineno 0;
1353 if k >= 0 && k <> 32 && k <> Char.code 'q' && k <> 13 then (
1354 let new_order, loop =
1355 (* Redraw the display. *)
1356 if k = 12 (* ^L *) then None, true
1357 (* Make the UP and DOWN arrow keys do something useful. *)
1358 else if k = Key.up then (
1359 if !selected_index > 0 then
1360 Some (List.nth all_sort_fields (!selected_index-1)), true
1364 else if k = Key.down then (
1365 if !selected_index < List.length all_sort_fields - 1 then
1366 Some (List.nth all_sort_fields (!selected_index+1)), true
1370 (* Also understand the regular accelerator keys. *)
1371 else if k = Char.code 'M' then
1373 else if k = Char.code 'P' then
1374 Some Processor, false
1375 else if k = Char.code 'T' then
1377 else if k = Char.code 'N' then
1378 Some DomainID, false
1380 (* It's one of the KEYs. *)
1381 let i = int_of_key k in
1382 if i >= 0 && i < List.length all_sort_fields then
1383 Some (List.nth all_sort_fields i), false
1388 (match new_order with
1391 sort_order := new_order;
1392 print_msg (sprintf "Sort order changed to: %s"
1393 (printable_sort_order new_order));
1400 if loop then change_sort_order ()
1403 (* Note: We need to clear_pcpu_display_data every time
1404 * we _leave_ PCPUDisplay mode.
1406 and set_tasks_display () = (* key 0 *)
1407 if !display_mode = PCPUDisplay then clear_pcpu_display_data ();
1408 display_mode := TaskDisplay
1410 and toggle_pcpu_display () = (* key 1 *)
1412 match !display_mode with
1413 | TaskDisplay | NetDisplay | BlockDisplay -> PCPUDisplay
1414 | PCPUDisplay -> clear_pcpu_display_data (); TaskDisplay
1416 and toggle_net_display () = (* key 2 *)
1418 match !display_mode with
1419 | PCPUDisplay -> clear_pcpu_display_data (); NetDisplay
1420 | TaskDisplay | BlockDisplay -> NetDisplay
1421 | NetDisplay -> TaskDisplay
1423 and toggle_block_display () = (* key 3 *)
1425 match !display_mode with
1426 | PCPUDisplay -> clear_pcpu_display_data (); BlockDisplay
1427 | TaskDisplay | NetDisplay -> BlockDisplay
1428 | BlockDisplay -> TaskDisplay
1430 (* Write an init file. *)
1431 and write_init_file () =
1432 match !init_file with
1433 | NoInitFile -> () (* Do nothing if --no-init-file *)
1434 | DefaultInitFile ->
1435 let home = try Sys.getenv "HOME" with Not_found -> "/" in
1436 let filename = home // ".virt-toprc" in
1437 _write_init_file filename
1438 | InitFile filename ->
1439 _write_init_file filename
1441 and _write_init_file filename =
1443 (* Create the new file as filename.new. *)
1444 let chan = open_out (filename ^ ".new") in
1446 let time = Unix.gettimeofday () in
1447 let tm = Unix.localtime time in
1448 let printable_date_time =
1449 sprintf "%04d-%02d-%02d %02d:%02d:%02d"
1450 (tm.Unix.tm_year + 1900) (tm.Unix.tm_mon+1) tm.Unix.tm_mday
1451 tm.Unix.tm_hour tm.Unix.tm_min tm.Unix.tm_sec in
1454 let uid = Unix.geteuid () in
1455 (Unix.getpwuid uid).Unix.pw_name
1457 Not_found -> "unknown" in
1460 let nl () = fp chan "\n" in
1461 fp chan "# .virt-toprc virt-top configuration file\n";
1462 fp chan "# generated on %s by %s\n" printable_date_time username;
1464 fp chan "display %s\n" (cli_of_display !display_mode);
1465 fp chan "delay %g\n" (float !delay /. 1000.);
1466 fp chan "hist-cpu %d\n" !historical_cpu_delay;
1467 if !iterations <> -1 then fp chan "iterations %d\n" !iterations;
1468 fp chan "sort %s\n" (cli_of_sort_order !sort_order);
1471 | Some uri -> fp chan "connect %s\n" uri
1473 if !batch_mode = true then fp chan "batch true\n";
1474 if !secure_mode = true then fp chan "secure true\n";
1476 fp chan "# To send debug and error messages to a file, uncomment next line\n";
1477 fp chan "#debug virt-top.out\n";
1479 fp chan "# Enable CSV output to the named file\n";
1480 fp chan "#csv virt-top.csv\n";
1482 fp chan "# To protect this file from being overwritten, uncomment next line\n";
1483 fp chan "#overwrite-init-file false\n";
1487 (* If the file exists, rename it as filename.old. *)
1488 (try Unix.rename filename (filename ^ ".old")
1489 with Unix.Unix_error _ -> ());
1491 (* Rename filename.new to filename. *)
1492 Unix.rename (filename ^ ".new") filename;
1494 print_msg (sprintf "Wrote settings to %s" filename);
1498 | Sys_error err -> print_msg "Error: %s"; refresh (); sleep 2
1499 | Unix.Unix_error (err, fn, str) ->
1500 print_msg (sprintf "Error: %s %s %s" (Unix.error_message err) fn str);
1504 and show_help (_, _, _, _, _, hostname,
1505 (libvirt_major, libvirt_minor, libvirt_release)) =
1508 (* Get the screen/window size. *)
1509 let lines, cols = get_size () in
1511 (* Banner at the top of the screen. *)
1513 sprintf "virt-top %s (libvirt %d.%d.%d) by Red Hat"
1514 Libvirt_version.version libvirt_major libvirt_minor libvirt_release in
1515 let banner = pad cols banner in
1517 mvaddstr 0 0 banner;
1522 (sprintf "Delay: %.1f secs; Batch: %s; Secure: %s; Sort: %s"
1523 (float !delay /. 1000.)
1524 (if !batch_mode then "On" else "Off")
1525 (if !secure_mode then "On" else "Off")
1526 (printable_sort_order !sort_order));
1528 (sprintf "Connect: %s; Hostname: %s"
1529 (match !uri with None -> "default" | Some s -> s)
1532 (* Misc keys on left. *)
1533 let banner = pad 38 "MAIN KEYS" in
1535 mvaddstr header_lineno 1 banner;
1539 let lineno = ref domains_lineno in
1540 fun () -> let i = !lineno in incr lineno; i
1542 let key keys description =
1543 let lineno = get_lineno () in
1544 move lineno 1; attron A.bold; addstr keys; attroff A.bold;
1545 move lineno 10; addstr description; ()
1547 key "space ^L" "Update display";
1549 key "d s" "Set update interval";
1553 ignore (get_lineno ());
1554 let banner = pad 38 "SORTING" in
1556 mvaddstr (get_lineno ()) 1 banner;
1559 key "P" "Sort by %CPU";
1560 key "M" "Sort by %MEM";
1561 key "T" "Sort by TIME";
1562 key "N" "Sort by ID";
1563 key "F" "Select sort field";
1565 (* Display modes on right. *)
1566 let banner = pad 39 "DISPLAY MODES" in
1568 mvaddstr header_lineno 40 banner;
1572 let lineno = ref domains_lineno in
1573 fun () -> let i = !lineno in incr lineno; i
1575 let key keys description =
1576 let lineno = get_lineno () in
1577 move lineno 40; attron A.bold; addstr keys; attroff A.bold;
1578 move lineno 49; addstr description; ()
1580 key "0" "Domains display";
1581 key "1" "Toggle physical CPUs";
1582 key "2" "Toggle network interfaces";
1583 key "3" "Toggle block devices";
1585 (* Update screen and wait for key press. *)
1586 mvaddstr (lines-1) 0
1587 "More help in virt-top(1) man page. Press any key to return.";
1591 and unknown_command k =
1592 print_msg "Unknown command - try 'h' for help";