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 let rcfile = ".virt-toprc"
33 (* Hook for XML support (see virt_top_xml.ml). *)
34 let parse_device_xml : (int -> [>`R] D.t -> string list * string list) ref =
39 (* Hooks for CSV support (see virt_top_csv.ml). *)
40 let csv_start : (string -> unit) ref =
42 fun _ -> failwith (s_"virt-top was compiled without support for CSV files")
44 let csv_write : (string list -> unit) ref =
49 (* Hook for calendar support (see virt_top_calendar.ml). *)
50 let parse_date_time : (string -> float) ref =
53 failwith (s_"virt-top was compiled without support for dates and times")
58 | DomainID | DomainName | Processor | Memory | Time
59 | NetRX | NetTX | BlockRdRq | BlockWrRq
60 let all_sort_fields = [
61 DomainID; DomainName; Processor; Memory; Time;
62 NetRX; NetTX; BlockRdRq; BlockWrRq
64 let printable_sort_order = function
65 | Processor -> s_"%CPU"
67 | Time -> s_"TIME (CPU time)"
68 | DomainID -> s_"Domain ID"
69 | DomainName -> s_"Domain name"
70 | NetRX -> s_"Net RX bytes"
71 | NetTX -> s_"Net TX bytes"
72 | BlockRdRq -> s_"Block read reqs"
73 | BlockWrRq -> s_"Block write reqs"
74 let sort_order_of_cli = function
75 | "cpu" | "processor" -> Processor
76 | "mem" | "memory" -> Memory
79 | "name" -> DomainName
80 | "netrx" -> NetRX | "nettx" -> NetTX
81 | "blockrdrq" -> BlockRdRq | "blockwrrq" -> BlockWrRq
83 failwithf (f_"%s: sort order should be: %s")
84 str "cpu|mem|time|id|name|netrx|nettx|blockrdrq|blockwrrq"
85 let cli_of_sort_order = function
90 | DomainName -> "name"
93 | BlockRdRq -> "blockrdrq"
94 | BlockWrRq -> "blockwrrq"
96 (* Current major display mode: TaskDisplay is the normal display. *)
97 type display = TaskDisplay | PCPUDisplay | BlockDisplay | NetDisplay
99 let display_of_cli = function
100 | "task" -> TaskDisplay
101 | "pcpu" -> PCPUDisplay
102 | "block" -> BlockDisplay
103 | "net" -> NetDisplay
105 failwithf (f_"%s: display should be %s") str "task|pcpu|block|net"
106 let cli_of_display = function
107 | TaskDisplay -> "task"
108 | PCPUDisplay -> "pcpu"
109 | BlockDisplay -> "block"
110 | NetDisplay -> "net"
113 type init_file = NoInitFile | DefaultInitFile | InitFile of string
117 let delay = ref 3000 (* milliseconds *)
118 let historical_cpu_delay = ref 20 (* secs *)
119 let iterations = ref (-1)
120 let end_time = ref None
121 let batch_mode = ref false
122 let secure_mode = ref false
123 let sort_order = ref Processor
124 let display_mode = ref TaskDisplay
126 let debug_file = ref ""
127 let csv_enabled = ref false
128 let csv_cpu = ref true
129 let csv_block = ref true
130 let csv_net = ref true
131 let init_file = ref DefaultInitFile
132 let script_mode = ref false
134 (* Tuple of never-changing data returned by start_up function. *)
136 Libvirt.ro C.t * bool * bool * bool * C.node_info * string *
139 (* Function to read command line arguments and go into curses mode. *)
141 (* Read command line arguments. *)
142 let rec set_delay newdelay =
143 if newdelay <= 0. then
144 failwith (s_"-d: cannot set a negative delay");
145 delay := int_of_float (newdelay *. 1000.)
146 and set_uri = function "" -> uri := None | u -> uri := Some u
147 and set_sort order = sort_order := sort_order_of_cli order
148 and set_pcpu_mode () = display_mode := PCPUDisplay
149 and set_net_mode () = display_mode := NetDisplay
150 and set_block_mode () = display_mode := BlockDisplay
151 and set_csv filename =
152 (!csv_start) filename;
154 and no_init_file () = init_file := NoInitFile
155 and set_init_file filename = init_file := InitFile filename
156 and set_end_time time = end_time := Some ((!parse_date_time) time)
157 and display_version () =
158 printf "virt-top %s ocaml-libvirt %s\n"
159 Virt_top_version.version Libvirt_version.version;
162 let argspec = Arg.align [
163 "-1", Arg.Unit set_pcpu_mode,
164 " " ^ s_"Start by displaying pCPUs (default: tasks)";
165 "-2", Arg.Unit set_net_mode,
166 " " ^ s_"Start by displaying network interfaces";
167 "-3", Arg.Unit set_block_mode,
168 " " ^ s_"Start by displaying block devices";
169 "-b", Arg.Set batch_mode,
170 " " ^ s_"Batch mode";
171 "-c", Arg.String set_uri,
172 "uri " ^ s_"Connect to URI (default: Xen)";
173 "--connect", Arg.String set_uri,
174 "uri " ^ s_"Connect to URI (default: Xen)";
175 "--csv", Arg.String set_csv,
176 "file " ^ s_"Log statistics to CSV file";
177 "--no-csv-cpu", Arg.Clear csv_cpu,
178 " " ^ s_"Disable CPU stats in CSV";
179 "--no-csv-block", Arg.Clear csv_block,
180 " " ^ s_"Disable block device stats in CSV";
181 "--no-csv-net", Arg.Clear csv_net,
182 " " ^ s_"Disable net stats in CSV";
183 "-d", Arg.Float set_delay,
184 "delay " ^ s_"Delay time interval (seconds)";
185 "--debug", Arg.Set_string debug_file,
186 "file " ^ s_"Send debug messages to file";
187 "--end-time", Arg.String set_end_time,
188 "time " ^ s_"Exit at given time";
189 "--hist-cpu", Arg.Set_int historical_cpu_delay,
190 "secs " ^ s_"Historical CPU delay";
191 "--init-file", Arg.String set_init_file,
192 "file " ^ s_"Set name of init file";
193 "--no-init-file", Arg.Unit no_init_file,
194 " " ^ s_"Do not read init file";
195 "-n", Arg.Set_int iterations,
196 "iterations " ^ s_"Number of iterations to run";
197 "-o", Arg.String set_sort,
198 "sort " ^ sprintf (f_"Set sort order (%s)") "cpu|mem|time|id|name";
199 "-s", Arg.Set secure_mode,
200 " " ^ s_"Secure (\"kiosk\") mode";
201 "--script", Arg.Set script_mode,
202 " " ^ s_"Run from a script (no user interface)";
203 "--version", Arg.Unit display_version,
204 " " ^ s_"Display version number and exit";
207 raise (Arg.Bad (sprintf (f_"%s: unknown parameter") str)) in
208 let usage_msg = s_"virt-top : a 'top'-like utility for virtualization
214 Arg.parse argspec anon_fun usage_msg;
216 (* Read the init file. *)
217 let try_to_read_init_file filename =
218 let config = read_config_file filename in
221 | _, "display", mode -> display_mode := display_of_cli mode
222 | _, "delay", secs -> set_delay (float_of_string secs)
223 | _, "hist-cpu", secs -> historical_cpu_delay := int_of_string secs
224 | _, "iterations", n -> iterations := int_of_string n
225 | _, "sort", order -> set_sort order
226 | _, "connect", uri -> set_uri uri
227 | _, "debug", filename -> debug_file := filename
228 | _, "csv", filename -> set_csv filename
229 | _, "csv-cpu", b -> csv_cpu := bool_of_string b
230 | _, "csv-block", b -> csv_block := bool_of_string b
231 | _, "csv-net", b -> csv_net := bool_of_string b
232 | _, "batch", b -> batch_mode := bool_of_string b
233 | _, "secure", b -> secure_mode := bool_of_string b
234 | _, "script", b -> script_mode := bool_of_string b
235 | _, "end-time", t -> set_end_time t
236 | _, "overwrite-init-file", "false" -> no_init_file ()
238 eprintf (f_"%s:%d: configuration item ``%s'' ignored\n%!")
242 (match !init_file with
245 let home = try Sys.getenv "HOME" with Not_found -> "/" in
246 let filename = home // rcfile in
247 try_to_read_init_file filename
248 | InitFile filename ->
249 try_to_read_init_file filename
252 (* Connect to the hypervisor before going into curses mode, since
253 * this is the most likely thing to fail.
257 try C.connect_readonly ?name ()
259 Libvirt.Virterror err ->
260 prerr_endline (Libvirt.Virterror.to_string err);
261 (* If non-root and no explicit connection URI, print a warning. *)
262 if Unix.geteuid () <> 0 && name = None then (
263 print_endline (s_"NB: If you want to monitor a local Xen hypervisor, you usually need to be root");
267 (* Get the node_info. This never changes, right? So we get it just once. *)
268 let node_info = C.get_node_info conn in
270 (* Hostname and libvirt library version also don't change. *)
272 try C.get_hostname conn
274 (* qemu:/// and other URIs didn't support virConnectGetHostname until
275 * libvirt 0.3.3. Before that they'd throw a virterror. *)
276 | Libvirt.Virterror _
277 | Libvirt.Not_supported "virConnectGetHostname" -> "unknown" in
279 let libvirt_version =
280 let v, _ = Libvirt.get_version () in
281 v / 1_000_000, (v / 1_000) mod 1_000, v mod 1_000 in
283 (* Open debug file if specified.
284 * NB: Do this just before jumping into curses mode.
286 (match !debug_file with
287 | "" -> (* No debug file specified, send stderr to /dev/null unless
288 * we're in script mode.
290 if not !script_mode then (
291 let fd = Unix.openfile "/dev/null" [Unix.O_WRONLY] 0o644 in
292 Unix.dup2 fd Unix.stderr;
295 | filename -> (* Send stderr to the named file. *)
297 Unix.openfile filename [Unix.O_WRONLY;Unix.O_CREAT;Unix.O_TRUNC]
299 Unix.dup2 fd Unix.stderr;
303 (* Curses voodoo (see ncurses(3)). *)
304 if not !script_mode then (
309 let stdscr = stdscr () in
310 ignore (intrflush stdscr false);
311 ignore (keypad stdscr true);
315 (* This tuple of static information is called 'setup' in other parts
316 * of this program, and is passed to other functions such as redraw and
317 * main_loop. See virt_top_main.ml.
320 !batch_mode, !script_mode, !csv_enabled, (* immutable modes *)
321 node_info, hostname, libvirt_version (* info that doesn't change *)
324 (* Show a domain state (the 'S' column). *)
325 let show_state = function
326 | D.InfoNoState -> '?'
327 | D.InfoRunning -> 'R'
328 | D.InfoBlocked -> 'S'
329 | D.InfoPaused -> 'P'
330 | D.InfoShutdown -> 'D'
331 | D.InfoShutoff -> 'O'
332 | D.InfoCrashed -> 'X'
334 (* Sleep in seconds. *)
335 let sleep = Unix.sleep
337 (* Sleep in milliseconds. *)
339 ignore (Unix.select [] [] [] (float n /. 1000.))
341 (* The curses getstr/getnstr functions are just weird.
342 * This helper function also enables echo temporarily.
344 let get_string maxlen =
346 let str = String.create maxlen in
347 let ok = getstr str in (* Safe because binding calls getnstr. *)
351 (* Chop at first '\0'. *)
353 let i = String.index str '\000' in
356 Not_found -> str (* it is full maxlen bytes *)
361 let summary_lineno = 1 (* this takes 2 lines *)
362 let message_lineno = 3
363 let header_lineno = 4
364 let domains_lineno = 5
366 (* Easier to use versions of curses functions addstr, mvaddstr, etc. *)
367 let move y x = ignore (move y x)
368 let refresh () = ignore (refresh ())
369 let addch c = ignore (addch (int_of_char c))
370 let addstr s = ignore (addstr s)
371 let mvaddstr y x s = ignore (mvaddstr y x s)
373 (* Print in the "message area". *)
374 let clear_msg () = move message_lineno 0; clrtoeol ()
375 let print_msg str = clear_msg (); mvaddstr message_lineno 0 str
377 (* Intermediate "domain + stats" structure that we use to collect
378 * everything we know about a domain within the collect function.
380 type rd_domain = Inactive | Active of rd_active
382 rd_domid : int; (* Domain ID. *)
383 rd_dom : [`R] D.t; (* Domain object. *)
384 rd_info : D.info; (* Domain CPU info now. *)
385 rd_block_stats : (string * D.block_stats) list;
386 (* Domain block stats now. *)
387 rd_interface_stats : (string * D.interface_stats) list;
388 (* Domain net stats now. *)
389 rd_prev_info : D.info option; (* Domain CPU info previously. *)
390 rd_prev_block_stats : (string * D.block_stats) list;
391 (* Domain block stats prev. *)
392 rd_prev_interface_stats : (string * D.interface_stats) list;
393 (* Domain interface stats prev. *)
394 (* The following are since the last slice, or 0 if cannot be calculated: *)
395 rd_cpu_time : float; (* CPU time used in nanoseconds. *)
396 rd_percent_cpu : float; (* CPU time as percent of total. *)
397 (* The following are since the last slice, or None if cannot be calc'd: *)
398 rd_block_rd_reqs : int64 option; (* Number of block device read rqs. *)
399 rd_block_wr_reqs : int64 option; (* Number of block device write rqs. *)
400 rd_net_rx_bytes : int64 option; (* Number of bytes received. *)
401 rd_net_tx_bytes : int64 option; (* Number of bytes transmitted. *)
405 let collect, clear_pcpu_display_data =
406 (* We cache the list of block devices and interfaces for each domain
407 * here, so we don't need to reparse the XML each time.
409 let devices = Hashtbl.create 13 in
411 (* Function to get the list of block devices, network interfaces for
412 * a particular domain. Get it from the devices cache, and if not
413 * there then parse the domain XML.
415 let get_devices id dom =
416 try Hashtbl.find devices id
418 let blkdevs, netifs = (!parse_device_xml) id dom in
419 Hashtbl.replace devices id (blkdevs, netifs);
423 (* We save the state of domains across redraws here, which allows us
424 * to deduce %CPU usage from the running total.
426 let last_info = Hashtbl.create 13 in
427 let last_time = ref (Unix.gettimeofday ()) in
429 (* Save vcpuinfo structures across redraws too (only for pCPU display). *)
430 let last_vcpu_info = Hashtbl.create 13 in
432 let clear_pcpu_display_data () =
433 (* Clear out vcpu_info used by PCPUDisplay display_mode
434 * when we switch back to TaskDisplay mode.
436 Hashtbl.clear last_vcpu_info
439 let collect (conn, _, _, _, node_info, _, _) =
440 (* Number of physical CPUs (some may be disabled). *)
441 let nr_pcpus = C.maxcpus_of_node_info node_info in
443 (* Get the current time. *)
444 let time = Unix.gettimeofday () in
445 let tm = Unix.localtime time in
447 sprintf "%02d:%02d:%02d" tm.Unix.tm_hour tm.Unix.tm_min tm.Unix.tm_sec in
449 (* What's the total CPU time elapsed since we were last called? (ns) *)
450 let total_cpu_per_pcpu = 1_000_000_000. *. (time -. !last_time) in
451 (* Avoid division by zero. *)
452 let total_cpu_per_pcpu =
453 if total_cpu_per_pcpu <= 0. then 1. else total_cpu_per_pcpu in
454 let total_cpu = float node_info.C.cpus *. total_cpu_per_pcpu in
456 (* Get the domains. Match up with their last_info (if any). *)
458 (* Active domains. *)
459 let n = C.num_of_domains conn in
461 if n > 0 then Array.to_list (C.list_domains conn n)
467 let dom = D.lookup_by_id conn id in
468 let name = D.get_name dom in
469 let blkdevs, netifs = get_devices id dom in
471 (* Get current CPU, block and network stats. *)
472 let info = D.get_info dom in
474 try List.map (fun dev -> dev, D.block_stats dom dev) blkdevs
476 | Libvirt.Not_supported "virDomainBlockStats"
477 | Libvirt.Virterror _ -> [] in
478 let interface_stats =
479 try List.map (fun dev -> dev, D.interface_stats dom dev) netifs
481 | Libvirt.Not_supported "virDomainInterfaceStats"
482 | Libvirt.Virterror _ -> [] in
484 let prev_info, prev_block_stats, prev_interface_stats =
486 let prev_info, prev_block_stats, prev_interface_stats =
487 Hashtbl.find last_info id in
488 Some prev_info, prev_block_stats, prev_interface_stats
489 with Not_found -> None, [], [] in
492 rd_domid = id; rd_dom = dom; rd_info = info;
493 rd_block_stats = block_stats;
494 rd_interface_stats = interface_stats;
495 rd_prev_info = prev_info;
496 rd_prev_block_stats = prev_block_stats;
497 rd_prev_interface_stats = prev_interface_stats;
498 rd_cpu_time = 0.; rd_percent_cpu = 0.;
499 rd_block_rd_reqs = None; rd_block_wr_reqs = None;
500 rd_net_rx_bytes = None; rd_net_tx_bytes = None;
503 Libvirt.Virterror _ -> None (* ignore transient error *)
506 (* Inactive domains. *)
509 let n = C.num_of_defined_domains conn in
511 if n > 0 then Array.to_list (C.list_defined_domains conn n)
513 List.map (fun name -> name, Inactive) names
515 (* Ignore transient errors, in particular errors from
516 * num_of_defined_domains if it cannot contact xend.
518 | Libvirt.Virterror _ -> [] in
520 doms @ doms_inactive in
522 (* Calculate the CPU time (ns) and %CPU used by each domain. *)
526 (* We have previous CPU info from which to calculate it? *)
527 | name, Active ({ rd_prev_info = Some prev_info } as rd) ->
529 Int64.to_float (rd.rd_info.D.cpu_time -^ prev_info.D.cpu_time) in
530 let percent_cpu = 100. *. cpu_time /. total_cpu in
532 rd_cpu_time = cpu_time;
533 rd_percent_cpu = percent_cpu } in
535 (* For all other domains we can't calculate it, so leave as 0 *)
539 (* Calculate the number of block device read/write requests across
540 * all block devices attached to a domain.
545 (* Do we have stats from the previous slice? *)
546 | name, Active ({ rd_prev_block_stats = ((_::_) as prev_block_stats) }
548 let block_stats = rd.rd_block_stats in (* stats now *)
550 (* Add all the devices together. Throw away device names. *)
551 let prev_block_stats =
552 sum_block_stats (List.map snd prev_block_stats) in
554 sum_block_stats (List.map snd block_stats) in
556 (* Calculate increase in read & write requests. *)
558 block_stats.D.rd_req -^ prev_block_stats.D.rd_req in
560 block_stats.D.wr_req -^ prev_block_stats.D.wr_req in
563 rd_block_rd_reqs = Some read_reqs;
564 rd_block_wr_reqs = Some write_reqs } in
566 (* For all other domains we can't calculate it, so leave as None. *)
570 (* Calculate the same as above for network interfaces across
571 * all network interfaces attached to a domain.
576 (* Do we have stats from the previous slice? *)
577 | name, Active ({ rd_prev_interface_stats =
578 ((_::_) as prev_interface_stats) }
580 let interface_stats = rd.rd_interface_stats in (* stats now *)
582 (* Add all the devices together. Throw away device names. *)
583 let prev_interface_stats =
584 sum_interface_stats (List.map snd prev_interface_stats) in
585 let interface_stats =
586 sum_interface_stats (List.map snd interface_stats) in
588 (* Calculate increase in rx & tx bytes. *)
590 interface_stats.D.rx_bytes -^ prev_interface_stats.D.rx_bytes in
592 interface_stats.D.tx_bytes -^ prev_interface_stats.D.tx_bytes in
595 rd_net_rx_bytes = Some rx_bytes;
596 rd_net_tx_bytes = Some tx_bytes } in
598 (* For all other domains we can't calculate it, so leave as None. *)
602 (* Collect some extra information in PCPUDisplay display_mode. *)
604 if !display_mode = PCPUDisplay then (
605 (* Get the VCPU info and VCPU->PCPU mappings for active domains.
606 * Also cull some data we don't care about.
608 let doms = List.filter_map (
610 | (name, Active rd) ->
612 let domid = rd.rd_domid in
613 let maplen = C.cpumaplen nr_pcpus in
614 let maxinfo = rd.rd_info.D.nr_virt_cpu in
615 let nr_vcpus, vcpu_infos, cpumaps =
616 D.get_vcpus rd.rd_dom maxinfo maplen in
618 (* Got previous vcpu_infos for this domain? *)
619 let prev_vcpu_infos =
620 try Some (Hashtbl.find last_vcpu_info domid)
621 with Not_found -> None in
622 (* Update last_vcpu_info. *)
623 Hashtbl.replace last_vcpu_info domid vcpu_infos;
625 (match prev_vcpu_infos with
626 | Some prev_vcpu_infos
627 when Array.length prev_vcpu_infos = Array.length vcpu_infos ->
628 Some (domid, name, nr_vcpus, vcpu_infos, prev_vcpu_infos,
630 | _ -> None (* ignore missing / unequal length prev_vcpu_infos *)
633 Libvirt.Virterror _ -> None(* ignore transient libvirt errs *)
635 | (_, Inactive) -> None (* ignore inactive doms *)
637 let nr_doms = List.length doms in
639 (* Rearrange the data into a matrix. Major axis (down) is
640 * pCPUs. Minor axis (right) is domains. At each node we store:
641 * cpu_time (on this pCPU only, nanosecs),
642 * average? (if set, then cpu_time is an average because the
643 * vCPU is pinned to more than one pCPU)
644 * running? (if set, we were instantaneously running on this pCPU)
646 let empty_node = (0L, false, false) in
647 let pcpus = Array.make_matrix nr_pcpus nr_doms empty_node in
650 fun di (domid, name, nr_vcpus, vcpu_infos, prev_vcpu_infos,
652 (* Which pCPUs can this dom run on? *)
653 for v = 0 to nr_vcpus-1 do
654 let pcpu = vcpu_infos.(v).D.cpu in (* instantaneous pCPU *)
655 let nr_poss_pcpus = ref 0 in (* how many pcpus can it run on? *)
656 for p = 0 to nr_pcpus-1 do
657 (* vcpu v can reside on pcpu p *)
658 if C.cpu_usable cpumaps maplen v p then
661 let nr_poss_pcpus = Int64.of_int !nr_poss_pcpus in
662 for p = 0 to nr_pcpus-1 do
663 (* vcpu v can reside on pcpu p *)
664 if C.cpu_usable cpumaps maplen v p then
665 let vcpu_time_on_pcpu =
666 vcpu_infos.(v).D.vcpu_time
667 -^ prev_vcpu_infos.(v).D.vcpu_time in
668 let vcpu_time_on_pcpu =
669 vcpu_time_on_pcpu /^ nr_poss_pcpus in
671 (vcpu_time_on_pcpu, nr_poss_pcpus > 1L, p = pcpu)
676 (* Sum the CPU time used by each pCPU, for the %CPU column. *)
677 let pcpus_cpu_time = Array.map (
679 let cpu_time = ref 0L in
680 for di = 0 to Array.length row-1 do
681 let t, _, _ = row.(di) in
682 cpu_time := !cpu_time +^ t
684 Int64.to_float !cpu_time
687 Some (doms, pcpus, pcpus_cpu_time)
691 (* Calculate totals. *)
692 let totals = List.fold_left (
693 fun (count, running, blocked, paused, shutdown, shutoff,
694 crashed, active, inactive,
695 total_cpu_time, total_memory, total_domU_memory) ->
697 | (name, Active rd) ->
698 let test state orig =
699 if rd.rd_info.D.state = state then orig+1 else orig
701 let running = test D.InfoRunning running in
702 let blocked = test D.InfoBlocked blocked in
703 let paused = test D.InfoPaused paused in
704 let shutdown = test D.InfoShutdown shutdown in
705 let shutoff = test D.InfoShutoff shutoff in
706 let crashed = test D.InfoCrashed crashed in
708 let total_cpu_time = total_cpu_time +. rd.rd_cpu_time in
709 let total_memory = total_memory +^ rd.rd_info.D.memory in
710 let total_domU_memory = total_domU_memory +^
711 if rd.rd_domid > 0 then rd.rd_info.D.memory else 0L in
713 (count+1, running, blocked, paused, shutdown, shutoff,
714 crashed, active+1, inactive,
715 total_cpu_time, total_memory, total_domU_memory)
717 | (name, Inactive) -> (* inactive domain *)
718 (count+1, running, blocked, paused, shutdown, shutoff,
719 crashed, active, inactive+1,
720 total_cpu_time, total_memory, total_domU_memory)
721 ) (0,0,0,0,0,0,0,0,0, 0.,0L,0L) doms in
723 (* Update last_time, last_info. *)
725 Hashtbl.clear last_info;
729 let info = rd.rd_info, rd.rd_block_stats, rd.rd_interface_stats in
730 Hashtbl.add last_info rd.rd_domid info
735 time, printable_time,
736 nr_pcpus, total_cpu, total_cpu_per_pcpu,
741 collect, clear_pcpu_display_data
743 (* Redraw the display. *)
745 (* Keep a historical list of %CPU usages. *)
746 let historical_cpu = ref [] in
747 let historical_cpu_last_time = ref (Unix.gettimeofday ()) in
749 (_, _, _, _, node_info, _, _) (* setup *)
751 time, printable_time,
752 nr_pcpus, total_cpu, total_cpu_per_pcpu,
754 pcpu_display) (* state *) ->
757 (* Get the screen/window size. *)
758 let lines, cols = get_size () in
761 mvaddstr top_lineno 0 (sprintf "virt-top %s - " printable_time);
763 (* Basic node_info. *)
765 (sprintf "%s %d/%dCPU %dMHz %LdMB "
766 node_info.C.model node_info.C.cpus nr_pcpus node_info.C.mhz
767 (node_info.C.memory /^ 1024L));
768 (* Save the cursor position for when we come to draw the
769 * historical CPU times (down in this function).
771 let stdscr = stdscr () in
772 let historical_cursor = getyx stdscr in
774 (match !display_mode with
775 | TaskDisplay -> (*---------- Showing domains ----------*)
776 (* Sort domains on current sort_order. *)
779 match !sort_order with
781 (fun _ -> 0) (* fallthrough to default name compare *)
784 | Active rd1, Active rd2 ->
785 compare rd2.rd_percent_cpu rd1.rd_percent_cpu
786 | Active _, Inactive -> -1
787 | Inactive, Active _ -> 1
788 | Inactive, Inactive -> 0)
791 | Active { rd_info = info1 }, Active { rd_info = info2 } ->
792 compare info2.D.memory info1.D.memory
793 | Active _, Inactive -> -1
794 | Inactive, Active _ -> 1
795 | Inactive, Inactive -> 0)
798 | Active { rd_info = info1 }, Active { rd_info = info2 } ->
799 compare info2.D.cpu_time info1.D.cpu_time
800 | Active _, Inactive -> -1
801 | Inactive, Active _ -> 1
802 | Inactive, Inactive -> 0)
805 | Active { rd_domid = id1 }, Active { rd_domid = id2 } ->
807 | Active _, Inactive -> -1
808 | Inactive, Active _ -> 1
809 | Inactive, Inactive -> 0)
812 | Active { rd_net_rx_bytes = r1 }, Active { rd_net_rx_bytes = r2 } ->
814 | Active _, Inactive -> -1
815 | Inactive, Active _ -> 1
816 | Inactive, Inactive -> 0)
819 | Active { rd_net_tx_bytes = r1 }, Active { rd_net_tx_bytes = r2 } ->
821 | Active _, Inactive -> -1
822 | Inactive, Active _ -> 1
823 | Inactive, Inactive -> 0)
826 | Active { rd_block_rd_reqs = r1 }, Active { rd_block_rd_reqs = r2 } ->
828 | Active _, Inactive -> -1
829 | Inactive, Active _ -> 1
830 | Inactive, Inactive -> 0)
833 | Active { rd_block_wr_reqs = r1 }, Active { rd_block_wr_reqs = r2 } ->
835 | Active _, Inactive -> -1
836 | Inactive, Active _ -> 1
837 | Inactive, Inactive -> 0)
839 let cmp (name1, dom1) (name2, dom2) =
840 let r = cmp (dom1, dom2) in
842 else compare name1 name2
844 List.sort ~cmp doms in
848 mvaddstr header_lineno 0
849 (pad cols " ID S RDRQ WRRQ RXBY TXBY %CPU %MEM TIME NAME");
852 let rec loop lineno = function
854 | (name, Active rd) :: doms ->
855 if lineno < lines then (
856 let state = show_state rd.rd_info.D.state in
857 let rd_req = Show.int64_option rd.rd_block_rd_reqs in
858 let wr_req = Show.int64_option rd.rd_block_wr_reqs in
859 let rx_bytes = Show.int64_option rd.rd_net_rx_bytes in
860 let tx_bytes = Show.int64_option rd.rd_net_tx_bytes in
861 let percent_cpu = Show.percent rd.rd_percent_cpu in
863 100L *^ rd.rd_info.D.memory /^ node_info.C.memory in
864 let percent_mem = Int64.to_float percent_mem in
865 let percent_mem = Show.percent percent_mem in
866 let time = Show.time rd.rd_info.D.cpu_time in
868 let line = sprintf "%5d %c %s %s %s %s %s %s %s %s"
869 rd.rd_domid state rd_req wr_req rx_bytes tx_bytes
870 percent_cpu percent_mem time name in
871 let line = pad cols line in
872 mvaddstr lineno 0 line;
875 | (name, Inactive) :: doms -> (* inactive domain *)
876 if lineno < lines then (
881 let line = pad cols line in
882 mvaddstr lineno 0 line;
886 loop domains_lineno doms
888 | PCPUDisplay -> (*---------- Showing physical CPUs ----------*)
889 let doms, pcpus, pcpus_cpu_time =
890 match pcpu_display with
892 | None -> failwith "internal error: no pcpu_display data" in
894 (* Display the pCPUs. *)
898 fun (_, name, _, _, _, _, _) ->
899 let len = String.length name in
900 let width = max (len+1) 7 in
905 mvaddstr header_lineno 0 (pad cols ("PHYCPU %CPU " ^ dom_names));
910 mvaddstr (p+domains_lineno) 0 (sprintf "%4d " p);
911 let cpu_time = pcpus_cpu_time.(p) in (* ns used on this CPU *)
912 let percent_cpu = 100. *. cpu_time /. total_cpu_per_pcpu in
913 addstr (Show.percent percent_cpu);
917 fun di (domid, name, _, _, _, _, _) ->
918 let t, is_average, is_running = pcpus.(p).(di) in
919 let len = String.length name in
920 let width = max (len+1) 7 in
924 let t = Int64.to_float t in
925 let percent = 100. *. t /. total_cpu_per_pcpu in
926 sprintf "%s%c%c " (Show.percent percent)
927 (if is_average then '=' else ' ')
928 (if is_running then '#' else ' ')
930 addstr (pad width str);
935 | NetDisplay -> (*---------- Showing network interfaces ----------*)
936 (* Only care about active domains. *)
937 let doms = List.filter_map (
939 | (name, Active rd) -> Some (name, rd)
940 | (_, Inactive) -> None
943 (* For each domain we have a list of network interfaces seen
944 * this slice, and seen in the previous slice, which we now
945 * match up to get a list of (domain, interface) for which
946 * we have current & previous knowledge. (And ignore the rest).
954 (* Have prev slice stats for this device? *)
956 List.assoc dev rd.rd_prev_interface_stats in
957 Some (dev, name, rd, stats, prev_stats)
958 with Not_found -> None
959 ) rd.rd_interface_stats
962 (* Finally we have a list of:
963 * device name, domain name, rd_* stuff, curr stats, prev stats.
965 let devs : (string * string * rd_active *
966 D.interface_stats * D.interface_stats) list =
969 (* Difference curr slice & prev slice. *)
970 let devs = List.map (
971 fun (dev, name, rd, curr, prev) ->
972 dev, name, rd, diff_interface_stats curr prev
975 (* Sort by current sort order, but map some of the standard
976 * sort orders into ones which makes sense here.
980 match !sort_order with
982 (fun _ -> 0) (* fallthrough to default name compare *)
984 (fun (_, { rd_domid = id1 }, _, { rd_domid = id2 }) ->
986 | Processor | Memory | Time | BlockRdRq | BlockWrRq
987 (* fallthrough to RXBY comparison. *)
989 (fun ({ D.rx_bytes = b1 }, _, { D.rx_bytes = b2 }, _) ->
992 (fun ({ D.tx_bytes = b1 }, _, { D.tx_bytes = b2 }, _) ->
995 let cmp (dev1, name1, rd1, stats1) (dev2, name2, rd2, stats2) =
996 let r = cmp (stats1, rd1, stats2, rd2) in
998 else compare (dev1, name1) (dev2, name2)
1000 List.sort ~cmp devs in
1002 (* Print the header for network devices. *)
1004 mvaddstr header_lineno 0
1005 (pad cols " ID S RXBY TXBY RXPK TXPK DOMAIN INTERFACE");
1008 (* Print domains and devices. *)
1009 let rec loop lineno = function
1011 | (dev, name, rd, stats) :: devs ->
1012 if lineno < lines then (
1013 let state = show_state rd.rd_info.D.state in
1015 if stats.D.rx_bytes >= 0L
1016 then Show.int64 stats.D.rx_bytes
1019 if stats.D.tx_bytes >= 0L
1020 then Show.int64 stats.D.tx_bytes
1023 if stats.D.rx_packets >= 0L
1024 then Show.int64 stats.D.rx_packets
1027 if stats.D.tx_packets >= 0L
1028 then Show.int64 stats.D.tx_packets
1031 let line = sprintf "%5d %c %s %s %s %s %-12s %s"
1034 rx_packets tx_packets
1035 (pad 12 name) dev in
1036 let line = pad cols line in
1037 mvaddstr lineno 0 line;
1038 loop (lineno+1) devs
1041 loop domains_lineno devs
1043 | BlockDisplay -> (*---------- Showing block devices ----------*)
1044 (* Only care about active domains. *)
1045 let doms = List.filter_map (
1047 | (name, Active rd) -> Some (name, rd)
1048 | (_, Inactive) -> None
1051 (* For each domain we have a list of block devices seen
1052 * this slice, and seen in the previous slice, which we now
1053 * match up to get a list of (domain, device) for which
1054 * we have current & previous knowledge. (And ignore the rest).
1062 (* Have prev slice stats for this device? *)
1064 List.assoc dev rd.rd_prev_block_stats in
1065 Some (dev, name, rd, stats, prev_stats)
1066 with Not_found -> None
1070 (* Finally we have a list of:
1071 * device name, domain name, rd_* stuff, curr stats, prev stats.
1073 let devs : (string * string * rd_active *
1074 D.block_stats * D.block_stats) list =
1075 List.flatten devs in
1077 (* Difference curr slice & prev slice. *)
1078 let devs = List.map (
1079 fun (dev, name, rd, curr, prev) ->
1080 dev, name, rd, diff_block_stats curr prev
1083 (* Sort by current sort order, but map some of the standard
1084 * sort orders into ones which makes sense here.
1088 match !sort_order with
1090 (fun _ -> 0) (* fallthrough to default name compare *)
1092 (fun (_, { rd_domid = id1 }, _, { rd_domid = id2 }) ->
1094 | Processor | Memory | Time | NetRX | NetTX
1095 (* fallthrough to RDRQ comparison. *)
1097 (fun ({ D.rd_req = b1 }, _, { D.rd_req = b2 }, _) ->
1100 (fun ({ D.wr_req = b1 }, _, { D.wr_req = b2 }, _) ->
1103 let cmp (dev1, name1, rd1, stats1) (dev2, name2, rd2, stats2) =
1104 let r = cmp (stats1, rd1, stats2, rd2) in
1106 else compare (dev1, name1) (dev2, name2)
1108 List.sort ~cmp devs in
1110 (* Print the header for block devices. *)
1112 mvaddstr header_lineno 0
1113 (pad cols " ID S RDBY WRBY RDRQ WRRQ DOMAIN DEVICE");
1116 (* Print domains and devices. *)
1117 let rec loop lineno = function
1119 | (dev, name, rd, stats) :: devs ->
1120 if lineno < lines then (
1121 let state = show_state rd.rd_info.D.state in
1123 if stats.D.rd_bytes >= 0L
1124 then Show.int64 stats.D.rd_bytes
1127 if stats.D.wr_bytes >= 0L
1128 then Show.int64 stats.D.wr_bytes
1131 if stats.D.rd_req >= 0L
1132 then Show.int64 stats.D.rd_req
1135 if stats.D.wr_req >= 0L
1136 then Show.int64 stats.D.wr_req
1139 let line = sprintf "%5d %c %s %s %s %s %-12s %s"
1143 (pad 12 name) dev in
1144 let line = pad cols line in
1145 mvaddstr lineno 0 line;
1146 loop (lineno+1) devs
1149 loop domains_lineno devs
1150 ); (* end of display_mode conditional section *)
1152 let (count, running, blocked, paused, shutdown, shutoff,
1153 crashed, active, inactive,
1154 total_cpu_time, total_memory, total_domU_memory) = totals in
1156 mvaddstr summary_lineno 0
1158 (f_"%d domains, %d active, %d running, %d sleeping, %d paused, %d inactive D:%d O:%d X:%d")
1159 count active running blocked paused inactive shutdown shutoff crashed);
1161 (* Total %CPU used, and memory summary. *)
1162 let percent_cpu = 100. *. total_cpu_time /. total_cpu in
1163 mvaddstr (summary_lineno+1) 0
1165 (f_"CPU: %2.1f%% Mem: %Ld MB (%Ld MB by guests)")
1166 percent_cpu (total_memory /^ 1024L) (total_domU_memory /^ 1024L));
1168 (* Time to grab another historical %CPU for the list? *)
1169 if time >= !historical_cpu_last_time +. float !historical_cpu_delay
1171 historical_cpu := percent_cpu :: List.take 10 !historical_cpu;
1172 historical_cpu_last_time := time
1175 (* Display historical CPU time. *)
1177 let x, y = historical_cursor in (* Yes, it's a bug in ocaml-curses *)
1178 let maxwidth = cols - x in
1181 (List.map (sprintf "%2.1f%%") !historical_cpu) in
1182 let line = pad maxwidth line in
1186 move message_lineno 0; (* Park cursor in message area, as with top. *)
1187 refresh () (* Refresh the display. *)
1189 (* Write CSV header row. *)
1190 let write_csv_header () =
1192 [ "Hostname"; "Time"; "Arch"; "Physical CPUs";
1193 "Count"; "Running"; "Blocked"; "Paused"; "Shutdown";
1194 "Shutoff"; "Crashed"; "Active"; "Inactive";
1196 "Total hardware memory (KB)";
1197 "Total memory (KB)"; "Total guest memory (KB)";
1198 "Total CPU time (ns)" ] @
1199 (* These fields are repeated for each domain: *)
1200 [ "Domain ID"; "Domain name"; ] @
1201 (if !csv_cpu then [ "CPU (ns)"; "%CPU"; ] else []) @
1202 (if !csv_block then [ "Block RDRQ"; "Block WRRQ"; ] else []) @
1203 (if !csv_net then [ "Net RXBY"; "Net TXBY" ] else [])
1206 (* Write summary data to CSV file. *)
1208 (_, _, _, _, node_info, hostname, _) (* setup *)
1211 nr_pcpus, total_cpu, _,
1215 (* The totals / summary fields. *)
1216 let (count, running, blocked, paused, shutdown, shutoff,
1217 crashed, active, inactive,
1218 total_cpu_time, total_memory, total_domU_memory) = totals in
1220 let percent_cpu = 100. *. total_cpu_time /. total_cpu in
1222 let summary_fields = [
1223 hostname; printable_time; node_info.C.model; string_of_int nr_pcpus;
1224 string_of_int count; string_of_int running; string_of_int blocked;
1225 string_of_int paused; string_of_int shutdown; string_of_int shutoff;
1226 string_of_int crashed; string_of_int active; string_of_int inactive;
1227 sprintf "%2.1f" percent_cpu;
1228 Int64.to_string node_info.C.memory;
1229 Int64.to_string total_memory; Int64.to_string total_domU_memory;
1230 Int64.to_string (Int64.of_float total_cpu_time)
1235 * Sort them by ID so that the list of relatively stable. Ignore
1238 let doms = List.filter_map (
1240 | _, Inactive -> None (* Ignore inactive domains. *)
1241 | name, Active rd -> Some (name, rd)
1243 let cmp (_, { rd_domid = rd_domid1 }) (_, { rd_domid = rd_domid2 }) =
1244 compare rd_domid1 rd_domid2
1246 let doms = List.sort ~cmp doms in
1248 let string_of_int64_option = Option.map_default Int64.to_string "" in
1250 let domain_fields = List.map (
1251 fun (domname, rd) ->
1252 [ string_of_int rd.rd_domid; domname ] @
1254 string_of_float rd.rd_cpu_time; string_of_float rd.rd_percent_cpu
1256 (if !csv_block then [
1257 string_of_int64_option rd.rd_block_rd_reqs;
1258 string_of_int64_option rd.rd_block_wr_reqs;
1261 string_of_int64_option rd.rd_net_rx_bytes;
1262 string_of_int64_option rd.rd_net_tx_bytes;
1265 let domain_fields = List.flatten domain_fields in
1267 (!csv_write) (summary_fields @ domain_fields)
1270 let rec main_loop ((_, batch_mode, script_mode, csv_enabled, _, _, _)
1272 if csv_enabled then write_csv_header ();
1275 let state = collect setup in (* Collect stats. *)
1276 if not script_mode then redraw setup state; (* Redraw display. *)
1277 if csv_enabled then append_csv setup state; (* Update CSV file. *)
1279 (* Clear up unused virDomainPtr objects. *)
1282 (* Get next key. This does the sleep. *)
1283 if not batch_mode && not script_mode then
1284 get_key_press setup;
1286 (* Max iterations? *)
1287 if !iterations >= 0 then (
1289 if !iterations = 0 then quit := true
1293 (match !end_time with
1296 let (_, time, _, _, _, _, _, _) = state in
1297 let delay_secs = float !delay /. 1000. in
1298 if end_time <= time +. delay_secs then quit := true
1301 (* Batch mode or script mode. We didn't call get_key_press above, so
1302 * we didn't sleep. Sleep now, unless we are about to quit.
1304 if batch_mode || script_mode then
1309 and get_key_press setup =
1310 (* Read the next key, waiting up to !delay milliseconds. *)
1313 timeout (-1); (* Reset to blocking mode. *)
1315 if k >= 0 && k <> 32 (* ' ' *) && k <> 12 (* ^L *) && k <> Key.resize
1317 if k = Char.code 'q' then quit := true
1318 else if k = Char.code 'h' then show_help setup
1319 else if k = Char.code 's' || k = Char.code 'd' then change_delay ()
1320 else if k = Char.code 'M' then sort_order := Memory
1321 else if k = Char.code 'P' then sort_order := Processor
1322 else if k = Char.code 'T' then sort_order := Time
1323 else if k = Char.code 'N' then sort_order := DomainID
1324 else if k = Char.code 'F' then change_sort_order ()
1325 else if k = Char.code '0' then set_tasks_display ()
1326 else if k = Char.code '1' then toggle_pcpu_display ()
1327 else if k = Char.code '2' then toggle_net_display ()
1328 else if k = Char.code '3' then toggle_block_display ()
1329 else if k = Char.code 'W' then write_init_file ()
1330 else unknown_command k
1333 and change_delay () =
1335 (sprintf (f_"Change delay from %.1f to: ") (float !delay /. 1000.));
1336 let str = get_string 16 in
1337 (* Try to parse the number. *)
1340 let newdelay = float_of_string str in
1341 if newdelay <= 0. then (
1342 print_msg (s_"Delay must be > 0"); true
1344 delay := int_of_float (newdelay *. 1000.); false
1347 Failure "float_of_string" ->
1348 print_msg (s_"Not a valid number"); true in
1350 sleep (if error then 2 else 1)
1352 and change_sort_order () =
1354 let lines, cols = get_size () in
1356 mvaddstr top_lineno 0 (s_"Set sort order for main display");
1357 mvaddstr summary_lineno 0 (s_"Type key or use up and down cursor keys.");
1360 mvaddstr header_lineno 0 (pad cols "KEY Sort field");
1363 let accelerator_key = function
1364 | Memory -> "(key: M)"
1365 | Processor -> "(key: P)"
1366 | Time -> "(key: T)"
1367 | DomainID -> "(key: N)"
1368 | _ -> (* all others have to be changed from here *) ""
1371 let rec key_of_int = function
1372 | i when i < 10 -> Char.chr (i + Char.code '0')
1373 | i when i < 20 -> Char.chr (i + Char.code 'a')
1375 and int_of_key = function
1376 | k when k >= 0x30 && k <= 0x39 (* '0' - '9' *) -> k - 0x30
1377 | k when k >= 0x61 && k <= 0x7a (* 'a' - 'j' *) -> k - 0x61 + 10
1378 | k when k >= 0x41 && k <= 0x6a (* 'A' - 'J' *) -> k - 0x41 + 10
1382 (* Display possible sort fields. *)
1383 let selected_index = ref 0 in
1386 let selected = !sort_order = ord in
1387 if selected then selected_index := i;
1388 mvaddstr (domains_lineno+i) 0
1389 (sprintf " %c %s %s %s"
1390 (key_of_int i) (if selected then "*" else " ")
1391 (printable_sort_order ord)
1392 (accelerator_key ord))
1395 move message_lineno 0;
1398 if k >= 0 && k <> 32 && k <> Char.code 'q' && k <> 13 then (
1399 let new_order, loop =
1400 (* Redraw the display. *)
1401 if k = 12 (* ^L *) then None, true
1402 (* Make the UP and DOWN arrow keys do something useful. *)
1403 else if k = Key.up then (
1404 if !selected_index > 0 then
1405 Some (List.nth all_sort_fields (!selected_index-1)), true
1409 else if k = Key.down then (
1410 if !selected_index < List.length all_sort_fields - 1 then
1411 Some (List.nth all_sort_fields (!selected_index+1)), true
1415 (* Also understand the regular accelerator keys. *)
1416 else if k = Char.code 'M' then
1418 else if k = Char.code 'P' then
1419 Some Processor, false
1420 else if k = Char.code 'T' then
1422 else if k = Char.code 'N' then
1423 Some DomainID, false
1425 (* It's one of the KEYs. *)
1426 let i = int_of_key k in
1427 if i >= 0 && i < List.length all_sort_fields then
1428 Some (List.nth all_sort_fields i), false
1433 (match new_order with
1436 sort_order := new_order;
1437 print_msg (sprintf "Sort order changed to: %s"
1438 (printable_sort_order new_order));
1445 if loop then change_sort_order ()
1448 (* Note: We need to clear_pcpu_display_data every time
1449 * we _leave_ PCPUDisplay mode.
1451 and set_tasks_display () = (* key 0 *)
1452 if !display_mode = PCPUDisplay then clear_pcpu_display_data ();
1453 display_mode := TaskDisplay
1455 and toggle_pcpu_display () = (* key 1 *)
1457 match !display_mode with
1458 | TaskDisplay | NetDisplay | BlockDisplay -> PCPUDisplay
1459 | PCPUDisplay -> clear_pcpu_display_data (); TaskDisplay
1461 and toggle_net_display () = (* key 2 *)
1463 match !display_mode with
1464 | PCPUDisplay -> clear_pcpu_display_data (); NetDisplay
1465 | TaskDisplay | BlockDisplay -> NetDisplay
1466 | NetDisplay -> TaskDisplay
1468 and toggle_block_display () = (* key 3 *)
1470 match !display_mode with
1471 | PCPUDisplay -> clear_pcpu_display_data (); BlockDisplay
1472 | TaskDisplay | NetDisplay -> BlockDisplay
1473 | BlockDisplay -> TaskDisplay
1475 (* Write an init file. *)
1476 and write_init_file () =
1477 match !init_file with
1478 | NoInitFile -> () (* Do nothing if --no-init-file *)
1479 | DefaultInitFile ->
1480 let home = try Sys.getenv "HOME" with Not_found -> "/" in
1481 let filename = home // rcfile in
1482 _write_init_file filename
1483 | InitFile filename ->
1484 _write_init_file filename
1486 and _write_init_file filename =
1488 (* Create the new file as filename.new. *)
1489 let chan = open_out (filename ^ ".new") in
1491 let time = Unix.gettimeofday () in
1492 let tm = Unix.localtime time in
1493 let printable_date_time =
1494 sprintf "%04d-%02d-%02d %02d:%02d:%02d"
1495 (tm.Unix.tm_year + 1900) (tm.Unix.tm_mon+1) tm.Unix.tm_mday
1496 tm.Unix.tm_hour tm.Unix.tm_min tm.Unix.tm_sec in
1499 let uid = Unix.geteuid () in
1500 (Unix.getpwuid uid).Unix.pw_name
1502 Not_found -> "unknown" in
1505 let nl () = fp chan "\n" in
1506 let () = fp chan (f_"# %s virt-top configuration file\n") rcfile in
1507 let () = fp chan (f_"# generated on %s by %s\n") printable_date_time username in
1509 fp chan "display %s\n" (cli_of_display !display_mode);
1510 fp chan "delay %g\n" (float !delay /. 1000.);
1511 fp chan "hist-cpu %d\n" !historical_cpu_delay;
1512 if !iterations <> -1 then fp chan "iterations %d\n" !iterations;
1513 fp chan "sort %s\n" (cli_of_sort_order !sort_order);
1516 | Some uri -> fp chan "connect %s\n" uri
1518 if !batch_mode = true then fp chan "batch true\n";
1519 if !secure_mode = true then fp chan "secure true\n";
1521 output_string chan (s_"# To send debug and error messages to a file, uncomment next line\n");
1522 fp chan "#debug virt-top.out\n";
1524 output_string chan (s_"# Enable CSV output to the named file\n");
1525 fp chan "#csv virt-top.csv\n";
1527 output_string chan (s_"# To protect this file from being overwritten, uncomment next line\n");
1528 fp chan "#overwrite-init-file false\n";
1532 (* If the file exists, rename it as filename.old. *)
1533 (try Unix.rename filename (filename ^ ".old")
1534 with Unix.Unix_error _ -> ());
1536 (* Rename filename.new to filename. *)
1537 Unix.rename (filename ^ ".new") filename;
1539 print_msg (sprintf (f_"Wrote settings to %s") filename);
1544 print_msg (s_"Error" ^ ": " ^ err);
1546 | Unix.Unix_error (err, fn, str) ->
1547 print_msg (s_"Error" ^ ": " ^
1548 (Unix.error_message err) ^ " " ^ fn ^ " " ^ str);
1552 and show_help (_, _, _, _, _, hostname,
1553 (libvirt_major, libvirt_minor, libvirt_release)) =
1556 (* Get the screen/window size. *)
1557 let lines, cols = get_size () in
1559 (* Banner at the top of the screen. *)
1561 sprintf (f_"virt-top %s ocaml-libvirt %s libvirt %d.%d.%d by Red Hat")
1562 Virt_top_version.version
1563 Libvirt_version.version
1564 libvirt_major libvirt_minor libvirt_release in
1565 let banner = pad cols banner in
1567 mvaddstr 0 0 banner;
1573 (f_"Delay: %.1f secs; Batch: %s; Secure: %s; Sort: %s")
1574 (float !delay /. 1000.)
1575 (if !batch_mode then s_"On" else s_"Off")
1576 (if !secure_mode then s_"On" else s_"Off")
1577 (printable_sort_order !sort_order));
1580 (f_"Connect: %s; Hostname: %s")
1581 (match !uri with None -> s_"default" | Some s -> s)
1584 (* Misc keys on left. *)
1585 let banner = pad 38 (s_"MAIN KEYS") in
1587 mvaddstr header_lineno 1 banner;
1591 let lineno = ref domains_lineno in
1592 fun () -> let i = !lineno in incr lineno; i
1594 let key keys description =
1595 let lineno = get_lineno () in
1596 move lineno 1; attron A.bold; addstr keys; attroff A.bold;
1597 move lineno 10; addstr description
1599 key "space ^L" (s_"Update display");
1601 key "d s" (s_"Set update interval");
1605 ignore (get_lineno ());
1606 let banner = pad 38 (s_"SORTING") in
1608 mvaddstr (get_lineno ()) 1 banner;
1611 key "P" (s_"Sort by %CPU");
1612 key "M" (s_"Sort by %MEM");
1613 key "T" (s_"Sort by TIME");
1614 key "N" (s_"Sort by ID");
1615 key "F" (s_"Select sort field");
1617 (* Display modes on right. *)
1618 let banner = pad 39 (s_"DISPLAY MODES") in
1620 mvaddstr header_lineno 40 banner;
1624 let lineno = ref domains_lineno in
1625 fun () -> let i = !lineno in incr lineno; i
1627 let key keys description =
1628 let lineno = get_lineno () in
1629 move lineno 40; attron A.bold; addstr keys; attroff A.bold;
1630 move lineno 49; addstr description
1632 key "0" (s_"Domains display");
1633 key "1" (s_"Toggle physical CPUs");
1634 key "2" (s_"Toggle network interfaces");
1635 key "3" (s_"Toggle block devices");
1637 (* Update screen and wait for key press. *)
1638 mvaddstr (lines-1) 0
1639 (s_"More help in virt-top(1) man page. Press any key to return.");
1643 and unknown_command k =
1644 print_msg (s_"Unknown command - try 'h' for help");