1 (* 'top'-like tool for libvirt domains.
2 * $Id: virt_top.ml,v 1.5 2007/08/30 13:52:40 rjones Exp $
9 module C = Libvirt.Connect
10 module D = Libvirt.Domain
11 module N = Libvirt.Network
13 (* Hook for XML support (see virt_top_xml.ml). *)
14 let parse_device_xml : (int -> [>`R] D.t -> string list * string list) ref =
19 (* Hooks for CSV support (see virt_top_csv.ml). *)
20 let csv_start : (string -> unit) ref =
22 fun _ -> failwith "virt-top was compiled without support for CSV"
24 let csv_write : (string list -> unit) ref =
29 (* Int64 operators for convenience. *)
32 let ( *^ ) = Int64.mul
36 | DomainID | DomainName | Processor | Memory | Time
37 | NetRX | NetTX | BlockRdRq | BlockWrRq
38 let all_sort_fields = [
39 DomainID; DomainName; Processor; Memory; Time;
40 NetRX; NetTX; BlockRdRq; BlockWrRq
42 let printable_sort_order = function
45 | Time -> "TIME (CPU time)"
46 | DomainID -> "Domain ID"
47 | DomainName -> "Domain name"
48 | NetRX -> "Net RX bytes"
49 | NetTX -> "Net TX bytes"
50 | BlockRdRq -> "Block read reqs"
51 | BlockWrRq -> "Block write reqs"
53 (* Current major display mode: TaskDisplay is the normal display. *)
54 type display = TaskDisplay | PCPUDisplay | BlockDisplay | NetDisplay
58 let delay = ref 3000 (* milliseconds *)
59 let historical_cpu_delay = ref 20 (* secs *)
60 let iterations = ref (-1)
61 let batch_mode = ref false
62 let secure_mode = ref false
63 let sort_order = ref Processor
64 let display_mode = ref TaskDisplay
66 let debug_file = ref ""
67 let csv_enabled = ref false
69 (* Function to read command line arguments and go into curses mode. *)
71 (* Read command line arguments. *)
72 let rec set_delay newdelay =
73 if newdelay <= 0. then
74 failwith "-d: cannot set a negative delay";
75 delay := int_of_float (newdelay *. 1000.)
76 and set_uri = function "" -> uri := None | u -> uri := Some u
77 and set_sort = function
78 | "cpu" | "processor" -> sort_order := Processor
79 | "mem" | "memory" -> sort_order := Memory
80 | "time" -> sort_order := Time
81 | "id" -> sort_order := DomainID
82 | "name" -> sort_order := DomainName
83 | "netrx" -> sort_order := NetRX | "nettx" -> sort_order := NetTX
84 | "blockrdrq" -> sort_order := BlockRdRq
85 | "blockwrrq" -> sort_order := BlockWrRq
86 | str -> failwith (str ^ ": sort order should be: cpu|mem|time|id|name|netrx|nettx|blockrdrq|blockwrrq")
87 and set_pcpu_mode () = display_mode := PCPUDisplay
88 and set_net_mode () = display_mode := NetDisplay
89 and set_block_mode () = display_mode := BlockDisplay
90 and set_csv filename =
91 (!csv_start) filename;
94 let argspec = Arg.align [
95 "-1", Arg.Unit set_pcpu_mode, " Start by displaying pCPUs (default: tasks)";
96 "-2", Arg.Unit set_net_mode, " Start by displaying network interfaces";
97 "-3", Arg.Unit set_block_mode, " Start by displaying block devices";
98 "-b", Arg.Set batch_mode, " Batch mode";
99 "-c", Arg.String set_uri, "uri Connect to URI (default: Xen)";
100 "--connect", Arg.String set_uri, "uri Connect to URI (default: Xen)";
101 "--csv", Arg.String set_csv, "file Log statistics to CSV file";
102 "-d", Arg.Float set_delay, "delay Delay time interval (seconds)";
103 "--debug", Arg.Set_string debug_file, "file Send debug messages to file";
104 "--hist-cpu", Arg.Set_int historical_cpu_delay, "secs Historical CPU delay";
105 "-n", Arg.Set_int iterations, "iterations Number of iterations to run";
106 "-o", Arg.String set_sort, "sort Set sort order (cpu|mem|time|id|name)";
107 "-s", Arg.Set secure_mode, " Secure (\"kiosk\") mode";
109 let anon_fun str = raise (Arg.Bad (str ^ ": unknown parameter")) in
110 let usage_msg = "virt-top : a 'top'-like utility for virtualization
116 Arg.parse argspec anon_fun usage_msg;
118 (* Connect to the hypervisor before going into curses mode, since
119 * this is the most likely thing to fail.
123 try C.connect_readonly ?name ()
125 Libvirt.Virterror err ->
126 prerr_endline (Libvirt.Virterror.to_string err);
127 (* If non-root and no explicit connection URI, print a warning. *)
128 if Unix.geteuid () <> 0 && name = None then (
129 print_endline "NB: If you want to monitor a local Xen hypervisor, you usually need to be root";
133 (* Get the node_info. This never changes, right? So we get it just once. *)
134 let node_info = C.get_node_info conn in
136 (* Hostname and libvirt library version also don't change. *)
138 try C.get_hostname conn
140 (* qemu:/// and other URIs didn't support virConnectGetHostname until
141 * libvirt 0.3.3. Before that they'd throw a virterror. *)
142 | Libvirt.Virterror _
143 | Invalid_argument "virConnectGetHostname not supported" -> "unknown" in
145 let libvirt_version =
146 let v, _ = Libvirt.get_version () in
147 v / 1_000_000, (v / 1_000) mod 1_000, v mod 1_000 in
149 (* Open debug file if specified.
150 * NB: Do this just before jumping into curses mode.
152 (match !debug_file with
153 | "" -> (* No debug file specified, send stderr to /dev/null. *)
155 let fd = Unix.openfile "/dev/null" [Unix.O_WRONLY] 0o644 in
156 Unix.dup2 fd Unix.stderr;
159 Unix.Unix_error _ -> ()
161 | filename -> (* Send stderr to the named file. *)
163 Unix.openfile filename [Unix.O_WRONLY;Unix.O_CREAT;Unix.O_TRUNC]
165 Unix.dup2 fd Unix.stderr;
169 (* Curses voodoo (see ncurses(3)). *)
175 let stdscr = stdscr () in
176 intrflush stdscr false;
180 (* This tuple of static information is called 'state' in other parts
181 * of this program, and is passed to other functions such as redraw and
182 * main_loop. See virt_top_main.ml. It's not really "state" though.
184 conn, stdscr, node_info, hostname, libvirt_version
186 (* Show a percentage in 4 chars. *)
187 let show_percent percent =
188 if percent <= 0. then " 0.0"
189 else if percent <= 9.9 then sprintf " %1.1f" percent
190 else if percent <= 99.9 then sprintf "%2.1f" percent
193 (* Show an int64 option in 4 chars. *)
194 let rec show_int64_option = function
196 | Some n -> show_int64 n
197 (* Show an int64 in 4 chars. *)
198 and show_int64 = function
199 | n when n < 0L -> "-!!!"
200 | n when n <= 9999L ->
202 | n when n /^ 1024L <= 999L ->
203 sprintf "%3LdK" (n /^ 1024L)
204 | n when n /^ 1_048_576L <= 999L ->
205 sprintf "%3LdM" (n /^ 1_048_576L)
206 | n when n /^ 1_073_741_824L <= 999L ->
207 sprintf "%3LdG" (n /^ 1_073_741_824L)
210 (* Format the total time (may be large!) in 9 chars. *)
212 let secs_in_ns = 1_000_000_000L in
213 let mins_in_ns = 60_000_000_000L in
214 let hours_in_ns = 3_600_000_000_000L in
216 let hours = ns /^ hours_in_ns in
217 let ns = ns -^ (hours *^ hours_in_ns) in
218 let mins = ns /^ mins_in_ns in
219 let ns = ns -^ (mins *^ mins_in_ns) in
220 let secs = ns /^ secs_in_ns in
221 let ns = ns -^ (secs *^ secs_in_ns) in
222 let pennies = ns /^ 10_000_000L in
225 sprintf "%3Ld:%02Ld.%02Ld" (hours *^ 60L +^ mins) secs pennies
226 else if hours <= 999L then
227 sprintf "%3Ld:%02Ld:%02Ld" hours mins secs
229 let days = hours /^ 24L in
230 let hours = hours -^ (days *^ 24L) in
231 sprintf "%3Ldd%02Ld:%02Ld" days hours mins
234 (* Show a domain state (the 'S' column). *)
235 let show_state = function
236 | D.InfoNoState -> '?'
237 | D.InfoRunning -> 'R'
238 | D.InfoBlocked -> 'S'
239 | D.InfoPaused -> 'P'
240 | D.InfoShutdown -> 'D'
241 | D.InfoShutoff -> 'O'
242 | D.InfoCrashed -> 'X'
244 (* Sum Domain.block_stats structures together. Missing fields
245 * get forced to 0. Empty list returns all 0.
247 let zero_block_stats =
248 { D.rd_req = 0L; rd_bytes = 0L; wr_req = 0L; wr_bytes = 0L; errs = 0L }
249 let add_block_stats bs1 bs2 =
250 let add f1 f2 = if f1 >= 0L && f2 >= 0L then f1 +^ f2 else 0L in
251 { D.rd_req = add bs1.D.rd_req bs2.D.rd_req;
252 rd_bytes = add bs1.D.rd_bytes bs2.D.rd_bytes;
253 wr_req = add bs1.D.wr_req bs2.D.wr_req;
254 wr_bytes = add bs1.D.wr_bytes bs2.D.wr_bytes;
255 errs = add bs1.D.errs bs2.D.errs }
256 let sum_block_stats =
257 List.fold_left add_block_stats zero_block_stats
259 (* Get the difference between two block_stats structures. Missing data
260 * forces the difference to -1.
262 let diff_block_stats curr prev =
263 let sub f1 f2 = if f1 >= 0L && f2 >= 0L then f1 -^ f2 else -1L in
264 { D.rd_req = sub curr.D.rd_req prev.D.rd_req;
265 rd_bytes = sub curr.D.rd_bytes prev.D.rd_bytes;
266 wr_req = sub curr.D.wr_req prev.D.wr_req;
267 wr_bytes = sub curr.D.wr_bytes prev.D.wr_bytes;
268 errs = sub curr.D.errs prev.D.errs }
270 (* Sum Domain.interface_stats structures together. Missing fields
271 * get forced to 0. Empty list returns all 0.
273 let zero_interface_stats =
274 { D.rx_bytes = 0L; rx_packets = 0L; rx_errs = 0L; rx_drop = 0L;
275 tx_bytes = 0L; tx_packets = 0L; tx_errs = 0L; tx_drop = 0L }
276 let add_interface_stats is1 is2 =
277 let add f1 f2 = if f1 >= 0L && f2 >= 0L then f1 +^ f2 else 0L in
278 { D.rx_bytes = add is1.D.rx_bytes is2.D.rx_bytes;
279 rx_packets = add is1.D.rx_packets is2.D.rx_packets;
280 rx_errs = add is1.D.rx_errs is2.D.rx_errs;
281 rx_drop = add is1.D.rx_drop is2.D.rx_drop;
282 tx_bytes = add is1.D.tx_bytes is2.D.tx_bytes;
283 tx_packets = add is1.D.tx_packets is2.D.tx_packets;
284 tx_errs = add is1.D.tx_errs is2.D.tx_errs;
285 tx_drop = add is1.D.tx_drop is2.D.tx_drop }
286 let sum_interface_stats =
287 List.fold_left add_interface_stats zero_interface_stats
289 (* Get the difference between two interface_stats structures.
290 * Missing data forces the difference to -1.
292 let diff_interface_stats curr prev =
293 let sub f1 f2 = if f1 >= 0L && f2 >= 0L then f1 -^ f2 else -1L in
294 { D.rx_bytes = sub curr.D.rx_bytes prev.D.rx_bytes;
295 rx_packets = sub curr.D.rx_packets prev.D.rx_packets;
296 rx_errs = sub curr.D.rx_errs prev.D.rx_errs;
297 rx_drop = sub curr.D.rx_drop prev.D.rx_drop;
298 tx_bytes = sub curr.D.tx_bytes prev.D.tx_bytes;
299 tx_packets = sub curr.D.tx_packets prev.D.tx_packets;
300 tx_errs = sub curr.D.tx_errs prev.D.tx_errs;
301 tx_drop = sub curr.D.tx_drop prev.D.tx_drop }
303 (* Update the display and sleep for given number of seconds. *)
304 let sleep n = refresh (); Unix.sleep n
306 (* The curses getstr/getnstr functions are just weird.
307 * This helper function also enables echo temporarily.
309 let get_string maxlen =
311 let str = String.create maxlen in
312 let ok = getstr str in (* Safe because binding calls getnstr. *)
316 (* Chop at first '\0'. *)
318 let i = String.index str '\000' in
321 Not_found -> str (* it is full maxlen bytes *)
324 (* Pad a string to the full width with spaces. If too long, truncate. *)
326 let n = String.length str in
327 if n = width then str
328 else if n > width then String.sub str 0 width
329 else (* if n < width then *) str ^ String.make (width-n) ' '
333 let summary_lineno = 1 (* this takes 2 lines *)
334 let message_lineno = 3
335 let header_lineno = 4
336 let domains_lineno = 5
338 (* Print in the "message area". *)
339 let clear_msg () = move message_lineno 0; clrtoeol ()
340 let print_msg str = clear_msg (); mvaddstr message_lineno 0 str; ()
342 (* Write CSV header row. *)
343 let write_csv_header () =
344 (!csv_write) [ "Hostname"; "Time"; "Arch"; "Physical CPUs";
345 "Count"; "Running"; "Blocked"; "Paused"; "Shutdown";
346 "Shutoff"; "Crashed"; "Active"; "Inactive";
347 "%CPU"; "Total memory KB"; "Total guest memory KB";
348 "Total CPU time ns" ]
350 (* Intermediate "domain + stats" structure that we use to collect
351 * everything we know about a domain within the redraw function.
353 type rd_domain = Inactive | Active of rd_active
355 rd_domid : int; (* Domain ID. *)
356 rd_dom : [`R] D.t; (* Domain object. *)
357 rd_info : D.info; (* Domain CPU info now. *)
358 rd_block_stats : (string * D.block_stats) list;
359 (* Domain block stats now. *)
360 rd_interface_stats : (string * D.interface_stats) list;
361 (* Domain net stats now. *)
362 rd_prev_info : D.info option; (* Domain CPU info previously. *)
363 rd_prev_block_stats : (string * D.block_stats) list;
364 (* Domain block stats prev. *)
365 rd_prev_interface_stats : (string * D.interface_stats) list;
366 (* Domain interface stats prev. *)
367 (* The following are since the last slice, or 0 if cannot be calculated: *)
368 rd_cpu_time : float; (* CPU time used in nanoseconds. *)
369 rd_percent_cpu : float; (* CPU time as percent of total. *)
370 (* The following are since the last slice, or None if cannot be calc'd: *)
371 rd_block_rd_reqs : int64 option; (* Number of block device read rqs. *)
372 rd_block_wr_reqs : int64 option; (* Number of block device write rqs. *)
373 rd_net_rx_bytes : int64 option; (* Number of bytes received. *)
374 rd_net_tx_bytes : int64 option; (* Number of bytes transmitted. *)
377 (* Redraw the display. *)
378 let redraw, clear_pcpu_display_data =
379 (* We cache the list of block devices and interfaces for each domain
380 * here, so we don't need to reparse the XML each time.
382 let devices = Hashtbl.create 13 in
384 (* Function to get the list of block devices, network interfaces for
385 * a particular domain. Get it from the devices cache, and if not
386 * there then parse the domain XML.
388 let get_devices id dom =
389 try Hashtbl.find devices id
391 let blkdevs, netifs = (!parse_device_xml) id dom in
392 Hashtbl.replace devices id (blkdevs, netifs);
396 (* We save the state of domains across redraws here, which allows us
397 * to deduce %CPU usage from the running total.
399 let last_info = Hashtbl.create 13 in
400 let last_time = ref (Unix.gettimeofday ()) in
402 (* Save vcpuinfo structures across redraws too (only for pCPU display). *)
403 let last_vcpu_info = Hashtbl.create 13 in
405 (* Keep a historical list of %CPU usages. *)
406 let historical_cpu = ref [] in
407 let historical_cpu_last_time = ref (Unix.gettimeofday ()) in
409 let redraw (conn, stdscr, node_info, hostname, _) =
412 (* Get the screen/window size. *)
413 let lines, cols = get_size () in
415 (* Number of physical CPUs (some may be disabled). *)
416 let nr_pcpus = C.maxcpus_of_node_info node_info in
418 (* Get the current time. *)
419 let time = Unix.gettimeofday () in
420 let tm = Unix.localtime time in
422 sprintf "%02d:%02d:%02d" tm.Unix.tm_hour tm.Unix.tm_min tm.Unix.tm_sec in
423 mvaddstr top_lineno 0 ("virt-top " ^ printable_time ^ " - ");
425 (* What's the total CPU time elapsed since we were last called? (ns) *)
426 let total_cpu_per_pcpu = 1_000_000_000. *. (time -. !last_time) in
427 (* Avoid division by zero. *)
428 let total_cpu_per_pcpu =
429 if total_cpu_per_pcpu <= 0. then 1. else total_cpu_per_pcpu in
430 let total_cpu = float node_info.C.cpus *. total_cpu_per_pcpu in
432 (* Basic node_info. *)
433 addstr (sprintf "%s %d/%dCPU %dMHz %LdMB "
434 node_info.C.model node_info.C.cpus nr_pcpus node_info.C.mhz
435 (node_info.C.memory /^ 1024L));
436 (* Save the cursor position for when we come to draw the
437 * historical CPU times (down in this function).
439 let historical_cursor = getyx stdscr in
441 (* Get the domains. Match up with their last_info (if any). *)
443 (* Active domains. *)
444 let n = C.num_of_domains conn in
446 if n > 0 then Array.to_list (C.list_domains conn n)
452 let dom = D.lookup_by_id conn id in
453 let name = D.get_name dom in
454 let blkdevs, netifs = get_devices id dom in
456 (* Get current CPU, block and network stats. *)
457 let info = D.get_info dom in
459 try List.map (fun dev -> dev, D.block_stats dom dev) blkdevs
461 | Invalid_argument "virDomainBlockStats not supported"
462 | Libvirt.Virterror _ -> [] in
463 let interface_stats =
464 try List.map (fun dev -> dev, D.interface_stats dom dev) netifs
466 | Invalid_argument "virDomainInterfaceStats not supported"
467 | Libvirt.Virterror _ -> [] in
469 let prev_info, prev_block_stats, prev_interface_stats =
471 let prev_info, prev_block_stats, prev_interface_stats =
472 Hashtbl.find last_info id in
473 Some prev_info, prev_block_stats, prev_interface_stats
474 with Not_found -> None, [], [] in
477 rd_domid = id; rd_dom = dom; rd_info = info;
478 rd_block_stats = block_stats;
479 rd_interface_stats = interface_stats;
480 rd_prev_info = prev_info;
481 rd_prev_block_stats = prev_block_stats;
482 rd_prev_interface_stats = prev_interface_stats;
483 rd_cpu_time = 0.; rd_percent_cpu = 0.;
484 rd_block_rd_reqs = None; rd_block_wr_reqs = None;
485 rd_net_rx_bytes = None; rd_net_tx_bytes = None;
488 Libvirt.Virterror _ -> None (* ignore transient error *)
491 (* Inactive domains. *)
494 let n = C.num_of_defined_domains conn in
496 if n > 0 then Array.to_list (C.list_defined_domains conn n)
498 List.map (fun name -> name, Inactive) names
500 (* Ignore transient errors, in particular errors from
501 * num_of_defined_domains if it cannot contact xend.
503 | Libvirt.Virterror _ -> [] in
505 doms @ doms_inactive in
507 (* Calculate the CPU time (ns) and %CPU used by each domain. *)
511 (* We have previous CPU info from which to calculate it? *)
512 | name, Active ({ rd_prev_info = Some prev_info } as rd) ->
514 Int64.to_float (rd.rd_info.D.cpu_time -^ prev_info.D.cpu_time) in
515 let percent_cpu = 100. *. cpu_time /. total_cpu in
517 rd_cpu_time = cpu_time;
518 rd_percent_cpu = percent_cpu } in
520 (* For all other domains we can't calculate it, so leave as 0 *)
524 (* Calculate the number of block device read/write requests across
525 * all block devices attached to a domain.
530 (* Do we have stats from the previous slice? *)
531 | name, Active ({ rd_prev_block_stats = ((_::_) as prev_block_stats) }
533 let block_stats = rd.rd_block_stats in (* stats now *)
535 (* Add all the devices together. Throw away device names. *)
536 let prev_block_stats =
537 sum_block_stats (List.map snd prev_block_stats) in
539 sum_block_stats (List.map snd block_stats) in
541 (* Calculate increase in read & write requests. *)
543 block_stats.D.rd_req -^ prev_block_stats.D.rd_req in
545 block_stats.D.wr_req -^ prev_block_stats.D.wr_req in
548 rd_block_rd_reqs = Some read_reqs;
549 rd_block_wr_reqs = Some write_reqs } in
551 (* For all other domains we can't calculate it, so leave as None. *)
555 (* Calculate the same as above for network interfaces across
556 * all network interfaces attached to a domain.
561 (* Do we have stats from the previous slice? *)
562 | name, Active ({ rd_prev_interface_stats =
563 ((_::_) as prev_interface_stats) }
565 let interface_stats = rd.rd_interface_stats in (* stats now *)
567 (* Add all the devices together. Throw away device names. *)
568 let prev_interface_stats =
569 sum_interface_stats (List.map snd prev_interface_stats) in
570 let interface_stats =
571 sum_interface_stats (List.map snd interface_stats) in
573 (* Calculate increase in rx & tx bytes. *)
575 interface_stats.D.rx_bytes -^ prev_interface_stats.D.rx_bytes in
577 interface_stats.D.tx_bytes -^ prev_interface_stats.D.tx_bytes in
580 rd_net_rx_bytes = Some rx_bytes;
581 rd_net_tx_bytes = Some tx_bytes } in
583 (* For all other domains we can't calculate it, so leave as None. *)
587 (match !display_mode with
588 | TaskDisplay -> (*---------- Showing domains ----------*)
589 (* Sort domains on current sort_order. *)
592 match !sort_order with
594 (fun _ -> 0) (* fallthrough to default name compare *)
597 | Active rd1, Active rd2 ->
598 compare rd2.rd_percent_cpu rd1.rd_percent_cpu
599 | Active _, Inactive -> -1
600 | Inactive, Active _ -> 1
601 | Inactive, Inactive -> 0)
604 | Active { rd_info = info1 }, Active { rd_info = info2 } ->
605 compare info2.D.memory info1.D.memory
606 | Active _, Inactive -> -1
607 | Inactive, Active _ -> 1
608 | Inactive, Inactive -> 0)
611 | Active { rd_info = info1 }, Active { rd_info = info2 } ->
612 compare info2.D.cpu_time info1.D.cpu_time
613 | Active _, Inactive -> -1
614 | Inactive, Active _ -> 1
615 | Inactive, Inactive -> 0)
618 | Active { rd_domid = id1 }, Active { rd_domid = id2 } ->
620 | Active _, Inactive -> -1
621 | Inactive, Active _ -> 1
622 | Inactive, Inactive -> 0)
625 | Active { rd_net_rx_bytes = r1 }, Active { rd_net_rx_bytes = r2 } ->
627 | Active _, Inactive -> -1
628 | Inactive, Active _ -> 1
629 | Inactive, Inactive -> 0)
632 | Active { rd_net_tx_bytes = r1 }, Active { rd_net_tx_bytes = r2 } ->
634 | Active _, Inactive -> -1
635 | Inactive, Active _ -> 1
636 | Inactive, Inactive -> 0)
639 | Active { rd_block_rd_reqs = r1 }, Active { rd_block_rd_reqs = r2 } ->
641 | Active _, Inactive -> -1
642 | Inactive, Active _ -> 1
643 | Inactive, Inactive -> 0)
646 | Active { rd_block_wr_reqs = r1 }, Active { rd_block_wr_reqs = r2 } ->
648 | Active _, Inactive -> -1
649 | Inactive, Active _ -> 1
650 | Inactive, Inactive -> 0)
652 let cmp (name1, dom1) (name2, dom2) =
653 let r = cmp (dom1, dom2) in
655 else compare name1 name2
657 List.sort ~cmp doms in
661 mvaddstr header_lineno 0
662 (pad cols " ID S RDRQ WRRQ RXBY TXBY %CPU %MEM TIME NAME");
665 let rec loop lineno = function
667 | (name, Active rd) :: doms ->
668 if lineno < lines then (
669 let state = show_state rd.rd_info.D.state in
670 let rd_req = show_int64_option rd.rd_block_rd_reqs in
671 let wr_req = show_int64_option rd.rd_block_wr_reqs in
672 let rx_bytes = show_int64_option rd.rd_net_rx_bytes in
673 let tx_bytes = show_int64_option rd.rd_net_tx_bytes in
674 let percent_cpu = show_percent rd.rd_percent_cpu in
676 100L *^ rd.rd_info.D.memory /^ node_info.C.memory in
677 let percent_mem = Int64.to_float percent_mem in
678 let percent_mem = show_percent percent_mem in
679 let time = show_time rd.rd_info.D.cpu_time in
681 let line = sprintf "%5d %c %s %s %s %s %s %s %s %s"
682 rd.rd_domid state rd_req wr_req rx_bytes tx_bytes
683 percent_cpu percent_mem time name in
684 let line = pad cols line in
685 mvaddstr lineno 0 line;
688 | (name, Inactive) :: doms -> (* inactive domain *)
689 if lineno < lines then (
694 let line = pad cols line in
695 mvaddstr lineno 0 line;
699 loop domains_lineno doms
701 | PCPUDisplay -> (*---------- Showing physical CPUs ----------*)
702 (* Get the VCPU info and VCPU->PCPU mappings for active domains.
703 * Also cull some data we don't care about.
705 let doms = List.filter_map (
707 | (name, Active rd) ->
709 let domid = rd.rd_domid in
710 let maplen = C.cpumaplen nr_pcpus in
711 let maxinfo = rd.rd_info.D.nr_virt_cpu in
712 let nr_vcpus, vcpu_infos, cpumaps =
713 D.get_vcpus rd.rd_dom maxinfo maplen in
715 (* Got previous vcpu_infos for this domain? *)
716 let prev_vcpu_infos =
717 try Some (Hashtbl.find last_vcpu_info domid)
718 with Not_found -> None in
719 (* Update last_vcpu_info. *)
720 Hashtbl.replace last_vcpu_info domid vcpu_infos;
722 (match prev_vcpu_infos with
723 | Some prev_vcpu_infos
724 when Array.length prev_vcpu_infos = Array.length vcpu_infos ->
725 Some (domid, name, nr_vcpus, vcpu_infos, prev_vcpu_infos,
727 | _ -> None (* ignore missing / unequal length prev_vcpu_infos *)
730 Libvirt.Virterror _ -> None(* ignore transient libvirt errs *)
732 | (_, Inactive) -> None (* ignore inactive doms *)
734 let nr_doms = List.length doms in
736 (* Rearrange the data into a matrix. Major axis (down) is
737 * pCPUs. Minor axis (right) is domains. At each node we store:
738 * cpu_time (on this pCPU only, nanosecs),
739 * average? (if set, then cpu_time is an average because the
740 * vCPU is pinned to more than one pCPU)
741 * running? (if set, we were instantaneously running on this pCPU)
743 let empty_node = (0L, false, false) in
744 let pcpus = Array.make_matrix nr_pcpus nr_doms empty_node in
747 fun di (domid, name, nr_vcpus, vcpu_infos, prev_vcpu_infos,
749 (* Which pCPUs can this dom run on? *)
750 for v = 0 to nr_vcpus-1 do
751 let pcpu = vcpu_infos.(v).D.cpu in (* instantaneous pCPU *)
752 let nr_poss_pcpus = ref 0 in (* how many pcpus can it run on? *)
753 for p = 0 to nr_pcpus-1 do
754 (* vcpu v can reside on pcpu p *)
755 if C.cpu_usable cpumaps maplen v p then
758 let nr_poss_pcpus = Int64.of_int !nr_poss_pcpus in
759 for p = 0 to nr_pcpus-1 do
760 (* vcpu v can reside on pcpu p *)
761 if C.cpu_usable cpumaps maplen v p then
762 let vcpu_time_on_pcpu =
763 vcpu_infos.(v).D.vcpu_time
764 -^ prev_vcpu_infos.(v).D.vcpu_time in
765 let vcpu_time_on_pcpu =
766 vcpu_time_on_pcpu /^ nr_poss_pcpus in
768 (vcpu_time_on_pcpu, nr_poss_pcpus > 1L, p = pcpu)
773 (* Sum the CPU time used by each pCPU, for the %CPU column. *)
774 let pcpus_cpu_time = Array.map (
776 let cpu_time = ref 0L in
777 for di = 0 to Array.length row-1 do
778 let t, _, _ = row.(di) in
779 cpu_time := !cpu_time +^ t
781 Int64.to_float !cpu_time
784 (* Display the pCPUs. *)
788 fun (_, name, _, _, _, _, _) ->
789 let len = String.length name in
790 let width = max (len+1) 7 in
795 mvaddstr header_lineno 0 (pad cols ("PHYCPU %CPU " ^ dom_names));
800 mvaddstr (p+domains_lineno) 0 (sprintf "%4d " p);
801 let cpu_time = pcpus_cpu_time.(p) in (* ns used on this CPU *)
802 let percent_cpu = 100. *. cpu_time /. total_cpu_per_pcpu in
803 addstr (show_percent percent_cpu);
807 fun di (domid, name, _, _, _, _, _) ->
808 let t, is_average, is_running = pcpus.(p).(di) in
809 let len = String.length name in
810 let width = max (len+1) 7 in
814 let t = Int64.to_float t in
815 let percent = 100. *. t /. total_cpu_per_pcpu in
816 sprintf "%s%c%c " (show_percent percent)
817 (if is_average then '=' else ' ')
818 (if is_running then '#' else ' ')
820 addstr (pad width str);
825 | NetDisplay -> (*---------- Showing network interfaces ----------*)
826 (* Only care about active domains. *)
827 let doms = List.filter_map (
829 | (name, Active rd) -> Some (name, rd)
830 | (_, Inactive) -> None
833 (* For each domain we have a list of network interfaces seen
834 * this slice, and seen in the previous slice, which we now
835 * match up to get a list of (domain, interface) for which
836 * we have current & previous knowledge. (And ignore the rest).
844 (* Have prev slice stats for this device? *)
846 List.assoc dev rd.rd_prev_interface_stats in
847 Some (dev, name, rd, stats, prev_stats)
848 with Not_found -> None
849 ) rd.rd_interface_stats
852 (* Finally we have a list of:
853 * device name, domain name, rd_* stuff, curr stats, prev stats.
855 let devs : (string * string * rd_active *
856 D.interface_stats * D.interface_stats) list =
859 (* Difference curr slice & prev slice. *)
860 let devs = List.map (
861 fun (dev, name, rd, curr, prev) ->
862 dev, name, rd, diff_interface_stats curr prev
865 (* Sort by current sort order, but map some of the standard
866 * sort orders into ones which makes sense here.
870 match !sort_order with
872 (fun _ -> 0) (* fallthrough to default name compare *)
874 (fun (_, { rd_domid = id1 }, _, { rd_domid = id2 }) ->
876 | Processor | Memory | Time | BlockRdRq | BlockWrRq
877 (* fallthrough to RXBY comparison. *)
879 (fun ({ D.rx_bytes = b1 }, _, { D.rx_bytes = b2 }, _) ->
882 (fun ({ D.tx_bytes = b1 }, _, { D.tx_bytes = b2 }, _) ->
885 let cmp (dev1, name1, rd1, stats1) (dev2, name2, rd2, stats2) =
886 let r = cmp (stats1, rd1, stats2, rd2) in
888 else compare (dev1, name1) (dev2, name2)
890 List.sort ~cmp devs in
892 (* Print the header for network devices. *)
894 mvaddstr header_lineno 0
895 (pad cols " ID S RXBY TXBY RXPK TXPK DOMAIN INTERFACE");
898 (* Print domains and devices. *)
899 let rec loop lineno = function
901 | (dev, name, rd, stats) :: devs ->
902 if lineno < lines then (
903 let state = show_state rd.rd_info.D.state in
905 if stats.D.rx_bytes >= 0L
906 then show_int64 stats.D.rx_bytes
909 if stats.D.tx_bytes >= 0L
910 then show_int64 stats.D.tx_bytes
913 if stats.D.rx_packets >= 0L
914 then show_int64 stats.D.rx_packets
917 if stats.D.tx_packets >= 0L
918 then show_int64 stats.D.tx_packets
921 let line = sprintf "%5d %c %s %s %s %s %-12s %s"
924 rx_packets tx_packets
926 let line = pad cols line in
927 mvaddstr lineno 0 line;
931 loop domains_lineno devs
933 | BlockDisplay -> (*---------- Showing block devices ----------*)
934 (* Only care about active domains. *)
935 let doms = List.filter_map (
937 | (name, Active rd) -> Some (name, rd)
938 | (_, Inactive) -> None
941 (* For each domain we have a list of block devices seen
942 * this slice, and seen in the previous slice, which we now
943 * match up to get a list of (domain, device) for which
944 * we have current & previous knowledge. (And ignore the rest).
952 (* Have prev slice stats for this device? *)
954 List.assoc dev rd.rd_prev_block_stats in
955 Some (dev, name, rd, stats, prev_stats)
956 with Not_found -> None
960 (* Finally we have a list of:
961 * device name, domain name, rd_* stuff, curr stats, prev stats.
963 let devs : (string * string * rd_active *
964 D.block_stats * D.block_stats) list =
967 (* Difference curr slice & prev slice. *)
968 let devs = List.map (
969 fun (dev, name, rd, curr, prev) ->
970 dev, name, rd, diff_block_stats curr prev
973 (* Sort by current sort order, but map some of the standard
974 * sort orders into ones which makes sense here.
978 match !sort_order with
980 (fun _ -> 0) (* fallthrough to default name compare *)
982 (fun (_, { rd_domid = id1 }, _, { rd_domid = id2 }) ->
984 | Processor | Memory | Time | NetRX | NetTX
985 (* fallthrough to RDRQ comparison. *)
987 (fun ({ D.rd_req = b1 }, _, { D.rd_req = b2 }, _) ->
990 (fun ({ D.wr_req = b1 }, _, { D.wr_req = b2 }, _) ->
993 let cmp (dev1, name1, rd1, stats1) (dev2, name2, rd2, stats2) =
994 let r = cmp (stats1, rd1, stats2, rd2) in
996 else compare (dev1, name1) (dev2, name2)
998 List.sort ~cmp devs in
1000 (* Print the header for block devices. *)
1002 mvaddstr header_lineno 0
1003 (pad cols " ID S RDBY WRBY RDRQ WRRQ DOMAIN DEVICE");
1006 (* Print domains and devices. *)
1007 let rec loop lineno = function
1009 | (dev, name, rd, stats) :: devs ->
1010 if lineno < lines then (
1011 let state = show_state rd.rd_info.D.state in
1013 if stats.D.rd_bytes >= 0L
1014 then show_int64 stats.D.rd_bytes
1017 if stats.D.wr_bytes >= 0L
1018 then show_int64 stats.D.wr_bytes
1021 if stats.D.rd_req >= 0L
1022 then show_int64 stats.D.rd_req
1025 if stats.D.wr_req >= 0L
1026 then show_int64 stats.D.wr_req
1029 let line = sprintf "%5d %c %s %s %s %s %-12s %s"
1033 (pad 12 name) dev in
1034 let line = pad cols line in
1035 mvaddstr lineno 0 line;
1036 loop (lineno+1) devs
1039 loop domains_lineno devs
1042 (* Calculate and print totals. *)
1044 let totals = List.fold_left (
1045 fun (count, running, blocked, paused, shutdown, shutoff,
1046 crashed, active, inactive,
1047 total_cpu_time, total_memory, total_domU_memory) ->
1049 | (name, Active rd) ->
1050 let test state orig =
1051 if rd.rd_info.D.state = state then orig+1 else orig
1053 let running = test D.InfoRunning running in
1054 let blocked = test D.InfoBlocked blocked in
1055 let paused = test D.InfoPaused paused in
1056 let shutdown = test D.InfoShutdown shutdown in
1057 let shutoff = test D.InfoShutoff shutoff in
1058 let crashed = test D.InfoCrashed crashed in
1060 let total_cpu_time = total_cpu_time +. rd.rd_cpu_time in
1061 let total_memory = total_memory +^ rd.rd_info.D.memory in
1062 let total_domU_memory = total_domU_memory +^
1063 if rd.rd_domid > 0 then rd.rd_info.D.memory else 0L in
1065 (count+1, running, blocked, paused, shutdown, shutoff,
1066 crashed, active+1, inactive,
1067 total_cpu_time, total_memory, total_domU_memory)
1069 | (name, Inactive) -> (* inactive domain *)
1070 (count+1, running, blocked, paused, shutdown, shutoff,
1071 crashed, active, inactive+1,
1072 total_cpu_time, total_memory, total_domU_memory)
1073 ) (0,0,0,0,0,0,0,0,0, 0.,0L,0L) doms in
1075 let (count, running, blocked, paused, shutdown, shutoff,
1076 crashed, active, inactive,
1077 total_cpu_time, total_memory, total_domU_memory) = totals in
1079 mvaddstr summary_lineno 0
1080 (sprintf "%d domains, %d active, %d running, %d sleeping, %d paused, %d inactive D:%d O:%d X:%d"
1081 count active running blocked paused inactive shutdown shutoff
1084 (* Total %CPU used, and memory summary. *)
1085 let percent_cpu = 100. *. total_cpu_time /. total_cpu in
1086 mvaddstr (summary_lineno+1) 0
1087 (sprintf "CPU: %2.1f%% Mem: %Ld MB (%Ld MB by guests)"
1088 percent_cpu (total_memory /^ 1024L) (total_domU_memory /^ 1024L));
1090 (* Time to grab another historical %CPU for the list? *)
1091 if time >= !historical_cpu_last_time +. float !historical_cpu_delay
1093 historical_cpu := percent_cpu :: List.take 10 !historical_cpu;
1094 historical_cpu_last_time := time
1097 (* Display historical CPU time. *)
1099 let x, y = historical_cursor in (* Yes, it's a bug in ocaml-curses *)
1100 let maxwidth = cols - x in
1103 (List.map (sprintf "%2.1f%%") !historical_cpu) in
1104 let line = pad maxwidth line in
1108 (* Write summary data to CSV file. See also write_csv_header (). *)
1109 if !csv_enabled then (
1111 hostname; printable_time; node_info.C.model; string_of_int nr_pcpus;
1112 string_of_int count; string_of_int running; string_of_int blocked;
1113 string_of_int paused; string_of_int shutdown; string_of_int shutoff;
1114 string_of_int crashed; string_of_int active; string_of_int inactive;
1115 sprintf "%2.1f" percent_cpu;
1116 Int64.to_string total_memory; Int64.to_string total_domU_memory;
1117 Int64.to_string (Int64.of_float total_cpu_time)
1124 (* Update last_info, last_time. *)
1126 Hashtbl.clear last_info;
1130 let info = rd.rd_info, rd.rd_block_stats, rd.rd_interface_stats in
1131 Hashtbl.add last_info rd.rd_domid info
1135 move message_lineno 0 (* Park cursor in message area, as with top. *)
1138 let clear_pcpu_display_data () =
1139 (* Clear out vcpu_info used by PCPUDisplay
1140 * display_mode when we switch back to TaskDisplay mode.
1142 Hashtbl.clear last_vcpu_info
1145 redraw, clear_pcpu_display_data
1148 let rec main_loop state =
1149 if !csv_enabled then write_csv_header ();
1155 (* Clear up unused virDomainPtr objects. *)
1158 if not !batch_mode then
1160 else (* Batch mode - just sleep, ignore keys. *)
1161 Unix.sleep (!delay / 1000);
1163 (* Max iterations? *)
1164 if !iterations >= 0 then (
1166 if !iterations = 0 then quit := true
1170 and get_key_press state =
1171 (* Read the next key, waiting up to !delay milliseconds. *)
1174 timeout (-1); (* Reset to blocking mode. *)
1176 if k >= 0 && k <> 32 (* ' ' *) && k <> 12 (* ^L *) && k <> Key.resize
1178 if k = Char.code 'q' then quit := true
1179 else if k = Char.code 'h' then show_help state
1180 else if k = Char.code 's' || k = Char.code 'd' then change_delay ()
1181 else if k = Char.code 'M' then sort_order := Memory
1182 else if k = Char.code 'P' then sort_order := Processor
1183 else if k = Char.code 'T' then sort_order := Time
1184 else if k = Char.code 'N' then sort_order := DomainID
1185 else if k = Char.code 'F' then change_sort_order ()
1186 else if k = Char.code '0' then set_tasks_display ()
1187 else if k = Char.code '1' then toggle_pcpu_display ()
1188 else if k = Char.code '2' then toggle_net_display ()
1189 else if k = Char.code '3' then toggle_block_display ()
1190 else unknown_command k
1193 and change_delay () =
1194 print_msg (sprintf "Change delay from %.1f to: " (float !delay /. 1000.));
1195 let str = get_string 16 in
1196 (* Try to parse the number. *)
1199 let newdelay = float_of_string str in
1200 if newdelay <= 0. then (
1201 print_msg "Delay must be > 0"; true
1203 delay := int_of_float (newdelay *. 1000.); false
1206 Failure "float_of_string" ->
1207 print_msg "Not a valid number"; true in
1208 sleep (if error then 2 else 1)
1210 and change_sort_order () =
1212 let lines, cols = get_size () in
1214 mvaddstr top_lineno 0 "Set sort order for main display";
1215 mvaddstr summary_lineno 0 "Type key or use up and down cursor keys.";
1218 mvaddstr header_lineno 0 (pad cols "KEY Sort field");
1221 let accelerator_key = function
1222 | Memory -> "(key: M)"
1223 | Processor -> "(key: P)"
1224 | Time -> "(key: T)"
1225 | DomainID -> "(key: N)"
1226 | _ -> (* all others have to be changed from here *) ""
1229 let rec key_of_int = function
1230 | i when i < 10 -> Char.chr (i + Char.code '0')
1231 | i when i < 20 -> Char.chr (i + Char.code 'a')
1233 and int_of_key = function
1234 | k when k >= 0x30 && k <= 0x39 (* '0' - '9' *) -> k - 0x30
1235 | k when k >= 0x61 && k <= 0x7a (* 'a' - 'j' *) -> k - 0x61 + 10
1236 | k when k >= 0x41 && k <= 0x6a (* 'A' - 'J' *) -> k - 0x41 + 10
1240 (* Display possible sort fields. *)
1241 let selected_index = ref 0 in
1244 let selected = !sort_order = ord in
1245 if selected then selected_index := i;
1246 mvaddstr (domains_lineno+i) 0
1247 (sprintf " %c %s %s %s"
1248 (key_of_int i) (if selected then "*" else " ")
1249 (printable_sort_order ord)
1250 (accelerator_key ord))
1253 move message_lineno 0;
1256 if k >= 0 && k <> 32 && k <> Char.code 'q' && k <> 13 then (
1257 let new_order, loop =
1258 (* Redraw the display. *)
1259 if k = 12 (* ^L *) then None, true
1260 (* Make the UP and DOWN arrow keys do something useful. *)
1261 else if k = Key.up then (
1262 if !selected_index > 0 then
1263 Some (List.nth all_sort_fields (!selected_index-1)), true
1267 else if k = Key.down then (
1268 if !selected_index < List.length all_sort_fields - 1 then
1269 Some (List.nth all_sort_fields (!selected_index+1)), true
1273 (* Also understand the regular accelerator keys. *)
1274 else if k = Char.code 'M' then
1276 else if k = Char.code 'P' then
1277 Some Processor, false
1278 else if k = Char.code 'T' then
1280 else if k = Char.code 'N' then
1281 Some DomainID, false
1283 (* It's one of the KEYs. *)
1284 let i = int_of_key k in
1285 if i >= 0 && i < List.length all_sort_fields then
1286 Some (List.nth all_sort_fields i), false
1291 (match new_order with
1294 sort_order := new_order;
1295 print_msg (sprintf "Sort order changed to: %s"
1296 (printable_sort_order new_order));
1297 if not loop then sleep 1
1300 if loop then change_sort_order ()
1303 (* Note: We need to clear_pcpu_display_data every time
1304 * we _leave_ PCPUDisplay mode.
1306 and set_tasks_display () = (* key 0 *)
1307 if !display_mode = PCPUDisplay then clear_pcpu_display_data ();
1308 display_mode := TaskDisplay
1310 and toggle_pcpu_display () = (* key 1 *)
1312 match !display_mode with
1313 | TaskDisplay | NetDisplay | BlockDisplay -> PCPUDisplay
1314 | PCPUDisplay -> clear_pcpu_display_data (); TaskDisplay
1316 and toggle_net_display () = (* key 2 *)
1318 match !display_mode with
1319 | PCPUDisplay -> clear_pcpu_display_data (); NetDisplay
1320 | TaskDisplay | BlockDisplay -> NetDisplay
1321 | NetDisplay -> TaskDisplay
1323 and toggle_block_display () = (* key 3 *)
1325 match !display_mode with
1326 | PCPUDisplay -> clear_pcpu_display_data (); BlockDisplay
1327 | TaskDisplay | NetDisplay -> BlockDisplay
1328 | BlockDisplay -> TaskDisplay
1330 and show_help (_, _, _, hostname,
1331 (libvirt_major, libvirt_minor, libvirt_release)) =
1334 (* Get the screen/window size. *)
1335 let lines, cols = get_size () in
1337 (* Banner at the top of the screen. *)
1339 sprintf "virt-top %s (libvirt %d.%d.%d) by Red Hat"
1340 Libvirt_version.version libvirt_major libvirt_minor libvirt_release in
1341 let banner = pad cols banner in
1343 mvaddstr 0 0 banner;
1348 (sprintf "Delay: %.1f secs; Batch: %s; Secure: %s; Sort: %s"
1349 (float !delay /. 1000.)
1350 (if !batch_mode then "On" else "Off")
1351 (if !secure_mode then "On" else "Off")
1352 (printable_sort_order !sort_order));
1354 (sprintf "Connect: %s; Hostname: %s"
1355 (match !uri with None -> "default" | Some s -> s)
1358 (* Misc keys on left. *)
1359 let banner = pad 38 "MAIN KEYS" in
1361 mvaddstr header_lineno 1 banner;
1365 let lineno = ref domains_lineno in
1366 fun () -> let i = !lineno in incr lineno; i
1368 let key keys description =
1369 let lineno = get_lineno () in
1370 move lineno 1; attron A.bold; addstr keys; attroff A.bold;
1371 move lineno 10; addstr description; ()
1373 key "space ^L" "Update display";
1375 key "d s" "Set update interval";
1379 ignore (get_lineno ());
1380 let banner = pad 38 "SORTING" in
1382 mvaddstr (get_lineno ()) 1 banner;
1385 key "P" "Sort by %CPU";
1386 key "M" "Sort by %MEM";
1387 key "T" "Sort by TIME";
1388 key "N" "Sort by ID";
1389 key "F" "Select sort field";
1391 (* Display modes on right. *)
1392 let banner = pad 39 "DISPLAY MODES" in
1394 mvaddstr header_lineno 40 banner;
1398 let lineno = ref domains_lineno in
1399 fun () -> let i = !lineno in incr lineno; i
1401 let key keys description =
1402 let lineno = get_lineno () in
1403 move lineno 40; attron A.bold; addstr keys; attroff A.bold;
1404 move lineno 49; addstr description; ()
1406 key "0" "Domains display";
1407 key "1" "Toggle physical CPUs";
1408 key "2" "Toggle network interfaces";
1409 key "3" "Toggle block devices";
1411 (* Update screen and wait for key press. *)
1412 mvaddstr (lines-1) 0
1413 "More help in virt-top(1) man page. Press any key to return.";
1417 and unknown_command k =
1418 print_msg "Unknown command - try 'h' for help";