05024c53a9952651e6f41bf73167f5be98391efc
[virt-top.git] / virt-ctrl / vc_connections.ml
1 (* virt-ctrl: A graphical management tool.
2    (C) Copyright 2007 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 open Printf
21
22 module C = Libvirt.Connect
23 module D = Libvirt.Domain
24 module N = Libvirt.Network
25
26 open Vc_helpers
27
28 (* List of currently open connections.  Actually it's a list of
29  * (id, Libvirt.Connect.t) so that we can easily identify
30  * connections by their unique ID.
31  *)
32 let get_conns, add_conn, del_conn =
33   let conns = ref [] in
34   let id = ref 0 in
35   let get_conns () = !conns in
36   let add_conn conn =
37     incr id; let id = !id in
38     conns := (id, conn) :: !conns;
39     id
40   in
41   let del_conn id =
42     conns := List.filter (fun (id', _) -> id <> id') !conns
43   in
44   get_conns, add_conn, del_conn
45
46 (* Store the node_info and hostname for each connection, fetched
47  * once just after we connect since these don't normally change.
48  * Hash of connid -> (C.node_info, hostname option, uri)
49  *)
50 let static_conn_info = Hashtbl.create 13
51
52 let open_connection uri =
53   (* If this fails, let the exception escape and be printed
54    * in the global exception handler.
55    *)
56   let conn = C.connect ~name:uri () in
57
58   let node_info = C.get_node_info conn in
59   let hostname =
60     try Some (C.get_hostname conn)
61     with
62     | Libvirt.Not_supported "virConnectGetHostname"
63     | Libvirt.Virterror _ -> None in
64
65   (* Add it to our list of connections. *)
66   let conn_id = add_conn conn in
67   Hashtbl.add static_conn_info conn_id (node_info, hostname, uri)
68
69 (* Stores the state and history for each domain.
70  * Hash of (connid, domid) -> mutable domhistory structure.
71  * We never delete entries in this hash table, which may be a problem
72  * for very very long-lived instances of virt-ctrl.
73  *)
74 type domhistory = {
75   (* for %CPU calculation: *)
76   mutable last_cpu_time : int64;        (* last virDomainInfo->cpuTime *)
77   mutable last_time : float;            (* exact time we measured the above *)
78
79   (* historical data for graphs etc: *)
80   mutable hist : dhentry array;         (* historical data *)
81   mutable hist_posn : int;              (* position within array *)
82 }
83 and dhentry = {
84   hist_cpu : int;                       (* historical %CPU entry *)
85   hist_mem : int64;                     (* historical memory entry (KB) *)
86 }
87
88 let domhistory = Hashtbl.create 13
89
90 let empty_dhentry = {
91   hist_cpu = 0; hist_mem = 0L;
92 }
93 let new_domhistory () = {
94   last_cpu_time = 0L; last_time = 0.;
95   hist = Array.make 0 empty_dhentry; hist_posn = 0;
96 }
97
98 (* These set limits on the amount of history we collect. *)
99 let hist_max = 86400                    (* max history stored, seconds *)
100 let hist_rot = 3600                     (* rotation of array when we hit max *)
101
102 (* The current state.  This is used so that we can see changes that
103  * have happened and add or remove parts of the model.  (Previously
104  * we used to recreate the whole model each time, but the problem
105  * with that is we "forget" things like the selection).
106  *)
107 type state = connection list
108 and connection = int (* connection ID *) * (active list * inactive list)
109 and active = int (* domain's ID *)
110 and inactive = string (* domain's name *)
111
112 (* The types of the display columns in the main window.  The interesting
113  * one of the final (int) field which stores the ID of the row, either
114  * connid or domid.
115  *)
116 type columns = string GTree.column * string GTree.column * string GTree.column * string GTree.column * string GTree.column * int GTree.column
117
118 let debug_repopulate = false
119
120 (* Populate the tree with the current list of connections, domains.
121  * This function is called once per second.
122  *)
123 let repopulate (tree : GTree.view) (model : GTree.tree_store)
124     (col_name_id, col_domname, col_status, col_cpu, col_mem, col_id)
125     state =
126   (* Which connections have been added or removed? *)
127   let conns = get_conns () in
128   let added, _, removed =
129     let old_conn_ids = List.map fst state
130     and new_conn_ids = List.map fst conns in
131     differences old_conn_ids new_conn_ids in
132
133   (* Remove the subtrees for any connections which have gone. *)
134   if debug_repopulate then List.iter (eprintf "-connection %d\n%!") removed;
135
136   List.iter (
137     fun conn_id ->
138       filter_top_level_rows model
139         (fun row -> conn_id <> model#get ~row ~column:col_id)
140   ) removed;
141
142   (* Add placeholder subtree for any new connections. *)
143   if debug_repopulate then List.iter (eprintf "+connection %d\n%!") added;
144
145   List.iter (
146     fun conn_id ->
147       let row = model#append () in
148       (* Get the connection name, usually the hostname. *)
149       let name =
150         match Hashtbl.find static_conn_info conn_id with
151         | (_, Some hostname, _) -> hostname
152         | (_, None, _) -> sprintf "Conn #%d" conn_id in
153       model#set ~row ~column:col_name_id name;
154       model#set ~row ~column:col_id conn_id;
155       (* Expand the new row. *)
156       (* XXX This doesn't work, why? - Because we haven't create subrows yet.*)
157       tree#expand_row (model#get_path row)
158   ) added;
159
160   let new_state =
161     List.map (
162       fun (conn_id, conn) ->
163         (* Get the old list of active and inactive domains.  If this
164          * connection is newly created, start with empty lists.
165          *)
166         let old_active, old_inactive =
167           try List.assoc conn_id state
168           with Not_found -> [], [] in
169
170         (* Get the top level row in the model corresponding to this
171          * connection.
172          *)
173         let parent =
174           try find_top_level_row model
175             (fun row -> conn_id = model#get ~row ~column:col_id)
176           with Not_found -> assert false (* Should never happen. *) in
177
178         try
179           (* Number of CPUs available. *)
180           let node_info, _, _ = Hashtbl.find static_conn_info conn_id in
181           let nr_cpus = C.maxcpus_of_node_info node_info in
182
183           (* For this connection, get a current list of active domains (IDs) *)
184           let active =
185             let n = C.num_of_domains conn in
186             let doms = C.list_domains conn n in
187             Array.to_list doms in
188
189           (* Which active domains have been added or removed? *)
190           let added, _, removed = differences old_active active in
191
192           (* Remove any active domains which have disappeared. *)
193           if debug_repopulate then
194             List.iter (eprintf "-active %d\n%!") removed;
195
196           List.iter (
197             fun domid ->
198               filter_rows model
199                 (fun row -> domid <> model#get ~row ~column:col_id)
200                 (model#iter_children (Some parent))
201           ) removed;
202
203           (* Add any active domains which have appeared. *)
204           if debug_repopulate then
205             List.iter (eprintf "+active %d\n%!") added;
206
207           List.iter (
208             fun domid ->
209               let domname =
210                 try
211                   let dom = D.lookup_by_id conn domid in
212                   D.get_name dom
213                 with _ -> "" in (* Ignore any transient error. *)
214
215               let row = model#append ~parent () in
216               model#set ~row ~column:col_name_id (string_of_int domid);
217               model#set ~row ~column:col_domname domname;
218               model#set ~row ~column:col_id domid
219           ) added;
220
221           (* Get a current list of inactive domains (names). *)
222           let inactive =
223             let n = C.num_of_defined_domains conn in
224             let doms = C.list_defined_domains conn n in
225             Array.to_list doms in
226
227           (* Which inactive domains have been added or removed? *)
228           let added, _, removed = differences old_inactive inactive in
229
230           (* Remove any inactive domains which have disappeared. *)
231           if debug_repopulate then
232             List.iter (eprintf "-inactive %s\n%!") removed;
233
234           List.iter (
235             fun domname ->
236               filter_rows model
237                 (fun row ->
238                    model#get ~row ~column:col_id <> -1 ||
239                    model#get ~row ~column:col_domname <> domname)
240                 (model#iter_children (Some parent))
241           ) removed;
242
243           (* Add any inactive domains which have appeared. *)
244           if debug_repopulate then
245             List.iter (eprintf "+inactive %s\n%!") added;
246
247           List.iter (
248             fun domname ->
249               let row = model#append ~parent () in
250               model#set ~row ~column:col_name_id "";
251               model#set ~row ~column:col_domname domname;
252               model#set ~row ~column:col_status "inactive";
253               model#set ~row ~column:col_id (-1)
254           ) added;
255
256           (* Now iterate over all active domains and update their state,
257            * CPU and memory.
258            *)
259           iter_rows model (
260             fun row ->
261               let domid = model#get ~row ~column:col_id in
262               if domid >= 0 then ( (* active *)
263                 try
264                   let dom = D.lookup_by_id conn domid in
265                   let info = D.get_info dom in
266                   let status = string_of_domain_state info.D.state in
267                   model#set ~row ~column:col_status status;
268                   let memory = sprintf "%Ld K" info.D.memory in
269                   model#set ~row ~column:col_mem memory;
270
271                   (* Get domhistory.  For a new domain it won't exist, so
272                    * create an empty one.
273                    *)
274                   let dh =
275                     let key = conn_id, domid in
276                     try Hashtbl.find domhistory key
277                     with Not_found ->
278                       let dh = new_domhistory () in
279                       Hashtbl.add domhistory key dh;
280                       dh in
281
282                   (* Measure current time and domain cpuTime as close
283                    * together as possible.
284                    *)
285                   let time_now = Unix.gettimeofday () in
286                   let cpu_now = info.D.cpu_time in
287
288                   let time_prev = dh.last_time in
289                   let cpu_prev =
290                     if dh.last_cpu_time > cpu_now then 0L (* Rebooted? *)
291                     else dh.last_cpu_time in
292
293                   dh.last_time <- time_now;
294                   dh.last_cpu_time <- cpu_now;
295
296                   let cpu_percent =
297                     if time_prev > 0. then (
298                       let cpu_now = Int64.to_float cpu_now in
299                       let cpu_prev = Int64.to_float cpu_prev in
300                       let cpu_used = cpu_now -. cpu_prev in
301                       let cpu_available = 1_000_000_000. *. float nr_cpus in
302                       let time_passed = time_now -. time_prev in
303
304                       let cpu_percent =
305                         100. *. (cpu_used /. cpu_available) /. time_passed in
306
307                       let cpu_percent =
308                         if cpu_percent < 0. then 0.
309                         else if cpu_percent > 100. then 100.
310                         else cpu_percent in
311
312                       let cpu_percent_str = sprintf "%.1f %%" cpu_percent in
313                       model#set ~row ~column:col_cpu cpu_percent_str;
314                       int_of_float cpu_percent
315                     ) else -1 in
316
317                   (* Store history. *)
318                   let datum = { hist_cpu = cpu_percent;
319                                 hist_mem = info.D.memory } in
320
321                   if dh.hist_posn >= hist_max then (
322                     (* rotate the array *)
323                     Array.blit dh.hist hist_rot dh.hist 0 (hist_max-hist_rot);
324                     dh.hist_posn <- dh.hist_posn - hist_rot;
325                     dh.hist.(dh.hist_posn) <- datum;
326                   ) else (
327                     let len = Array.length dh.hist in
328                     if dh.hist_posn < len then
329                       (* normal update *)
330                       dh.hist.(dh.hist_posn) <- datum
331                     else (
332                       (* extend the array *)
333                       let len' = min (max (2*len) 1) hist_max in
334                       let arr' = Array.make len' datum in
335                       Array.blit dh.hist 0 arr' 0 len;
336                       dh.hist <- arr';
337                     )
338                   );
339                   dh.hist_posn <- dh.hist_posn+1
340
341                 with
342                   Libvirt.Virterror _ -> () (* Ignore any transient error *)
343               )
344           ) (model#iter_children (Some parent));
345
346           (* Return new state. *)
347           conn_id, (active, inactive)
348         with
349         (* Libvirt errors here are not really fatal.  They can happen
350          * if the state changes at the moment we read it.  If it does
351          * happen, just return the old state, and next time we come
352          * around to this connection it'll be fixed.
353          *)
354         | Libvirt.Virterror err ->
355             prerr_endline (Libvirt.Virterror.to_string err);
356             conn_id, (old_active, old_inactive)
357         | Failure msg ->
358             prerr_endline msg;
359             conn_id, (old_active, old_inactive)
360     ) conns in
361
362   (* Return the updated state. *)
363   new_state
364
365 (* Make the treeview which displays the connections and domains. *)
366 let make_treeview ?packing () =
367   let cols = new GTree.column_list in
368   let col_name_id = cols#add Gobject.Data.string in
369   let col_domname = cols#add Gobject.Data.string in
370   let col_status = cols#add Gobject.Data.string in
371   let col_cpu = cols#add Gobject.Data.string in
372   let col_mem = cols#add Gobject.Data.string in
373   (* Hidden column containing the connection ID or domain ID.  For
374    * inactive domains, this contains -1 and col_domname is the name. *)
375   let col_id = cols#add Gobject.Data.int in
376   let model = GTree.tree_store cols in
377
378   (* Column sorting functions. *)
379   let make_sort_func_on column =
380     fun (model : GTree.model) row1 row2 ->
381       let col1 = model#get ~row:row1 ~column in
382       let col2 = model#get ~row:row2 ~column in
383       compare col1 col2
384   in
385   (*model#set_default_sort_func (make_sort_func_on col_domname);*)
386   model#set_sort_func 0 (make_sort_func_on col_name_id);
387   model#set_sort_func 1 (make_sort_func_on col_domname);
388   model#set_sort_column_id 1 `ASCENDING;
389
390   (* Make the GtkTreeView and attach column renderers to it. *)
391   let tree = GTree.view ~model ~reorderable:false ?packing () in
392
393   let append_visible_column title column sort =
394     let renderer = GTree.cell_renderer_text [], ["text", column] in
395     let view_col = GTree.view_column ~title ~renderer () in
396     ignore (tree#append_column view_col);
397     match sort with
398     | None -> ()
399     | Some (sort_indicator, sort_order, sort_column_id) ->
400         view_col#set_sort_indicator sort_indicator;
401         view_col#set_sort_order sort_order;
402         view_col#set_sort_column_id sort_column_id
403   in
404   append_visible_column "ID" col_name_id (Some (false, `ASCENDING, 0));
405   append_visible_column "Name" col_domname (Some (true, `ASCENDING, 1));
406   append_visible_column "Status" col_status None;
407   append_visible_column "CPU" col_cpu None;
408   append_visible_column "Memory" col_mem None;
409
410   let columns =
411     col_name_id, col_domname, col_status, col_cpu, col_mem, col_id in
412   let state = repopulate tree model columns [] in
413
414   (tree, model, columns, state)
415
416 (* Get historical data size. *)
417 let get_hist_size connid domid =
418   try
419     let dh = Hashtbl.find domhistory (connid, domid) in
420     dh.hist_posn
421   with
422     Not_found -> 0
423
424 (* Get historical data entries. *)
425 let _get_hist ?(latest=0) ?earliest ?(granularity=1)
426     extract fold zero connid domid =
427   try
428     let dh = Hashtbl.find domhistory (connid, domid) in
429     let earliest =
430       match earliest with
431       | None -> dh.hist_posn
432       | Some e -> min e dh.hist_posn in
433
434     let src = dh.hist in
435     let src_start = dh.hist_posn - earliest in assert (src_start >= 0);
436     let src_end = dh.hist_posn - latest in     assert (src_end <= dh.hist_posn);
437
438     (* Create a sufficiently large array to store the result. *)
439     let len = (earliest-latest) / granularity in
440     let r = Array.make len zero in
441
442     if granularity = 1 then (
443       for j = 0 to len-1 do
444         r.(j) <- extract src.(src_start+j)
445       done
446     ) else (
447       let i = ref src_start in
448       for j = 0 to len-1 do
449         let sub = Array.sub src !i (min (!i+granularity) src_end - !i) in
450         let sub = Array.map extract sub in
451         r.(j) <- fold sub;
452         i := !i + granularity
453       done
454     );
455     r
456   with
457     Not_found -> [| |]
458
459 let get_hist_cpu ?latest ?earliest ?granularity connid domid =
460   let zero = 0 in
461   let extract { hist_cpu = c } = c in
462   let fold a =
463     let len = Array.length a in
464     if len > 0 then Array.fold_left (+) zero a / len else -1 in
465   _get_hist ?latest ?earliest ?granularity extract fold zero connid domid
466
467 let get_hist_mem ?latest ?earliest ?granularity connid domid =
468   let zero = 0L in
469   let extract { hist_mem = m } = m in
470   let fold a =
471     let len = Array.length a in
472     if len > 0 then
473       Int64.div (Array.fold_left (Int64.add) zero a) (Int64.of_int len)
474     else
475       -1L in
476   _get_hist ?latest ?earliest ?granularity extract fold zero connid domid