guestfs-examples(3) Virtualization Support guestfs-examples(3)
NAME
guestfs-examples - Examples of using libguestfs from C
SYNOPSIS
#include <guestfs.h>
guestfs_h *g = guestfs_create ();
guestfs_add_drive_ro (g, "disk.img");
guestfs_launch (g);
cc prog.c -o prog -lguestfs
or:
cc prog.c -o prog `pkg-config libguestfs --cflags --libs`
DESCRIPTION
This manual page contains examples of calling libguestfs from the C programming language. If you are not familiar with using libguestfs,
you also need to read guestfs(3).
EXAMPLE
: CREATE A DISK IMAGE
/* Example showing how to create a disk image. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <guestfs.h>
int
main (int argc, char *argv[])
{
guestfs_h *g;
size_t i;
g = guestfs_create ();
if (g == NULL) {
perror ("failed to create libguestfs handle");
exit (EXIT_FAILURE);
}
/* Create a raw-format sparse disk image, 512 MB in size. */
int fd = open ("disk.img", O_CREAT|O_WRONLY|O_TRUNC|O_NOCTTY, 0666);
if (fd == -1) {
perror ("disk.img");
exit (EXIT_FAILURE);
}
if (ftruncate (fd, 512 * 1024 * 1024) == -1) {
perror ("disk.img: truncate");
exit (EXIT_FAILURE);
}
if (close (fd) == -1) {
perror ("disk.img: close");
exit (EXIT_FAILURE);
}
/* Set the trace flag so that we can see each libguestfs call. */
guestfs_set_trace (g, 1);
/* Add the disk image to libguestfs. */
if (guestfs_add_drive_opts (g, "disk.img",
GUESTFS_ADD_DRIVE_OPTS_FORMAT, "raw", /* raw format */
GUESTFS_ADD_DRIVE_OPTS_READONLY, 0, /* for write */
-1) /* this marks end of optional arguments */
== -1)
exit (EXIT_FAILURE);
/* Run the libguestfs back-end. */
if (guestfs_launch (g) == -1)
exit (EXIT_FAILURE);
/* Get the list of devices. Because we only added one drive
* above, we expect that this list should contain a single
* element.
*/
char **devices = guestfs_list_devices (g);
if (devices == NULL)
exit (EXIT_FAILURE);
if (devices[0] == NULL || devices[1] != NULL) {
fprintf (stderr, "error: expected a single device from list-devices
");
exit (EXIT_FAILURE);
}
/* Partition the disk as one single MBR partition. */
if (guestfs_part_disk (g, devices[0], "mbr") == -1)
exit (EXIT_FAILURE);
/* Get the list of partitions. We expect a single element, which
* is the partition we have just created.
*/
char **partitions = guestfs_list_partitions (g);
if (partitions == NULL)
exit (EXIT_FAILURE);
if (partitions[0] == NULL || partitions[1] != NULL) {
fprintf (stderr, "error: expected a single partition from list-partitions
");
exit (EXIT_FAILURE);
}
/* Create a filesystem on the partition. */
if (guestfs_mkfs (g, "ext4", partitions[0]) == -1)
exit (EXIT_FAILURE);
/* Now mount the filesystem so that we can add files. */
if (guestfs_mount (g, partitions[0], "/") == -1)
exit (EXIT_FAILURE);
/* Create some files and directories. */
if (guestfs_touch (g, "/empty") == -1)
exit (EXIT_FAILURE);
const char *message = "Hello, world
";
if (guestfs_write (g, "/hello", message, strlen (message)) == -1)
exit (EXIT_FAILURE);
if (guestfs_mkdir (g, "/foo") == -1)
exit (EXIT_FAILURE);
/* This one uploads the local file /etc/resolv.conf into
* the disk image.
*/
if (guestfs_upload (g, "/etc/resolv.conf", "/foo/resolv.conf") == -1)
exit (EXIT_FAILURE);
/* Because we wrote to the disk and we want to detect write
* errors, call guestfs_shutdown. You don't need to do this:
* guestfs_close will do it implicitly.
*/
if (guestfs_shutdown (g) == -1)
exit (EXIT_FAILURE);
guestfs_close (g);
/* Free up the lists. */
for (i = 0; devices[i] != NULL; ++i)
free (devices[i]);
free (devices);
for (i = 0; partitions[i] != NULL; ++i)
free (partitions[i]);
free (partitions);
exit (EXIT_SUCCESS);
}
EXAMPLE
: INSPECT A VIRTUAL MACHINE DISK IMAGE
/* Inspect a disk image and display operating systems it may contain. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <guestfs.h>
static int
compare_keys_len (const void *p1, const void *p2)
{
const char *key1 = * (char * const *) p1;
const char *key2 = * (char * const *) p2;
return strlen (key1) - strlen (key2);
}
static size_t
count_strings (char *const *argv)
{
size_t c;
for (c = 0; argv[c]; ++c)
;
return c;
}
int
main (int argc, char *argv[])
{
guestfs_h *g;
const char *disk;
char **roots, *root, *str, **mountpoints, **lines;
size_t i, j;
if (argc != 2) {
fprintf (stderr, "usage: inspect_vm disk.img
");
exit (EXIT_FAILURE);
}
disk = argv[1];
g = guestfs_create ();
if (g == NULL) {
perror ("failed to create libguestfs handle");
exit (EXIT_FAILURE);
}
/* Attach the disk image read-only to libguestfs. */
if (guestfs_add_drive_opts (g, disk,
/* GUESTFS_ADD_DRIVE_OPTS_FORMAT, "raw", */
GUESTFS_ADD_DRIVE_OPTS_READONLY, 1,
-1) /* this marks end of optional arguments */
== -1)
exit (EXIT_FAILURE);
/* Run the libguestfs back-end. */
if (guestfs_launch (g) == -1)
exit (EXIT_FAILURE);
/* Ask libguestfs to inspect for operating systems. */
roots = guestfs_inspect_os (g);
if (roots == NULL)
exit (EXIT_FAILURE);
if (roots[0] == NULL) {
fprintf (stderr, "inspect_vm: no operating systems found
");
exit (EXIT_FAILURE);
}
for (j = 0; roots[j] != NULL; ++j) {
root = roots[j];
printf ("Root device: %s
", root);
/* Print basic information about the operating system. */
str = guestfs_inspect_get_product_name (g, root);
if (str)
printf (" Product name: %s
", str);
free (str);
printf (" Version: %d.%d
",
guestfs_inspect_get_major_version (g, root),
guestfs_inspect_get_minor_version (g, root));
str = guestfs_inspect_get_type (g, root);
if (str)
printf (" Type: %s
", str);
free (str);
str = guestfs_inspect_get_distro (g, root);
if (str)
printf (" Distro: %s
", str);
free (str);
/* Mount up the disks, like guestfish -i.
*
* Sort keys by length, shortest first, so that we end up
* mounting the filesystems in the correct order.
*/
mountpoints = guestfs_inspect_get_mountpoints (g, root);
if (mountpoints == NULL)
exit (EXIT_FAILURE);
qsort (mountpoints, count_strings (mountpoints) / 2, 2 * sizeof (char *),
compare_keys_len);
for (i = 0; mountpoints[i] != NULL; i += 2) {
/* Ignore failures from this call, since bogus entries can
* appear in the guest's /etc/fstab.
*/
guestfs_mount_ro (g, mountpoints[i+1], mountpoints[i]);
free (mountpoints[i]);
free (mountpoints[i+1]);
}
free (mountpoints);
/* If /etc/issue.net file exists, print up to 3 lines. */
if (guestfs_is_file (g, "/etc/issue.net") > 0) {
printf ("--- /etc/issue.net ---
");
lines = guestfs_head_n (g, 3, "/etc/issue.net");
if (lines == NULL)
exit (EXIT_FAILURE);
for (i = 0; lines[i] != NULL; ++i) {
printf ("%s
", lines[i]);
free (lines[i]);
}
free (lines);
}
/* Unmount everything. */
if (guestfs_umount_all (g) == -1)
exit (EXIT_FAILURE);
free (root);
}
free (roots);
guestfs_close (g);
exit (EXIT_SUCCESS);
}
EXAMPLE
: ENABLE DEBUGGING AND LOGGING
/* Example showing how to enable debugging, and capture it into any
* custom logging system (syslog in this example, but any could be
* used). Note this uses the event API which is also available in
* non-C language bindings.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <syslog.h>
#include <guestfs.h>
static void message_callback (guestfs_h *g, void *opaque, uint64_t event, int event_handle, int flags, const char *buf, size_t buf_len, const uint64_t *array, size_t array_len);
/* Events we are interested in. This bitmask covers all trace and
* debug messages.
*/
static const uint64_t event_bitmask =
GUESTFS_EVENT_LIBRARY | GUESTFS_EVENT_APPLIANCE | GUESTFS_EVENT_TRACE;
int
main (int argc, char *argv[])
{
guestfs_h *g;
g = guestfs_create ();
if (g == NULL) {
perror ("failed to create libguestfs handle");
exit (EXIT_FAILURE);
}
/* By default, debugging information is printed on stderr. To
* capture it somewhere else you have to set up an event handler
* which will be called back as debug messages are generated. To do
* this use the event API.
*
* For more information see EVENTS in guestfs(3).
*/
if (guestfs_set_event_callback (g, message_callback,
event_bitmask, 0, NULL) == -1)
exit (EXIT_FAILURE);
/* This is how debugging is enabled:
*
* Setting the 'trace' flag in the handle means that each libguestfs
* call is logged (name, parameters, return). This flag is useful
* to see how libguestfs is being used by a program.
*
* Setting the 'verbose' flag enables a great deal of extra
* debugging throughout the system. This is useful if there is a
* libguestfs error which you don't understand.
*
* Note that you should set the flags early on after creating the
* handle. In particular if you set the verbose flag after launch
* then you won't see all messages.
*
* For more information see:
* http://libguestfs.org/guestfs-faq.1.html#debugging-libguestfs
*
* Error messages raised by APIs are *not* debugging information,
* and they are not affected by any of this. You may have to log
* them separately.
*/
guestfs_set_trace (g, 1);
guestfs_set_verbose (g, 1);
/* Do some operations which will generate plenty of trace and debug
* messages.
*/
if (guestfs_add_drive (g, "/dev/null") == -1)
exit (EXIT_FAILURE);
printf ("There is no output from this program. "
"Take a look in your system log file,
"
"eg. /var/log/messages.
");
if (guestfs_launch (g) == -1)
exit (EXIT_FAILURE);
guestfs_close (g);
exit (EXIT_SUCCESS);
}
/* This function is called back by libguestfs whenever a trace or
* debug message is generated.
*
* For the classes of events we have registered above, 'array' and
* 'array_len' will not be meaningful. Only 'buf' and 'buf_len' will
* be interesting and these will contain the trace or debug message.
*
* This example simply redirects these messages to syslog, but
* obviously you could do something more advanced here.
*/
static void
message_callback (guestfs_h *g, void *opaque,
uint64_t event, int event_handle,
int flags,
const char *buf, size_t buf_len,
const uint64_t *array, size_t array_len)
{
const int priority = LOG_USER|LOG_INFO;
char *event_name, *msg;
if (buf_len > 0) {
event_name = guestfs_event_to_string (event);
msg = strndup (buf, buf_len);
syslog (priority, "[%s] %s", event_name, msg);
free (msg);
free (event_name);
}
}
EXAMPLE
: DISPLAY THE OPERATING SYSTEM ICON OF A GUEST
/* This example inspects a guest using libguestfs inspection (see
* "INSPECTION" in guestfs(3)), and if possible displays a
* representative icon or logo for the guest's operating system.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <guestfs.h>
static int
compare_keys_len (const void *p1, const void *p2)
{
const char *key1 = * (char * const *) p1;
const char *key2 = * (char * const *) p2;
return strlen (key1) - strlen (key2);
}
static size_t
count_strings (char *const *argv)
{
size_t c;
for (c = 0; argv[c]; ++c)
;
return c;
}
int
main (int argc, char *argv[])
{
guestfs_h *g;
const char *disk;
char **roots, *root, **mountpoints, *icon;
size_t i, j, icon_size;
FILE *fp;
if (argc != 2) {
fprintf (stderr, "usage: display-icon disk.img
");
exit (EXIT_FAILURE);
}
disk = argv[1];
g = guestfs_create ();
if (g == NULL) {
perror ("failed to create libguestfs handle");
exit (EXIT_FAILURE);
}
/* Attach the disk image read-only to libguestfs. */
if (guestfs_add_drive_opts (g, disk,
/* GUESTFS_ADD_DRIVE_OPTS_FORMAT, "raw", */
GUESTFS_ADD_DRIVE_OPTS_READONLY, 1,
-1) /* this marks end of optional arguments */
== -1)
exit (EXIT_FAILURE);
/* Run the libguestfs back-end. */
if (guestfs_launch (g) == -1)
exit (EXIT_FAILURE);
/* Ask libguestfs to inspect for operating systems. */
roots = guestfs_inspect_os (g);
if (roots == NULL)
exit (EXIT_FAILURE);
if (roots[0] == NULL) {
fprintf (stderr, "display-icon: no operating systems found
");
exit (EXIT_FAILURE);
}
for (j = 0; roots[j] != NULL; ++j) {
root = roots[j];
/* Mount up the disks, like guestfish -i.
*
* Sort keys by length, shortest first, so that we end up
* mounting the filesystems in the correct order.
*/
mountpoints = guestfs_inspect_get_mountpoints (g, root);
if (mountpoints == NULL)
exit (EXIT_FAILURE);
qsort (mountpoints, count_strings (mountpoints) / 2, 2 * sizeof (char *),
compare_keys_len);
for (i = 0; mountpoints[i] != NULL; i += 2) {
/* Ignore failures from this call, since bogus entries can
* appear in the guest's /etc/fstab.
*/
guestfs_mount_ro (g, mountpoints[i+1], mountpoints[i]);
free (mountpoints[i]);
free (mountpoints[i+1]);
}
free (mountpoints);
/* Get the icon.
* This function returns a buffer ('icon'). Normally it is a png
* file, returned as a string, but it can also be a zero length
* buffer which has a special meaning, or NULL which means there
* was an error.
*/
icon = guestfs_inspect_get_icon (g, root, &icon_size, -1);
if (!icon) /* actual libguestfs error */
exit (EXIT_FAILURE);
if (icon_size == 0) /* no icon available */
fprintf (stderr, "%s: %s: no icon available for this operating system
",
disk, root);
else {
/* Display the icon. */
fp = popen ("display -", "w");
if (fp == NULL) {
perror ("display");
exit (EXIT_FAILURE);
}
if (fwrite (icon, 1, icon_size, fp) != icon_size) {
perror ("write");
exit (EXIT_FAILURE);
}
if (pclose (fp) == -1) {
perror ("pclose");
exit (EXIT_FAILURE);
}
}
free (icon);
/* Unmount everything. */
if (guestfs_umount_all (g) == -1)
exit (EXIT_FAILURE);
free (root);
}
free (roots);
guestfs_close (g);
exit (EXIT_SUCCESS);
}
EXAMPLE
: THE LIBVIRT AUTHENTICATION API
/* Example of using the libvirt authentication event-driven API.
*
* See "LIBVIRT AUTHENTICATION" in guestfs(3).
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <guestfs.h>
static void
usage (void)
{
fprintf (stderr,
"Usage:
"
"
"
" libvirt-auth URI domain
"
"
"
"where:
"
"
"
" URI is the libvirt URI, eg. qemu+libssh2://USER@localhost/system
"
" domain is the name of the guest
"
"
"
"Example:
"
"
"
" libvirt-auth 'qemu+libssh2://USER@localhost/system' 'foo'
"
"
"
"would connect (read-only) to libvirt URI given and open the guest
"
"called 'foo' and list some information about its filesystems.
"
"
"
"The important point of this example is that any libvirt authentication
"
"required to connect to the server should be done.
"
"
");
}
static void auth_callback (guestfs_h *g, void *opaque, uint64_t event, int event_handle, int flags, const char *buf, size_t buf_len, const uint64_t *array, size_t array_len);
int
main (int argc, char *argv[])
{
const char *uri, *dom;
guestfs_h *g;
const char *creds[] = { "authname", "passphrase",
"echoprompt", "noechoprompt", NULL };
int r, eh;
char **filesystems;
size_t i;
if (argc != 3) {
usage ();
exit (EXIT_FAILURE);
}
uri = argv[1];
dom = argv[2];
g = guestfs_create ();
if (!g)
exit (EXIT_FAILURE);
r = guestfs_set_libvirt_supported_credentials (g, (char **) creds);
if (r == -1)
exit (EXIT_FAILURE);
/* Set up the event handler. */
eh = guestfs_set_event_callback (g, auth_callback,
GUESTFS_EVENT_LIBVIRT_AUTH, 0, NULL);
if (eh == -1)
exit (EXIT_FAILURE);
/* Add the named domain. */
r = guestfs_add_domain (g, dom,
GUESTFS_ADD_DOMAIN_LIBVIRTURI, uri,
-1);
if (r == -1)
exit (EXIT_FAILURE);
/* Launch and do some simple inspection. */
r = guestfs_launch (g);
if (r == -1)
exit (EXIT_FAILURE);
filesystems = guestfs_list_filesystems (g);
for (i = 0; filesystems[i] != NULL; i += 2) {
printf ("%s:%s is a %s filesystem
",
dom, filesystems[i], filesystems[i+1]);
free (filesystems[i]);
free (filesystems[i+1]);
}
free (filesystems);
exit (EXIT_SUCCESS);
}
static void
auth_callback (guestfs_h *g,
void *opaque,
uint64_t event,
int event_handle,
int flags,
const char *buf, size_t buf_len,
const uint64_t *array, size_t array_len)
{
char **creds;
size_t i;
char *prompt;
char *reply = NULL;
size_t allocsize;
char *pass;
ssize_t len;
int r;
printf ("libvirt-auth.c: authentication required for libvirt URI '%s'
",
buf);
/* Ask libguestfs what credentials libvirt is demanding. */
creds = guestfs_get_libvirt_requested_credentials (g);
if (creds == NULL)
exit (EXIT_FAILURE);
/* Now ask the user for answers. */
for (i = 0; creds[i] != NULL; ++i)
{
printf ("libvirt-auth.c: credential '%s'
", creds[i]);
if (strcmp (creds[i], "authname") == 0 ||
strcmp (creds[i], "echoprompt") == 0) {
prompt = guestfs_get_libvirt_requested_credential_prompt (g, i);
if (prompt && strcmp (prompt, "") != 0)
printf ("%s: ", prompt);
free (prompt);
len = getline (&reply, &allocsize, stdin);
if (len == -1) {
perror ("getline");
exit (EXIT_FAILURE);
}
if (len > 0 && reply[len-1] == '
')
reply[--len] = '