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.
24 open Virt_top_gettext.Gettext
27 module C = Libvirt.Connect
28 module D = Libvirt.Domain
29 module N = Libvirt.Network
31 (* Hook for XML support (see virt_top_xml.ml). *)
32 let parse_device_xml : (int -> [>`R] D.t -> string list * string list) ref =
37 (* Hooks for CSV support (see virt_top_csv.ml). *)
38 let csv_start : (string -> unit) ref =
40 fun _ -> failwith (s_ "virt-top was compiled without support for CSV files")
42 let csv_write : (string list -> unit) ref =
47 (* Hook for calendar support (see virt_top_calendar.ml). *)
48 let parse_date_time : (string -> float) ref =
51 failwith (s_ "virt-top was compiled without support for dates and times")
56 | DomainID | DomainName | Processor | Memory | Time
57 | NetRX | NetTX | BlockRdRq | BlockWrRq
58 let all_sort_fields = [
59 DomainID; DomainName; Processor; Memory; Time;
60 NetRX; NetTX; BlockRdRq; BlockWrRq
62 let printable_sort_order = function
63 | Processor -> s_ "%CPU"
65 | Time -> s_ "TIME (CPU time)"
66 | DomainID -> s_ "Domain ID"
67 | DomainName -> s_ "Domain name"
68 | NetRX -> s_ "Net RX bytes"
69 | NetTX -> s_ "Net TX bytes"
70 | BlockRdRq -> s_ "Block read reqs"
71 | BlockWrRq -> s_ "Block write reqs"
72 let sort_order_of_cli = function
73 | "cpu" | "processor" -> Processor
74 | "mem" | "memory" -> Memory
77 | "name" -> DomainName
78 | "netrx" -> NetRX | "nettx" -> NetTX
79 | "blockrdrq" -> BlockRdRq | "blockwrrq" -> BlockWrRq
82 (sprintf (f_ "%s: sort order should be: %s")
83 str "cpu|mem|time|id|name|netrx|nettx|blockrdrq|blockwrrq")
84 let cli_of_sort_order = function
89 | DomainName -> "name"
92 | BlockRdRq -> "blockrdrq"
93 | BlockWrRq -> "blockwrrq"
95 (* Current major display mode: TaskDisplay is the normal display. *)
96 type display = TaskDisplay | PCPUDisplay | BlockDisplay | NetDisplay
98 let display_of_cli = function
99 | "task" -> TaskDisplay
100 | "pcpu" -> PCPUDisplay
101 | "block" -> BlockDisplay
102 | "net" -> NetDisplay
105 (sprintf (f_ "%s: display should be %s")
106 str "task|pcpu|block|net")
107 let cli_of_display = function
108 | TaskDisplay -> "task"
109 | PCPUDisplay -> "pcpu"
110 | BlockDisplay -> "block"
111 | NetDisplay -> "net"
114 type init_file = NoInitFile | DefaultInitFile | InitFile of string
118 let delay = ref 3000 (* milliseconds *)
119 let historical_cpu_delay = ref 20 (* secs *)
120 let iterations = ref (-1)
121 let end_time = ref None
122 let batch_mode = ref false
123 let secure_mode = ref false
124 let sort_order = ref Processor
125 let display_mode = ref TaskDisplay
127 let debug_file = ref ""
128 let csv_enabled = ref false
129 let csv_cpu = ref true
130 let csv_block = ref true
131 let csv_net = ref true
132 let init_file = ref DefaultInitFile
133 let script_mode = ref false
135 (* Tuple of never-changing data returned by start_up function. *)
137 Libvirt.ro C.t * bool * bool * bool * C.node_info * string *
140 (* Function to read command line arguments and go into curses mode. *)
142 (* Read command line arguments. *)
143 let rec set_delay newdelay =
144 if newdelay <= 0. then
145 failwith (s_ "-d: cannot set a negative delay");
146 delay := int_of_float (newdelay *. 1000.)
147 and set_uri = function "" -> uri := None | u -> uri := Some u
148 and set_sort order = sort_order := sort_order_of_cli order
149 and set_pcpu_mode () = display_mode := PCPUDisplay
150 and set_net_mode () = display_mode := NetDisplay
151 and set_block_mode () = display_mode := BlockDisplay
152 and set_csv filename =
153 (!csv_start) filename;
155 and no_init_file () = init_file := NoInitFile
156 and set_init_file filename = init_file := InitFile filename
157 and set_end_time time = end_time := Some ((!parse_date_time) time)
159 let argspec = Arg.align [
160 "-1", Arg.Unit set_pcpu_mode,
161 " " ^ s_ "Start by displaying pCPUs (default: tasks)";
162 "-2", Arg.Unit set_net_mode,
163 " " ^ s_ "Start by displaying network interfaces";
164 "-3", Arg.Unit set_block_mode,
165 " " ^ s_ "Start by displaying block devices";
166 "-b", Arg.Set batch_mode,
167 " " ^ s_ "Batch mode";
168 "-c", Arg.String set_uri,
169 "uri " ^ s_ "Connect to URI (default: Xen)";
170 "--connect", Arg.String set_uri,
171 "uri " ^ s_ "Connect to URI (default: Xen)";
172 "--csv", Arg.String set_csv,
173 "file " ^ s_ "Log statistics to CSV file";
174 "--no-csv-cpu", Arg.Clear csv_cpu,
175 " " ^ s_ "Disable CPU stats in CSV";
176 "--no-csv-block", Arg.Clear csv_block,
177 " " ^ s_ "Disable block device stats in CSV";
178 "--no-csv-net", Arg.Clear csv_net,
179 " " ^ s_ "Disable net stats in CSV";
180 "-d", Arg.Float set_delay,
181 "delay " ^ s_ "Delay time interval (seconds)";
182 "--debug", Arg.Set_string debug_file,
183 "file " ^ s_ "Send debug messages to file";
184 "--end-time", Arg.String set_end_time,
185 "time " ^ s_ "Exit at given time";
186 "--hist-cpu", Arg.Set_int historical_cpu_delay,
187 "secs " ^ s_ "Historical CPU delay";
188 "--init-file", Arg.String set_init_file,
189 "file " ^ s_ "Set name of init file";
190 "--no-init-file", Arg.Unit no_init_file,
191 " " ^ s_ "Do not read init file";
192 "-n", Arg.Set_int iterations,
193 "iterations " ^ s_ "Number of iterations to run";
194 "-o", Arg.String set_sort,
195 "sort " ^ sprintf (f_ "Set sort order (%s)") "cpu|mem|time|id|name";
196 "-s", Arg.Set secure_mode,
197 " " ^ s_ "Secure (\"kiosk\") mode";
198 "--script", Arg.Set script_mode,
199 " " ^ s_ "Run from a script (no user interface)";
202 raise (Arg.Bad (sprintf (f_ "%s: unknown parameter") str)) in
203 let usage_msg = s_ "virt-top : a 'top'-like utility for virtualization
209 Arg.parse argspec anon_fun usage_msg;
211 (* Read the init file. *)
212 let try_to_read_init_file filename =
213 let config = read_config_file filename in
216 | _, "display", mode -> display_mode := display_of_cli mode
217 | _, "delay", secs -> set_delay (float_of_string secs)
218 | _, "hist-cpu", secs -> historical_cpu_delay := int_of_string secs
219 | _, "iterations", n -> iterations := int_of_string n
220 | _, "sort", order -> set_sort order
221 | _, "connect", uri -> set_uri uri
222 | _, "debug", filename -> debug_file := filename
223 | _, "csv", filename -> set_csv filename
224 | _, "csv-cpu", b -> csv_cpu := bool_of_string b
225 | _, "csv-block", b -> csv_block := bool_of_string b
226 | _, "csv-net", b -> csv_net := bool_of_string b
227 | _, "batch", b -> batch_mode := bool_of_string b
228 | _, "secure", b -> secure_mode := bool_of_string b
229 | _, "script", b -> script_mode := bool_of_string b
230 | _, "end-time", t -> set_end_time t
231 | _, "overwrite-init-file", "false" -> no_init_file ()
233 eprintf (f_ "%s:%d: configuration item ``%s'' ignored\n%!")
237 (match !init_file with
240 let home = try Sys.getenv "HOME" with Not_found -> "/" in
241 let filename = home // ".virt-toprc" in
242 try_to_read_init_file filename
243 | InitFile filename ->
244 try_to_read_init_file filename
247 (* Connect to the hypervisor before going into curses mode, since
248 * this is the most likely thing to fail.
252 try C.connect_readonly ?name ()
254 Libvirt.Virterror err ->
255 prerr_endline (Libvirt.Virterror.to_string err);
256 (* If non-root and no explicit connection URI, print a warning. *)
257 if Unix.geteuid () <> 0 && name = None then (
258 print_endline (s_ "NB: If you want to monitor a local Xen hypervisor, you usually need to be root");
262 (* Get the node_info. This never changes, right? So we get it just once. *)
263 let node_info = C.get_node_info conn in
265 (* Hostname and libvirt library version also don't change. *)
267 try C.get_hostname conn
269 (* qemu:/// and other URIs didn't support virConnectGetHostname until
270 * libvirt 0.3.3. Before that they'd throw a virterror. *)
271 | Libvirt.Virterror _
272 | Libvirt.Not_supported "virConnectGetHostname" -> "unknown" in
274 let libvirt_version =
275 let v, _ = Libvirt.get_version () in
276 v / 1_000_000, (v / 1_000) mod 1_000, v mod 1_000 in
278 (* Open debug file if specified.
279 * NB: Do this just before jumping into curses mode.
281 (match !debug_file with
282 | "" -> (* No debug file specified, send stderr to /dev/null unless
283 * we're in script mode.
285 if not !script_mode then (
286 let fd = Unix.openfile "/dev/null" [Unix.O_WRONLY] 0o644 in
287 Unix.dup2 fd Unix.stderr;
290 | filename -> (* Send stderr to the named file. *)
292 Unix.openfile filename [Unix.O_WRONLY;Unix.O_CREAT;Unix.O_TRUNC]
294 Unix.dup2 fd Unix.stderr;
298 (* Curses voodoo (see ncurses(3)). *)
299 if not !script_mode then (
304 let stdscr = stdscr () in
305 intrflush stdscr false;
310 (* This tuple of static information is called 'setup' in other parts
311 * of this program, and is passed to other functions such as redraw and
312 * main_loop. See virt_top_main.ml.
315 !batch_mode, !script_mode, !csv_enabled, (* immutable modes *)
316 node_info, hostname, libvirt_version (* info that doesn't change *)
319 (* Show a domain state (the 'S' column). *)
320 let show_state = function
321 | D.InfoNoState -> '?'
322 | D.InfoRunning -> 'R'
323 | D.InfoBlocked -> 'S'
324 | D.InfoPaused -> 'P'
325 | D.InfoShutdown -> 'D'
326 | D.InfoShutoff -> 'O'
327 | D.InfoCrashed -> 'X'
329 (* Sleep in seconds. *)
330 let sleep = Unix.sleep
332 (* Sleep in milliseconds. *)
334 ignore (Unix.select [] [] [] (float n /. 1000.))
336 (* The curses getstr/getnstr functions are just weird.
337 * This helper function also enables echo temporarily.
339 let get_string maxlen =
341 let str = String.create maxlen in
342 let ok = getstr str in (* Safe because binding calls getnstr. *)
346 (* Chop at first '\0'. *)
348 let i = String.index str '\000' in
351 Not_found -> str (* it is full maxlen bytes *)
356 let summary_lineno = 1 (* this takes 2 lines *)
357 let message_lineno = 3
358 let header_lineno = 4
359 let domains_lineno = 5
361 (* Print in the "message area". *)
362 let clear_msg () = move message_lineno 0; clrtoeol ()
363 let print_msg str = clear_msg (); mvaddstr message_lineno 0 str; ()
365 (* Intermediate "domain + stats" structure that we use to collect
366 * everything we know about a domain within the collect function.
368 type rd_domain = Inactive | Active of rd_active
370 rd_domid : int; (* Domain ID. *)
371 rd_dom : [`R] D.t; (* Domain object. *)
372 rd_info : D.info; (* Domain CPU info now. *)
373 rd_block_stats : (string * D.block_stats) list;
374 (* Domain block stats now. *)
375 rd_interface_stats : (string * D.interface_stats) list;
376 (* Domain net stats now. *)
377 rd_prev_info : D.info option; (* Domain CPU info previously. *)
378 rd_prev_block_stats : (string * D.block_stats) list;
379 (* Domain block stats prev. *)
380 rd_prev_interface_stats : (string * D.interface_stats) list;
381 (* Domain interface stats prev. *)
382 (* The following are since the last slice, or 0 if cannot be calculated: *)
383 rd_cpu_time : float; (* CPU time used in nanoseconds. *)
384 rd_percent_cpu : float; (* CPU time as percent of total. *)
385 (* The following are since the last slice, or None if cannot be calc'd: *)
386 rd_block_rd_reqs : int64 option; (* Number of block device read rqs. *)
387 rd_block_wr_reqs : int64 option; (* Number of block device write rqs. *)
388 rd_net_rx_bytes : int64 option; (* Number of bytes received. *)
389 rd_net_tx_bytes : int64 option; (* Number of bytes transmitted. *)
393 let collect, clear_pcpu_display_data =
394 (* We cache the list of block devices and interfaces for each domain
395 * here, so we don't need to reparse the XML each time.
397 let devices = Hashtbl.create 13 in
399 (* Function to get the list of block devices, network interfaces for
400 * a particular domain. Get it from the devices cache, and if not
401 * there then parse the domain XML.
403 let get_devices id dom =
404 try Hashtbl.find devices id
406 let blkdevs, netifs = (!parse_device_xml) id dom in
407 Hashtbl.replace devices id (blkdevs, netifs);
411 (* We save the state of domains across redraws here, which allows us
412 * to deduce %CPU usage from the running total.
414 let last_info = Hashtbl.create 13 in
415 let last_time = ref (Unix.gettimeofday ()) in
417 (* Save vcpuinfo structures across redraws too (only for pCPU display). *)
418 let last_vcpu_info = Hashtbl.create 13 in
420 let clear_pcpu_display_data () =
421 (* Clear out vcpu_info used by PCPUDisplay display_mode
422 * when we switch back to TaskDisplay mode.
424 Hashtbl.clear last_vcpu_info
427 let collect (conn, _, _, _, node_info, _, _) =
428 (* Number of physical CPUs (some may be disabled). *)
429 let nr_pcpus = C.maxcpus_of_node_info node_info in
431 (* Get the current time. *)
432 let time = Unix.gettimeofday () in
433 let tm = Unix.localtime time in
435 sprintf "%02d:%02d:%02d" tm.Unix.tm_hour tm.Unix.tm_min tm.Unix.tm_sec in
437 (* What's the total CPU time elapsed since we were last called? (ns) *)
438 let total_cpu_per_pcpu = 1_000_000_000. *. (time -. !last_time) in
439 (* Avoid division by zero. *)
440 let total_cpu_per_pcpu =
441 if total_cpu_per_pcpu <= 0. then 1. else total_cpu_per_pcpu in
442 let total_cpu = float node_info.C.cpus *. total_cpu_per_pcpu in
444 (* Get the domains. Match up with their last_info (if any). *)
446 (* Active domains. *)
447 let n = C.num_of_domains conn in
449 if n > 0 then Array.to_list (C.list_domains conn n)
455 let dom = D.lookup_by_id conn id in
456 let name = D.get_name dom in
457 let blkdevs, netifs = get_devices id dom in
459 (* Get current CPU, block and network stats. *)
460 let info = D.get_info dom in
462 try List.map (fun dev -> dev, D.block_stats dom dev) blkdevs
464 | Libvirt.Not_supported "virDomainBlockStats"
465 | Libvirt.Virterror _ -> [] in
466 let interface_stats =
467 try List.map (fun dev -> dev, D.interface_stats dom dev) netifs
469 | Libvirt.Not_supported "virDomainInterfaceStats"
470 | Libvirt.Virterror _ -> [] in
472 let prev_info, prev_block_stats, prev_interface_stats =
474 let prev_info, prev_block_stats, prev_interface_stats =
475 Hashtbl.find last_info id in
476 Some prev_info, prev_block_stats, prev_interface_stats
477 with Not_found -> None, [], [] in
480 rd_domid = id; rd_dom = dom; rd_info = info;
481 rd_block_stats = block_stats;
482 rd_interface_stats = interface_stats;
483 rd_prev_info = prev_info;
484 rd_prev_block_stats = prev_block_stats;
485 rd_prev_interface_stats = prev_interface_stats;
486 rd_cpu_time = 0.; rd_percent_cpu = 0.;
487 rd_block_rd_reqs = None; rd_block_wr_reqs = None;
488 rd_net_rx_bytes = None; rd_net_tx_bytes = None;
491 Libvirt.Virterror _ -> None (* ignore transient error *)
494 (* Inactive domains. *)
497 let n = C.num_of_defined_domains conn in
499 if n > 0 then Array.to_list (C.list_defined_domains conn n)
501 List.map (fun name -> name, Inactive) names
503 (* Ignore transient errors, in particular errors from
504 * num_of_defined_domains if it cannot contact xend.
506 | Libvirt.Virterror _ -> [] in
508 doms @ doms_inactive in
510 (* Calculate the CPU time (ns) and %CPU used by each domain. *)
514 (* We have previous CPU info from which to calculate it? *)
515 | name, Active ({ rd_prev_info = Some prev_info } as rd) ->
517 Int64.to_float (rd.rd_info.D.cpu_time -^ prev_info.D.cpu_time) in
518 let percent_cpu = 100. *. cpu_time /. total_cpu in
520 rd_cpu_time = cpu_time;
521 rd_percent_cpu = percent_cpu } in
523 (* For all other domains we can't calculate it, so leave as 0 *)
527 (* Calculate the number of block device read/write requests across
528 * all block devices attached to a domain.
533 (* Do we have stats from the previous slice? *)
534 | name, Active ({ rd_prev_block_stats = ((_::_) as prev_block_stats) }
536 let block_stats = rd.rd_block_stats in (* stats now *)
538 (* Add all the devices together. Throw away device names. *)
539 let prev_block_stats =
540 sum_block_stats (List.map snd prev_block_stats) in
542 sum_block_stats (List.map snd block_stats) in
544 (* Calculate increase in read & write requests. *)
546 block_stats.D.rd_req -^ prev_block_stats.D.rd_req in
548 block_stats.D.wr_req -^ prev_block_stats.D.wr_req in
551 rd_block_rd_reqs = Some read_reqs;
552 rd_block_wr_reqs = Some write_reqs } in
554 (* For all other domains we can't calculate it, so leave as None. *)
558 (* Calculate the same as above for network interfaces across
559 * all network interfaces attached to a domain.
564 (* Do we have stats from the previous slice? *)
565 | name, Active ({ rd_prev_interface_stats =
566 ((_::_) as prev_interface_stats) }
568 let interface_stats = rd.rd_interface_stats in (* stats now *)
570 (* Add all the devices together. Throw away device names. *)
571 let prev_interface_stats =
572 sum_interface_stats (List.map snd prev_interface_stats) in
573 let interface_stats =
574 sum_interface_stats (List.map snd interface_stats) in
576 (* Calculate increase in rx & tx bytes. *)
578 interface_stats.D.rx_bytes -^ prev_interface_stats.D.rx_bytes in
580 interface_stats.D.tx_bytes -^ prev_interface_stats.D.tx_bytes in
583 rd_net_rx_bytes = Some rx_bytes;
584 rd_net_tx_bytes = Some tx_bytes } in
586 (* For all other domains we can't calculate it, so leave as None. *)
590 (* Collect some extra information in PCPUDisplay display_mode. *)
592 if !display_mode = PCPUDisplay then (
593 (* Get the VCPU info and VCPU->PCPU mappings for active domains.
594 * Also cull some data we don't care about.
596 let doms = List.filter_map (
598 | (name, Active rd) ->
600 let domid = rd.rd_domid in
601 let maplen = C.cpumaplen nr_pcpus in
602 let maxinfo = rd.rd_info.D.nr_virt_cpu in
603 let nr_vcpus, vcpu_infos, cpumaps =
604 D.get_vcpus rd.rd_dom maxinfo maplen in
606 (* Got previous vcpu_infos for this domain? *)
607 let prev_vcpu_infos =
608 try Some (Hashtbl.find last_vcpu_info domid)
609 with Not_found -> None in
610 (* Update last_vcpu_info. *)
611 Hashtbl.replace last_vcpu_info domid vcpu_infos;
613 (match prev_vcpu_infos with
614 | Some prev_vcpu_infos
615 when Array.length prev_vcpu_infos = Array.length vcpu_infos ->
616 Some (domid, name, nr_vcpus, vcpu_infos, prev_vcpu_infos,
618 | _ -> None (* ignore missing / unequal length prev_vcpu_infos *)
621 Libvirt.Virterror _ -> None(* ignore transient libvirt errs *)
623 | (_, Inactive) -> None (* ignore inactive doms *)
625 let nr_doms = List.length doms in
627 (* Rearrange the data into a matrix. Major axis (down) is
628 * pCPUs. Minor axis (right) is domains. At each node we store:
629 * cpu_time (on this pCPU only, nanosecs),
630 * average? (if set, then cpu_time is an average because the
631 * vCPU is pinned to more than one pCPU)
632 * running? (if set, we were instantaneously running on this pCPU)
634 let empty_node = (0L, false, false) in
635 let pcpus = Array.make_matrix nr_pcpus nr_doms empty_node in
638 fun di (domid, name, nr_vcpus, vcpu_infos, prev_vcpu_infos,
640 (* Which pCPUs can this dom run on? *)
641 for v = 0 to nr_vcpus-1 do
642 let pcpu = vcpu_infos.(v).D.cpu in (* instantaneous pCPU *)
643 let nr_poss_pcpus = ref 0 in (* how many pcpus can it run on? *)
644 for p = 0 to nr_pcpus-1 do
645 (* vcpu v can reside on pcpu p *)
646 if C.cpu_usable cpumaps maplen v p then
649 let nr_poss_pcpus = Int64.of_int !nr_poss_pcpus in
650 for p = 0 to nr_pcpus-1 do
651 (* vcpu v can reside on pcpu p *)
652 if C.cpu_usable cpumaps maplen v p then
653 let vcpu_time_on_pcpu =
654 vcpu_infos.(v).D.vcpu_time
655 -^ prev_vcpu_infos.(v).D.vcpu_time in
656 let vcpu_time_on_pcpu =
657 vcpu_time_on_pcpu /^ nr_poss_pcpus in
659 (vcpu_time_on_pcpu, nr_poss_pcpus > 1L, p = pcpu)
664 (* Sum the CPU time used by each pCPU, for the %CPU column. *)
665 let pcpus_cpu_time = Array.map (
667 let cpu_time = ref 0L in
668 for di = 0 to Array.length row-1 do
669 let t, _, _ = row.(di) in
670 cpu_time := !cpu_time +^ t
672 Int64.to_float !cpu_time
675 Some (doms, pcpus, pcpus_cpu_time)
679 (* Calculate totals. *)
680 let totals = List.fold_left (
681 fun (count, running, blocked, paused, shutdown, shutoff,
682 crashed, active, inactive,
683 total_cpu_time, total_memory, total_domU_memory) ->
685 | (name, Active rd) ->
686 let test state orig =
687 if rd.rd_info.D.state = state then orig+1 else orig
689 let running = test D.InfoRunning running in
690 let blocked = test D.InfoBlocked blocked in
691 let paused = test D.InfoPaused paused in
692 let shutdown = test D.InfoShutdown shutdown in
693 let shutoff = test D.InfoShutoff shutoff in
694 let crashed = test D.InfoCrashed crashed in
696 let total_cpu_time = total_cpu_time +. rd.rd_cpu_time in
697 let total_memory = total_memory +^ rd.rd_info.D.memory in
698 let total_domU_memory = total_domU_memory +^
699 if rd.rd_domid > 0 then rd.rd_info.D.memory else 0L in
701 (count+1, running, blocked, paused, shutdown, shutoff,
702 crashed, active+1, inactive,
703 total_cpu_time, total_memory, total_domU_memory)
705 | (name, Inactive) -> (* inactive domain *)
706 (count+1, running, blocked, paused, shutdown, shutoff,
707 crashed, active, inactive+1,
708 total_cpu_time, total_memory, total_domU_memory)
709 ) (0,0,0,0,0,0,0,0,0, 0.,0L,0L) doms in
711 (* Update last_time, last_info. *)
713 Hashtbl.clear last_info;
717 let info = rd.rd_info, rd.rd_block_stats, rd.rd_interface_stats in
718 Hashtbl.add last_info rd.rd_domid info
723 time, printable_time,
724 nr_pcpus, total_cpu, total_cpu_per_pcpu,
729 collect, clear_pcpu_display_data
731 (* Redraw the display. *)
733 (* Keep a historical list of %CPU usages. *)
734 let historical_cpu = ref [] in
735 let historical_cpu_last_time = ref (Unix.gettimeofday ()) in
737 (_, _, _, _, node_info, _, _) (* setup *)
739 time, printable_time,
740 nr_pcpus, total_cpu, total_cpu_per_pcpu,
742 pcpu_display) (* state *) ->
745 (* Get the screen/window size. *)
746 let lines, cols = get_size () in
749 mvaddstr top_lineno 0 ("virt-top " ^ printable_time ^ " - ");
751 (* Basic node_info. *)
752 addstr (sprintf "%s %d/%dCPU %dMHz %LdMB "
753 node_info.C.model node_info.C.cpus nr_pcpus node_info.C.mhz
754 (node_info.C.memory /^ 1024L));
755 (* Save the cursor position for when we come to draw the
756 * historical CPU times (down in this function).
758 let stdscr = stdscr () in
759 let historical_cursor = getyx stdscr in
761 (match !display_mode with
762 | TaskDisplay -> (*---------- Showing domains ----------*)
763 (* Sort domains on current sort_order. *)
766 match !sort_order with
768 (fun _ -> 0) (* fallthrough to default name compare *)
771 | Active rd1, Active rd2 ->
772 compare rd2.rd_percent_cpu rd1.rd_percent_cpu
773 | Active _, Inactive -> -1
774 | Inactive, Active _ -> 1
775 | Inactive, Inactive -> 0)
778 | Active { rd_info = info1 }, Active { rd_info = info2 } ->
779 compare info2.D.memory info1.D.memory
780 | Active _, Inactive -> -1
781 | Inactive, Active _ -> 1
782 | Inactive, Inactive -> 0)
785 | Active { rd_info = info1 }, Active { rd_info = info2 } ->
786 compare info2.D.cpu_time info1.D.cpu_time
787 | Active _, Inactive -> -1
788 | Inactive, Active _ -> 1
789 | Inactive, Inactive -> 0)
792 | Active { rd_domid = id1 }, Active { rd_domid = id2 } ->
794 | Active _, Inactive -> -1
795 | Inactive, Active _ -> 1
796 | Inactive, Inactive -> 0)
799 | Active { rd_net_rx_bytes = r1 }, Active { rd_net_rx_bytes = r2 } ->
801 | Active _, Inactive -> -1
802 | Inactive, Active _ -> 1
803 | Inactive, Inactive -> 0)
806 | Active { rd_net_tx_bytes = r1 }, Active { rd_net_tx_bytes = r2 } ->
808 | Active _, Inactive -> -1
809 | Inactive, Active _ -> 1
810 | Inactive, Inactive -> 0)
813 | Active { rd_block_rd_reqs = r1 }, Active { rd_block_rd_reqs = r2 } ->
815 | Active _, Inactive -> -1
816 | Inactive, Active _ -> 1
817 | Inactive, Inactive -> 0)
820 | Active { rd_block_wr_reqs = r1 }, Active { rd_block_wr_reqs = r2 } ->
822 | Active _, Inactive -> -1
823 | Inactive, Active _ -> 1
824 | Inactive, Inactive -> 0)
826 let cmp (name1, dom1) (name2, dom2) =
827 let r = cmp (dom1, dom2) in
829 else compare name1 name2
831 List.sort ~cmp doms in
835 mvaddstr header_lineno 0
836 (pad cols " ID S RDRQ WRRQ RXBY TXBY %CPU %MEM TIME NAME");
839 let rec loop lineno = function
841 | (name, Active rd) :: doms ->
842 if lineno < lines then (
843 let state = show_state rd.rd_info.D.state in
844 let rd_req = Show.int64_option rd.rd_block_rd_reqs in
845 let wr_req = Show.int64_option rd.rd_block_wr_reqs in
846 let rx_bytes = Show.int64_option rd.rd_net_rx_bytes in
847 let tx_bytes = Show.int64_option rd.rd_net_tx_bytes in
848 let percent_cpu = Show.percent rd.rd_percent_cpu in
850 100L *^ rd.rd_info.D.memory /^ node_info.C.memory in
851 let percent_mem = Int64.to_float percent_mem in
852 let percent_mem = Show.percent percent_mem in
853 let time = Show.time rd.rd_info.D.cpu_time in
855 let line = sprintf "%5d %c %s %s %s %s %s %s %s %s"
856 rd.rd_domid state rd_req wr_req rx_bytes tx_bytes
857 percent_cpu percent_mem time name in
858 let line = pad cols line in
859 mvaddstr lineno 0 line;
862 | (name, Inactive) :: doms -> (* inactive domain *)
863 if lineno < lines then (
868 let line = pad cols line in
869 mvaddstr lineno 0 line;
873 loop domains_lineno doms
875 | PCPUDisplay -> (*---------- Showing physical CPUs ----------*)
876 let doms, pcpus, pcpus_cpu_time =
877 match pcpu_display with
879 | None -> failwith "internal error: no pcpu_display data" in
881 (* Display the pCPUs. *)
885 fun (_, name, _, _, _, _, _) ->
886 let len = String.length name in
887 let width = max (len+1) 7 in
892 mvaddstr header_lineno 0 (pad cols ("PHYCPU %CPU " ^ dom_names));
897 mvaddstr (p+domains_lineno) 0 (sprintf "%4d " p);
898 let cpu_time = pcpus_cpu_time.(p) in (* ns used on this CPU *)
899 let percent_cpu = 100. *. cpu_time /. total_cpu_per_pcpu in
900 addstr (Show.percent percent_cpu);
904 fun di (domid, name, _, _, _, _, _) ->
905 let t, is_average, is_running = pcpus.(p).(di) in
906 let len = String.length name in
907 let width = max (len+1) 7 in
911 let t = Int64.to_float t in
912 let percent = 100. *. t /. total_cpu_per_pcpu in
913 sprintf "%s%c%c " (Show.percent percent)
914 (if is_average then '=' else ' ')
915 (if is_running then '#' else ' ')
917 addstr (pad width str);
922 | NetDisplay -> (*---------- Showing network interfaces ----------*)
923 (* Only care about active domains. *)
924 let doms = List.filter_map (
926 | (name, Active rd) -> Some (name, rd)
927 | (_, Inactive) -> None
930 (* For each domain we have a list of network interfaces seen
931 * this slice, and seen in the previous slice, which we now
932 * match up to get a list of (domain, interface) for which
933 * we have current & previous knowledge. (And ignore the rest).
941 (* Have prev slice stats for this device? *)
943 List.assoc dev rd.rd_prev_interface_stats in
944 Some (dev, name, rd, stats, prev_stats)
945 with Not_found -> None
946 ) rd.rd_interface_stats
949 (* Finally we have a list of:
950 * device name, domain name, rd_* stuff, curr stats, prev stats.
952 let devs : (string * string * rd_active *
953 D.interface_stats * D.interface_stats) list =
956 (* Difference curr slice & prev slice. *)
957 let devs = List.map (
958 fun (dev, name, rd, curr, prev) ->
959 dev, name, rd, diff_interface_stats curr prev
962 (* Sort by current sort order, but map some of the standard
963 * sort orders into ones which makes sense here.
967 match !sort_order with
969 (fun _ -> 0) (* fallthrough to default name compare *)
971 (fun (_, { rd_domid = id1 }, _, { rd_domid = id2 }) ->
973 | Processor | Memory | Time | BlockRdRq | BlockWrRq
974 (* fallthrough to RXBY comparison. *)
976 (fun ({ D.rx_bytes = b1 }, _, { D.rx_bytes = b2 }, _) ->
979 (fun ({ D.tx_bytes = b1 }, _, { D.tx_bytes = b2 }, _) ->
982 let cmp (dev1, name1, rd1, stats1) (dev2, name2, rd2, stats2) =
983 let r = cmp (stats1, rd1, stats2, rd2) in
985 else compare (dev1, name1) (dev2, name2)
987 List.sort ~cmp devs in
989 (* Print the header for network devices. *)
991 mvaddstr header_lineno 0
992 (pad cols " ID S RXBY TXBY RXPK TXPK DOMAIN INTERFACE");
995 (* Print domains and devices. *)
996 let rec loop lineno = function
998 | (dev, name, rd, stats) :: devs ->
999 if lineno < lines then (
1000 let state = show_state rd.rd_info.D.state in
1002 if stats.D.rx_bytes >= 0L
1003 then Show.int64 stats.D.rx_bytes
1006 if stats.D.tx_bytes >= 0L
1007 then Show.int64 stats.D.tx_bytes
1010 if stats.D.rx_packets >= 0L
1011 then Show.int64 stats.D.rx_packets
1014 if stats.D.tx_packets >= 0L
1015 then Show.int64 stats.D.tx_packets
1018 let line = sprintf "%5d %c %s %s %s %s %-12s %s"
1021 rx_packets tx_packets
1022 (pad 12 name) dev in
1023 let line = pad cols line in
1024 mvaddstr lineno 0 line;
1025 loop (lineno+1) devs
1028 loop domains_lineno devs
1030 | BlockDisplay -> (*---------- Showing block devices ----------*)
1031 (* Only care about active domains. *)
1032 let doms = List.filter_map (
1034 | (name, Active rd) -> Some (name, rd)
1035 | (_, Inactive) -> None
1038 (* For each domain we have a list of block devices seen
1039 * this slice, and seen in the previous slice, which we now
1040 * match up to get a list of (domain, device) for which
1041 * we have current & previous knowledge. (And ignore the rest).
1049 (* Have prev slice stats for this device? *)
1051 List.assoc dev rd.rd_prev_block_stats in
1052 Some (dev, name, rd, stats, prev_stats)
1053 with Not_found -> None
1057 (* Finally we have a list of:
1058 * device name, domain name, rd_* stuff, curr stats, prev stats.
1060 let devs : (string * string * rd_active *
1061 D.block_stats * D.block_stats) list =
1062 List.flatten devs in
1064 (* Difference curr slice & prev slice. *)
1065 let devs = List.map (
1066 fun (dev, name, rd, curr, prev) ->
1067 dev, name, rd, diff_block_stats curr prev
1070 (* Sort by current sort order, but map some of the standard
1071 * sort orders into ones which makes sense here.
1075 match !sort_order with
1077 (fun _ -> 0) (* fallthrough to default name compare *)
1079 (fun (_, { rd_domid = id1 }, _, { rd_domid = id2 }) ->
1081 | Processor | Memory | Time | NetRX | NetTX
1082 (* fallthrough to RDRQ comparison. *)
1084 (fun ({ D.rd_req = b1 }, _, { D.rd_req = b2 }, _) ->
1087 (fun ({ D.wr_req = b1 }, _, { D.wr_req = b2 }, _) ->
1090 let cmp (dev1, name1, rd1, stats1) (dev2, name2, rd2, stats2) =
1091 let r = cmp (stats1, rd1, stats2, rd2) in
1093 else compare (dev1, name1) (dev2, name2)
1095 List.sort ~cmp devs in
1097 (* Print the header for block devices. *)
1099 mvaddstr header_lineno 0
1100 (pad cols " ID S RDBY WRBY RDRQ WRRQ DOMAIN DEVICE");
1103 (* Print domains and devices. *)
1104 let rec loop lineno = function
1106 | (dev, name, rd, stats) :: devs ->
1107 if lineno < lines then (
1108 let state = show_state rd.rd_info.D.state in
1110 if stats.D.rd_bytes >= 0L
1111 then Show.int64 stats.D.rd_bytes
1114 if stats.D.wr_bytes >= 0L
1115 then Show.int64 stats.D.wr_bytes
1118 if stats.D.rd_req >= 0L
1119 then Show.int64 stats.D.rd_req
1122 if stats.D.wr_req >= 0L
1123 then Show.int64 stats.D.wr_req
1126 let line = sprintf "%5d %c %s %s %s %s %-12s %s"
1130 (pad 12 name) dev in
1131 let line = pad cols line in
1132 mvaddstr lineno 0 line;
1133 loop (lineno+1) devs
1136 loop domains_lineno devs
1137 ); (* end of display_mode conditional section *)
1139 let (count, running, blocked, paused, shutdown, shutoff,
1140 crashed, active, inactive,
1141 total_cpu_time, total_memory, total_domU_memory) = totals in
1143 mvaddstr summary_lineno 0
1144 (sprintf (f_ "%d domains, %d active, %d running, %d sleeping, %d paused, %d inactive D:%d O:%d X:%d")
1145 count active running blocked paused inactive shutdown shutoff
1148 (* Total %CPU used, and memory summary. *)
1149 let percent_cpu = 100. *. total_cpu_time /. total_cpu in
1150 mvaddstr (summary_lineno+1) 0
1151 (sprintf (f_ "CPU: %2.1f%% Mem: %Ld MB (%Ld MB by guests)")
1152 percent_cpu (total_memory /^ 1024L) (total_domU_memory /^ 1024L));
1154 (* Time to grab another historical %CPU for the list? *)
1155 if time >= !historical_cpu_last_time +. float !historical_cpu_delay
1157 historical_cpu := percent_cpu :: List.take 10 !historical_cpu;
1158 historical_cpu_last_time := time
1161 (* Display historical CPU time. *)
1163 let x, y = historical_cursor in (* Yes, it's a bug in ocaml-curses *)
1164 let maxwidth = cols - x in
1167 (List.map (sprintf "%2.1f%%") !historical_cpu) in
1168 let line = pad maxwidth line in
1172 move message_lineno 0; (* Park cursor in message area, as with top. *)
1173 refresh (); (* Refresh the display. *)
1176 (* Write CSV header row. *)
1177 let write_csv_header () =
1179 [ "Hostname"; "Time"; "Arch"; "Physical CPUs";
1180 "Count"; "Running"; "Blocked"; "Paused"; "Shutdown";
1181 "Shutoff"; "Crashed"; "Active"; "Inactive";
1182 "%CPU"; "Total memory (KB)"; "Total guest memory (KB)";
1183 "Total CPU time (ns)" ] @
1184 (* These fields are repeated for each domain: *)
1185 [ "Domain ID"; "Domain name"; ] @
1186 (if !csv_cpu then [ "CPU (ns)"; "%CPU"; ] else []) @
1187 (if !csv_block then [ "Block RDRQ"; "Block WRRQ"; ] else []) @
1188 (if !csv_net then [ "Net RXBY"; "Net TXBY" ] else [])
1191 (* Write summary data to CSV file. *)
1193 (_, _, _, _, node_info, hostname, _) (* setup *)
1196 nr_pcpus, total_cpu, _,
1200 (* The totals / summary fields. *)
1201 let (count, running, blocked, paused, shutdown, shutoff,
1202 crashed, active, inactive,
1203 total_cpu_time, total_memory, total_domU_memory) = totals in
1205 let percent_cpu = 100. *. total_cpu_time /. total_cpu in
1207 let summary_fields = [
1208 hostname; printable_time; node_info.C.model; string_of_int nr_pcpus;
1209 string_of_int count; string_of_int running; string_of_int blocked;
1210 string_of_int paused; string_of_int shutdown; string_of_int shutoff;
1211 string_of_int crashed; string_of_int active; string_of_int inactive;
1212 sprintf "%2.1f" percent_cpu;
1213 Int64.to_string total_memory; Int64.to_string total_domU_memory;
1214 Int64.to_string (Int64.of_float total_cpu_time)
1219 * Sort them by ID so that the list of relatively stable. Ignore
1222 let doms = List.filter_map (
1224 | _, Inactive -> None (* Ignore inactive domains. *)
1225 | name, Active rd -> Some (name, rd)
1227 let cmp (_, { rd_domid = rd_domid1 }) (_, { rd_domid = rd_domid2 }) =
1228 compare rd_domid1 rd_domid2
1230 let doms = List.sort ~cmp doms in
1232 let string_of_int64_option = Option.map_default Int64.to_string "" in
1234 let domain_fields = List.map (
1235 fun (domname, rd) ->
1236 [ string_of_int rd.rd_domid; domname ] @
1238 string_of_float rd.rd_cpu_time; string_of_float rd.rd_percent_cpu
1240 (if !csv_block then [
1241 string_of_int64_option rd.rd_block_rd_reqs;
1242 string_of_int64_option rd.rd_block_wr_reqs;
1245 string_of_int64_option rd.rd_net_rx_bytes;
1246 string_of_int64_option rd.rd_net_tx_bytes;
1249 let domain_fields = List.flatten domain_fields in
1251 (!csv_write) (summary_fields @ domain_fields)
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 (* Get next key. This does the sleep. *)
1267 if not batch_mode && not script_mode then
1268 get_key_press setup;
1270 (* Max iterations? *)
1271 if !iterations >= 0 then (
1273 if !iterations = 0 then quit := true
1277 (match !end_time with
1280 let (_, time, _, _, _, _, _, _) = state in
1281 let delay_secs = float !delay /. 1000. in
1282 if end_time <= time +. delay_secs then quit := true
1285 (* Batch mode or script mode. We didn't call get_key_press above, so
1286 * we didn't sleep. Sleep now, unless we are about to quit.
1288 if batch_mode || script_mode then
1293 and get_key_press setup =
1294 (* Read the next key, waiting up to !delay milliseconds. *)
1297 timeout (-1); (* Reset to blocking mode. *)
1299 if k >= 0 && k <> 32 (* ' ' *) && k <> 12 (* ^L *) && k <> Key.resize
1301 if k = Char.code 'q' then quit := true
1302 else if k = Char.code 'h' then show_help setup
1303 else if k = Char.code 's' || k = Char.code 'd' then change_delay ()
1304 else if k = Char.code 'M' then sort_order := Memory
1305 else if k = Char.code 'P' then sort_order := Processor
1306 else if k = Char.code 'T' then sort_order := Time
1307 else if k = Char.code 'N' then sort_order := DomainID
1308 else if k = Char.code 'F' then change_sort_order ()
1309 else if k = Char.code '0' then set_tasks_display ()
1310 else if k = Char.code '1' then toggle_pcpu_display ()
1311 else if k = Char.code '2' then toggle_net_display ()
1312 else if k = Char.code '3' then toggle_block_display ()
1313 else if k = Char.code 'W' then write_init_file ()
1314 else unknown_command k
1317 and change_delay () =
1319 (sprintf (f_ "Change delay from %.1f to: ") (float !delay /. 1000.));
1320 let str = get_string 16 in
1321 (* Try to parse the number. *)
1324 let newdelay = float_of_string str in
1325 if newdelay <= 0. then (
1326 print_msg (s_ "Delay must be > 0"); true
1328 delay := int_of_float (newdelay *. 1000.); false
1331 Failure "float_of_string" ->
1332 print_msg (s_ "Not a valid number"); true in
1334 sleep (if error then 2 else 1)
1336 and change_sort_order () =
1338 let lines, cols = get_size () in
1340 mvaddstr top_lineno 0 (s_ "Set sort order for main display");
1341 mvaddstr summary_lineno 0 (s_ "Type key or use up and down cursor keys.");
1344 mvaddstr header_lineno 0 (pad cols "KEY Sort field");
1347 let accelerator_key = function
1348 | Memory -> "(key: M)"
1349 | Processor -> "(key: P)"
1350 | Time -> "(key: T)"
1351 | DomainID -> "(key: N)"
1352 | _ -> (* all others have to be changed from here *) ""
1355 let rec key_of_int = function
1356 | i when i < 10 -> Char.chr (i + Char.code '0')
1357 | i when i < 20 -> Char.chr (i + Char.code 'a')
1359 and int_of_key = function
1360 | k when k >= 0x30 && k <= 0x39 (* '0' - '9' *) -> k - 0x30
1361 | k when k >= 0x61 && k <= 0x7a (* 'a' - 'j' *) -> k - 0x61 + 10
1362 | k when k >= 0x41 && k <= 0x6a (* 'A' - 'J' *) -> k - 0x41 + 10
1366 (* Display possible sort fields. *)
1367 let selected_index = ref 0 in
1370 let selected = !sort_order = ord in
1371 if selected then selected_index := i;
1372 mvaddstr (domains_lineno+i) 0
1373 (sprintf " %c %s %s %s"
1374 (key_of_int i) (if selected then "*" else " ")
1375 (printable_sort_order ord)
1376 (accelerator_key ord))
1379 move message_lineno 0;
1382 if k >= 0 && k <> 32 && k <> Char.code 'q' && k <> 13 then (
1383 let new_order, loop =
1384 (* Redraw the display. *)
1385 if k = 12 (* ^L *) then None, true
1386 (* Make the UP and DOWN arrow keys do something useful. *)
1387 else if k = Key.up then (
1388 if !selected_index > 0 then
1389 Some (List.nth all_sort_fields (!selected_index-1)), true
1393 else if k = Key.down then (
1394 if !selected_index < List.length all_sort_fields - 1 then
1395 Some (List.nth all_sort_fields (!selected_index+1)), true
1399 (* Also understand the regular accelerator keys. *)
1400 else if k = Char.code 'M' then
1402 else if k = Char.code 'P' then
1403 Some Processor, false
1404 else if k = Char.code 'T' then
1406 else if k = Char.code 'N' then
1407 Some DomainID, false
1409 (* It's one of the KEYs. *)
1410 let i = int_of_key k in
1411 if i >= 0 && i < List.length all_sort_fields then
1412 Some (List.nth all_sort_fields i), false
1417 (match new_order with
1420 sort_order := new_order;
1421 print_msg (sprintf "Sort order changed to: %s"
1422 (printable_sort_order new_order));
1429 if loop then change_sort_order ()
1432 (* Note: We need to clear_pcpu_display_data every time
1433 * we _leave_ PCPUDisplay mode.
1435 and set_tasks_display () = (* key 0 *)
1436 if !display_mode = PCPUDisplay then clear_pcpu_display_data ();
1437 display_mode := TaskDisplay
1439 and toggle_pcpu_display () = (* key 1 *)
1441 match !display_mode with
1442 | TaskDisplay | NetDisplay | BlockDisplay -> PCPUDisplay
1443 | PCPUDisplay -> clear_pcpu_display_data (); TaskDisplay
1445 and toggle_net_display () = (* key 2 *)
1447 match !display_mode with
1448 | PCPUDisplay -> clear_pcpu_display_data (); NetDisplay
1449 | TaskDisplay | BlockDisplay -> NetDisplay
1450 | NetDisplay -> TaskDisplay
1452 and toggle_block_display () = (* key 3 *)
1454 match !display_mode with
1455 | PCPUDisplay -> clear_pcpu_display_data (); BlockDisplay
1456 | TaskDisplay | NetDisplay -> BlockDisplay
1457 | BlockDisplay -> TaskDisplay
1459 (* Write an init file. *)
1460 and write_init_file () =
1461 match !init_file with
1462 | NoInitFile -> () (* Do nothing if --no-init-file *)
1463 | DefaultInitFile ->
1464 let home = try Sys.getenv "HOME" with Not_found -> "/" in
1465 let filename = home // ".virt-toprc" in
1466 _write_init_file filename
1467 | InitFile filename ->
1468 _write_init_file filename
1470 and _write_init_file filename =
1472 (* Create the new file as filename.new. *)
1473 let chan = open_out (filename ^ ".new") in
1475 let time = Unix.gettimeofday () in
1476 let tm = Unix.localtime time in
1477 let printable_date_time =
1478 sprintf "%04d-%02d-%02d %02d:%02d:%02d"
1479 (tm.Unix.tm_year + 1900) (tm.Unix.tm_mon+1) tm.Unix.tm_mday
1480 tm.Unix.tm_hour tm.Unix.tm_min tm.Unix.tm_sec in
1483 let uid = Unix.geteuid () in
1484 (Unix.getpwuid uid).Unix.pw_name
1486 Not_found -> "unknown" in
1489 let nl () = fp chan "\n" in
1490 let () = fp chan (f_ "# .virt-toprc virt-top configuration file\n") in
1491 let () = fp chan (f_ "# generated on %s by %s\n") printable_date_time username in
1493 fp chan "display %s\n" (cli_of_display !display_mode);
1494 fp chan "delay %g\n" (float !delay /. 1000.);
1495 fp chan "hist-cpu %d\n" !historical_cpu_delay;
1496 if !iterations <> -1 then fp chan "iterations %d\n" !iterations;
1497 fp chan "sort %s\n" (cli_of_sort_order !sort_order);
1500 | Some uri -> fp chan "connect %s\n" uri
1502 if !batch_mode = true then fp chan "batch true\n";
1503 if !secure_mode = true then fp chan "secure true\n";
1505 let () = fp chan (f_ "# To send debug and error messages to a file, uncomment next line\n") in
1506 fp chan "#debug virt-top.out\n";
1508 let () = fp chan (f_ "# Enable CSV output to the named file\n") in
1509 fp chan "#csv virt-top.csv\n";
1511 let () = fp chan (f_ "# To protect this file from being overwritten, uncomment next line\n") in
1512 fp chan "#overwrite-init-file false\n";
1516 (* If the file exists, rename it as filename.old. *)
1517 (try Unix.rename filename (filename ^ ".old")
1518 with Unix.Unix_error _ -> ());
1520 (* Rename filename.new to filename. *)
1521 Unix.rename (filename ^ ".new") filename;
1523 print_msg (sprintf (f_ "Wrote settings to %s") filename);
1528 print_msg (s_ "Error" ^ ": " ^ err); refresh (); sleep 2
1529 | Unix.Unix_error (err, fn, str) ->
1530 print_msg (s_ ("Error" ^ ": " ^ Unix.error_message err ^ fn ^ str));
1534 and show_help (_, _, _, _, _, hostname,
1535 (libvirt_major, libvirt_minor, libvirt_release)) =
1538 (* Get the screen/window size. *)
1539 let lines, cols = get_size () in
1541 (* Banner at the top of the screen. *)
1543 sprintf (f_ "virt-top %s (libvirt %d.%d.%d) by Red Hat")
1544 Libvirt_version.version libvirt_major libvirt_minor libvirt_release in
1545 let banner = pad cols banner in
1547 mvaddstr 0 0 banner;
1552 (sprintf (f_ "Delay: %.1f secs; Batch: %s; Secure: %s; Sort: %s")
1553 (float !delay /. 1000.)
1554 (if !batch_mode then "On" else "Off")
1555 (if !secure_mode then "On" else "Off")
1556 (printable_sort_order !sort_order));
1558 (sprintf (f_ "Connect: %s; Hostname: %s")
1559 (match !uri with None -> "default" | Some s -> s)
1562 (* Misc keys on left. *)
1563 let banner = pad 38 (s_ "MAIN KEYS") in
1565 mvaddstr header_lineno 1 banner;
1569 let lineno = ref domains_lineno in
1570 fun () -> let i = !lineno in incr lineno; i
1572 let key keys description =
1573 let lineno = get_lineno () in
1574 move lineno 1; attron A.bold; addstr keys; attroff A.bold;
1575 move lineno 10; addstr description; ()
1577 key "space ^L" (s_ "Update display");
1578 key "q" (s_ "Quit");
1579 key "d s" (s_ "Set update interval");
1580 key "h" (s_ "Help");
1583 ignore (get_lineno ());
1584 let banner = pad 38 (s_ "SORTING") in
1586 mvaddstr (get_lineno ()) 1 banner;
1589 key "P" (s_ "Sort by %CPU");
1590 key "M" (s_ "Sort by %MEM");
1591 key "T" (s_ "Sort by TIME");
1592 key "N" (s_ "Sort by ID");
1593 key "F" (s_ "Select sort field");
1595 (* Display modes on right. *)
1596 let banner = pad 39 (s_ "DISPLAY MODES") in
1598 mvaddstr header_lineno 40 banner;
1602 let lineno = ref domains_lineno in
1603 fun () -> let i = !lineno in incr lineno; i
1605 let key keys description =
1606 let lineno = get_lineno () in
1607 move lineno 40; attron A.bold; addstr keys; attroff A.bold;
1608 move lineno 49; addstr description; ()
1610 key "0" (s_ "Domains display");
1611 key "1" (s_ "Toggle physical CPUs");
1612 key "2" (s_ "Toggle network interfaces");
1613 key "3" (s_ "Toggle block devices");
1615 (* Update screen and wait for key press. *)
1616 mvaddstr (lines-1) 0
1617 (s_ "More help in virt-top(1) man page. Press any key to return.");
1621 and unknown_command k =
1622 print_msg (s_ "Unknown command - try 'h' for help");