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 | Invalid_argument "virConnectGetHostname not supported" -> "unknown" in
142 let libvirt_version =
143 let v, _ = Libvirt.get_version () in
144 v / 1_000_000, (v / 1_000) mod 1_000, v mod 1_000 in
146 (* Open debug file if specified.
147 * NB: Do this just before jumping into curses mode.
149 (match !debug_file with
150 | "" -> (* No debug file specified, send stderr to /dev/null. *)
152 let fd = Unix.openfile "/dev/null" [Unix.O_WRONLY] 0o644 in
153 Unix.dup2 fd Unix.stderr;
156 Unix.Unix_error _ -> ()
158 | filename -> (* Send stderr to the named file. *)
160 Unix.openfile filename [Unix.O_WRONLY;Unix.O_CREAT;Unix.O_TRUNC]
162 Unix.dup2 fd Unix.stderr;
166 (* Curses voodoo (see ncurses(3)). *)
172 let stdscr = stdscr () in
173 intrflush stdscr false;
177 (* This tuple of static information is called 'state' in other parts
178 * of this program, and is passed to other functions such as redraw and
179 * main_loop. See virt_top_main.ml. It's not really "state" though.
181 conn, stdscr, node_info, hostname, libvirt_version
183 (* Show a percentage in 4 chars. *)
184 let show_percent percent =
185 if percent <= 0. then " 0.0"
186 else if percent <= 9.9 then sprintf " %1.1f" percent
187 else if percent <= 99.9 then sprintf "%2.1f" percent
190 (* Show an int64 option in 4 chars. *)
191 let rec show_int64_option = function
193 | Some n -> show_int64 n
194 (* Show an int64 in 4 chars. *)
195 and show_int64 = function
196 | n when n < 0L -> "-!!!"
197 | n when n <= 9999L ->
199 | n when n /^ 1024L <= 999L ->
200 sprintf "%3LdK" (n /^ 1024L)
201 | n when n /^ 1_048_576L <= 999L ->
202 sprintf "%3LdM" (n /^ 1_048_576L)
203 | n when n /^ 1_073_741_824L <= 999L ->
204 sprintf "%3LdG" (n /^ 1_073_741_824L)
207 (* Format the total time (may be large!) in 9 chars. *)
209 let secs_in_ns = 1_000_000_000L in
210 let mins_in_ns = 60_000_000_000L in
211 let hours_in_ns = 3_600_000_000_000L in
213 let hours = ns /^ hours_in_ns in
214 let ns = ns -^ (hours *^ hours_in_ns) in
215 let mins = ns /^ mins_in_ns in
216 let ns = ns -^ (mins *^ mins_in_ns) in
217 let secs = ns /^ secs_in_ns in
218 let ns = ns -^ (secs *^ secs_in_ns) in
219 let pennies = ns /^ 10_000_000L in
222 sprintf "%3Ld:%02Ld.%02Ld" (hours *^ 60L +^ mins) secs pennies
223 else if hours <= 999L then
224 sprintf "%3Ld:%02Ld:%02Ld" hours mins secs
226 let days = hours /^ 24L in
227 let hours = hours -^ (days *^ 24L) in
228 sprintf "%3Ldd%02Ld:%02Ld" days hours mins
231 (* Show a domain state (the 'S' column). *)
232 let show_state = function
233 | D.InfoNoState -> '?'
234 | D.InfoRunning -> 'R'
235 | D.InfoBlocked -> 'S'
236 | D.InfoPaused -> 'P'
237 | D.InfoShutdown -> 'D'
238 | D.InfoShutoff -> 'O'
239 | D.InfoCrashed -> 'X'
241 (* Sum Domain.block_stats structures together. Missing fields
242 * get forced to 0. Empty list returns all 0.
244 let zero_block_stats =
245 { D.rd_req = 0L; rd_bytes = 0L; wr_req = 0L; wr_bytes = 0L; errs = 0L }
246 let add_block_stats bs1 bs2 =
247 let add f1 f2 = if f1 >= 0L && f2 >= 0L then f1 +^ f2 else 0L in
248 { D.rd_req = add bs1.D.rd_req bs2.D.rd_req;
249 rd_bytes = add bs1.D.rd_bytes bs2.D.rd_bytes;
250 wr_req = add bs1.D.wr_req bs2.D.wr_req;
251 wr_bytes = add bs1.D.wr_bytes bs2.D.wr_bytes;
252 errs = add bs1.D.errs bs2.D.errs }
253 let sum_block_stats =
254 List.fold_left add_block_stats zero_block_stats
256 (* Get the difference between two block_stats structures. Missing data
257 * forces the difference to -1.
259 let diff_block_stats curr prev =
260 let sub f1 f2 = if f1 >= 0L && f2 >= 0L then f1 -^ f2 else -1L in
261 { D.rd_req = sub curr.D.rd_req prev.D.rd_req;
262 rd_bytes = sub curr.D.rd_bytes prev.D.rd_bytes;
263 wr_req = sub curr.D.wr_req prev.D.wr_req;
264 wr_bytes = sub curr.D.wr_bytes prev.D.wr_bytes;
265 errs = sub curr.D.errs prev.D.errs }
267 (* Sum Domain.interface_stats structures together. Missing fields
268 * get forced to 0. Empty list returns all 0.
270 let zero_interface_stats =
271 { D.rx_bytes = 0L; rx_packets = 0L; rx_errs = 0L; rx_drop = 0L;
272 tx_bytes = 0L; tx_packets = 0L; tx_errs = 0L; tx_drop = 0L }
273 let add_interface_stats is1 is2 =
274 let add f1 f2 = if f1 >= 0L && f2 >= 0L then f1 +^ f2 else 0L in
275 { D.rx_bytes = add is1.D.rx_bytes is2.D.rx_bytes;
276 rx_packets = add is1.D.rx_packets is2.D.rx_packets;
277 rx_errs = add is1.D.rx_errs is2.D.rx_errs;
278 rx_drop = add is1.D.rx_drop is2.D.rx_drop;
279 tx_bytes = add is1.D.tx_bytes is2.D.tx_bytes;
280 tx_packets = add is1.D.tx_packets is2.D.tx_packets;
281 tx_errs = add is1.D.tx_errs is2.D.tx_errs;
282 tx_drop = add is1.D.tx_drop is2.D.tx_drop }
283 let sum_interface_stats =
284 List.fold_left add_interface_stats zero_interface_stats
286 (* Get the difference between two interface_stats structures.
287 * Missing data forces the difference to -1.
289 let diff_interface_stats curr prev =
290 let sub f1 f2 = if f1 >= 0L && f2 >= 0L then f1 -^ f2 else -1L in
291 { D.rx_bytes = sub curr.D.rx_bytes prev.D.rx_bytes;
292 rx_packets = sub curr.D.rx_packets prev.D.rx_packets;
293 rx_errs = sub curr.D.rx_errs prev.D.rx_errs;
294 rx_drop = sub curr.D.rx_drop prev.D.rx_drop;
295 tx_bytes = sub curr.D.tx_bytes prev.D.tx_bytes;
296 tx_packets = sub curr.D.tx_packets prev.D.tx_packets;
297 tx_errs = sub curr.D.tx_errs prev.D.tx_errs;
298 tx_drop = sub curr.D.tx_drop prev.D.tx_drop }
300 (* Update the display and sleep for given number of seconds. *)
301 let sleep n = refresh (); Unix.sleep n
303 (* The curses getstr/getnstr functions are just weird.
304 * This helper function also enables echo temporarily.
306 let get_string maxlen =
308 let str = String.create maxlen in
309 let ok = getstr str in (* Safe because binding calls getnstr. *)
313 (* Chop at first '\0'. *)
315 let i = String.index str '\000' in
318 Not_found -> str (* it is full maxlen bytes *)
321 (* Pad a string to the full width with spaces. If too long, truncate. *)
323 let n = String.length str in
324 if n = width then str
325 else if n > width then String.sub str 0 width
326 else (* if n < width then *) str ^ String.make (width-n) ' '
330 let summary_lineno = 1 (* this takes 2 lines *)
331 let message_lineno = 3
332 let header_lineno = 4
333 let domains_lineno = 5
335 (* Print in the "message area". *)
336 let clear_msg () = move message_lineno 0; clrtoeol ()
337 let print_msg str = clear_msg (); mvaddstr message_lineno 0 str; ()
339 (* Write CSV header row. *)
340 let write_csv_header () =
341 (!csv_write) [ "Hostname"; "Time"; "Arch"; "Physical CPUs";
342 "Count"; "Running"; "Blocked"; "Paused"; "Shutdown";
343 "Shutoff"; "Crashed"; "Active"; "Inactive";
344 "%CPU"; "Total memory KB"; "Total guest memory KB";
345 "Total CPU time ns" ]
347 (* Intermediate "domain + stats" structure that we use to collect
348 * everything we know about a domain within the redraw function.
350 type rd_domain = Inactive | Active of rd_active
352 rd_domid : int; (* Domain ID. *)
353 rd_dom : [`R] D.t; (* Domain object. *)
354 rd_info : D.info; (* Domain CPU info now. *)
355 rd_block_stats : (string * D.block_stats) list;
356 (* Domain block stats now. *)
357 rd_interface_stats : (string * D.interface_stats) list;
358 (* Domain net stats now. *)
359 rd_prev_info : D.info option; (* Domain CPU info previously. *)
360 rd_prev_block_stats : (string * D.block_stats) list;
361 (* Domain block stats prev. *)
362 rd_prev_interface_stats : (string * D.interface_stats) list;
363 (* Domain interface stats prev. *)
364 (* The following are since the last slice, or 0 if cannot be calculated: *)
365 rd_cpu_time : float; (* CPU time used in nanoseconds. *)
366 rd_percent_cpu : float; (* CPU time as percent of total. *)
367 (* The following are since the last slice, or None if cannot be calc'd: *)
368 rd_block_rd_reqs : int64 option; (* Number of block device read rqs. *)
369 rd_block_wr_reqs : int64 option; (* Number of block device write rqs. *)
370 rd_net_rx_bytes : int64 option; (* Number of bytes received. *)
371 rd_net_tx_bytes : int64 option; (* Number of bytes transmitted. *)
374 (* Redraw the display. *)
375 let redraw, clear_pcpu_display_data =
376 (* We cache the list of block devices and interfaces for each domain
377 * here, so we don't need to reparse the XML each time.
379 let devices = Hashtbl.create 13 in
381 (* Function to get the list of block devices, network interfaces for
382 * a particular domain. Get it from the devices cache, and if not
383 * there then parse the domain XML.
385 let get_devices id dom =
386 try Hashtbl.find devices id
388 let blkdevs, netifs = (!parse_device_xml) id dom in
389 Hashtbl.replace devices id (blkdevs, netifs);
393 (* We save the state of domains across redraws here, which allows us
394 * to deduce %CPU usage from the running total.
396 let last_info = Hashtbl.create 13 in
397 let last_time = ref (Unix.gettimeofday ()) in
399 (* Save vcpuinfo structures across redraws too (only for pCPU display). *)
400 let last_vcpu_info = Hashtbl.create 13 in
402 (* Keep a historical list of %CPU usages. *)
403 let historical_cpu = ref [] in
404 let historical_cpu_last_time = ref (Unix.gettimeofday ()) in
406 let redraw (conn, stdscr, node_info, hostname, _) =
409 (* Get the screen/window size. *)
410 let lines, cols = get_size () in
412 (* Number of physical CPUs (some may be disabled). *)
413 let nr_pcpus = C.maxcpus_of_node_info node_info in
415 (* Get the current time. *)
416 let time = Unix.gettimeofday () in
417 let tm = Unix.localtime time in
419 sprintf "%02d:%02d:%02d" tm.Unix.tm_hour tm.Unix.tm_min tm.Unix.tm_sec in
420 mvaddstr top_lineno 0 ("virt-top " ^ printable_time ^ " - ");
422 (* What's the total CPU time elapsed since we were last called? (ns) *)
423 let total_cpu_per_pcpu = 1_000_000_000. *. (time -. !last_time) in
424 (* Avoid division by zero. *)
425 let total_cpu_per_pcpu =
426 if total_cpu_per_pcpu <= 0. then 1. else total_cpu_per_pcpu in
427 let total_cpu = float node_info.C.cpus *. total_cpu_per_pcpu in
429 (* Basic node_info. *)
430 addstr (sprintf "%s %d/%dCPU %dMHz %LdMB "
431 node_info.C.model node_info.C.cpus nr_pcpus node_info.C.mhz
432 (node_info.C.memory /^ 1024L));
433 (* Save the cursor position for when we come to draw the
434 * historical CPU times (down in this function).
436 let historical_cursor = getyx stdscr in
438 (* Get the domains. Match up with their last_info (if any). *)
440 (* Active domains. *)
441 let n = C.num_of_domains conn in
443 if n > 0 then Array.to_list (C.list_domains conn n)
449 let dom = D.lookup_by_id conn id in
450 let name = D.get_name dom in
451 let blkdevs, netifs = get_devices id dom in
453 (* Get current CPU, block and network stats. *)
454 let info = D.get_info dom in
456 try List.map (fun dev -> dev, D.block_stats dom dev) blkdevs
458 | Invalid_argument "virDomainBlockStats not supported"
459 | Libvirt.Virterror _ -> [] in
460 let interface_stats =
461 try List.map (fun dev -> dev, D.interface_stats dom dev) netifs
463 | Invalid_argument "virDomainInterfaceStats not supported"
464 | Libvirt.Virterror _ -> [] in
466 let prev_info, prev_block_stats, prev_interface_stats =
468 let prev_info, prev_block_stats, prev_interface_stats =
469 Hashtbl.find last_info id in
470 Some prev_info, prev_block_stats, prev_interface_stats
471 with Not_found -> None, [], [] in
474 rd_domid = id; rd_dom = dom; rd_info = info;
475 rd_block_stats = block_stats;
476 rd_interface_stats = interface_stats;
477 rd_prev_info = prev_info;
478 rd_prev_block_stats = prev_block_stats;
479 rd_prev_interface_stats = prev_interface_stats;
480 rd_cpu_time = 0.; rd_percent_cpu = 0.;
481 rd_block_rd_reqs = None; rd_block_wr_reqs = None;
482 rd_net_rx_bytes = None; rd_net_tx_bytes = None;
485 Libvirt.Virterror _ -> None (* ignore transient error *)
488 (* Inactive domains. *)
489 let n = C.num_of_defined_domains conn in
491 if n > 0 then Array.to_list (C.list_defined_domains conn n)
493 let doms_inactive = List.map (fun name -> name, Inactive) names in
495 doms @ doms_inactive in
497 (* Calculate the CPU time (ns) and %CPU used by each domain. *)
501 (* We have previous CPU info from which to calculate it? *)
502 | name, Active ({ rd_prev_info = Some prev_info } as rd) ->
504 Int64.to_float (rd.rd_info.D.cpu_time -^ prev_info.D.cpu_time) in
505 let percent_cpu = 100. *. cpu_time /. total_cpu in
507 rd_cpu_time = cpu_time;
508 rd_percent_cpu = percent_cpu } in
510 (* For all other domains we can't calculate it, so leave as 0 *)
514 (* Calculate the number of block device read/write requests across
515 * all block devices attached to a domain.
520 (* Do we have stats from the previous slice? *)
521 | name, Active ({ rd_prev_block_stats = ((_::_) as prev_block_stats) }
523 let block_stats = rd.rd_block_stats in (* stats now *)
525 (* Add all the devices together. Throw away device names. *)
526 let prev_block_stats =
527 sum_block_stats (List.map snd prev_block_stats) in
529 sum_block_stats (List.map snd block_stats) in
531 (* Calculate increase in read & write requests. *)
533 block_stats.D.rd_req -^ prev_block_stats.D.rd_req in
535 block_stats.D.wr_req -^ prev_block_stats.D.wr_req in
538 rd_block_rd_reqs = Some read_reqs;
539 rd_block_wr_reqs = Some write_reqs } in
541 (* For all other domains we can't calculate it, so leave as None. *)
545 (* Calculate the same as above for network interfaces across
546 * all network interfaces attached to a domain.
551 (* Do we have stats from the previous slice? *)
552 | name, Active ({ rd_prev_interface_stats =
553 ((_::_) as prev_interface_stats) }
555 let interface_stats = rd.rd_interface_stats in (* stats now *)
557 (* Add all the devices together. Throw away device names. *)
558 let prev_interface_stats =
559 sum_interface_stats (List.map snd prev_interface_stats) in
560 let interface_stats =
561 sum_interface_stats (List.map snd interface_stats) in
563 (* Calculate increase in rx & tx bytes. *)
565 interface_stats.D.rx_bytes -^ prev_interface_stats.D.rx_bytes in
567 interface_stats.D.tx_bytes -^ prev_interface_stats.D.tx_bytes in
570 rd_net_rx_bytes = Some rx_bytes;
571 rd_net_tx_bytes = Some tx_bytes } in
573 (* For all other domains we can't calculate it, so leave as None. *)
577 (match !display_mode with
578 | TaskDisplay -> (*---------- Showing domains ----------*)
579 (* Sort domains on current sort_order. *)
582 match !sort_order with
584 (fun _ -> 0) (* fallthrough to default name compare *)
587 | Active rd1, Active rd2 ->
588 compare rd2.rd_percent_cpu rd1.rd_percent_cpu
589 | Active _, Inactive -> -1
590 | Inactive, Active _ -> 1
591 | Inactive, Inactive -> 0)
594 | Active { rd_info = info1 }, Active { rd_info = info2 } ->
595 compare info2.D.memory info1.D.memory
596 | Active _, Inactive -> -1
597 | Inactive, Active _ -> 1
598 | Inactive, Inactive -> 0)
601 | Active { rd_info = info1 }, Active { rd_info = info2 } ->
602 compare info2.D.cpu_time info1.D.cpu_time
603 | Active _, Inactive -> -1
604 | Inactive, Active _ -> 1
605 | Inactive, Inactive -> 0)
608 | Active { rd_domid = id1 }, Active { rd_domid = id2 } ->
610 | Active _, Inactive -> -1
611 | Inactive, Active _ -> 1
612 | Inactive, Inactive -> 0)
615 | Active { rd_net_rx_bytes = r1 }, Active { rd_net_rx_bytes = r2 } ->
617 | Active _, Inactive -> -1
618 | Inactive, Active _ -> 1
619 | Inactive, Inactive -> 0)
622 | Active { rd_net_tx_bytes = r1 }, Active { rd_net_tx_bytes = r2 } ->
624 | Active _, Inactive -> -1
625 | Inactive, Active _ -> 1
626 | Inactive, Inactive -> 0)
629 | Active { rd_block_rd_reqs = r1 }, Active { rd_block_rd_reqs = r2 } ->
631 | Active _, Inactive -> -1
632 | Inactive, Active _ -> 1
633 | Inactive, Inactive -> 0)
636 | Active { rd_block_wr_reqs = r1 }, Active { rd_block_wr_reqs = r2 } ->
638 | Active _, Inactive -> -1
639 | Inactive, Active _ -> 1
640 | Inactive, Inactive -> 0)
642 let cmp (name1, dom1) (name2, dom2) =
643 let r = cmp (dom1, dom2) in
645 else compare name1 name2
647 List.sort ~cmp doms in
651 mvaddstr header_lineno 0
652 (pad cols " ID S RDRQ WRRQ RXBY TXBY %CPU %MEM TIME NAME");
655 let rec loop lineno = function
657 | (name, Active rd) :: doms ->
658 if lineno < lines then (
659 let state = show_state rd.rd_info.D.state in
660 let rd_req = show_int64_option rd.rd_block_rd_reqs in
661 let wr_req = show_int64_option rd.rd_block_wr_reqs in
662 let rx_bytes = show_int64_option rd.rd_net_rx_bytes in
663 let tx_bytes = show_int64_option rd.rd_net_tx_bytes in
664 let percent_cpu = show_percent rd.rd_percent_cpu in
666 100L *^ rd.rd_info.D.memory /^ node_info.C.memory in
667 let percent_mem = Int64.to_float percent_mem in
668 let percent_mem = show_percent percent_mem in
669 let time = show_time rd.rd_info.D.cpu_time in
671 let line = sprintf "%5d %c %s %s %s %s %s %s %s %s"
672 rd.rd_domid state rd_req wr_req rx_bytes tx_bytes
673 percent_cpu percent_mem time name in
674 let line = pad cols line in
675 mvaddstr lineno 0 line;
678 | (name, Inactive) :: doms -> (* inactive domain *)
679 if lineno < lines then (
684 let line = pad cols line in
685 mvaddstr lineno 0 line;
689 loop domains_lineno doms
691 | PCPUDisplay -> (*---------- Showing physical CPUs ----------*)
692 (* Get the VCPU info and VCPU->PCPU mappings for active domains.
693 * Also cull some data we don't care about.
695 let doms = List.filter_map (
697 | (name, Active rd) ->
699 let domid = rd.rd_domid in
700 let maplen = C.cpumaplen nr_pcpus in
701 let maxinfo = rd.rd_info.D.nr_virt_cpu in
702 let nr_vcpus, vcpu_infos, cpumaps =
703 D.get_vcpus rd.rd_dom maxinfo maplen in
705 (* Got previous vcpu_infos for this domain? *)
706 let prev_vcpu_infos =
707 try Some (Hashtbl.find last_vcpu_info domid)
708 with Not_found -> None in
709 (* Update last_vcpu_info. *)
710 Hashtbl.replace last_vcpu_info domid vcpu_infos;
712 (match prev_vcpu_infos with
713 | Some prev_vcpu_infos
714 when Array.length prev_vcpu_infos = Array.length vcpu_infos ->
715 Some (domid, name, nr_vcpus, vcpu_infos, prev_vcpu_infos,
717 | _ -> None (* ignore missing / unequal length prev_vcpu_infos *)
720 Libvirt.Virterror _ -> None(* ignore transient libvirt errs *)
722 | (_, Inactive) -> None (* ignore inactive doms *)
724 let nr_doms = List.length doms in
726 (* Rearrange the data into a matrix. Major axis (down) is
727 * pCPUs. Minor axis (right) is domains. At each node we store:
728 * cpu_time (on this pCPU only, nanosecs),
729 * average? (if set, then cpu_time is an average because the
730 * vCPU is pinned to more than one pCPU)
731 * running? (if set, we were instantaneously running on this pCPU)
733 let empty_node = (0L, false, false) in
734 let pcpus = Array.make_matrix nr_pcpus nr_doms empty_node in
737 fun di (domid, name, nr_vcpus, vcpu_infos, prev_vcpu_infos,
739 (* Which pCPUs can this dom run on? *)
740 for v = 0 to nr_vcpus-1 do
741 let pcpu = vcpu_infos.(v).D.cpu in (* instantaneous pCPU *)
742 let nr_poss_pcpus = ref 0 in (* how many pcpus can it run on? *)
743 for p = 0 to nr_pcpus-1 do
744 (* vcpu v can reside on pcpu p *)
745 if C.cpu_usable cpumaps maplen v p then
748 let nr_poss_pcpus = Int64.of_int !nr_poss_pcpus in
749 for p = 0 to nr_pcpus-1 do
750 (* vcpu v can reside on pcpu p *)
751 if C.cpu_usable cpumaps maplen v p then
752 let vcpu_time_on_pcpu =
753 vcpu_infos.(v).D.vcpu_time
754 -^ prev_vcpu_infos.(v).D.vcpu_time in
755 let vcpu_time_on_pcpu =
756 vcpu_time_on_pcpu /^ nr_poss_pcpus in
758 (vcpu_time_on_pcpu, nr_poss_pcpus > 1L, p = pcpu)
763 (* Sum the CPU time used by each pCPU, for the %CPU column. *)
764 let pcpus_cpu_time = Array.map (
766 let cpu_time = ref 0L in
767 for di = 0 to Array.length row-1 do
768 let t, _, _ = row.(di) in
769 cpu_time := !cpu_time +^ t
771 Int64.to_float !cpu_time
774 (* Display the pCPUs. *)
778 fun (_, name, _, _, _, _, _) ->
779 let len = String.length name in
780 let width = max (len+1) 7 in
785 mvaddstr header_lineno 0 (pad cols ("PHYCPU %CPU " ^ dom_names));
790 mvaddstr (p+domains_lineno) 0 (sprintf "%4d " p);
791 let cpu_time = pcpus_cpu_time.(p) in (* ns used on this CPU *)
792 let percent_cpu = 100. *. cpu_time /. total_cpu_per_pcpu in
793 addstr (show_percent percent_cpu);
797 fun di (domid, name, _, _, _, _, _) ->
798 let t, is_average, is_running = pcpus.(p).(di) in
799 let len = String.length name in
800 let width = max (len+1) 7 in
804 let t = Int64.to_float t in
805 let percent = 100. *. t /. total_cpu_per_pcpu in
806 sprintf "%s%c%c " (show_percent percent)
807 (if is_average then '=' else ' ')
808 (if is_running then '#' else ' ')
810 addstr (pad width str);
815 | NetDisplay -> (*---------- Showing network interfaces ----------*)
816 (* Only care about active domains. *)
817 let doms = List.filter_map (
819 | (name, Active rd) -> Some (name, rd)
820 | (_, Inactive) -> None
823 (* For each domain we have a list of network interfaces seen
824 * this slice, and seen in the previous slice, which we now
825 * match up to get a list of (domain, interface) for which
826 * we have current & previous knowledge. (And ignore the rest).
834 (* Have prev slice stats for this device? *)
836 List.assoc dev rd.rd_prev_interface_stats in
837 Some (dev, name, rd, stats, prev_stats)
838 with Not_found -> None
839 ) rd.rd_interface_stats
842 (* Finally we have a list of:
843 * device name, domain name, rd_* stuff, curr stats, prev stats.
845 let devs : (string * string * rd_active *
846 D.interface_stats * D.interface_stats) list =
849 (* Difference curr slice & prev slice. *)
850 let devs = List.map (
851 fun (dev, name, rd, curr, prev) ->
852 dev, name, rd, diff_interface_stats curr prev
855 (* Sort by current sort order, but map some of the standard
856 * sort orders into ones which makes sense here.
860 match !sort_order with
862 (fun _ -> 0) (* fallthrough to default name compare *)
864 (fun (_, { rd_domid = id1 }, _, { rd_domid = id2 }) ->
866 | Processor | Memory | Time | BlockRdRq | BlockWrRq
867 (* fallthrough to RXBY comparison. *)
869 (fun ({ D.rx_bytes = b1 }, _, { D.rx_bytes = b2 }, _) ->
872 (fun ({ D.tx_bytes = b1 }, _, { D.tx_bytes = b2 }, _) ->
875 let cmp (dev1, name1, rd1, stats1) (dev2, name2, rd2, stats2) =
876 let r = cmp (stats1, rd1, stats2, rd2) in
878 else compare (dev1, name1) (dev2, name2)
880 List.sort ~cmp devs in
882 (* Print the header for network devices. *)
884 mvaddstr header_lineno 0
885 (pad cols " ID S RXBY TXBY RXPK TXPK DOMAIN INTERFACE");
888 (* Print domains and devices. *)
889 let rec loop lineno = function
891 | (dev, name, rd, stats) :: devs ->
892 if lineno < lines then (
893 let state = show_state rd.rd_info.D.state in
895 if stats.D.rx_bytes >= 0L
896 then show_int64 stats.D.rx_bytes
899 if stats.D.tx_bytes >= 0L
900 then show_int64 stats.D.tx_bytes
903 if stats.D.rx_packets >= 0L
904 then show_int64 stats.D.rx_packets
907 if stats.D.tx_packets >= 0L
908 then show_int64 stats.D.tx_packets
911 let line = sprintf "%5d %c %s %s %s %s %-12s %s"
914 rx_packets tx_packets
916 let line = pad cols line in
917 mvaddstr lineno 0 line;
921 loop domains_lineno devs
923 | BlockDisplay -> (*---------- Showing block devices ----------*)
924 (* Only care about active domains. *)
925 let doms = List.filter_map (
927 | (name, Active rd) -> Some (name, rd)
928 | (_, Inactive) -> None
931 (* For each domain we have a list of block devices seen
932 * this slice, and seen in the previous slice, which we now
933 * match up to get a list of (domain, device) for which
934 * we have current & previous knowledge. (And ignore the rest).
942 (* Have prev slice stats for this device? *)
944 List.assoc dev rd.rd_prev_block_stats in
945 Some (dev, name, rd, stats, prev_stats)
946 with Not_found -> None
950 (* Finally we have a list of:
951 * device name, domain name, rd_* stuff, curr stats, prev stats.
953 let devs : (string * string * rd_active *
954 D.block_stats * D.block_stats) list =
957 (* Difference curr slice & prev slice. *)
958 let devs = List.map (
959 fun (dev, name, rd, curr, prev) ->
960 dev, name, rd, diff_block_stats curr prev
963 (* Sort by current sort order, but map some of the standard
964 * sort orders into ones which makes sense here.
968 match !sort_order with
970 (fun _ -> 0) (* fallthrough to default name compare *)
972 (fun (_, { rd_domid = id1 }, _, { rd_domid = id2 }) ->
974 | Processor | Memory | Time | NetRX | NetTX
975 (* fallthrough to RDRQ comparison. *)
977 (fun ({ D.rd_req = b1 }, _, { D.rd_req = b2 }, _) ->
980 (fun ({ D.wr_req = b1 }, _, { D.wr_req = b2 }, _) ->
983 let cmp (dev1, name1, rd1, stats1) (dev2, name2, rd2, stats2) =
984 let r = cmp (stats1, rd1, stats2, rd2) in
986 else compare (dev1, name1) (dev2, name2)
988 List.sort ~cmp devs in
990 (* Print the header for block devices. *)
992 mvaddstr header_lineno 0
993 (pad cols " ID S RDBY WRBY RDRQ WRRQ DOMAIN DEVICE");
996 (* Print domains and devices. *)
997 let rec loop lineno = function
999 | (dev, name, rd, stats) :: devs ->
1000 if lineno < lines then (
1001 let state = show_state rd.rd_info.D.state in
1003 if stats.D.rd_bytes >= 0L
1004 then show_int64 stats.D.rd_bytes
1007 if stats.D.wr_bytes >= 0L
1008 then show_int64 stats.D.wr_bytes
1011 if stats.D.rd_req >= 0L
1012 then show_int64 stats.D.rd_req
1015 if stats.D.wr_req >= 0L
1016 then show_int64 stats.D.wr_req
1019 let line = sprintf "%5d %c %s %s %s %s %-12s %s"
1023 (pad 12 name) dev in
1024 let line = pad cols line in
1025 mvaddstr lineno 0 line;
1026 loop (lineno+1) devs
1029 loop domains_lineno devs
1032 (* Calculate and print totals. *)
1034 let totals = List.fold_left (
1035 fun (count, running, blocked, paused, shutdown, shutoff,
1036 crashed, active, inactive,
1037 total_cpu_time, total_memory, total_domU_memory) ->
1039 | (name, Active rd) ->
1040 let test state orig =
1041 if rd.rd_info.D.state = state then orig+1 else orig
1043 let running = test D.InfoRunning running in
1044 let blocked = test D.InfoBlocked blocked in
1045 let paused = test D.InfoPaused paused in
1046 let shutdown = test D.InfoShutdown shutdown in
1047 let shutoff = test D.InfoShutoff shutoff in
1048 let crashed = test D.InfoCrashed crashed in
1050 let total_cpu_time = total_cpu_time +. rd.rd_cpu_time in
1051 let total_memory = total_memory +^ rd.rd_info.D.memory in
1052 let total_domU_memory = total_domU_memory +^
1053 if rd.rd_domid > 0 then rd.rd_info.D.memory else 0L in
1055 (count+1, running, blocked, paused, shutdown, shutoff,
1056 crashed, active+1, inactive,
1057 total_cpu_time, total_memory, total_domU_memory)
1059 | (name, Inactive) -> (* inactive domain *)
1060 (count+1, running, blocked, paused, shutdown, shutoff,
1061 crashed, active, inactive+1,
1062 total_cpu_time, total_memory, total_domU_memory)
1063 ) (0,0,0,0,0,0,0,0,0, 0.,0L,0L) doms in
1065 let (count, running, blocked, paused, shutdown, shutoff,
1066 crashed, active, inactive,
1067 total_cpu_time, total_memory, total_domU_memory) = totals in
1069 mvaddstr summary_lineno 0
1070 (sprintf "%d domains, %d active, %d running, %d sleeping, %d paused, %d inactive D:%d O:%d X:%d"
1071 count active running blocked paused inactive shutdown shutoff
1074 (* Total %CPU used, and memory summary. *)
1075 let percent_cpu = 100. *. total_cpu_time /. total_cpu in
1076 mvaddstr (summary_lineno+1) 0
1077 (sprintf "CPU: %2.1f%% Mem: %Ld MB (%Ld MB by guests)"
1078 percent_cpu (total_memory /^ 1024L) (total_domU_memory /^ 1024L));
1080 (* Time to grab another historical %CPU for the list? *)
1081 if time >= !historical_cpu_last_time +. float !historical_cpu_delay
1083 historical_cpu := percent_cpu :: List.take 10 !historical_cpu;
1084 historical_cpu_last_time := time
1087 (* Display historical CPU time. *)
1089 let x, y = historical_cursor in (* Yes, it's a bug in ocaml-curses *)
1090 let maxwidth = cols - x in
1093 (List.map (sprintf "%2.1f%%") !historical_cpu) in
1094 let line = pad maxwidth line in
1098 (* Write summary data to CSV file. See also write_csv_header (). *)
1099 if !csv_enabled then (
1101 hostname; printable_time; node_info.C.model; string_of_int nr_pcpus;
1102 string_of_int count; string_of_int running; string_of_int blocked;
1103 string_of_int paused; string_of_int shutdown; string_of_int shutoff;
1104 string_of_int crashed; string_of_int active; string_of_int inactive;
1105 sprintf "%2.1f" percent_cpu;
1106 Int64.to_string total_memory; Int64.to_string total_domU_memory;
1107 Int64.to_string (Int64.of_float total_cpu_time)
1114 (* Update last_info, last_time. *)
1116 Hashtbl.clear last_info;
1120 let info = rd.rd_info, rd.rd_block_stats, rd.rd_interface_stats in
1121 Hashtbl.add last_info rd.rd_domid info
1125 move message_lineno 0 (* Park cursor in message area, as with top. *)
1128 let clear_pcpu_display_data () =
1129 (* Clear out vcpu_info used by PCPUDisplay
1130 * display_mode when we switch back to TaskDisplay mode.
1132 Hashtbl.clear last_vcpu_info
1135 redraw, clear_pcpu_display_data
1138 let rec main_loop state =
1139 if !csv_enabled then write_csv_header ();
1145 (* Clear up unused virDomainPtr objects. *)
1148 if not !batch_mode then
1150 else (* Batch mode - just sleep, ignore keys. *)
1151 Unix.sleep (!delay / 1000);
1153 (* Max iterations? *)
1154 if !iterations >= 0 then (
1156 if !iterations = 0 then quit := true
1160 and get_key_press state =
1161 (* Read the next key, waiting up to !delay milliseconds. *)
1164 timeout (-1); (* Reset to blocking mode. *)
1166 if k >= 0 && k <> 32 (* ' ' *) && k <> 12 (* ^L *) && k <> Key.resize
1168 if k = Char.code 'q' then quit := true
1169 else if k = Char.code 'h' then show_help state
1170 else if k = Char.code 's' || k = Char.code 'd' then change_delay ()
1171 else if k = Char.code 'M' then sort_order := Memory
1172 else if k = Char.code 'P' then sort_order := Processor
1173 else if k = Char.code 'T' then sort_order := Time
1174 else if k = Char.code 'N' then sort_order := DomainID
1175 else if k = Char.code 'F' then change_sort_order ()
1176 else if k = Char.code '0' then set_tasks_display ()
1177 else if k = Char.code '1' then toggle_pcpu_display ()
1178 else if k = Char.code '2' then toggle_net_display ()
1179 else if k = Char.code '3' then toggle_block_display ()
1180 else unknown_command k
1183 and change_delay () =
1184 print_msg (sprintf "Change delay from %.1f to: " (float !delay /. 1000.));
1185 let str = get_string 16 in
1186 (* Try to parse the number. *)
1189 let newdelay = float_of_string str in
1190 if newdelay <= 0. then (
1191 print_msg "Delay must be > 0"; true
1193 delay := int_of_float (newdelay *. 1000.); false
1196 Failure "float_of_string" ->
1197 print_msg "Not a valid number"; true in
1198 sleep (if error then 2 else 1)
1200 and change_sort_order () =
1202 let lines, cols = get_size () in
1204 mvaddstr top_lineno 0 "Set sort order for main display";
1205 mvaddstr summary_lineno 0 "Type key or use up and down cursor keys.";
1208 mvaddstr header_lineno 0 (pad cols "KEY Sort field");
1211 let accelerator_key = function
1212 | Memory -> "(key: M)"
1213 | Processor -> "(key: P)"
1214 | Time -> "(key: T)"
1215 | DomainID -> "(key: N)"
1216 | _ -> (* all others have to be changed from here *) ""
1219 let rec key_of_int = function
1220 | i when i < 10 -> Char.chr (i + Char.code '0')
1221 | i when i < 20 -> Char.chr (i + Char.code 'a')
1223 and int_of_key = function
1224 | k when k >= 0x30 && k <= 0x39 (* '0' - '9' *) -> k - 0x30
1225 | k when k >= 0x61 && k <= 0x7a (* 'a' - 'j' *) -> k - 0x61 + 10
1226 | k when k >= 0x41 && k <= 0x6a (* 'A' - 'J' *) -> k - 0x41 + 10
1230 (* Display possible sort fields. *)
1231 let selected_index = ref 0 in
1234 let selected = !sort_order = ord in
1235 if selected then selected_index := i;
1236 mvaddstr (domains_lineno+i) 0
1237 (sprintf " %c %s %s %s"
1238 (key_of_int i) (if selected then "*" else " ")
1239 (printable_sort_order ord)
1240 (accelerator_key ord))
1243 move message_lineno 0;
1246 if k >= 0 && k <> 32 && k <> Char.code 'q' && k <> 13 then (
1247 let new_order, loop =
1248 (* Redraw the display. *)
1249 if k = 12 (* ^L *) then None, true
1250 (* Make the UP and DOWN arrow keys do something useful. *)
1251 else if k = Key.up then (
1252 if !selected_index > 0 then
1253 Some (List.nth all_sort_fields (!selected_index-1)), true
1257 else if k = Key.down then (
1258 if !selected_index < List.length all_sort_fields - 1 then
1259 Some (List.nth all_sort_fields (!selected_index+1)), true
1263 (* Also understand the regular accelerator keys. *)
1264 else if k = Char.code 'M' then
1266 else if k = Char.code 'P' then
1267 Some Processor, false
1268 else if k = Char.code 'T' then
1270 else if k = Char.code 'N' then
1271 Some DomainID, false
1273 (* It's one of the KEYs. *)
1274 let i = int_of_key k in
1275 if i >= 0 && i < List.length all_sort_fields then
1276 Some (List.nth all_sort_fields i), false
1281 (match new_order with
1284 sort_order := new_order;
1285 print_msg (sprintf "Sort order changed to: %s"
1286 (printable_sort_order new_order));
1287 if not loop then sleep 1
1290 if loop then change_sort_order ()
1293 (* Note: We need to clear_pcpu_display_data every time
1294 * we _leave_ PCPUDisplay mode.
1296 and set_tasks_display () = (* key 0 *)
1297 if !display_mode = PCPUDisplay then clear_pcpu_display_data ();
1298 display_mode := TaskDisplay
1300 and toggle_pcpu_display () = (* key 1 *)
1302 match !display_mode with
1303 | TaskDisplay | NetDisplay | BlockDisplay -> PCPUDisplay
1304 | PCPUDisplay -> clear_pcpu_display_data (); TaskDisplay
1306 and toggle_net_display () = (* key 2 *)
1308 match !display_mode with
1309 | PCPUDisplay -> clear_pcpu_display_data (); NetDisplay
1310 | TaskDisplay | BlockDisplay -> NetDisplay
1311 | NetDisplay -> TaskDisplay
1313 and toggle_block_display () = (* key 3 *)
1315 match !display_mode with
1316 | PCPUDisplay -> clear_pcpu_display_data (); BlockDisplay
1317 | TaskDisplay | NetDisplay -> BlockDisplay
1318 | BlockDisplay -> TaskDisplay
1320 and show_help (_, _, _, hostname,
1321 (libvirt_major, libvirt_minor, libvirt_release)) =
1324 (* Get the screen/window size. *)
1325 let lines, cols = get_size () in
1327 (* Banner at the top of the screen. *)
1329 sprintf "virt-top %s (libvirt %d.%d.%d) by Red Hat"
1330 Libvirt_version.version libvirt_major libvirt_minor libvirt_release in
1331 let banner = pad cols banner in
1333 mvaddstr 0 0 banner;
1338 (sprintf "Delay: %.1f secs; Batch: %s; Secure: %s; Sort: %s"
1339 (float !delay /. 1000.)
1340 (if !batch_mode then "On" else "Off")
1341 (if !secure_mode then "On" else "Off")
1342 (printable_sort_order !sort_order));
1344 (sprintf "Connect: %s; Hostname: %s"
1345 (match !uri with None -> "default" | Some s -> s)
1348 (* Misc keys on left. *)
1349 let banner = pad 38 "MAIN KEYS" in
1351 mvaddstr header_lineno 1 banner;
1355 let lineno = ref domains_lineno in
1356 fun () -> let i = !lineno in incr lineno; i
1358 let key keys description =
1359 let lineno = get_lineno () in
1360 move lineno 1; attron A.bold; addstr keys; attroff A.bold;
1361 move lineno 10; addstr description; ()
1363 key "space ^L" "Update display";
1365 key "d s" "Set update interval";
1369 ignore (get_lineno ());
1370 let banner = pad 38 "SORTING" in
1372 mvaddstr (get_lineno ()) 1 banner;
1375 key "P" "Sort by %CPU";
1376 key "M" "Sort by %MEM";
1377 key "T" "Sort by TIME";
1378 key "N" "Sort by ID";
1379 key "F" "Select sort field";
1381 (* Display modes on right. *)
1382 let banner = pad 39 "DISPLAY MODES" in
1384 mvaddstr header_lineno 40 banner;
1388 let lineno = ref domains_lineno in
1389 fun () -> let i = !lineno in incr lineno; i
1391 let key keys description =
1392 let lineno = get_lineno () in
1393 move lineno 40; attron A.bold; addstr keys; attroff A.bold;
1394 move lineno 49; addstr description; ()
1396 key "0" "Domains display";
1397 key "1" "Toggle physical CPUs";
1398 key "2" "Toggle network interfaces";
1399 key "3" "Toggle block devices";
1401 (* Update screen and wait for key press. *)
1402 mvaddstr (lines-1) 0
1403 "More help in virt-top(1) man page. Press any key to return.";
1407 and unknown_command k =
1408 print_msg "Unknown command - try 'h' for help";