Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the file system type for syscall.Mount() programmatically

The function Linux syscall.Mount requires a file system type.

If you try to run it with the file system auto, like this:

func main(){
    if err := syscall.Mount("/dev/sda1", "/mnt1", "auto", 0, "w"); err != nil {
        log.Printf("Mount(\"%s\", \"%s\", \"auto\", 0, \"rw\")\n","/dev/sda1","/mnt1")
        log.Fatal(err)
    }
}

It will fail with no such device. It was already described here that Linux syscall.Mount just wraps mount(2), which doesn't itself support the concept of an "auto" fstype.

I know how to find it using bash:

root@ubuntu:~/go/src# blkid /dev/sda1
/dev/sda1: UUID="527c895c-864e-4f4c-8fba-460754181173" TYPE="ext4" PARTUUID="db5c2e63-01"

or

root@ubuntu:~/go/src# file -sL /dev/sda1
/dev/sda1: Linux rev 1.0 ext4 filesystem data, UUID=527c895c-864e-4f4c-8fba-460754181173 (needs journal recovery) (extents) (large files) (huge files)

In both cases you get the ext4 file system type.

Replacing auto with ext4 in Go will solve the problem, but what I am interested in is, how can I use Go to get the file system type of, for example, /dev/sda1?

Is there a function similar to blkid or file that can show the file system type of the device?

like image 512
E235 Avatar asked Jul 06 '20 15:07

E235


1 Answers

Did you try using the package blkid ? It seems to work out of the box as it internally implements the blkid shell command underneath (see blkid.go#L101). You can just get the key name for the map returned from the Blkid() function and reuse it in your API

package main

import (
    "fmt"
    blkid "github.com/LDCS/qslinux/blkid"
)

func main() {
    rmap := blkid.Blkid(false)
    var key string
    var result *blkid.Blkiddata

    for key, result = range rmap {
        fmt.Printf("Devname: %q\n", key)
    }

    fmt.Printf("Uuid_=%q\n", result.Uuid_)
    fmt.Printf("Uuidsub_=%q\n", result.Uuidsub_)
    fmt.Printf("Type_=%q\n", result.Type_)
    fmt.Printf("Label_=%q\n", result.Label_)
    fmt.Printf("Parttype_=%q\n", result.Parttype_)
    fmt.Printf("Partuuid_=%q\n", result.Partuuid_)
    fmt.Printf("Partlabel_ =%q\n", result.Partlabel_)
}

The Blkiddata struct contains all the information as with the default Linux version

type Blkiddata struct {
    Devname_   string
    Uuid_      string
    Uuidsub_   string
    Type_      string
    Label_     string
    Parttype_  string
    Partuuid_  string
    Partlabel_ string
}

Just get the module using

go get github.com/LDCS/qslinux/blkid

It also implements the other family of Linux utils namely - df, dmidecode, etcfstab, etchosts, etcservice, etcshadow, etcuser, hp, md, nmap, parted, scsi, smartctl and tgtd. See module github.com/LDCS/qslinux

like image 171
Inian Avatar answered Oct 27 '22 00:10

Inian