Documentation: Added a section on libguestfs gotchas.
[libguestfs.git] / src / guestfs.pod
1 =encoding utf8
2
3 =head1 NAME
4
5 guestfs - Library for accessing and modifying virtual machine images
6
7 =head1 SYNOPSIS
8
9  #include <guestfs.h>
10  
11  guestfs_h *handle = guestfs_create ();
12  guestfs_add_drive (handle, "guest.img");
13  guestfs_launch (handle);
14  guestfs_mount (handle, "/dev/sda1", "/");
15  guestfs_touch (handle, "/hello");
16  guestfs_sync (handle);
17  guestfs_close (handle);
18
19 =head1 DESCRIPTION
20
21 Libguestfs is a library for accessing and modifying guest disk images.
22 Amongst the things this is good for: making batch configuration
23 changes to guests, getting disk used/free statistics (see also:
24 virt-df), migrating between virtualization systems (see also:
25 virt-p2v), performing partial backups, performing partial guest
26 clones, cloning guests and changing registry/UUID/hostname info, and
27 much else besides.
28
29 Libguestfs uses Linux kernel and qemu code, and can access any type of
30 guest filesystem that Linux and qemu can, including but not limited
31 to: ext2/3/4, btrfs, FAT and NTFS, LVM, many different disk partition
32 schemes, qcow, qcow2, vmdk.
33
34 Libguestfs provides ways to enumerate guest storage (eg. partitions,
35 LVs, what filesystem is in each LV, etc.).  It can also run commands
36 in the context of the guest.  Also you can access filesystems over FTP.
37
38 Libguestfs is a library that can be linked with C and C++ management
39 programs (or management programs written in OCaml, Perl, Python, Ruby,
40 Java, Haskell or C#).  You can also use it from shell scripts or the
41 command line.
42
43 You don't need to be root to use libguestfs, although obviously you do
44 need enough permissions to access the disk images.
45
46 Libguestfs is a large API because it can do many things.  For a gentle
47 introduction, please read the L</API OVERVIEW> section next.
48
49 =head1 API OVERVIEW
50
51 This section provides a gentler overview of the libguestfs API.  We
52 also try to group API calls together, where that may not be obvious
53 from reading about the individual calls below.
54
55 =head2 HANDLES
56
57 Before you can use libguestfs calls, you have to create a handle.
58 Then you must add at least one disk image to the handle, followed by
59 launching the handle, then performing whatever operations you want,
60 and finally closing the handle.  So the general structure of all
61 libguestfs-using programs looks like this:
62
63  guestfs_h *handle = guestfs_create ();
64  
65  /* Call guestfs_add_drive additional times if there are
66   * multiple disk images.
67   */
68  guestfs_add_drive (handle, "guest.img");
69  
70  /* Most manipulation calls won't work until you've launched
71   * the handle.  You have to do this _after_ adding drives
72   * and _before_ other commands.
73   */
74  guestfs_launch (handle);
75  
76  /* Now you can examine what partitions, LVs etc are available.
77   */
78  char **partitions = guestfs_list_partitions (handle);
79  char **logvols = guestfs_lvs (handle);
80  
81  /* To access a filesystem in the image, you must mount it.
82   */
83  guestfs_mount (handle, "/dev/sda1", "/");
84  
85  /* Now you can perform filesystem actions on the guest
86   * disk image.
87   */
88  guestfs_touch (handle, "/hello");
89  
90  /* You only need to call guestfs_sync if you have made
91   * changes to the guest image.
92   */
93  guestfs_sync (handle);
94  
95  /* Close the handle. */
96  guestfs_close (handle);
97
98 The code above doesn't include any error checking.  In real code you
99 should check return values carefully for errors.  In general all
100 functions that return integers return C<-1> on error, and all
101 functions that return pointers return C<NULL> on error.  See section
102 L</ERROR HANDLING> below for how to handle errors, and consult the
103 documentation for each function call below to see precisely how they
104 return error indications.
105
106 =head2 DISK IMAGES
107
108 The image filename (C<"guest.img"> in the example above) could be a
109 disk image from a virtual machine, a L<dd(1)> copy of a physical hard
110 disk, an actual block device, or simply an empty file of zeroes that
111 you have created through L<posix_fallocate(3)>.  Libguestfs lets you
112 do useful things to all of these.
113
114 You can add a disk read-only using C<guestfs_add_drive_ro>, in which
115 case libguestfs won't modify the file.
116
117 Be extremely cautious if the disk image is in use, eg. if it is being
118 used by a virtual machine.  Adding it read-write will almost certainly
119 cause disk corruption, but adding it read-only is safe.
120
121 You must add at least one disk image, and you may add multiple disk
122 images.  In the API, the disk images are usually referred to as
123 C</dev/sda> (for the first one you added), C</dev/sdb> (for the second
124 one you added), etc.
125
126 Once C<guestfs_launch> has been called you cannot add any more images.
127 You can call C<guestfs_list_devices> to get a list of the device
128 names, in the order that you added them.  See also L</BLOCK DEVICE
129 NAMING> below.
130
131 =head2 MOUNTING
132
133 Before you can read or write files, create directories and so on in a
134 disk image that contains filesystems, you have to mount those
135 filesystems using C<guestfs_mount>.  If you already know that a disk
136 image contains (for example) one partition with a filesystem on that
137 partition, then you can mount it directly:
138
139  guestfs_mount (handle, "/dev/sda1", "/");
140
141 where C</dev/sda1> means literally the first partition (C<1>) of the
142 first disk image that we added (C</dev/sda>).  If the disk contains
143 Linux LVM2 logical volumes you could refer to those instead (eg. C</dev/VG/LV>).
144
145 If you are given a disk image and you don't know what it contains then
146 you have to find out.  Libguestfs can do that too: use
147 C<guestfs_list_partitions> and C<guestfs_lvs> to list possible
148 partitions and LVs, and either try mounting each to see what is
149 mountable, or else examine them with C<guestfs_file>.  But you might
150 find it easier to look at higher level programs built on top of
151 libguestfs, in particular L<virt-inspector(1)>.
152
153 To mount a disk image read-only, use C<guestfs_mount_ro>.  There are
154 several other variations of the C<guestfs_mount_*> call.
155
156 =head2 FILESYSTEM ACCESS AND MODIFICATION
157
158 The majority of the libguestfs API consists of fairly low-level calls
159 for accessing and modifying the files, directories, symlinks etc on
160 mounted filesystems.  There are over a hundred such calls which you
161 can find listed in detail below in this man page, and we don't even
162 pretend to cover them all in this overview.
163
164 Specify filenames as full paths including the mount point.
165
166 For example, if you mounted a filesystem at C<"/"> and you want to
167 read the file called C<"etc/passwd"> then you could do:
168
169  char *data = guestfs_cat (handle, "/etc/passwd");
170
171 This would return C<data> as a newly allocated buffer containing the
172 full content of that file (with some conditions: see also
173 L</DOWNLOADING> below), or C<NULL> if there was an error.
174
175 As another example, to create a top-level directory on that filesystem
176 called C<"var"> you would do:
177
178  guestfs_mkdir (handle, "/var");
179
180 To create a symlink you could do:
181
182  guestfs_ln_s (handle, "/etc/init.d/portmap",
183                "/etc/rc3.d/S30portmap");
184
185 Libguestfs will reject attempts to use relative paths.  There is no
186 concept of a current working directory.  Libguestfs can return errors
187 in many situations: for example if the filesystem isn't writable, or
188 if a file or directory that you requested doesn't exist.  If you are
189 using the C API (documented here) you have to check for those error
190 conditions after each call.  (Other language bindings turn these
191 errors into exceptions).
192
193 File writes are affected by the per-handle umask, set by calling
194 C<guestfs_umask> and defaulting to 022.
195
196 =head2 PARTITIONING
197
198 Libguestfs contains API calls to read, create and modify partition
199 tables on disk images.
200
201 In the common case where you want to create a single partition
202 covering the whole disk, you should use the C<guestfs_part_disk>
203 call:
204
205  const char *parttype = "mbr";
206  if (disk_is_larger_than_2TB)
207    parttype = "gpt";
208  guestfs_part_disk (g, "/dev/sda", parttype);
209
210 Obviously this effectively wipes anything that was on that disk image
211 before.
212
213 In general MBR partitions are both unnecessarily complicated and
214 depend on archaic details, namely the Cylinder-Head-Sector (CHS)
215 geometry of the disk.  C<guestfs_sfdiskM> can be used to
216 create more complex arrangements where the relative sizes are
217 expressed in megabytes instead of cylinders, which is a small win.
218 C<guestfs_sfdiskM> will choose the nearest cylinder to approximate the
219 requested size.  There's a lot of crazy stuff to do with IDE and
220 virtio disks having different, incompatible CHS geometries, that you
221 probably don't want to know about.
222
223 My advice: make a single partition to cover the whole disk, then use
224 LVM on top.
225
226 =head2 LVM2
227
228 Libguestfs provides access to a large part of the LVM2 API, such as
229 C<guestfs_lvcreate> and C<guestfs_vgremove>.  It won't make much sense
230 unless you familiarize yourself with the concepts of physical volumes,
231 volume groups and logical volumes.
232
233 This author strongly recommends reading the LVM HOWTO, online at
234 L<http://tldp.org/HOWTO/LVM-HOWTO/>.
235
236 =head2 DOWNLOADING
237
238 Use C<guestfs_cat> to download small, text only files.  This call
239 is limited to files which are less than 2 MB and which cannot contain
240 any ASCII NUL (C<\0>) characters.  However it has a very simple
241 to use API.
242
243 C<guestfs_read_file> can be used to read files which contain
244 arbitrary 8 bit data, since it returns a (pointer, size) pair.
245 However it is still limited to "small" files, less than 2 MB.
246
247 C<guestfs_download> can be used to download any file, with no
248 limits on content or size (even files larger than 4 GB).
249
250 To download multiple files, see C<guestfs_tar_out> and
251 C<guestfs_tgz_out>.
252
253 =head2 UPLOADING
254
255 It's often the case that you want to write a file or files to the disk
256 image.
257
258 For small, single files, use C<guestfs_write_file>.  This call
259 currently contains a bug which limits the call to plain text files
260 (not containing ASCII NUL characters).
261
262 To upload a single file, use C<guestfs_upload>.  This call has no
263 limits on file content or size (even files larger than 4 GB).
264
265 To upload multiple files, see C<guestfs_tar_in> and C<guestfs_tgz_in>.
266
267 However the fastest way to upload I<large numbers of arbitrary files>
268 is to turn them into a squashfs or CD ISO (see L<mksquashfs(8)> and
269 L<mkisofs(8)>), then attach this using C<guestfs_add_drive_ro>.  If
270 you add the drive in a predictable way (eg. adding it last after all
271 other drives) then you can get the device name from
272 C<guestfs_list_devices> and mount it directly using
273 C<guestfs_mount_ro>.  Note that squashfs images are sometimes
274 non-portable between kernel versions, and they don't support labels or
275 UUIDs.  If you want to pre-build an image or you need to mount it
276 using a label or UUID, use an ISO image instead.
277
278 =head2 COPYING
279
280 There are various different commands for copying between files and
281 devices and in and out of the guest filesystem.  These are summarised
282 in the table below.
283
284 =over 4
285
286 =item B<file> to B<file>
287
288 Use L</guestfs_cp> to copy a single file, or
289 L</guestfs_cp_a> to copy directories recursively.
290
291 =item B<file or device> to B<file or device>
292
293 Use L</guestfs_dd> which efficiently uses L<dd(1)>
294 to copy between files and devices in the guest.
295
296 Example: duplicate the contents of an LV:
297
298  guestfs_dd (g, "/dev/VG/Original", "/dev/VG/Copy");
299
300 The destination (C</dev/VG/Copy>) must be at least as large as the
301 source (C</dev/VG/Original>).
302
303 =item B<file on the host> to B<file or device>
304
305 Use L</guestfs_upload>.  See L</UPLOADING> above.
306
307 =item B<file or device> to B<file on the host>
308
309 Use L</guestfs_download>.  See L</DOWNLOADING> above.
310
311 =back
312
313 =head2 LISTING FILES
314
315 C<guestfs_ll> is just designed for humans to read (mainly when using
316 the L<guestfish(1)>-equivalent command C<ll>).
317
318 C<guestfs_ls> is a quick way to get a list of files in a directory
319 from programs, as a flat list of strings.
320
321 C<guestfs_readdir> is a programmatic way to get a list of files in a
322 directory, plus additional information about each one.  It is more
323 equivalent to using the L<readdir(3)> call on a local filesystem.
324
325 C<guestfs_find> can be used to recursively list files.
326
327 =head2 RUNNING COMMANDS
328
329 Although libguestfs is a primarily an API for manipulating files
330 inside guest images, we also provide some limited facilities for
331 running commands inside guests.
332
333 There are many limitations to this:
334
335 =over 4
336
337 =item *
338
339 The kernel version that the command runs under will be different
340 from what it expects.
341
342 =item *
343
344 If the command needs to communicate with daemons, then most likely
345 they won't be running.
346
347 =item *
348
349 The command will be running in limited memory.
350
351 =item *
352
353 Only supports Linux guests (not Windows, BSD, etc).
354
355 =item *
356
357 Architecture limitations (eg. won't work for a PPC guest on
358 an X86 host).
359
360 =item *
361
362 For SELinux guests, you may need to enable SELinux and load policy
363 first.  See L</SELINUX> in this manpage.
364
365 =back
366
367 The two main API calls to run commands are C<guestfs_command> and
368 C<guestfs_sh> (there are also variations).
369
370 The difference is that C<guestfs_sh> runs commands using the shell, so
371 any shell globs, redirections, etc will work.
372
373 =head2 CONFIGURATION FILES
374
375 To read and write configuration files in Linux guest filesystems, we
376 strongly recommend using Augeas.  For example, Augeas understands how
377 to read and write, say, a Linux shadow password file or X.org
378 configuration file, and so avoids you having to write that code.
379
380 The main Augeas calls are bound through the C<guestfs_aug_*> APIs.  We
381 don't document Augeas itself here because there is excellent
382 documentation on the L<http://augeas.net/> website.
383
384 If you don't want to use Augeas (you fool!) then try calling
385 C<guestfs_read_lines> to get the file as a list of lines which
386 you can iterate over.
387
388 =head2 SELINUX
389
390 We support SELinux guests.  To ensure that labeling happens correctly
391 in SELinux guests, you need to enable SELinux and load the guest's
392 policy:
393
394 =over 4
395
396 =item 1.
397
398 Before launching, do:
399
400  guestfs_set_selinux (g, 1);
401
402 =item 2.
403
404 After mounting the guest's filesystem(s), load the policy.  This
405 is best done by running the L<load_policy(8)> command in the
406 guest itself:
407
408  guestfs_sh (g, "/usr/sbin/load_policy");
409
410 (Older versions of C<load_policy> require you to specify the
411 name of the policy file).
412
413 =item 3.
414
415 Optionally, set the security context for the API.  The correct
416 security context to use can only be known by inspecting the
417 guest.  As an example:
418
419  guestfs_setcon (g, "unconfined_u:unconfined_r:unconfined_t:s0");
420
421 =back
422
423 This will work for running commands and editing existing files.
424
425 When new files are created, you may need to label them explicitly,
426 for example by running the external command
427 C<restorecon pathname>.
428
429 =head2 SPECIAL CONSIDERATIONS FOR WINDOWS GUESTS
430
431 Libguestfs can mount NTFS partitions.  It does this using the
432 L<http://www.ntfs-3g.org/> driver.
433
434 DOS and Windows still use drive letters, and the filesystems are
435 always treated as case insensitive by Windows itself, and therefore
436 you might find a Windows configuration file referring to a path like
437 C<c:\windows\system32>.  When the filesystem is mounted in libguestfs,
438 that directory might be referred to as C</WINDOWS/System32>.
439
440 Drive letter mappings are outside the scope of libguestfs.  You have
441 to use libguestfs to read the appropriate Windows Registry and
442 configuration files, to determine yourself how drives are mapped (see
443 also L<virt-inspector(1)>).
444
445 Replacing backslash characters with forward slash characters is also
446 outside the scope of libguestfs, but something that you can easily do.
447
448 Where we can help is in resolving the case insensitivity of paths.
449 For this, call C<guestfs_case_sensitive_path>.
450
451 Libguestfs also provides some help for decoding Windows Registry
452 "hive" files, through the library C<libhivex> which is part of
453 libguestfs.  You have to locate and download the hive file(s)
454 yourself, and then pass them to C<libhivex> functions.  See also the
455 programs L<hivexml(1)>, L<hivexget(1)> and L<virt-win-reg(1)> for more
456 help on this issue.
457
458 =head2 USING LIBGUESTFS WITH OTHER PROGRAMMING LANGUAGES
459
460 Although we don't want to discourage you from using the C API, we will
461 mention here that the same API is also available in other languages.
462
463 The API is broadly identical in all supported languages.  This means
464 that the C call C<guestfs_mount(handle,path)> is
465 C<$handle-E<gt>mount($path)> in Perl, C<handle.mount(path)> in Python,
466 and C<Guestfs.mount handle path> in OCaml.  In other words, a
467 straightforward, predictable isomorphism between each language.
468
469 Error messages are automatically transformed
470 into exceptions if the language supports it.
471
472 We don't try to "object orientify" parts of the API in OO languages,
473 although contributors are welcome to write higher level APIs above
474 what we provide in their favourite languages if they wish.
475
476 =over 4
477
478 =item B<C++>
479
480 You can use the I<guestfs.h> header file from C++ programs.  The C++
481 API is identical to the C API.  C++ classes and exceptions are
482 not implemented.
483
484 =item B<C#>
485
486 The C# bindings are highly experimental.  Please read the warnings
487 at the top of C<csharp/Libguestfs.cs>.
488
489 =item B<Haskell>
490
491 This is the only language binding that working but incomplete.  Only
492 calls which return simple integers have been bound in Haskell, and we
493 are looking for help to complete this binding.
494
495 =item B<Java>
496
497 Full documentation is contained in the Javadoc which is distributed
498 with libguestfs.
499
500 =item B<OCaml>
501
502 For documentation see the file C<guestfs.mli>.
503
504 =item B<Perl>
505
506 For documentation see L<Sys::Guestfs(3)>.
507
508 =item B<Python>
509
510 For documentation do:
511
512  $ python
513  >>> import guestfs
514  >>> help (guestfs)
515
516 =item B<Ruby>
517
518 Use the Guestfs module.  There is no Ruby-specific documentation, but
519 you can find examples written in Ruby in the libguestfs source.
520
521 =item B<shell scripts>
522
523 For documentation see L<guestfish(1)>.
524
525 =back
526
527 =head2 LIBGUESTFS GOTCHAS
528
529 L<http://en.wikipedia.org/wiki/Gotcha_(programming)>: "A feature of a
530 system [...] that works in the way it is documented but is
531 counterintuitive and almost invites mistakes."
532
533 Since we developed libguestfs and the associated tools, there are
534 several things we would have designed differently, but are now stuck
535 with for backwards compatibility or other reasons.  If there is ever a
536 libguestfs 2.0 release, you can expect these to change.  Beware of
537 them.
538
539 =over 4
540
541 =item Autosync / forgetting to sync.
542
543 When modifying a filesystem from C or another language, you B<must>
544 unmount all filesystems and call L</guestfs_sync> explicitly before
545 you close the libguestfs handle.  You can also call:
546
547  guestfs_set_autosync (handle, 1);
548
549 to have the unmount/sync done automatically for you when the handle is
550 closed.  (This feature is called "autosync", L</guestfs_set_autosync>
551 q.v.)
552
553 If you forget to do this, then it is entirely possible that your
554 changes won't be written out, or will be partially written, or (very
555 rarely) that you'll get disk corruption.
556
557 Note that in L<guestfish(3)> I<autosync is the default>.  So quick and
558 dirty guestfish scripts that forget to sync will work just fine, which
559 can make this extra-puzzling if you are trying to debug a problem.
560
561 =item Read-only should be the default.
562
563 In L<guestfish(3)>, I<--ro> should be the default, and you should
564 have to specify I<--rw> if you want to make changes to the image.
565
566 This would reduce the potential to corrupt live VM images.
567
568 Note that many filesystems change the disk when you just mount and
569 unmount, even if you didn't perform any writes.  You need to use
570 C<guestfs_add_drive_ro> to guarantee that the disk is not changed.
571
572 =item guestfish command line is hard to use.
573
574 C<guestfish disk.img> doesn't do what people expect (open C<disk.img>
575 for examination).  It tries to run a guestfish command C<disk.img>
576 which doesn't exist, so it fails, and it fails with a strange and
577 unintuitive error message.  Like the Bourne shell, we should have used
578 C<guestfish -c command> to run commands.
579
580 =back
581
582 =head1 CONNECTION MANAGEMENT
583
584 =head2 guestfs_h *
585
586 C<guestfs_h> is the opaque type representing a connection handle.
587 Create a handle by calling C<guestfs_create>.  Call C<guestfs_close>
588 to free the handle and release all resources used.
589
590 For information on using multiple handles and threads, see the section
591 L</MULTIPLE HANDLES AND MULTIPLE THREADS> below.
592
593 =head2 guestfs_create
594
595  guestfs_h *guestfs_create (void);
596
597 Create a connection handle.
598
599 You have to call C<guestfs_add_drive> on the handle at least once.
600
601 This function returns a non-NULL pointer to a handle on success or
602 NULL on error.
603
604 After configuring the handle, you have to call C<guestfs_launch>.
605
606 You may also want to configure error handling for the handle.  See
607 L</ERROR HANDLING> section below.
608
609 =head2 guestfs_close
610
611  void guestfs_close (guestfs_h *handle);
612
613 This closes the connection handle and frees up all resources used.
614
615 =head1 ERROR HANDLING
616
617 The convention in all functions that return C<int> is that they return
618 C<-1> to indicate an error.  You can get additional information on
619 errors by calling C<guestfs_last_error> and/or by setting up an error
620 handler with C<guestfs_set_error_handler>.
621
622 The default error handler prints the information string to C<stderr>.
623
624 Out of memory errors are handled differently.  The default action is
625 to call L<abort(3)>.  If this is undesirable, then you can set a
626 handler using C<guestfs_set_out_of_memory_handler>.
627
628 =head2 guestfs_last_error
629
630  const char *guestfs_last_error (guestfs_h *handle);
631
632 This returns the last error message that happened on C<handle>.  If
633 there has not been an error since the handle was created, then this
634 returns C<NULL>.
635
636 The lifetime of the returned string is until the next error occurs, or
637 C<guestfs_close> is called.
638
639 The error string is not localized (ie. is always in English), because
640 this makes searching for error messages in search engines give the
641 largest number of results.
642
643 =head2 guestfs_set_error_handler
644
645  typedef void (*guestfs_error_handler_cb) (guestfs_h *handle,
646                                            void *data,
647                                            const char *msg);
648  void guestfs_set_error_handler (guestfs_h *handle,
649                                  guestfs_error_handler_cb cb,
650                                  void *data);
651
652 The callback C<cb> will be called if there is an error.  The
653 parameters passed to the callback are an opaque data pointer and the
654 error message string.
655
656 Note that the message string C<msg> is freed as soon as the callback
657 function returns, so if you want to stash it somewhere you must make
658 your own copy.
659
660 The default handler prints messages on C<stderr>.
661
662 If you set C<cb> to C<NULL> then I<no> handler is called.
663
664 =head2 guestfs_get_error_handler
665
666  guestfs_error_handler_cb guestfs_get_error_handler (guestfs_h *handle,
667                                                      void **data_rtn);
668
669 Returns the current error handler callback.
670
671 =head2 guestfs_set_out_of_memory_handler
672
673  typedef void (*guestfs_abort_cb) (void);
674  int guestfs_set_out_of_memory_handler (guestfs_h *handle,
675                                         guestfs_abort_cb);
676
677 The callback C<cb> will be called if there is an out of memory
678 situation.  I<Note this callback must not return>.
679
680 The default is to call L<abort(3)>.
681
682 You cannot set C<cb> to C<NULL>.  You can't ignore out of memory
683 situations.
684
685 =head2 guestfs_get_out_of_memory_handler
686
687  guestfs_abort_fn guestfs_get_out_of_memory_handler (guestfs_h *handle);
688
689 This returns the current out of memory handler.
690
691 =head1 PATH
692
693 Libguestfs needs a kernel and initrd.img, which it finds by looking
694 along an internal path.
695
696 By default it looks for these in the directory C<$libdir/guestfs>
697 (eg. C</usr/local/lib/guestfs> or C</usr/lib64/guestfs>).
698
699 Use C<guestfs_set_path> or set the environment variable
700 C<LIBGUESTFS_PATH> to change the directories that libguestfs will
701 search in.  The value is a colon-separated list of paths.  The current
702 directory is I<not> searched unless the path contains an empty element
703 or C<.>.  For example C<LIBGUESTFS_PATH=:/usr/lib/guestfs> would
704 search the current directory and then C</usr/lib/guestfs>.
705
706 =head1 HIGH-LEVEL API ACTIONS
707
708 =head2 ABI GUARANTEE
709
710 We guarantee the libguestfs ABI (binary interface), for public,
711 high-level actions as outlined in this section.  Although we will
712 deprecate some actions, for example if they get replaced by newer
713 calls, we will keep the old actions forever.  This allows you the
714 developer to program in confidence against libguestfs.
715
716 @ACTIONS@
717
718 =head1 STRUCTURES
719
720 @STRUCTS@
721
722 =head1 AVAILABILITY
723
724 =head2 GROUPS OF FUNCTIONALITY IN THE APPLIANCE
725
726 Using L</guestfs_available> you can test availability of
727 the following groups of functions.  This test queries the
728 appliance to see if the appliance you are currently using
729 supports the functionality.
730
731 @AVAILABILITY@
732
733 =head2 SINGLE CALLS AT COMPILE TIME
734
735 If you need to test whether a single libguestfs function is
736 available at compile time, we recommend using build tools
737 such as autoconf or cmake.  For example in autotools you could
738 use:
739
740  AC_CHECK_LIB([guestfs],[guestfs_create])
741  AC_CHECK_FUNCS([guestfs_dd])
742
743 which would result in C<HAVE_GUESTFS_DD> being either defined
744 or not defined in your program.
745
746 =head2 SINGLE CALLS AT RUN TIME
747
748 Testing at compile time doesn't guarantee that a function really
749 exists in the library.  The reason is that you might be dynamically
750 linked against a previous I<libguestfs.so> (dynamic library)
751 which doesn't have the call.  This situation unfortunately results
752 in a segmentation fault, which is a shortcoming of the C dynamic
753 linking system itself.
754
755 You can use L<dlopen(3)> to test if a function is available
756 at run time, as in this example program (note that you still
757 need the compile time check as well):
758
759  #include <config.h>
760  
761  #include <stdio.h>
762  #include <stdlib.h>
763  #include <unistd.h>
764  #include <dlfcn.h>
765  #include <guestfs.h>
766  
767  main ()
768  {
769  #ifdef HAVE_GUESTFS_DD
770    void *dl;
771    int has_function;
772  
773    /* Test if the function guestfs_dd is really available. */
774    dl = dlopen (NULL, RTLD_LAZY);
775    if (!dl) {
776      fprintf (stderr, "dlopen: %s\n", dlerror ());
777      exit (1);
778    }
779    has_function = dlsym (dl, "guestfs_dd") != NULL;
780    dlclose (dl);
781  
782    if (!has_function)
783      printf ("this libguestfs.so does NOT have guestfs_dd function\n");
784    else {
785      printf ("this libguestfs.so has guestfs_dd function\n");
786      /* Now it's safe to call
787      guestfs_dd (g, "foo", "bar");
788      */
789    }
790  #else
791    printf ("guestfs_dd function was not found at compile time\n");
792  #endif
793   }
794
795 You may think the above is an awful lot of hassle, and it is.
796 There are other ways outside of the C linking system to ensure
797 that this kind of incompatibility never arises, such as using
798 package versioning:
799
800  Requires: libguestfs >= 1.0.80
801
802 =begin html
803
804 <!-- old anchor for the next section -->
805 <a name="state_machine_and_low_level_event_api"/>
806
807 =end html
808
809 =head1 ARCHITECTURE
810
811 Internally, libguestfs is implemented by running an appliance (a
812 special type of small virtual machine) using L<qemu(1)>.  Qemu runs as
813 a child process of the main program.
814
815   ___________________
816  /                   \
817  | main program      |
818  |                   |
819  |                   |           child process / appliance
820  |                   |           __________________________
821  |                   |          / qemu                     \
822  +-------------------+   RPC    |      +-----------------+ |
823  | libguestfs     <--------------------> guestfsd        | |
824  |                   |          |      +-----------------+ |
825  \___________________/          |      | Linux kernel    | |
826                                 |      +--^--------------+ |
827                                 \_________|________________/
828                                           |
829                                    _______v______
830                                   /              \
831                                   | Device or    |
832                                   | disk image   |
833                                   \______________/
834
835 The library, linked to the main program, creates the child process and
836 hence the appliance in the L</guestfs_launch> function.
837
838 Inside the appliance is a Linux kernel and a complete stack of
839 userspace tools (such as LVM and ext2 programs) and a small
840 controlling daemon called C<guestfsd>.  The library talks to
841 C<guestfsd> using remote procedure calls (RPC).  There is a mostly
842 one-to-one correspondence between libguestfs API calls and RPC calls
843 to the daemon.  Lastly the disk image(s) are attached to the qemu
844 process which translates device access by the appliance's Linux kernel
845 into accesses to the image.
846
847 A common misunderstanding is that the appliance "is" the virtual
848 machine.  Although the disk image you are attached to might also be
849 used by some virtual machine, libguestfs doesn't know or care about
850 this.  (But you will care if both libguestfs's qemu process and your
851 virtual machine are trying to update the disk image at the same time,
852 since these usually results in massive disk corruption).
853
854 =head1 STATE MACHINE
855
856 libguestfs uses a state machine to model the child process:
857
858                          |
859                     guestfs_create
860                          |
861                          |
862                      ____V_____
863                     /          \
864                     |  CONFIG  |
865                     \__________/
866                      ^ ^   ^  \
867                     /  |    \  \ guestfs_launch
868                    /   |    _\__V______
869                   /    |   /           \
870                  /     |   | LAUNCHING |
871                 /      |   \___________/
872                /       |       /
873               /        |  guestfs_launch
874              /         |     /
875     ______  /        __|____V
876    /      \ ------> /        \
877    | BUSY |         | READY  |
878    \______/ <------ \________/
879
880 The normal transitions are (1) CONFIG (when the handle is created, but
881 there is no child process), (2) LAUNCHING (when the child process is
882 booting up), (3) alternating between READY and BUSY as commands are
883 issued to, and carried out by, the child process.
884
885 The guest may be killed by C<guestfs_kill_subprocess>, or may die
886 asynchronously at any time (eg. due to some internal error), and that
887 causes the state to transition back to CONFIG.
888
889 Configuration commands for qemu such as C<guestfs_add_drive> can only
890 be issued when in the CONFIG state.
891
892 The high-level API offers two calls that go from CONFIG through
893 LAUNCHING to READY.  C<guestfs_launch> blocks until the child process
894 is READY to accept commands (or until some failure or timeout).
895 C<guestfs_launch> internally moves the state from CONFIG to LAUNCHING
896 while it is running.
897
898 High-level API actions such as C<guestfs_mount> can only be issued
899 when in the READY state.  These high-level API calls block waiting for
900 the command to be carried out (ie. the state to transition to BUSY and
901 then back to READY).  But using the low-level event API, you get
902 non-blocking versions.  (But you can still only carry out one
903 operation per handle at a time - that is a limitation of the
904 communications protocol we use).
905
906 Finally, the child process sends asynchronous messages back to the
907 main program, such as kernel log messages.  Mostly these are ignored
908 by the high-level API, but using the low-level event API you can
909 register to receive these messages.
910
911 =head2 SETTING CALLBACKS TO HANDLE EVENTS
912
913 The child process generates events in some situations.  Current events
914 include: receiving a log message, the child process exits.
915
916 Use the C<guestfs_set_*_callback> functions to set a callback for
917 different types of events.
918
919 Only I<one callback of each type> can be registered for each handle.
920 Calling C<guestfs_set_*_callback> again overwrites the previous
921 callback of that type.  Cancel all callbacks of this type by calling
922 this function with C<cb> set to C<NULL>.
923
924 =head2 guestfs_set_log_message_callback
925
926  typedef void (*guestfs_log_message_cb) (guestfs_h *g, void *opaque,
927                                          char *buf, int len);
928  void guestfs_set_log_message_callback (guestfs_h *handle,
929                                         guestfs_log_message_cb cb,
930                                         void *opaque);
931
932 The callback function C<cb> will be called whenever qemu or the guest
933 writes anything to the console.
934
935 Use this function to capture kernel messages and similar.
936
937 Normally there is no log message handler, and log messages are just
938 discarded.
939
940 =head2 guestfs_set_subprocess_quit_callback
941
942  typedef void (*guestfs_subprocess_quit_cb) (guestfs_h *g, void *opaque);
943  void guestfs_set_subprocess_quit_callback (guestfs_h *handle,
944                                             guestfs_subprocess_quit_cb cb,
945                                             void *opaque);
946
947 The callback function C<cb> will be called when the child process
948 quits, either asynchronously or if killed by
949 C<guestfs_kill_subprocess>.  (This corresponds to a transition from
950 any state to the CONFIG state).
951
952 =head2 guestfs_set_launch_done_callback
953
954  typedef void (*guestfs_launch_done_cb) (guestfs_h *g, void *opaque);
955  void guestfs_set_launch_done_callback (guestfs_h *handle,
956                                         guestfs_ready_cb cb,
957                                         void *opaque);
958
959 The callback function C<cb> will be called when the child process
960 becomes ready first time after it has been launched.  (This
961 corresponds to a transition from LAUNCHING to the READY state).
962
963 =head1 BLOCK DEVICE NAMING
964
965 In the kernel there is now quite a profusion of schemata for naming
966 block devices (in this context, by I<block device> I mean a physical
967 or virtual hard drive).  The original Linux IDE driver used names
968 starting with C</dev/hd*>.  SCSI devices have historically used a
969 different naming scheme, C</dev/sd*>.  When the Linux kernel I<libata>
970 driver became a popular replacement for the old IDE driver
971 (particularly for SATA devices) those devices also used the
972 C</dev/sd*> scheme.  Additionally we now have virtual machines with
973 paravirtualized drivers.  This has created several different naming
974 systems, such as C</dev/vd*> for virtio disks and C</dev/xvd*> for Xen
975 PV disks.
976
977 As discussed above, libguestfs uses a qemu appliance running an
978 embedded Linux kernel to access block devices.  We can run a variety
979 of appliances based on a variety of Linux kernels.
980
981 This causes a problem for libguestfs because many API calls use device
982 or partition names.  Working scripts and the recipe (example) scripts
983 that we make available over the internet could fail if the naming
984 scheme changes.
985
986 Therefore libguestfs defines C</dev/sd*> as the I<standard naming
987 scheme>.  Internally C</dev/sd*> names are translated, if necessary,
988 to other names as required.  For example, under RHEL 5 which uses the
989 C</dev/hd*> scheme, any device parameter C</dev/sda2> is translated to
990 C</dev/hda2> transparently.
991
992 Note that this I<only> applies to parameters.  The
993 C<guestfs_list_devices>, C<guestfs_list_partitions> and similar calls
994 return the true names of the devices and partitions as known to the
995 appliance.
996
997 =head2 ALGORITHM FOR BLOCK DEVICE NAME TRANSLATION
998
999 Usually this translation is transparent.  However in some (very rare)
1000 cases you may need to know the exact algorithm.  Such cases include
1001 where you use C<guestfs_config> to add a mixture of virtio and IDE
1002 devices to the qemu-based appliance, so have a mixture of C</dev/sd*>
1003 and C</dev/vd*> devices.
1004
1005 The algorithm is applied only to I<parameters> which are known to be
1006 either device or partition names.  Return values from functions such
1007 as C<guestfs_list_devices> are never changed.
1008
1009 =over 4
1010
1011 =item *
1012
1013 Is the string a parameter which is a device or partition name?
1014
1015 =item *
1016
1017 Does the string begin with C</dev/sd>?
1018
1019 =item *
1020
1021 Does the named device exist?  If so, we use that device.
1022 However if I<not> then we continue with this algorithm.
1023
1024 =item *
1025
1026 Replace initial C</dev/sd> string with C</dev/hd>.
1027
1028 For example, change C</dev/sda2> to C</dev/hda2>.
1029
1030 If that named device exists, use it.  If not, continue.
1031
1032 =item *
1033
1034 Replace initial C</dev/sd> string with C</dev/vd>.
1035
1036 If that named device exists, use it.  If not, return an error.
1037
1038 =back
1039
1040 =head2 PORTABILITY CONCERNS
1041
1042 Although the standard naming scheme and automatic translation is
1043 useful for simple programs and guestfish scripts, for larger programs
1044 it is best not to rely on this mechanism.
1045
1046 Where possible for maximum future portability programs using
1047 libguestfs should use these future-proof techniques:
1048
1049 =over 4
1050
1051 =item *
1052
1053 Use C<guestfs_list_devices> or C<guestfs_list_partitions> to list
1054 actual device names, and then use those names directly.
1055
1056 Since those device names exist by definition, they will never be
1057 translated.
1058
1059 =item *
1060
1061 Use higher level ways to identify filesystems, such as LVM names,
1062 UUIDs and filesystem labels.
1063
1064 =back
1065
1066 =head1 INTERNALS
1067
1068 =head2 COMMUNICATION PROTOCOL
1069
1070 Don't rely on using this protocol directly.  This section documents
1071 how it currently works, but it may change at any time.
1072
1073 The protocol used to talk between the library and the daemon running
1074 inside the qemu virtual machine is a simple RPC mechanism built on top
1075 of XDR (RFC 1014, RFC 1832, RFC 4506).
1076
1077 The detailed format of structures is in C<src/guestfs_protocol.x>
1078 (note: this file is automatically generated).
1079
1080 There are two broad cases, ordinary functions that don't have any
1081 C<FileIn> and C<FileOut> parameters, which are handled with very
1082 simple request/reply messages.  Then there are functions that have any
1083 C<FileIn> or C<FileOut> parameters, which use the same request and
1084 reply messages, but they may also be followed by files sent using a
1085 chunked encoding.
1086
1087 =head3 ORDINARY FUNCTIONS (NO FILEIN/FILEOUT PARAMS)
1088
1089 For ordinary functions, the request message is:
1090
1091  total length (header + arguments,
1092       but not including the length word itself)
1093  struct guestfs_message_header (encoded as XDR)
1094  struct guestfs_<foo>_args (encoded as XDR)
1095
1096 The total length field allows the daemon to allocate a fixed size
1097 buffer into which it slurps the rest of the message.  As a result, the
1098 total length is limited to C<GUESTFS_MESSAGE_MAX> bytes (currently
1099 4MB), which means the effective size of any request is limited to
1100 somewhere under this size.
1101
1102 Note also that many functions don't take any arguments, in which case
1103 the C<guestfs_I<foo>_args> is completely omitted.
1104
1105 The header contains the procedure number (C<guestfs_proc>) which is
1106 how the receiver knows what type of args structure to expect, or none
1107 at all.
1108
1109 The reply message for ordinary functions is:
1110
1111  total length (header + ret,
1112       but not including the length word itself)
1113  struct guestfs_message_header (encoded as XDR)
1114  struct guestfs_<foo>_ret (encoded as XDR)
1115
1116 As above the C<guestfs_I<foo>_ret> structure may be completely omitted
1117 for functions that return no formal return values.
1118
1119 As above the total length of the reply is limited to
1120 C<GUESTFS_MESSAGE_MAX>.
1121
1122 In the case of an error, a flag is set in the header, and the reply
1123 message is slightly changed:
1124
1125  total length (header + error,
1126       but not including the length word itself)
1127  struct guestfs_message_header (encoded as XDR)
1128  struct guestfs_message_error (encoded as XDR)
1129
1130 The C<guestfs_message_error> structure contains the error message as a
1131 string.
1132
1133 =head3 FUNCTIONS THAT HAVE FILEIN PARAMETERS
1134
1135 A C<FileIn> parameter indicates that we transfer a file I<into> the
1136 guest.  The normal request message is sent (see above).  However this
1137 is followed by a sequence of file chunks.
1138
1139  total length (header + arguments,
1140       but not including the length word itself,
1141       and not including the chunks)
1142  struct guestfs_message_header (encoded as XDR)
1143  struct guestfs_<foo>_args (encoded as XDR)
1144  sequence of chunks for FileIn param #0
1145  sequence of chunks for FileIn param #1 etc.
1146
1147 The "sequence of chunks" is:
1148
1149  length of chunk (not including length word itself)
1150  struct guestfs_chunk (encoded as XDR)
1151  length of chunk
1152  struct guestfs_chunk (encoded as XDR)
1153    ...
1154  length of chunk
1155  struct guestfs_chunk (with data.data_len == 0)
1156
1157 The final chunk has the C<data_len> field set to zero.  Additionally a
1158 flag is set in the final chunk to indicate either successful
1159 completion or early cancellation.
1160
1161 At time of writing there are no functions that have more than one
1162 FileIn parameter.  However this is (theoretically) supported, by
1163 sending the sequence of chunks for each FileIn parameter one after
1164 another (from left to right).
1165
1166 Both the library (sender) I<and> the daemon (receiver) may cancel the
1167 transfer.  The library does this by sending a chunk with a special
1168 flag set to indicate cancellation.  When the daemon sees this, it
1169 cancels the whole RPC, does I<not> send any reply, and goes back to
1170 reading the next request.
1171
1172 The daemon may also cancel.  It does this by writing a special word
1173 C<GUESTFS_CANCEL_FLAG> to the socket.  The library listens for this
1174 during the transfer, and if it gets it, it will cancel the transfer
1175 (it sends a cancel chunk).  The special word is chosen so that even if
1176 cancellation happens right at the end of the transfer (after the
1177 library has finished writing and has started listening for the reply),
1178 the "spurious" cancel flag will not be confused with the reply
1179 message.
1180
1181 This protocol allows the transfer of arbitrary sized files (no 32 bit
1182 limit), and also files where the size is not known in advance
1183 (eg. from pipes or sockets).  However the chunks are rather small
1184 (C<GUESTFS_MAX_CHUNK_SIZE>), so that neither the library nor the
1185 daemon need to keep much in memory.
1186
1187 =head3 FUNCTIONS THAT HAVE FILEOUT PARAMETERS
1188
1189 The protocol for FileOut parameters is exactly the same as for FileIn
1190 parameters, but with the roles of daemon and library reversed.
1191
1192  total length (header + ret,
1193       but not including the length word itself,
1194       and not including the chunks)
1195  struct guestfs_message_header (encoded as XDR)
1196  struct guestfs_<foo>_ret (encoded as XDR)
1197  sequence of chunks for FileOut param #0
1198  sequence of chunks for FileOut param #1 etc.
1199
1200 =head3 INITIAL MESSAGE
1201
1202 Because the underlying channel (QEmu -net channel) doesn't have any
1203 sort of connection control, when the daemon launches it sends an
1204 initial word (C<GUESTFS_LAUNCH_FLAG>) which indicates that the guest
1205 and daemon is alive.  This is what C<guestfs_launch> waits for.
1206
1207 =head1 MULTIPLE HANDLES AND MULTIPLE THREADS
1208
1209 All high-level libguestfs actions are synchronous.  If you want
1210 to use libguestfs asynchronously then you must create a thread.
1211
1212 Only use the handle from a single thread.  Either use the handle
1213 exclusively from one thread, or provide your own mutex so that two
1214 threads cannot issue calls on the same handle at the same time.
1215
1216 =head1 QEMU WRAPPERS
1217
1218 If you want to compile your own qemu, run qemu from a non-standard
1219 location, or pass extra arguments to qemu, then you can write a
1220 shell-script wrapper around qemu.
1221
1222 There is one important rule to remember: you I<must C<exec qemu>> as
1223 the last command in the shell script (so that qemu replaces the shell
1224 and becomes the direct child of the libguestfs-using program).  If you
1225 don't do this, then the qemu process won't be cleaned up correctly.
1226
1227 Here is an example of a wrapper, where I have built my own copy of
1228 qemu from source:
1229
1230  #!/bin/sh -
1231  qemudir=/home/rjones/d/qemu
1232  exec $qemudir/x86_64-softmmu/qemu-system-x86_64 -L $qemudir/pc-bios "$@"
1233
1234 Save this script as C</tmp/qemu.wrapper> (or wherever), C<chmod +x>,
1235 and then use it by setting the LIBGUESTFS_QEMU environment variable.
1236 For example:
1237
1238  LIBGUESTFS_QEMU=/tmp/qemu.wrapper guestfish
1239
1240 Note that libguestfs also calls qemu with the -help and -version
1241 options in order to determine features.
1242
1243 =head1 ENVIRONMENT VARIABLES
1244
1245 =over 4
1246
1247 =item LIBGUESTFS_APPEND
1248
1249 Pass additional options to the guest kernel.
1250
1251 =item LIBGUESTFS_DEBUG
1252
1253 Set C<LIBGUESTFS_DEBUG=1> to enable verbose messages.  This
1254 has the same effect as calling C<guestfs_set_verbose (handle, 1)>.
1255
1256 =item LIBGUESTFS_MEMSIZE
1257
1258 Set the memory allocated to the qemu process, in megabytes.  For
1259 example:
1260
1261  LIBGUESTFS_MEMSIZE=700
1262
1263 =item LIBGUESTFS_PATH
1264
1265 Set the path that libguestfs uses to search for kernel and initrd.img.
1266 See the discussion of paths in section PATH above.
1267
1268 =item LIBGUESTFS_QEMU
1269
1270 Set the default qemu binary that libguestfs uses.  If not set, then
1271 the qemu which was found at compile time by the configure script is
1272 used.
1273
1274 See also L</QEMU WRAPPERS> above.
1275
1276 =item LIBGUESTFS_TRACE
1277
1278 Set C<LIBGUESTFS_TRACE=1> to enable command traces.  This
1279 has the same effect as calling C<guestfs_set_trace (handle, 1)>.
1280
1281 =item TMPDIR
1282
1283 Location of temporary directory, defaults to C</tmp>.
1284
1285 If libguestfs was compiled to use the supermin appliance then each
1286 handle will require rather a large amount of space in this directory
1287 for short periods of time (~ 80 MB).  You can use C<$TMPDIR> to
1288 configure another directory to use in case C</tmp> is not large
1289 enough.
1290
1291 =back
1292
1293 =head1 SEE ALSO
1294
1295 L<guestfish(1)>,
1296 L<qemu(1)>,
1297 L<febootstrap(1)>,
1298 L<http://libguestfs.org/>.
1299
1300 Tools with a similar purpose:
1301 L<fdisk(8)>,
1302 L<parted(8)>,
1303 L<kpartx(8)>,
1304 L<lvm(8)>,
1305 L<disktype(1)>.
1306
1307 =head1 BUGS
1308
1309 To get a list of bugs against libguestfs use this link:
1310
1311 L<https://bugzilla.redhat.com/buglist.cgi?component=libguestfs&product=Virtualization+Tools>
1312
1313 To report a new bug against libguestfs use this link:
1314
1315 L<https://bugzilla.redhat.com/enter_bug.cgi?component=libguestfs&product=Virtualization+Tools>
1316
1317 When reporting a bug, please check:
1318
1319 =over 4
1320
1321 =item *
1322
1323 That the bug hasn't been reported already.
1324
1325 =item *
1326
1327 That you are testing a recent version.
1328
1329 =item *
1330
1331 Describe the bug accurately, and give a way to reproduce it.
1332
1333 =item *
1334
1335 Run libguestfs-test-tool and paste the B<complete, unedited>
1336 output into the bug report.
1337
1338 =back
1339
1340 =head1 AUTHORS
1341
1342 Richard W.M. Jones (C<rjones at redhat dot com>)
1343
1344 =head1 COPYRIGHT
1345
1346 Copyright (C) 2009 Red Hat Inc.
1347 L<http://libguestfs.org/>
1348
1349 This library is free software; you can redistribute it and/or
1350 modify it under the terms of the GNU Lesser General Public
1351 License as published by the Free Software Foundation; either
1352 version 2 of the License, or (at your option) any later version.
1353
1354 This library is distributed in the hope that it will be useful,
1355 but WITHOUT ANY WARRANTY; without even the implied warranty of
1356 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
1357 Lesser General Public License for more details.
1358
1359 You should have received a copy of the GNU Lesser General Public
1360 License along with this library; if not, write to the Free Software
1361 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA