Tip: libguestfs API: Get the mounted device from a path

This useful libguestfs API tip shows you how to get the device name that contains a mounted path. You can use this if you want to find out the filesystem type of a path (eg. is this directory mounted on ext4?).

What you do is call guestfs_mountpoints which returns a hash of device name to mount point, eg:

/dev/sda1 -> /boot
/dev/sda2 -> /
/dev/sda3 -> /usr

Then compare the pathname (“/boot/grub”) to each entry in the hash. If the mountpoint is a string prefix of the path, give this entry a score which is the length of the mountpoint string. If it is not a prefix, give the entry a score 0. So:

/dev/sda1 -> /boot (score: 5)
/dev/sda2 -> / (score: 1)
/dev/sda3 -> /usr (score: 0)

Then sort the entries to pick the highest score. If the hash is empty or the highest score is 0, then return an error, otherwise return the device with the highest score.

Here is the code to implement this in OCaml:

open Printf
open ExtString
open ExtList

let get_mounted_device g path =
  let mps = g#mountpoints () in
  let mps = List.map (
    fun (dev, mp) ->
      if String.starts_with path mp then
        dev, String.length mp
        dev, 0
  ) mps in
  let cmp (_,n1) (_,n2) = compare n2 n1 in
  let mps = List.sort ~cmp mps in
  match mps with
  | [] ->
      invalid_arg (sprintf "%s: not mounted" path)
  | (_,0) :: _ ->
      invalid_arg (sprintf "%s: not found on any filesystem" path)
  | (dev,_) :: _ -> dev

To answer the question “is this directory mounted on ext4?” you would then call guestfs_vfs_type on the result of this, eg:

if g#vfs_type (get_mounted_device g "/boot/grub") = "ext4" then
  (* do something based on ext4 *)

Leave a comment

Filed under Uncategorized

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.