1 (* 'top'-like tool for libvirt domains.
2 (C) Copyright 2007-2017 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.
20 module C = Libvirt.Connect
21 module D = Libvirt.Domain
29 (* Hook for XML support (see [opt_xml.ml]). *)
30 let parse_device_xml : (int -> [>`R] D.t -> string list * string list) ref =
35 (* Intermediate "domain + stats" structure that we use to collect
36 * everything we know about a domain within the collect function.
38 type rd_domain = Inactive | Active of rd_active
40 rd_domid : int; (* Domain ID. *)
41 rd_dom : [`R] D.t; (* Domain object. *)
42 rd_info : D.info; (* Domain CPU info now. *)
43 rd_block_stats : (string * D.block_stats) list;
44 (* Domain block stats now. *)
45 rd_interface_stats : (string * D.interface_stats) list;
46 (* Domain net stats now. *)
47 rd_prev_info : D.info option; (* Domain CPU info previously. *)
48 rd_prev_block_stats : (string * D.block_stats) list;
49 (* Domain block stats prev. *)
50 rd_prev_interface_stats : (string * D.interface_stats) list;
51 (* Domain interface stats prev. *)
52 (* The following are since the last slice, or 0 if cannot be calculated: *)
53 rd_cpu_time : float; (* CPU time used in nanoseconds. *)
54 rd_percent_cpu : float; (* CPU time as percent of total. *)
55 rd_mem_bytes : int64; (* Memory usage in bytes *)
56 rd_mem_percent: int64; (* Memory usage as percent of total *)
57 (* The following are since the last slice, or None if cannot be calc'd: *)
58 rd_block_rd_reqs : int64 option; (* Number of block device read rqs. *)
59 rd_block_wr_reqs : int64 option; (* Number of block device write rqs. *)
60 rd_block_rd_bytes : int64 option; (* Number of bytes block device read *)
61 rd_block_wr_bytes : int64 option; (* Number of bytes block device write *)
62 rd_net_rx_bytes : int64 option; (* Number of bytes received. *)
63 rd_net_tx_bytes : int64 option; (* Number of bytes transmitted. *)
67 rd_doms : (string * rd_domain) list; (* List of domains. *)
69 rd_printable_time : string;
72 rd_total_cpu_per_pcpu : float;
73 rd_totals : (int * int * int * int * int * int * int * int * int * float *
78 rd_pcpu_doms : (int * string * int *
79 Libvirt.Domain.vcpu_info array * int64 array array *
80 int64 array array * string * int) list;
81 rd_pcpu_pcpus : int64 array array array;
82 rd_pcpu_pcpus_cpu_time : float array
85 (* We cache the list of block devices and interfaces for each domain
86 * here, so we don't need to reparse the XML each time.
88 let devices = Hashtbl.create 13
90 (* Function to get the list of block devices, network interfaces for
91 * a particular domain. Get it from the devices cache, and if not
92 * there then parse the domain XML.
94 let get_devices id dom =
95 try Hashtbl.find devices id
97 let blkdevs, netifs = (!parse_device_xml) id dom in
98 Hashtbl.replace devices id (blkdevs, netifs);
101 (* We save the state of domains across redraws here, which allows us
102 * to deduce %CPU usage from the running total.
104 let last_info = Hashtbl.create 13
105 let last_time = ref (Unix.gettimeofday ())
107 (* Save pcpu_usages structures across redraws too (only for pCPU display). *)
108 let last_pcpu_usages = Hashtbl.create 13
110 let clear_pcpu_display_data () =
111 Hashtbl.clear last_pcpu_usages
113 let collect (conn, _, _, _, _, node_info, _, _) =
114 (* Number of physical CPUs (some may be disabled). *)
115 let nr_pcpus = C.maxcpus_of_node_info node_info in
117 (* Get the current time. *)
118 let time = Unix.gettimeofday () in
119 let tm = Unix.localtime time in
121 sprintf "%02d:%02d:%02d" tm.Unix.tm_hour tm.Unix.tm_min tm.Unix.tm_sec in
123 (* What's the total CPU time elapsed since we were last called? (ns) *)
124 let total_cpu_per_pcpu = 1_000_000_000. *. (time -. !last_time) in
125 (* Avoid division by zero. *)
126 let total_cpu_per_pcpu =
127 if total_cpu_per_pcpu <= 0. then 1. else total_cpu_per_pcpu in
128 let total_cpu = float node_info.C.cpus *. total_cpu_per_pcpu in
130 (* Get the domains. Match up with their last_info (if any). *)
132 (* Active domains. *)
133 let n = C.num_of_domains conn in
135 if n > 0 then Array.to_list (C.list_domains conn n)
141 let dom = D.lookup_by_id conn id in
142 let name = D.get_name dom in
143 let blkdevs, netifs = get_devices id dom in
145 (* Get current CPU, block and network stats. *)
146 let info = D.get_info dom in
148 try List.map (fun dev -> dev, D.block_stats dom dev) blkdevs
150 | Libvirt.Not_supported "virDomainBlockStats"
151 | Libvirt.Virterror _ -> [] in
152 let interface_stats =
153 try List.map (fun dev -> dev, D.interface_stats dom dev) netifs
155 | Libvirt.Not_supported "virDomainInterfaceStats"
156 | Libvirt.Virterror _ -> [] in
158 let prev_info, prev_block_stats, prev_interface_stats =
160 let prev_info, prev_block_stats, prev_interface_stats =
161 Hashtbl.find last_info id in
162 Some prev_info, prev_block_stats, prev_interface_stats
163 with Not_found -> None, [], [] in
167 rd_domid = id; rd_dom = dom; rd_info = info;
168 rd_block_stats = block_stats;
169 rd_interface_stats = interface_stats;
170 rd_prev_info = prev_info;
171 rd_prev_block_stats = prev_block_stats;
172 rd_prev_interface_stats = prev_interface_stats;
173 rd_cpu_time = 0.; rd_percent_cpu = 0.;
174 rd_mem_bytes = 0L; rd_mem_percent = 0L;
175 rd_block_rd_reqs = None; rd_block_wr_reqs = None;
176 rd_block_rd_bytes = None; rd_block_wr_bytes = None;
177 rd_net_rx_bytes = None; rd_net_tx_bytes = None;
180 Libvirt.Virterror _ -> None (* ignore transient error *)
183 (* Inactive domains. *)
186 let n = C.num_of_defined_domains conn in
188 if n > 0 then Array.to_list (C.list_defined_domains conn n)
190 List.map (fun name -> name, Inactive) names
192 (* Ignore transient errors, in particular errors from
193 * num_of_defined_domains if it cannot contact xend.
195 | Libvirt.Virterror _ -> [] in
197 doms @ doms_inactive in
199 (* Calculate the CPU time (ns) and %CPU used by each domain. *)
203 (* We have previous CPU info from which to calculate it? *)
204 | name, Active ({ rd_prev_info = Some prev_info } as rd) ->
206 Int64.to_float (rd.rd_info.D.cpu_time -^ prev_info.D.cpu_time) in
207 let percent_cpu = 100. *. cpu_time /. total_cpu in
208 let mem_usage = rd.rd_info.D.memory in
210 100L *^ rd.rd_info.D.memory /^ node_info.C.memory in
212 rd_cpu_time = cpu_time;
213 rd_percent_cpu = percent_cpu;
214 rd_mem_bytes = mem_usage;
215 rd_mem_percent = mem_percent} in
217 (* For all other domains we can't calculate it, so leave as 0 *)
221 (* Calculate the number of block device read/write requests across
222 * all block devices attached to a domain.
227 (* Do we have stats from the previous slice? *)
228 | name, Active ({ rd_prev_block_stats = ((_::_) as prev_block_stats) }
230 let block_stats = rd.rd_block_stats in (* stats now *)
232 (* Add all the devices together. Throw away device names. *)
233 let prev_block_stats =
234 sum_block_stats (List.map snd prev_block_stats) in
236 sum_block_stats (List.map snd block_stats) in
238 (* Calculate increase in read & write requests. *)
240 block_stats.D.rd_req -^ prev_block_stats.D.rd_req in
242 block_stats.D.wr_req -^ prev_block_stats.D.wr_req in
244 block_stats.D.rd_bytes -^ prev_block_stats.D.rd_bytes in
246 block_stats.D.wr_bytes -^ prev_block_stats.D.wr_bytes in
249 rd_block_rd_reqs = Some read_reqs;
250 rd_block_wr_reqs = Some write_reqs;
251 rd_block_rd_bytes = Some read_bytes;
252 rd_block_wr_bytes = Some write_bytes;
255 (* For all other domains we can't calculate it, so leave as None. *)
259 (* Calculate the same as above for network interfaces across
260 * all network interfaces attached to a domain.
265 (* Do we have stats from the previous slice? *)
266 | name, Active ({ rd_prev_interface_stats =
267 ((_::_) as prev_interface_stats) }
269 let interface_stats = rd.rd_interface_stats in (* stats now *)
271 (* Add all the devices together. Throw away device names. *)
272 let prev_interface_stats =
273 sum_interface_stats (List.map snd prev_interface_stats) in
274 let interface_stats =
275 sum_interface_stats (List.map snd interface_stats) in
277 (* Calculate increase in rx & tx bytes. *)
279 interface_stats.D.rx_bytes -^ prev_interface_stats.D.rx_bytes in
281 interface_stats.D.tx_bytes -^ prev_interface_stats.D.tx_bytes in
284 rd_net_rx_bytes = Some rx_bytes;
285 rd_net_tx_bytes = Some tx_bytes } in
287 (* For all other domains we can't calculate it, so leave as None. *)
291 (* Calculate totals. *)
294 fun (count, running, blocked, paused, shutdown, shutoff,
295 crashed, active, inactive,
296 total_cpu_time, total_memory, total_domU_memory) ->
298 | (name, Active rd) ->
299 let test state orig =
300 if rd.rd_info.D.state = state then orig+1 else orig
302 let running = test D.InfoRunning running in
303 let blocked = test D.InfoBlocked blocked in
304 let paused = test D.InfoPaused paused in
305 let shutdown = test D.InfoShutdown shutdown in
306 let shutoff = test D.InfoShutoff shutoff in
307 let crashed = test D.InfoCrashed crashed in
309 let total_cpu_time = total_cpu_time +. rd.rd_cpu_time in
310 let total_memory = total_memory +^ rd.rd_info.D.memory in
311 let total_domU_memory =
313 if rd.rd_domid > 0 then rd.rd_info.D.memory else 0L in
315 (count+1, running, blocked, paused, shutdown, shutoff,
316 crashed, active+1, inactive,
317 total_cpu_time, total_memory, total_domU_memory)
319 | (name, Inactive) -> (* inactive domain *)
320 (count+1, running, blocked, paused, shutdown, shutoff,
321 crashed, active, inactive+1,
322 total_cpu_time, total_memory, total_domU_memory)
323 ) (0,0,0,0,0,0,0,0,0, 0.,0L,0L) doms in
325 (* Update last_time, last_info. *)
327 Hashtbl.clear last_info;
331 let info = rd.rd_info, rd.rd_block_stats, rd.rd_interface_stats in
332 Hashtbl.add last_info rd.rd_domid info
338 rd_printable_time = printable_time;
339 rd_nr_pcpus = nr_pcpus;
340 rd_total_cpu = total_cpu;
341 rd_total_cpu_per_pcpu = total_cpu_per_pcpu;
344 (* Collect some extra information in PCPUDisplay display_mode. *)
345 let collect_pcpu { rd_doms = doms; rd_nr_pcpus = nr_pcpus } =
346 (* Get the VCPU info and VCPU->PCPU mappings for active domains.
347 * Also cull some data we don't care about.
352 | (name, Active rd) ->
354 let domid = rd.rd_domid in
355 let maplen = C.cpumaplen nr_pcpus in
356 let cpu_stats = D.get_cpu_stats rd.rd_dom in
358 (* Note the terminology is confusing.
360 * In libvirt, cpu_time is the total time (hypervisor +
361 * vCPU). vcpu_time is the time only taken by the vCPU,
362 * excluding time taken inside the hypervisor.
364 * For each pCPU, libvirt may return either "cpu_time"
365 * or "vcpu_time" or neither or both. This function
366 * returns an array pair [|cpu_time, vcpu_time|];
367 * if either is missing it is returned as 0.
369 let find_cpu_usages params =
370 let rec find_uint64_field name = function
371 | (n, D.TypedFieldUInt64 usage) :: _ when n = name ->
373 | _ :: params -> find_uint64_field name params
376 [| find_uint64_field "cpu_time" params;
377 find_uint64_field "vcpu_time" params |]
380 let pcpu_usages = Array.map find_cpu_usages cpu_stats in
381 let maxinfo = rd.rd_info.D.nr_virt_cpu in
382 let nr_vcpus, vcpu_infos, cpumaps =
383 D.get_vcpus rd.rd_dom maxinfo maplen in
385 (* Got previous pcpu_usages for this domain? *)
386 let prev_pcpu_usages =
387 try Some (Hashtbl.find last_pcpu_usages domid)
388 with Not_found -> None in
389 (* Update last_pcpu_usages. *)
390 Hashtbl.replace last_pcpu_usages domid pcpu_usages;
392 (match prev_pcpu_usages with
393 | Some prev_pcpu_usages
394 when Array.length prev_pcpu_usages = Array.length pcpu_usages ->
395 Some (domid, name, nr_vcpus, vcpu_infos, pcpu_usages,
396 prev_pcpu_usages, cpumaps, maplen)
397 | _ -> None (* ignore missing / unequal length prev_vcpu_infos *)
400 Libvirt.Virterror _ -> None (* ignore transient libvirt errors *)
402 | (_, Inactive) -> None (* ignore inactive doms *)
404 let nr_doms = List.length doms in
406 (* Rearrange the data into a matrix. Major axis (down) is
407 * pCPUs. Minor axis (right) is domains. At each node we store:
408 * cpu_time hypervisor + domain (on this pCPU only, nanosecs),
409 * vcpu_time domain only (on this pCPU only, nanosecs).
411 let make_3d_array dimx dimy dimz e =
412 Array.init dimx (fun _ -> Array.make_matrix dimy dimz e)
414 let pcpus = make_3d_array nr_pcpus nr_doms 2 0L in
417 fun di (domid, name, nr_vcpus, vcpu_infos, pcpu_usages,
418 prev_pcpu_usages, cpumaps, maplen) ->
419 (* Which pCPUs can this dom run on? *)
420 for p = 0 to Array.length pcpu_usages - 1 do
421 pcpus.(p).(di).(0) <-
422 pcpu_usages.(p).(0) -^ prev_pcpu_usages.(p).(0);
423 pcpus.(p).(di).(1) <-
424 pcpu_usages.(p).(1) -^ prev_pcpu_usages.(p).(1)
428 (* Sum the total CPU time used by each pCPU, for the %CPU column. *)
432 let cpu_time = ref 0L in
433 for di = 0 to Array.length row-1 do
434 let t = row.(di).(0) in
435 cpu_time := !cpu_time +^ t
437 Int64.to_float !cpu_time
440 { rd_pcpu_doms = doms;
441 rd_pcpu_pcpus = pcpus;
442 rd_pcpu_pcpus_cpu_time = pcpus_cpu_time }