guestfs-ocaml(3) Virtualization Support guestfs-ocaml(3)

guestfs-ocaml - How to use libguestfs from OCaml

Module style:

let g = Guestfs.create () in
Guestfs.add_drive_opts g ~format:"raw" ~readonly:true "disk.img";
Guestfs.launch g;

Object-oriented style:

 let g = new Guestfs.guestfs () in
 g#add_drive_opts ~format:"raw" ~readonly:true "disk.img";
 g#launch ();
 ocamlfind opt prog.ml -package guestfs -linkpkg -o prog
or:
 ocamlopt -I +guestfs mlguestfs.cmxa prog.ml -o prog

This manual page documents how to call libguestfs from the OCaml programming language. This page just documents the differences from the C API and gives some examples. If you are not familiar with using libguestfs, you also need to read guestfs(3).

There are two different programming styles supported by the OCaml bindings. You can use a module style, with each C function mapped to an OCaml function:

int guestfs_set_verbose (guestfs_h *g, int flag);

becomes:

val Guestfs.set_verbose : Guestfs.t -> bool -> unit

Alternately you can use an object-oriented style, calling methods on the class "Guestfs.guestfs":

method set_verbose : bool -> unit

The object-oriented style is usually briefer, and the minor performance penalty isn't noticeable in the general overhead of performing libguestfs functions.

The handle is closed when it is reaped by the garbage collector. Because libguestfs handles include a lot of state, it is also possible to close (and hence free) them explicitly by calling "Guestfs.close" or the "#close" method.

Errors from libguestfs functions are mapped into the "Guestfs.Error" exception. This has a single parameter which is the error message (a string).

Calling any function/method on a closed handle raises "Guestfs.Handle_closed". The single parameter is the name of the function that you called.

(* Example showing how to create a disk image. *)

open Unix
open Printf

let output = "disk.img"

let () =
  let g = new Guestfs.guestfs () in

  (* Create a raw-format sparse disk image, 512 MB in size. *)
  g#disk_create output "raw" (Int64.of_int (512 * 1024 * 1024));

  (* Set the trace flag so that we can see each libguestfs call. *)
  g#set_trace true;

  (* Attach the disk image to libguestfs. *)
  g#add_drive_opts ~format:"raw" ~readonly:false output;

  (* Run the libguestfs back-end. *)
  g#launch ();

  (* Get the list of devices.  Because we only added one drive
   * above, we expect that this list should contain a single
   * element.
   *)
  let devices = g#list_devices () in
  if Array.length devices <> 1 then
    failwith "error: expected a single device from list-devices";

  (* Partition the disk as one single MBR partition. *)
  g#part_disk devices.(0) "mbr";

  (* Get the list of partitions.  We expect a single element, which
   * is the partition we have just created.
   *)
  let partitions = g#list_partitions () in
  if Array.length partitions <> 1 then
    failwith "error: expected a single partition from list-partitions";

  (* Create a filesystem on the partition. *)
  g#mkfs "ext4" partitions.(0);

  (* Now mount the filesystem so that we can add files. *)
  g#mount partitions.(0) "/";

  (* Create some files and directories. *)
  g#touch "/empty";
  let message = "Hello, world\n" in
  g#write "/hello" message;
  g#mkdir "/foo";

  (* This one uploads the local file /etc/resolv.conf into
   * the disk image.
   *)
  g#upload "/etc/resolv.conf" "/foo/resolv.conf";

  (* Because we wrote to the disk and we want to detect write
   * errors, call g#shutdown.  You don't need to do this:
   * g#close will do it implicitly.
   *)
  g#shutdown ();

  (* Note also that handles are automatically closed if they are
   * reaped by the garbage collector.  You only need to call close
   * if you want to close the handle right away.
   *)
  g#close ()

(* Example showing how to inspect a virtual machine disk. *)

open Printf

let disk =
  if Array.length Sys.argv = 2 then
    Sys.argv.(1)
  else
    failwith "usage: inspect_vm disk.img"

let () =
  let g = new Guestfs.guestfs () in

  (* Attach the disk image read-only to libguestfs. *)
  g#add_drive_opts (*~format:"raw"*) ~readonly:true disk;

  (* Run the libguestfs back-end. *)
  g#launch ();

  (* Ask libguestfs to inspect for operating systems. *)
  let roots = g#inspect_os () in
  if Array.length roots = 0 then
    failwith "inspect_vm: no operating systems found";

  Array.iter (
    fun root ->
      printf "Root device: %s\n" root;

      (* Print basic information about the operating system. *)
      printf "  Product name: %s\n" (g#inspect_get_product_name root);
      printf "  Version:      %d.%d\n"
        (g#inspect_get_major_version root)
        (g#inspect_get_minor_version root);
      printf "  Type:         %s\n" (g#inspect_get_type root);
      printf "  Distro:       %s\n" (g#inspect_get_distro root);

      (* 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.
       *)
      let mps = g#inspect_get_mountpoints root in
      let cmp (a,_) (b,_) =
        compare (String.length a) (String.length b) in
      let mps = List.sort cmp mps in
      List.iter (
        fun (mp, dev) ->
          try g#mount_ro dev mp
          with Guestfs.Error msg -> eprintf "%s (ignored)\n" msg
      ) mps;

      (* If /etc/issue.net file exists, print up to 3 lines. *)
      let filename = "/etc/issue.net" in
      if g#is_file filename then (
        printf "--- %s ---\n" filename;
        let lines = g#head_n 3 filename in
        Array.iter print_endline lines
      );

      (* Unmount everything. *)
      g#umount_all ()
  ) roots

(* Example showing how to enable debugging, and capture it into any
 * custom logging system.
 *)

(* Events we are interested in.  This bitmask covers all trace and
 * debug messages.
 *)
let event_bitmask = [
  Guestfs.EVENT_LIBRARY;
  Guestfs.EVENT_WARNING;
  Guestfs.EVENT_APPLIANCE;
  Guestfs.EVENT_TRACE
]

let rec main () =
  let g = new Guestfs.guestfs () in

  (* 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).
   *)
  ignore (g#set_event_callback message_callback event_bitmask);

  (* 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.
   *)
  g#set_trace true;
  g#set_verbose true;

  (* Do some operations which will generate plenty of trace and debug
   * messages.
   *)
  g#add_drive "/dev/null";
  g#launch ();
  g#close ()

(* 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.
 *)
and message_callback event event_handle buf array =
  if String.length buf > 0 then (
    let event_name = Guestfs.event_to_string [event] in
    Printf.printf "[%s] %S\n%!" event_name buf
  )

let () = main ()

guestfs(3), guestfs-examples(3), guestfs-erlang(3), guestfs-gobject(3), guestfs-golang(3), guestfs-java(3), guestfs-lua(3), guestfs-perl(3), guestfs-python(3), guestfs-recipes(1), guestfs-ruby(3), http://libguestfs.org/, http://caml.inria.fr/.

Richard W.M. Jones ("rjones at redhat dot com")

Copyright (C) 2010-2023 Red Hat Inc.

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

To get a list of bugs against libguestfs, use this link: https://bugzilla.redhat.com/buglist.cgi?component=libguestfs&product=Virtualization+Tools

To report a new bug against libguestfs, use this link: https://bugzilla.redhat.com/enter_bug.cgi?component=libguestfs&product=Virtualization+Tools

When reporting a bug, please supply:

  • The version of libguestfs.
  • Where you got libguestfs (eg. which Linux distro, compiled from source, etc)
  • Describe the bug accurately and give a way to reproduce it.
  • Run libguestfs-test-tool(1) and paste the complete, unedited output into the bug report.
2024-10-08 libguestfs-1.54.0