1 (* This is a virtual machine graphical viewer tool.
2 * Written by Richard W.M. Jones, Sept. 2009.
4 * It demonstrates some complex programming techniques: OCaml, Gtk+,
5 * threads, and use of both libguestfs and libvirt from threads.
7 * You will need the following installed in order to compile it:
8 * - ocaml (http://caml.inria.fr/)
9 * - ocamlfind (http://projects.camlcity.org/projects/findlib.html/)
10 * - extlib (http://code.google.com/p/ocaml-extlib/)
11 * - lablgtk2 (http://wwwfun.kurims.kyoto-u.ac.jp/soft/lsl/lablgtk.html
12 * - xml-light (http://tech.motion-twin.com/xmllight.html)
13 * - ocaml-libvirt (http://libvirt.org/ocaml)
16 * Note that most/all of these are available as packages via Fedora,
17 * Debian, Ubuntu or GODI. You won't need to compile them from source.
19 * You will also need to configure libguestfs:
20 * ./configure --enable-ocaml-viewer
22 * All programs in the ocaml/examples subdirectory, including this
23 * one, may be freely copied without any restrictions.
26 (* Architecturally, there is one main thread which does all the Gtk
27 * calls, and one slave thread which executes all libguestfs and
28 * libvirt calls. The main thread sends commands to the slave thread,
29 * which are delivered in a queue and acted on in sequence. Responses
30 * are delivered back to the main thread as commands finish.
32 * The commands are just OCaml objects (type: Slave.command). The
33 * queue of commands is an OCaml Queue. The responses are sent by adding
34 * idle events to the glib main loop[1].
36 * If a command fails, it causes the input queue to be cleared. In
37 * this case, a failure response is sent to the main loop which
38 * causes the display to be reset and possibly an error message to
41 * The global variables [conn], [dom] and [g] are the libvirt
42 * connection, current domain, and libguestfs handle respectively.
43 * Because these can be accessed by both threads, they are
44 * protected from the main thread by access methods which
45 * (a) prevent the main thread from using them unlocked, and
46 * (b) prevent the main thread from doing arbitrary / long-running
47 * operations on them (the main thread must send a command instead).
49 * [1] http://library.gnome.org/devel/gtk-faq/stable/x499.html
55 let (//) = Filename.concat
57 (* Short names for commonly used modules. *)
58 module C = Libvirt.Connect
60 module D = Libvirt.Domain
65 let verbose = ref false (* Verbose mode. *)
68 let f str = if !verbose then ( prerr_string str; prerr_newline () ) in
71 (*----------------------------------------------------------------------*)
72 (* Slave thread. The signature describes what operations the main
73 * thread can perform, and protects the locked internals of the
77 type 'a callback = 'a -> unit
80 pt_name : string; (** device / LV name *)
81 pt_size : int64; (** in bytes *)
82 pt_content : string; (** the output of the 'file' command *)
83 pt_statvfs : G.statvfs option; (** None if not mountable *)
86 val no_callback : 'a callback
87 (** Use this as the callback if you don't want a callback. *)
89 val set_failure_callback : exn callback -> unit
90 (** Set the function that is called in the main thread whenever
91 there is a command failure in the slave. The command queue
92 is cleared before this is sent. [exn] is the exception
93 associated with the failure. *)
95 val set_busy_callback : [`Busy|`Idle] callback -> unit
96 (** Set the function that is called in the main thread whenever
97 the slave thread goes busy or idle. *)
99 val exit_thread : unit -> unit
100 (** [exit_thread ()] causes the slave thread to exit. *)
102 val connect : string option -> string option callback -> unit
103 (** [connect uri cb] connects to libvirt [uri], and calls [cb]
104 if it completes successfully. Any previous connection is
105 automatically cleaned up and disconnected. *)
107 val get_domains : string list callback -> unit
108 (** [get_domains cb] gets the list of active domains from libvirt,
109 and calls [cb domains] with the names of those domains. *)
111 val open_domain : string -> partinfo list callback -> unit
112 (** [open_domain dom cb] sets the domain [dom] as the current
113 domain, and launches a libguestfs handle for it. Any previously
114 current domain and libguestfs handle is closed. Once the
115 libguestfs handle is opened (which usually takes some time),
116 callback [cb] is called with the list of partitions found
119 val slave_loop : unit -> unit
120 (** The slave thread's main loop, running in the slave thread. *)
127 pt_statvfs : G.statvfs option;
130 (* Commands sent by the main thread to the slave thread. When
131 * [cmd] is successfully completed, [callback] will be delivered
132 * (in the main thread). If [cmd] fails, then the global error
133 * callback will be delivered in the main thread.
137 | Connect of string option * string option callback
138 | Get_domains of string list callback
139 | Open_domain of string * partinfo list callback
140 and 'a callback = 'a -> unit
142 let string_of_command = function
143 | Exit_thread -> "Exit_thread"
144 | Connect (None, _) -> "Connect [no uri]"
145 | Connect (Some uri, _) -> "Connect " ^ uri
146 | Get_domains _ -> "Get_domains"
147 | Open_domain (name, _) -> "Open_domain " ^ name
149 let no_callback _ = ()
151 let failure_cb = ref (fun _ -> ())
152 let set_failure_callback cb = failure_cb := cb
154 let busy_cb = ref (fun _ -> ())
155 let set_busy_callback cb = busy_cb := cb
157 (* Execute a function, while holding a mutex. If the function
158 * fails, ensure we release the mutex before rethrowing the
161 type ('a, 'b) choice = Either of 'a | Or of 'b
164 let r = try Either (f ()) with exn -> Or exn in
168 | Or exn -> raise exn
170 let q = Q.create () (* queue of commands *)
171 let q_lock = M.create ()
172 let q_cond = Cd.create ()
174 (* Send a command message to the slave thread. *)
175 let send_to_slave c =
176 debug "sending to slave: %s" (string_of_command c);
184 with_lock q_lock (fun () -> Q.clear q);
185 send_to_slave Exit_thread
188 send_to_slave (Connect (uri, cb))
191 send_to_slave (Get_domains cb)
193 let open_domain dom cb =
194 send_to_slave (Open_domain (dom, cb))
196 (* These are not protected by a mutex because we don't allow
197 * any references to these objects to escape from the slave
200 let conn = ref None (* libvirt connection *)
201 let dom = ref None (* libvirt domain *)
202 let g = ref None (* libguestfs handle *)
206 let rec slave_loop () =
207 debug "Slave.slave_loop: waiting for a command";
211 while Q.is_empty q do
212 Cd.wait q_cond q_lock
218 debug "Slave.slave_loop: executing: %s" (string_of_command c);
222 debug "Slave.slave_loop: command succeeded";
224 (* If an exception is thrown, it means the command failed. In
225 * this case we clear the command queue and deliver the failure
226 * callback in the main thread.
228 debug "Slave.slave_loop: command failed";
230 with_lock q_lock (fun () -> Q.clear q);
231 GtkThread.async !failure_cb exn
234 if !quit then Thread.exit ();
237 and exec_command = function
239 quit := true; (* quit first in case disconnect_all throws an exn *)
242 | Connect (name, cb) ->
244 conn := Some (C.connect_readonly ?name ());
248 let conn = Option.get !conn in
249 let doms = D.get_domains conn [D.ListAll] in
250 (* Only return the names, so that the libvirt objects
251 * aren't leaked outside the slave thread.
253 let doms = List.map D.get_name doms in
256 | Open_domain (domname, cb) ->
257 let conn = Option.get !conn in
259 dom := Some (D.lookup_by_name conn domname);
260 let dom = Option.get !dom in
262 (* Get the devices. *)
263 let xml = D.get_xml_desc dom in
264 let devs = get_devices_from_xml xml in
266 (* Create the libguestfs handle and launch it. *)
267 let g' = G.create () in
268 List.iter (G.add_drive_ro g') devs;
272 (* Get the list of partitions. *)
273 let parts = Array.to_list (G.list_partitions g') in
274 (* Remove any which are PVs. *)
275 let pvs = Array.to_list (G.pvs g') in
276 let parts = List.filter (fun part -> not (List.mem part pvs)) parts in
277 let lvs = Array.to_list (G.lvs g') in
278 let parts = parts @ lvs in
280 let parts = List.map (
282 (* Find out the size of each partition. *)
283 let size = G.blockdev_getsize64 g' part in
285 (* Find out what's on each partition. *)
286 let content = G.file g' part in
288 (* Try to mount it. *)
291 G.mount_ro g' part "/";
292 Some (G.statvfs g' "/")
296 { pt_name = part; pt_size = size; pt_content = content;
297 pt_statvfs = statvfs }
300 (* Call the callback. *)
303 (* Close all libvirt/libguestfs handles. *)
304 and disconnect_all () =
306 (match !conn with Some conn -> C.close conn | None -> ());
309 (* Close dom and libguestfs handles. *)
310 and disconnect_dom () =
311 (match !g with Some g -> G.close g | None -> ());
313 (match !dom with Some dom -> D.free dom | None -> ());
316 (* This would be much simpler if OCaml had either a decent XPath
317 * implementation, or if ocamlduce was stable enough that we
318 * could rely on it being available. So this is *not* an example
319 * of either good OCaml or good programming. XXX
321 and get_devices_from_xml xml =
322 let xml = Xml.parse_string xml in
325 | Xml.Element ("domain", _, children) ->
329 | Xml.Element ("devices", _, devices) -> Some devices
334 failwith "get_xml_desc didn't return <domain/>" in
335 let rec source_dev_of = function
337 | Xml.Element ("source", attrs, _) :: rest ->
338 (try Some (List.assoc "dev" attrs)
339 with Not_found -> source_dev_of rest)
340 | _ :: rest -> source_dev_of rest
342 let rec source_file_of = function
344 | Xml.Element ("source", attrs, _) :: rest ->
345 (try Some (List.assoc "file" attrs)
346 with Not_found -> source_file_of rest)
347 | _ :: rest -> source_file_of rest
352 | Xml.Element ("disk", _, children) -> source_dev_of children
358 | Xml.Element ("disk", _, children) -> source_file_of children
363 (* End of slave thread code. *)
364 (*----------------------------------------------------------------------*)
367 type display_state = {
368 window : GWindow.window;
369 vmlist_set : string list -> unit;
370 throbber_set : [`Busy|`Idle] -> unit;
371 da : GMisc.drawing_area;
372 draw : GDraw.drawable;
373 drawing_area_repaint : unit -> unit;
374 set_statusbar : string -> unit;
375 clear_statusbar : unit -> unit;
376 pango_large_context : GPango.context_rw;
377 pango_small_context : GPango.context_rw;
380 (* This is called in the main thread whenever a command fails in the
381 * slave thread. The command queue has been cleared before this is
382 * called, so our job here is to reset the main window, and if
383 * necessary to turn the exception into an error message.
386 debug "failure callback: %s" (Printexc.to_string exn)
388 (* This is called in the main thread when the slave thread transitions
391 let busy ds state = ds.throbber_set state
393 (* Main window and callbacks from menu etc. *)
394 let main_window opened_domain repaint =
395 let window_title = "Virtual machine graphical viewer" in
396 let window = GWindow.window ~width:800 ~height:600 ~title:window_title () in
397 let vbox = GPack.vbox ~packing:window#add () in
400 let menubar = GMenu.menu_bar ~packing:vbox#pack () in
401 let factory = new GMenu.factory menubar in
402 let accel_group = factory#accel_group in
403 let connect_menu = factory#add_submenu "_Connect" in
405 let factory = new GMenu.factory connect_menu ~accel_group in
406 let quit_item = factory#add_item "E_xit" ~key:GdkKeysyms._Q in
409 let quit _ = GMain.quit (); false in
410 ignore (window#connect#destroy ~callback:GMain.quit);
411 ignore (window#event#connect#delete ~callback:quit);
412 ignore (quit_item#connect#activate
413 ~callback:(fun () -> ignore (quit ()); ()));
415 (* Top status area. *)
416 let hbox = GPack.hbox ~border_width:4 ~packing:vbox#pack () in
417 ignore (GMisc.label ~text:"Guest: " ~packing:hbox#pack ());
420 let vmcombo = GEdit.combo_box_text ~packing:hbox#pack () in
421 let vmlist_set names =
422 let combo, (model, column) = vmcombo in
426 let row = model#append () in
427 model#set ~row ~column name
431 (* Throbber, http://faq.pygtk.org/index.py?req=show&file=faq23.037.htp *)
432 let static = Throbber.static () in
433 (*let animation = Throbber.animation () in*)
435 GMisc.image ~pixbuf:static ~packing:(hbox#pack ~from:`END) () in
436 let throbber_set = function
437 | `Busy -> (*throbber#set_pixbuf animation*)
438 (* Workaround because no binding for GdkPixbufAnimation: *)
439 let file = Filename.dirname Sys.argv.(0) // "Throbber.gif" in
440 throbber#set_file file
441 | `Idle -> throbber#set_pixbuf static
445 let da = GMisc.drawing_area ~packing:(vbox#pack ~expand:true ~fill:true) () in
447 let draw = new GDraw.drawable da#misc#window in
448 window#set_geometry_hints ~min_size:(80,80) (da :> GObj.widget);
450 (* Calling this can be used to force a redraw of the drawing area. *)
451 let drawing_area_repaint () = GtkBase.Widget.queue_draw da#as_widget in
453 (* Pango contexts used to draw large and small text. *)
454 let pango_large_context = da#misc#create_pango_context in
455 pango_large_context#set_font_description (Pango.Font.from_string "Sans 12");
456 let pango_small_context = da#misc#create_pango_context in
457 pango_small_context#set_font_description (Pango.Font.from_string "Sans 8");
459 (* Status bar at the bottom of the screen. *)
461 let statusbar = GMisc.statusbar ~packing:vbox#pack () in
462 let context = statusbar#new_context ~name:"Standard" in
463 ignore (context#push window_title);
466 ignore (context#push msg)
468 let clear_statusbar () = set_statusbar "" in
470 (* Display the window and enter Gtk+ main loop. *)
472 window#add_accel_group accel_group;
474 (* display_state which is threaded through all the other callbacks,
475 * allowing callbacks to update the window.
478 { window = window; vmlist_set = vmlist_set; throbber_set = throbber_set;
479 da = da; draw = draw; drawing_area_repaint = drawing_area_repaint;
480 set_statusbar = set_statusbar; clear_statusbar = clear_statusbar;
481 pango_large_context = pango_large_context;
482 pango_small_context = pango_small_context; } in
484 (* Set up some callbacks which require access to the display_state. *)
486 let combo, (model, column) = vmcombo in
487 combo#connect#changed
490 match combo#active_iter with
493 let name = model#get ~row ~column in
494 ds.set_statusbar (sprintf "Opening %s ..." name);
495 Slave.open_domain name (opened_domain ds))
498 ignore (da#event#connect#expose ~callback:(repaint ds));
502 (* Partition info for the current domain, if one is loaded. *)
505 (* This is called in the main thread when we've connected to libvirt. *)
506 let rec connected ds uri =
507 debug "connected callback";
510 | None -> "Connected to libvirt"
511 | Some uri -> sprintf "Connected to %s" uri in
512 ds.set_statusbar msg;
513 Slave.get_domains (got_domains ds)
515 (* This is called in the main thread when we've got the list of domains. *)
516 and got_domains ds doms =
517 debug "got_domains callback: (%s)" (String.concat " " doms);
520 (* This is called when we have opened a domain. *)
521 and opened_domain ds parts' =
522 debug "opened_domain callback";
523 ds.clear_statusbar ();
524 parts := Some parts';
525 ds.drawing_area_repaint ()
531 real_repaint ds parts
535 and real_repaint ds parts =
536 let width, height = ds.draw#size in
537 ds.draw#set_background `WHITE;
538 ds.draw#set_foreground `WHITE;
539 ds.draw#rectangle ~x:0 ~y:0 ~width ~height ~filled:true ();
541 let sum = List.fold_left Int64.add 0L in
542 let totsize = sum (List.map (fun { Slave.pt_size = size } -> size) parts) in
544 let scale = (float height -. 16.) /. Int64.to_float totsize in
546 (* Calculate the height in pixels of each partition, if we were to
547 * display it at a true relative size.
551 fun ({ Slave.pt_size = size } as part) ->
552 let h = scale *. Int64.to_float size in
558 eprintf "real_repaint: before borrowing:\n";
561 eprintf "%s\t%g pix\n" part.Slave.pt_name h
566 (* Now adjust the heights of small partitions so they "borrow" some
567 * height from the larger partitions.
570 let rec borrow needed = function
572 | (h, part) :: parts ->
573 let spare = h -. min_h in
574 if spare >= needed then (
575 needed, (h -. needed, part) :: parts
576 ) else if spare > 0. then (
577 let needed = needed -. spare in
578 let spare', parts = borrow needed parts in
579 spare +. spare', (h -. spare, part) :: parts
581 let spare', parts = borrow needed parts in
582 spare', (h, part) :: parts
585 let rec loop = function
586 | parts, [] -> List.rev parts
587 | prev, ((h, part) :: parts) ->
588 let needed = min_h -. h in
590 if needed > 0. then (
591 (* Find some spare height in a succeeding partition(s). *)
592 let spare, parts = borrow needed parts in
593 (* Or if not, in a preceeding partition(s). *)
595 if spare = 0. then borrow needed prev else spare, prev in
596 h +. spare, prev, parts
600 loop (((h, part) :: prev), parts)
602 let parts = loop ([], parts) in
606 eprintf "real_repaint: after borrowing:\n";
609 eprintf "%s\t%g pix\n" part.Slave.pt_name h
614 (* Calculate the proportion space used in each partition. *)
615 let parts = List.map (
618 match part.Slave.pt_statvfs with
620 | Some { G.bavail = bavail; blocks = blocks } ->
621 let num = Int64.to_float (Int64.sub blocks bavail) in
622 let denom = Int64.to_float blocks in
630 fun y (h, used, part) ->
631 (* This partition occupies pixels 8+y .. 8+y+h-1 *)
632 let yb = 8 + int_of_float y
633 and yt = 8 + int_of_float (y +. h) in
635 ds.draw#set_foreground `WHITE;
636 ds.draw#rectangle ~x:8 ~y:yb ~width:(width-16) ~height:(yt-yb)
640 if used < 0.6 then `NAME "grey"
641 else if used < 0.8 then `NAME "pink"
642 else if used < 0.9 then `NAME "hot pink"
644 ds.draw#set_foreground col;
645 let w = int_of_float (used *. (float width -. 16.)) in
646 ds.draw#rectangle ~x:8 ~y:yb ~width:w ~height:(yt-yb) ~filled:true ();
648 ds.draw#set_foreground `BLACK;
649 ds.draw#rectangle ~x:8 ~y:yb ~width:(width-16) ~height:(yt-yb) ();
651 (* Large text - the device name. *)
652 let txt = ds.pango_large_context#create_layout in
653 Pango.Layout.set_text txt part.Slave.pt_name;
654 let fore = `NAME "dark slate grey" in
655 ds.draw#put_layout ~x:12 ~y:(yb+4) ~fore txt;
657 let { Pango.height = txtheight; Pango.width = txtwidth } =
658 Pango.Layout.get_pixel_extent txt in
660 (* Small text below - the content. *)
661 let txt = ds.pango_small_context#create_layout in
662 Pango.Layout.set_text txt part.Slave.pt_content;
664 ds.draw#put_layout ~x:12 ~y:(yb+4+txtheight) ~fore txt;
666 (* Small text right - size. *)
668 match part.Slave.pt_statvfs with
669 | None -> printable_size part.Slave.pt_size
670 | Some { G.blocks = blocks; bsize = bsize } ->
671 let bytes = Int64.mul blocks bsize in
672 let pc = 100. *. used in
673 sprintf "%s (%.1f%% used)" (printable_size bytes) pc in
674 let txt = ds.pango_small_context#create_layout in
675 Pango.Layout.set_text txt size;
676 ds.draw#put_layout ~x:(16+txtwidth) ~y:(yb+4) ~fore txt;
682 and printable_size bytes =
683 if bytes < 16_384L then sprintf "%Ld bytes" bytes
684 else if bytes < 16_777_216L then
685 sprintf "%Ld KiB" (Int64.div bytes 1024L)
686 else if bytes < 17_179_869_184L then
687 sprintf "%Ld MiB" (Int64.div bytes 1_048_576L)
689 sprintf "%Ld GiB" (Int64.div bytes 1_073_741_824L)
691 let default_uri = ref ""
693 let argspec = Arg.align [
694 "-verbose", Arg.Set verbose, "Verbose mode";
695 "-connect", Arg.Set_string default_uri, "Connect to libvirt URI";
699 failwith (sprintf "%s: unknown command line argument"
700 (Filename.basename Sys.executable_name))
705 %s: graphical virtual machine disk usage viewer
708 (Filename.basename Sys.executable_name)
711 Arg.parse argspec anon_fun usage_msg;
713 (* Start up the slave thread. *)
714 let slave = Thread.create Slave.slave_loop () in
716 (* Set up the display. *)
717 let ds = main_window opened_domain repaint in
719 Slave.set_failure_callback (failure ds);
720 Slave.set_busy_callback (busy ds);
721 let uri = match !default_uri with "" -> None | s -> Some s in
722 Slave.connect uri (connected ds);
724 (* Run the main thread. When this returns, the application has been closed. *)
727 (* Tell the slave thread to exit and wait for it to do so. *)
728 Slave.exit_thread ();