20fa608acf835ad30f140ff40fe6f69e83380035
[libguestfs.git] / ocaml / examples / viewer.ml
1 (* This is a virtual machine graphical viewer tool.
2  * Written by Richard W.M. Jones, Sept. 2009.
3  *
4  * It demonstrates some complex programming techniques: OCaml, Gtk+,
5  * threads, and use of both libguestfs and libvirt from threads.
6  *
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)
14  *   - ocaml-libguestfs
15  *
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.
18  *
19  * You will also need to configure libguestfs:
20  *   ./configure --enable-ocaml-viewer
21  *
22  * All programs in the ocaml/examples subdirectory, including this
23  * one, may be freely copied without any restrictions.
24  *)
25
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.
31  *
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].
35  *
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
39  * be shown.
40  *
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).
48  *
49  * [1] http://library.gnome.org/devel/gtk-faq/stable/x499.html
50  *)
51
52 open Printf
53 open ExtList
54
55 let (//) = Filename.concat
56
57 (* Short names for commonly used modules. *)
58 module C = Libvirt.Connect
59 module Cd = Condition
60 module D = Libvirt.Domain
61 module G = Guestfs
62 module M = Mutex
63 module Q = Queue
64
65 let verbose = ref false                (* Verbose mode. *)
66
67 let debug fs =
68   let f str = if !verbose then ( prerr_string str; prerr_newline () ) in
69   ksprintf f fs
70
71 (*----------------------------------------------------------------------*)
72 (* Slave thread.  The signature describes what operations the main
73  * thread can perform, and protects the locked internals of the
74  * slave thread.
75  *)
76 module Slave : sig
77   type 'a callback = 'a -> unit
78
79   type partinfo = {
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 *)
84   }
85
86   val no_callback : 'a callback
87     (** Use this as the callback if you don't want a callback. *)
88
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. *)
94
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. *)
98
99   val exit_thread : unit -> unit
100     (** [exit_thread ()] causes the slave thread to exit. *)
101
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. *)
106
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. *)
110
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
117         in the guest. *)
118
119   val slave_loop : unit -> unit
120     (** The slave thread's main loop, running in the slave thread. *)
121
122 end = struct
123   type partinfo = {
124     pt_name : string;
125     pt_size : int64;
126     pt_content : string;
127     pt_statvfs : G.statvfs option;
128   }
129
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.
134    *)
135   type command =
136     | Exit_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
141
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
148
149   let no_callback _ = ()
150
151   let failure_cb = ref (fun _ -> ())
152   let set_failure_callback cb = failure_cb := cb
153
154   let busy_cb = ref (fun _ -> ())
155   let set_busy_callback cb = busy_cb := cb
156
157   (* Execute a function, while holding a mutex.  If the function
158    * fails, ensure we release the mutex before rethrowing the
159    * exception.
160    *)
161   type ('a, 'b) choice = Either of 'a | Or of 'b
162   let with_lock m f =
163     M.lock m;
164     let r = try Either (f ()) with exn -> Or exn in
165     M.unlock m;
166     match r with
167     | Either r -> r
168     | Or exn -> raise exn
169
170   let q = Q.create ()                   (* queue of commands *)
171   let q_lock = M.create ()
172   let q_cond = Cd.create ()
173
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);
177     with_lock q_lock (
178       fun () ->
179         Q.push c q;
180         Cd.signal q_cond
181     )
182
183   let exit_thread () =
184     with_lock q_lock (fun () -> Q.clear q);
185     send_to_slave Exit_thread
186
187   let connect uri cb =
188     send_to_slave (Connect (uri, cb))
189
190   let get_domains cb =
191     send_to_slave (Get_domains cb)
192
193   let open_domain dom cb =
194     send_to_slave (Open_domain (dom, cb))
195
196   (* These are not protected by a mutex because we don't allow
197    * any references to these objects to escape from the slave
198    * thread.
199    *)
200   let conn = ref None                   (* libvirt connection *)
201   let dom = ref None                    (* libvirt domain *)
202   let g = ref None                      (* libguestfs handle *)
203
204   let quit = ref false
205
206   let rec slave_loop () =
207     debug "Slave.slave_loop: waiting for a command";
208     let c =
209       with_lock q_lock (
210         fun () ->
211           while Q.is_empty q do
212             Cd.wait q_cond q_lock
213           done;
214           Q.pop q
215       ) in
216
217     (try
218        debug "Slave.slave_loop: executing: %s" (string_of_command c);
219        !busy_cb `Busy;
220        exec_command c;
221        !busy_cb `Idle;
222        debug "Slave.slave_loop: command succeeded";
223      with exn ->
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.
227         *)
228        debug "Slave.slave_loop: command failed";
229
230        with_lock q_lock (fun () -> Q.clear q);
231        GtkThread.async !failure_cb exn
232     );
233
234     if !quit then Thread.exit ();
235     slave_loop ()
236
237   and exec_command = function
238     | Exit_thread ->
239         quit := true; (* quit first in case disconnect_all throws an exn *)
240         disconnect_all ()
241
242     | Connect (name, cb) ->
243         disconnect_all ();
244         conn := Some (C.connect_readonly ?name ());
245         cb name
246
247     | Get_domains cb ->
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.
252          *)
253         let doms = List.map D.get_name doms in
254         cb doms
255
256     | Open_domain (domname, cb) ->
257         let conn = Option.get !conn in
258         disconnect_dom ();
259         dom := Some (D.lookup_by_name conn domname);
260         let dom = Option.get !dom in
261
262         (* Get the devices. *)
263         let xml = D.get_xml_desc dom in
264         let devs = get_devices_from_xml xml in
265
266         (* Create the libguestfs handle and launch it. *)
267         let g' = G.create () in
268         List.iter (G.add_drive_ro g') devs;
269         G.launch g';
270         g := Some g';
271
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
279
280         let parts = List.map (
281           fun part ->
282             (* Find out the size of each partition. *)
283             let size = G.blockdev_getsize64 g' part in
284
285             (* Find out what's on each partition. *)
286             let content = G.file g' part in
287
288             (* Try to mount it. *)
289             let statvfs =
290               try
291                 G.mount_ro g' part "/";
292                 Some (G.statvfs g' "/")
293               with _ -> None in
294             G.umount_all g';
295
296             { pt_name = part; pt_size = size; pt_content = content;
297               pt_statvfs = statvfs }
298         ) parts in
299
300         (* Call the callback. *)
301         cb parts
302
303   (* Close all libvirt/libguestfs handles. *)
304   and disconnect_all () =
305     disconnect_dom ();
306     (match !conn with Some conn -> C.close conn | None -> ());
307     conn := None
308
309   (* Close dom and libguestfs handles. *)
310   and disconnect_dom () =
311     (match !g with Some g -> G.close g | None -> ());
312     g := None;
313     (match !dom with Some dom -> D.free dom | None -> ());
314     dom := None
315
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
320    *)
321   and get_devices_from_xml xml =
322     let xml = Xml.parse_string xml in
323     let devices =
324       match xml with
325       | Xml.Element ("domain", _, children) ->
326           let devices =
327             List.filter_map (
328               function
329               | Xml.Element ("devices", _, devices) -> Some devices
330               | _ -> None
331             ) children in
332           List.concat devices
333       | _ ->
334           failwith "get_xml_desc didn't return <domain/>" in
335     let rec source_dev_of = function
336       | [] -> None
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
341     in
342     let rec source_file_of = function
343       | [] -> None
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
348     in
349     let devs =
350       List.filter_map (
351         function
352         | Xml.Element ("disk", _, children) -> source_dev_of children
353         | _ -> None
354       ) devices in
355     let files =
356       List.filter_map (
357         function
358         | Xml.Element ("disk", _, children) -> source_file_of children
359         | _ -> None
360       ) devices in
361     devs @ files
362 end
363 (* End of slave thread code. *)
364 (*----------------------------------------------------------------------*)
365
366 (* Display state. *)
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;
378 }
379
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.
384  *)
385 let failure ds exn =
386   debug "failure callback: %s" (Printexc.to_string exn)
387
388 (* This is called in the main thread when the slave thread transitions
389  * to busy or idle.
390  *)
391 let busy ds state = ds.throbber_set state
392
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
398
399   (* Do the menus. *)
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
404
405   let factory = new GMenu.factory connect_menu ~accel_group in
406   let quit_item = factory#add_item "E_xit" ~key:GdkKeysyms._Q in
407
408   (* Quit. *)
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 ()); ()));
414
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 ());
418
419   (* List of VMs. *)
420   let vmcombo = GEdit.combo_box_text ~packing:hbox#pack () in
421   let vmlist_set names =
422     let combo, (model, column) = vmcombo in
423     model#clear ();
424     List.iter (
425       fun name ->
426         let row = model#append () in
427         model#set ~row ~column name
428     ) names
429   in
430
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*)
434   let throbber =
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
442   in
443
444   (* Drawing area. *)
445   let da = GMisc.drawing_area ~packing:(vbox#pack ~expand:true ~fill:true) () in
446   da#misc#realize ();
447   let draw = new GDraw.drawable da#misc#window in
448   window#set_geometry_hints ~min_size:(80,80) (da :> GObj.widget);
449
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
452
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");
458
459   (* Status bar at the bottom of the screen. *)
460   let set_statusbar =
461     let statusbar = GMisc.statusbar ~packing:vbox#pack () in
462     let context = statusbar#new_context ~name:"Standard" in
463     ignore (context#push window_title);
464     fun msg ->
465       context#pop ();
466       ignore (context#push msg)
467   in
468   let clear_statusbar () = set_statusbar "" in
469
470   (* Display the window and enter Gtk+ main loop. *)
471   window#show ();
472   window#add_accel_group accel_group;
473
474   (* display_state which is threaded through all the other callbacks,
475    * allowing callbacks to update the window.
476    *)
477   let ds =
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
483
484   (* Set up some callbacks which require access to the display_state. *)
485   ignore (
486     let combo, (model, column) = vmcombo in
487     combo#connect#changed
488       ~callback:(
489         fun () ->
490           match combo#active_iter with
491           | None -> ()
492           | Some row ->
493               let name = model#get ~row ~column in
494               ds.set_statusbar (sprintf "Opening %s ..." name);
495               Slave.open_domain name (opened_domain ds))
496   );
497
498   ignore (da#event#connect#expose ~callback:(repaint ds));
499
500   ds
501
502 (* Partition info for the current domain, if one is loaded. *)
503 let parts = ref None
504
505 (* This is called in the main thread when we've connected to libvirt. *)
506 let rec connected ds uri =
507   debug "connected callback";
508   let msg =
509     match uri with
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)
514
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);
518   ds.vmlist_set doms
519
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 ()
526
527 and repaint ds _ =
528   (match !parts with
529    | None -> ()
530    | Some parts ->
531        real_repaint ds parts
532   );
533   false
534
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 ();
540
541   let sum = List.fold_left Int64.add 0L in
542   let totsize = sum (List.map (fun { Slave.pt_size = size } -> size) parts) in
543
544   let scale = (float height -. 16.) /. Int64.to_float totsize in
545
546   (* Calculate the height in pixels of each partition, if we were to
547    * display it at a true relative size.
548    *)
549   let parts =
550     List.map (
551       fun ({ Slave.pt_size = size } as part) ->
552         let h = scale *. Int64.to_float size in
553         (h, part)
554     ) parts in
555
556   (*
557   if !verbose then (
558     eprintf "real_repaint: before borrowing:\n";
559     List.iter (
560       fun (h, part) ->
561         eprintf "%s\t%g pix\n" part.Slave.pt_name h
562     ) parts
563   );
564   *)
565
566   (* Now adjust the heights of small partitions so they "borrow" some
567    * height from the larger partitions.
568    *)
569   let min_h = 32. in
570   let rec borrow needed = function
571     | [] -> 0., []
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
580         ) else (
581           let spare', parts = borrow needed parts in
582           spare', (h, part) :: parts
583         )
584   in
585   let rec loop = function
586     | parts, [] -> List.rev parts
587     | prev, ((h, part) :: parts) ->
588         let needed = min_h -. h in
589         let h, prev, parts =
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). *)
594             let spare, prev =
595               if spare = 0. then borrow needed prev else spare, prev in
596             h +. spare, prev, parts
597           ) else (
598             h, prev, parts
599           ) in
600         loop (((h, part) :: prev), parts)
601   in
602   let parts = loop ([], parts) in
603
604   (*
605   if !verbose then (
606     eprintf "real_repaint: after borrowing:\n";
607     List.iter (
608       fun (h, part) ->
609         eprintf "%s\t%g pix\n" part.Slave.pt_name h
610     ) parts
611   );
612   *)
613
614   (* Calculate the proportion space used in each partition. *)
615   let parts = List.map (
616     fun (h, part) ->
617       let used =
618         match part.Slave.pt_statvfs with
619         | None -> 0.
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
623             num /. denom in
624       (h, used, part)
625   ) parts in
626
627   (* Draw it. *)
628   ignore (
629     List.fold_left (
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
634
635         ds.draw#set_foreground `WHITE;
636         ds.draw#rectangle ~x:8 ~y:yb ~width:(width-16) ~height:(yt-yb)
637           ~filled:true ();
638
639         let col =
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"
643           else `NAME "red" in
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 ();
647
648         ds.draw#set_foreground `BLACK;
649         ds.draw#rectangle ~x:8 ~y:yb ~width:(width-16) ~height:(yt-yb) ();
650
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;
656
657         let { Pango.height = txtheight; Pango.width = txtwidth } =
658           Pango.Layout.get_pixel_extent txt in
659
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;
663         let fore = `BLACK in
664         ds.draw#put_layout ~x:12 ~y:(yb+4+txtheight) ~fore txt;
665
666         (* Small text right - size. *)
667         let 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;
677
678         (y +. h)
679     ) 0. parts
680   )
681
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)
688   else
689     sprintf "%Ld GiB" (Int64.div bytes 1_073_741_824L)
690
691 let default_uri = ref ""
692
693 let argspec = Arg.align [
694   "-verbose", Arg.Set verbose, "Verbose mode";
695   "-connect", Arg.Set_string default_uri, "Connect to libvirt URI";
696 ]
697
698 let anon_fun _ =
699   failwith (sprintf "%s: unknown command line argument"
700               (Filename.basename Sys.executable_name))
701
702 let usage_msg =
703   sprintf "\
704
705 %s: graphical virtual machine disk usage viewer
706
707 Options:"
708     (Filename.basename Sys.executable_name)
709
710 let main () =
711   Arg.parse argspec anon_fun usage_msg;
712
713   (* Start up the slave thread. *)
714   let slave = Thread.create Slave.slave_loop () in
715
716   (* Set up the display. *)
717   let ds = main_window opened_domain repaint in
718
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);
723
724   (* Run the main thread. When this returns, the application has been closed. *)
725   GtkThread.main ();
726
727   (* Tell the slave thread to exit and wait for it to do so. *)
728   Slave.exit_thread ();
729   Thread.join slave
730
731 let () =
732   main ()