1guestfs-java(3)             Virtualization Support             guestfs-java(3)
2
3
4

NAME

6       guestfs-java - How to use libguestfs from Java
7

SYNOPSIS

9        import com.redhat.et.libguestfs.*;
10
11        GuestFS g = new GuestFS ();
12        g.add_drive ("disk.img",
13                     new HashMap<String,Object>() {
14                       {
15                           put ("readonly", Boolean.TRUE);
16                           put ("format", "raw");
17                       }
18                     });
19        g.launch ();
20

DESCRIPTION

22       This manual page documents how to call libguestfs from the Java
23       programming language.  This page just documents the differences from
24       the C API and gives some examples.  If you are not familiar with using
25       libguestfs, you also need to read guestfs(3).
26
27   CLOSING THE HANDLE
28       The handle is closed when it is reaped by the garbage collector.
29       Because libguestfs handles include a lot of state, it is also possible
30       to close (and hence free) them explicitly by calling the "close"
31       method.
32
33   EXCEPTIONS
34       Errors from libguestfs functions are mapped into the
35       "LibGuestFSException" exception.  This has a single parameter which is
36       the error message (a "String").
37
38       Calling any method on a closed handle raises the same exception.
39
40       If malloc(3) or some other allocation fails inside the bindings, the
41       "LibGuestFSOutOfMemory" exception is thrown.
42
43   EVENTS
44       The libguestfs event API is fully supported from Java.  Create a class
45       which implements the "EventCallback" interface, create an instance of
46       this class, and then call the "GuestFS#set_event_callback" method to
47       register this instance.  The "event" method of the class is called when
48       libguestfs generates an event.
49
50       For example, this will print all trace events:
51
52        GuestFS g = new GuestFS ();
53        g.set_trace (true);
54        g.set_event_callback (
55          new EventCallback () {
56            public void event (long event, int eh,
57                               String buffer, long[] array) {
58              System.out.println (GuestFS.eventToString (event) +
59                                  ": " + buffer);
60            }
61          },
62          GuestFS.EVENT_TRACE);
63        g.add_drive_ro ("disk.img");
64        // etc.
65
66       The output looks similar to this:
67
68        EVENT_TRACE: add_drive_ro "disk.img"
69        EVENT_TRACE: add_drive_ro = 0
70        // etc.
71
72   OPTIONAL ARGUMENTS
73       Some methods take an optional map of optional parameters.  An example
74       of this is "g.add_drive" which can be called in one of two ways:
75
76        g.add_drive ("disk.img");
77
78       or with optional arguments:
79
80        Map<String, Object> optargs =
81          new HashMap<String, Object>() {
82          {
83            put ("readonly", Boolean.TRUE);
84            put ("format", "raw");
85          }
86        };
87        g.add_drive ("disk.img", optargs);
88
89       For more information on this topic, see "CALLS WITH OPTIONAL ARGUMENTS"
90       in guestfs(3).
91
92       Optional handle parameters
93
94       When creating the handle you can also pass a map of optional
95       parameters:
96
97        Map<String, Object> optargs =
98          new HashMap<String, Object>() {
99          {
100            put ("close_on_exit", Boolean.FALSE);
101            put ("environment", Boolean.TRUE);
102          }
103        };
104        GuestFS g = new GuestFS (optargs);
105
106       For more information, see "guestfs_create_flags" in guestfs(3).
107

COMPILING AND RUNNING

109       Libguestfs for Java is a Java Native Interface (JNI) extension,
110       supplied in three parts:
111
112       libguestfs.jar
113       libguestfs-VERSION.jar
114           The pure Java JAR file which contains several classes, the primary
115           one being "com.redhat.et.libguestfs.GuestFS".  Upstream, the JAR
116           file contains a version number in the filename, but some Linux
117           distros may rename it without the version number.
118
119       libguestfs_jni.so
120           The JNI code (written in C).  This contains private native
121           functions that interface between Java code and the regular
122           libguestfs C library.  You should not call these directly.
123
124       libguestfs.so
125           The regular libguestfs C library.
126
127       To compile your Java program, you need to locate the JAR file and add
128       it to the class path.  For example:
129
130        export CLASSPATH=/usr/share/java/libguestfs.jar
131        javac MyProgram.java
132
133       To run your Java program, you also need to ensure that the JAR file is
134       on the class path, as well as the path of your program.  For example:
135
136        export CLASSPATH=.:/usr/share/java/libguestfs.jar
137        java MyProgram
138

EXAMPLE 1: CREATE A DISK IMAGE

140        // Example showing how to create a disk image.
141
142        import java.io.*;
143        import java.util.Map;
144        import java.util.HashMap;
145        import com.redhat.et.libguestfs.*;
146
147        public class CreateDisk
148        {
149            static String output = "disk.img";
150
151            public static void main (String[] argv)
152            {
153                try {
154                    GuestFS g = new GuestFS ();
155
156                    // Create a raw-format sparse disk image, 512 MB in size.
157                    RandomAccessFile f = new RandomAccessFile (output, "rw");
158                    f.setLength (512 * 1024 * 1024);
159                    f.close ();
160
161                    // Set the trace flag so that we can see each libguestfs call.
162                    g.set_trace (true);
163
164                    // Attach the disk image to libguestfs.
165                    @SuppressWarnings("serial") Map<String, Object> optargs =
166                        new HashMap<String, Object>() {
167                        {
168                            put ("format", "raw");
169                            put ("readonly", Boolean.FALSE);
170                        }
171                    };
172                    g.add_drive_opts (output, optargs);
173
174                    // Run the libguestfs back-end.
175                    g.launch ();
176
177                    // Get the list of devices.  Because we only added one drive
178                    // above, we expect that this list should contain a single
179                    // element.
180                    String[] devices = g.list_devices ();
181                    if (devices.length != 1)
182                        throw new Error ("expected a single device from list-devices");
183
184                    // Partition the disk as one single MBR partition.
185                    g.part_disk (devices[0], "mbr");
186
187                    // Get the list of partitions.  We expect a single element, which
188                    // is the partition we have just created.
189                    String[] partitions = g.list_partitions ();
190                    if (partitions.length != 1)
191                        throw new Error ("expected a single partition from list-partitions");
192
193                    // Create a filesystem on the partition.
194                    g.mkfs ("ext4", partitions[0]);
195
196                    // Now mount the filesystem so that we can add files.
197                    g.mount (partitions[0], "/");
198
199                    // Create some files and directories.
200                    g.touch ("/empty");
201                    String message = "Hello, world\n";
202                    g.write ("/hello", message.getBytes());
203                    g.mkdir ("/foo");
204
205                    // This one uploads the local file /etc/resolv.conf into
206                    // the disk image.
207                    g.upload ("/etc/resolv.conf", "/foo/resolv.conf");
208
209                    // Because we wrote to the disk and we want to detect write
210                    // errors, call g.shutdown.  You don't need to do this:
211                    // g.close will do it implicitly.
212                    g.shutdown ();
213
214                    // Note also that handles are automatically closed if they are
215                    // reaped by the garbage collector.  You only need to call close
216                    // if you want to close the handle right away.
217                    g.close ();
218                }
219                catch (Exception exn) {
220                    System.err.println (exn);
221                    System.exit (1);
222                }
223            }
224        }
225

EXAMPLE 2: INSPECT A VIRTUAL MACHINE DISK IMAGE

227        // Example showing how to inspect a virtual machine disk.
228
229        import java.util.ArrayList;
230        import java.util.Collections;
231        import java.util.Comparator;
232        import java.util.HashMap;
233        import java.util.List;
234        import java.util.Map;
235        import com.redhat.et.libguestfs.*;
236
237        public class InspectVM
238        {
239            static final Comparator<String> COMPARE_KEYS_LEN =
240                new Comparator<String>() {
241                public int compare (String k1, String k2) {
242                    return k1.length() - k2.length();
243                }
244            };
245
246            public static void main (String[] argv)
247            {
248                try {
249                    if (argv.length != 1)
250                        throw new Error ("usage: InspectVM disk.img");
251
252                    String disk = argv[0];
253
254                    GuestFS g = new GuestFS ();
255
256                    // Attach the disk image read-only to libguestfs.
257                    @SuppressWarnings("serial") Map<String, Object> optargs =
258                        new HashMap<String, Object>() {
259                        {
260                            //put ("format", "raw");
261                            put ("readonly", Boolean.TRUE);
262                        }
263                    };
264
265                    g.add_drive_opts (disk, optargs);
266
267                    // Run the libguestfs back-end.
268                    g.launch ();
269
270                    // Ask libguestfs to inspect for operating systems.
271                    String roots[] = g.inspect_os ();
272                    if (roots.length == 0)
273                        throw new Error ("inspect_vm: no operating systems found");
274
275                    for (String root : roots) {
276                        System.out.println ("Root device: " + root);
277
278                        // Print basic information about the operating system.
279                        System.out.println ("  Product name: " +
280                                            g.inspect_get_product_name (root));
281                        System.out.println ("  Version:      " +
282                                            g.inspect_get_major_version (root) +
283                                            "." +
284                                            g.inspect_get_minor_version (root));
285                        System.out.println ("  Type:         " +
286                                            g.inspect_get_type (root));
287                        System.out.println ("  Distro:       " +
288                                            g.inspect_get_distro (root));
289
290                        // Mount up the disks, like guestfish -i.
291                        //
292                        // Sort keys by length, shortest first, so that we end up
293                        // mounting the filesystems in the correct order.
294                        Map<String,String> mps = g.inspect_get_mountpoints (root);
295                        List<String> mps_keys = new ArrayList<String> (mps.keySet ());
296                        Collections.sort (mps_keys, COMPARE_KEYS_LEN);
297
298                        for (String mp : mps_keys) {
299                            String dev = mps.get (mp);
300                            try {
301                                g.mount_ro (dev, mp);
302                            }
303                            catch (Exception exn) {
304                                System.err.println (exn + " (ignored)");
305                            }
306                        }
307
308                        // If /etc/issue.net file exists, print up to 3 lines.
309                        String filename = "/etc/issue.net";
310                        if (g.is_file (filename)) {
311                            System.out.println ("--- " + filename + " ---");
312                            String[] lines = g.head_n (3, filename);
313                            for (String line : lines)
314                                System.out.println (line);
315                        }
316
317                        // Unmount everything.
318                        g.umount_all ();
319                    }
320                }
321                catch (Exception exn) {
322                    System.err.println (exn);
323                    System.exit (1);
324                }
325            }
326        }
327

SEE ALSO

329       guestfs(3), guestfs-examples(3), guestfs-erlang(3), guestfs-gobject(3),
330       guestfs-golang(3), guestfs-lua(3), guestfs-ocaml(3), guestfs-perl(3),
331       guestfs-python(3), guestfs-recipes(1), guestfs-ruby(3),
332       http://libguestfs.org/, http://caml.inria.fr/.
333

AUTHORS

335       Richard W.M. Jones ("rjones at redhat dot com")
336
338       Copyright (C) 2011-2012 Red Hat Inc.
339

LICENSE

341       This manual page contains examples which we hope you will use in your
342       programs.  The examples may be freely copied, modified and distributed
343       for any purpose without any restrictions.
344

BUGS

346       To get a list of bugs against libguestfs, use this link:
347       https://bugzilla.redhat.com/buglist.cgi?component=libguestfs&product=Virtualization+Tools
348
349       To report a new bug against libguestfs, use this link:
350       https://bugzilla.redhat.com/enter_bug.cgi?component=libguestfs&product=Virtualization+Tools
351
352       When reporting a bug, please supply:
353
354       ·   The version of libguestfs.
355
356       ·   Where you got libguestfs (eg. which Linux distro, compiled from
357           source, etc)
358
359       ·   Describe the bug accurately and give a way to reproduce it.
360
361       ·   Run libguestfs-test-tool(1) and paste the complete, unedited output
362           into the bug report.
363
364
365
366libguestfs-1.40.1                 2019-01-17                   guestfs-java(3)
Impressum