7bd77159ee11656a49ef90a53f3b546c3f027efd
[libguestfs.git] / ocaml / t / guestfs_400_events.ml
1 (* libguestfs OCaml bindings
2  * Copyright (C) 2011 Red Hat Inc.
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17  *)
18
19 open Printf
20
21 let log g ev eh buf array =
22   let ev =
23     match ev with
24     | Guestfs.EVENT_CLOSE -> "close"
25     | Guestfs.EVENT_SUBPROCESS_QUIT -> "subprocess_quit"
26     | Guestfs.EVENT_LAUNCH_DONE -> "launch_done"
27     | Guestfs.EVENT_PROGRESS -> "progress"
28     | Guestfs.EVENT_APPLIANCE -> "appliance"
29     | Guestfs.EVENT_LIBRARY -> "library"
30     | Guestfs.EVENT_TRACE -> "trace" in
31
32   let eh : int = Obj.magic eh in
33
34   printf "ocaml event logged: event=%s eh=%d buf=%S array=[%s]\n"
35     ev eh buf
36     (String.concat ", " (List.map Int64.to_string (Array.to_list array)))
37
38 let close_invoked = ref 0
39
40 let close g ev eh buf array =
41   incr close_invoked;
42   log g ev eh buf array
43
44 let () =
45   let g = new Guestfs.guestfs () in
46
47   (* Grab log, trace and daemon messages into our own custom handler
48    * which prints the messages with a particular prefix.
49    *)
50   let events = [Guestfs.EVENT_APPLIANCE; Guestfs.EVENT_LIBRARY;
51                 Guestfs.EVENT_TRACE] in
52   ignore (g#set_event_callback log events);
53
54   (* Check that the close event is invoked. *)
55   ignore (g#set_event_callback close [Guestfs.EVENT_CLOSE]);
56
57   (* Now make sure we see some messages. *)
58   g#set_trace true;
59   g#set_verbose true;
60
61   (* Do some stuff. *)
62   g#add_drive_ro "/dev/null";
63   g#set_autosync true;
64
65   (* Close the handle -- should call the close callback. *)
66   assert (!close_invoked = 0);
67   g#close ();
68   assert (!close_invoked = 1);
69
70   (* Run full garbage collection. *)
71   Gc.compact ()