448ce8cf33db13eb8040c50a99b0ea8f239e1c84
[virt-top.git] / src / collect.ml
1 (* 'top'-like tool for libvirt domains.
2    (C) Copyright 2007-2017 Richard W.M. Jones, Red Hat Inc.
3    http://libvirt.org/
4
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.
9
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.
14
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.
18 *)
19
20 module C = Libvirt.Connect
21 module D = Libvirt.Domain
22
23 open Printf
24 open ExtList
25
26 open Utils
27 open Types
28
29 (* Hook for XML support (see [opt_xml.ml]). *)
30 let parse_device_xml : (int -> [>`R] D.t -> string list * string list) ref =
31   ref (
32     fun _ _ -> [], []
33   )
34
35 (* Intermediate "domain + stats" structure that we use to collect
36  * everything we know about a domain within the collect function.
37  *)
38 type rd_domain = Inactive | Active of rd_active
39 and 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. *)
64 }
65
66 type stats = {
67   rd_doms : (string * rd_domain) list;  (* List of domains. *)
68   rd_time : float;
69   rd_printable_time : string;
70   rd_nr_pcpus : int;
71   rd_total_cpu : float;
72   rd_total_cpu_per_pcpu : float;
73   rd_totals : (int * int * int * int * int * int * int * int * int * float *
74                  int64 * int64);
75 }
76
77 type pcpu_stats = {
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
83 }
84
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.
87  *)
88 let devices = Hashtbl.create 13
89
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.
93  *)
94 let get_devices id dom =
95   try Hashtbl.find devices id
96   with Not_found ->
97     let blkdevs, netifs = (!parse_device_xml) id dom in
98     Hashtbl.replace devices id (blkdevs, netifs);
99     blkdevs, netifs
100
101 (* We save the state of domains across redraws here, which allows us
102  * to deduce %CPU usage from the running total.
103  *)
104 let last_info = Hashtbl.create 13
105 let last_time = ref (Unix.gettimeofday ())
106
107 (* Save pcpu_usages structures across redraws too (only for pCPU display). *)
108 let last_pcpu_usages = Hashtbl.create 13
109
110 let clear_pcpu_display_data () =
111   Hashtbl.clear last_pcpu_usages
112
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
116
117   (* Get the current time. *)
118   let time = Unix.gettimeofday () in
119   let tm = Unix.localtime time in
120   let printable_time =
121     sprintf "%02d:%02d:%02d" tm.Unix.tm_hour tm.Unix.tm_min tm.Unix.tm_sec in
122
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
129
130   (* Get the domains.  Match up with their last_info (if any). *)
131   let doms =
132     (* Active domains. *)
133     let n = C.num_of_domains conn in
134     let ids =
135       if n > 0 then Array.to_list (C.list_domains conn n)
136       else [] in
137     let doms =
138       List.filter_map (
139         fun id ->
140           try
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
144
145             (* Get current CPU, block and network stats. *)
146             let info = D.get_info dom in
147             let block_stats =
148               try List.map (fun dev -> dev, D.block_stats dom dev) blkdevs
149               with
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
154               with
155               | Libvirt.Not_supported "virDomainInterfaceStats"
156               | Libvirt.Virterror _ -> [] in
157
158             let prev_info, prev_block_stats, prev_interface_stats =
159               try
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
164
165             Some (name,
166                   Active {
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;
178                     })
179           with
180             Libvirt.Virterror _ -> None (* ignore transient error *)
181       ) ids in
182
183     (* Inactive domains. *)
184     let doms_inactive =
185       try
186         let n = C.num_of_defined_domains conn in
187         let names =
188           if n > 0 then Array.to_list (C.list_defined_domains conn n)
189           else [] in
190         List.map (fun name -> name, Inactive) names
191       with
192       (* Ignore transient errors, in particular errors from
193        * num_of_defined_domains if it cannot contact xend.
194        *)
195       | Libvirt.Virterror _ -> [] in
196
197     doms @ doms_inactive in
198
199   (* Calculate the CPU time (ns) and %CPU used by each domain. *)
200   let doms =
201     List.map (
202       function
203       (* We have previous CPU info from which to calculate it? *)
204       | name, Active ({ rd_prev_info = Some prev_info } as rd) ->
205          let cpu_time =
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
209          let mem_percent =
210            100L *^ rd.rd_info.D.memory /^ node_info.C.memory in
211          let rd = { rd with
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
216          name, Active rd
217       (* For all other domains we can't calculate it, so leave as 0 *)
218       | rd -> rd
219     ) doms in
220
221   (* Calculate the number of block device read/write requests across
222    * all block devices attached to a domain.
223    *)
224   let doms =
225     List.map (
226       function
227       (* Do we have stats from the previous slice? *)
228       | name, Active ({ rd_prev_block_stats = ((_::_) as prev_block_stats) }
229                       as rd) ->
230          let block_stats = rd.rd_block_stats in (* stats now *)
231
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
235          let block_stats =
236            sum_block_stats (List.map snd block_stats) in
237
238          (* Calculate increase in read & write requests. *)
239          let read_reqs =
240            block_stats.D.rd_req -^ prev_block_stats.D.rd_req in
241          let write_reqs =
242            block_stats.D.wr_req -^ prev_block_stats.D.wr_req in
243          let read_bytes =
244            block_stats.D.rd_bytes -^ prev_block_stats.D.rd_bytes in
245          let write_bytes =
246            block_stats.D.wr_bytes -^ prev_block_stats.D.wr_bytes in
247
248          let rd = { rd with
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;
253          } in
254          name, Active rd
255       (* For all other domains we can't calculate it, so leave as None. *)
256       | rd -> rd
257     ) doms in
258
259   (* Calculate the same as above for network interfaces across
260    * all network interfaces attached to a domain.
261    *)
262   let doms =
263     List.map (
264       function
265       (* Do we have stats from the previous slice? *)
266       | name, Active ({ rd_prev_interface_stats =
267                           ((_::_) as prev_interface_stats) }
268                       as rd) ->
269          let interface_stats = rd.rd_interface_stats in (* stats now *)
270
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
276
277          (* Calculate increase in rx & tx bytes. *)
278          let rx_bytes =
279            interface_stats.D.rx_bytes -^ prev_interface_stats.D.rx_bytes in
280          let tx_bytes =
281            interface_stats.D.tx_bytes -^ prev_interface_stats.D.tx_bytes in
282
283          let rd = { rd with
284                     rd_net_rx_bytes = Some rx_bytes;
285                     rd_net_tx_bytes = Some tx_bytes } in
286          name, Active rd
287       (* For all other domains we can't calculate it, so leave as None. *)
288       | rd -> rd
289     ) doms in
290
291   (* Calculate totals. *)
292   let totals =
293     List.fold_left (
294         fun (count, running, blocked, paused, shutdown, shutoff,
295              crashed, active, inactive,
296              total_cpu_time, total_memory, total_domU_memory) ->
297         function
298         | (name, Active rd) ->
299            let test state orig =
300              if rd.rd_info.D.state = state then orig+1 else orig
301            in
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
308
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 =
312              total_domU_memory +^
313                if rd.rd_domid > 0 then rd.rd_info.D.memory else 0L in
314
315            (count+1, running, blocked, paused, shutdown, shutoff,
316             crashed, active+1, inactive,
317             total_cpu_time, total_memory, total_domU_memory)
318
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
324
325   (* Update last_time, last_info. *)
326   last_time := time;
327   Hashtbl.clear last_info;
328   List.iter (
329     function
330     | (_, Active rd) ->
331        let info = rd.rd_info, rd.rd_block_stats, rd.rd_interface_stats in
332        Hashtbl.add last_info rd.rd_domid info
333     | _ -> ()
334   ) doms;
335
336   { rd_doms = doms;
337     rd_time = time;
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;
342     rd_totals = totals }
343
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.
348    *)
349   let doms =
350     List.filter_map (
351       function
352       | (name, Active rd) ->
353          (try
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
357
358              (* Note the terminology is confusing.
359               *
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.
363               *
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.
368               *)
369              let find_cpu_usages params =
370                let rec find_uint64_field name = function
371                  | (n, D.TypedFieldUInt64 usage) :: _ when n = name ->
372                     usage
373                  | _ :: params -> find_uint64_field name params
374                  | [] -> 0L
375                in
376                [| find_uint64_field "cpu_time" params;
377                   find_uint64_field "vcpu_time" params |]
378              in
379
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
384
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;
391
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 *)
398              );
399            with
400              Libvirt.Virterror _ -> None (* ignore transient libvirt errors *)
401          )
402       | (_, Inactive) -> None (* ignore inactive doms *)
403     ) doms in
404   let nr_doms = List.length doms in
405
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).
410    *)
411   let make_3d_array dimx dimy dimz e =
412     Array.init dimx (fun _ -> Array.make_matrix dimy dimz e)
413   in
414   let pcpus = make_3d_array nr_pcpus nr_doms 2 0L in
415
416   List.iteri (
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)
425       done
426   ) doms;
427
428   (* Sum the total CPU time used by each pCPU, for the %CPU column. *)
429   let pcpus_cpu_time =
430     Array.map (
431       fun row ->
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
436         done;
437         Int64.to_float !cpu_time
438     ) pcpus in
439
440   { rd_pcpu_doms = doms;
441     rd_pcpu_pcpus = pcpus;
442     rd_pcpu_pcpus_cpu_time = pcpus_cpu_time }