Tag Archives: jruby

Tip: Call libguestfs from JRuby

You can call libguestfs from JRuby.

JRuby only recently got support for Ruby C extensions, and support is currently quite wobbly. This excellent blog post summarizes the situation.

There are two ways to get access to libguestfs from JRuby. One way would be via the usual Ruby C extension, but as I said above, that’s wobbly and in fact does not work. The second way, which is what we’ll use, is to use the native Java module for libguestfs.

One thing to note is that the Ruby extension and the Java-via-Ruby extension are similar but not quite the same. In fact I found you can copy and paste most Ruby libguestfs code directly, and have it run, but some things need alteration.

Here is the example JRuby libguestfs program:

include Java

Dir["/usr/share/java/libguestfs-*.jar"].each { |jar| require jar }

guestfs = com.redhat.et.libguestfs

g = guestfs.GuestFS().new
version = g.version

printf("libguestfs %d.%d.%d%s\n",
       version.major, version.minor, version.release, version.extra)

# Create an empty, raw format 500 MB disk.
File.open("test.img", "w") {
  |f| f.seek(500*1024*1024); f.write("")
}

# Note that the key must be a string ("format") and
# not an atom (:format).
optargs = java.util.HashMap.new( {"format" => "raw"} )
g.add_drive_opts("test.img", optargs)
g.launch()

g.pvcreate("/dev/sda")
g.vgcreate("VG", ["/dev/sda"]);
g.lvcreate("LV1", "VG", 200);
g.lvcreate("LV2", "VG", 200);

puts "Created test.img"
puts "Now try running: virt-filesystems -a test.img --all --long -h"

You can run it by saving the above to test.rb, and then doing (on Fedora Rawhide or upcoming Fedora 16):

# yum install jruby libguestfs-java-devel
$ jruby test.rb

1 Comment

Filed under Uncategorized