Created
May 24, 2021 15:42
-
-
Save mjudeikis/aaab32354b6662208c09e4e870dcd834 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package mount | |
import ( | |
"fmt" | |
"os" | |
"path/filepath" | |
"syscall" | |
diskfs "github.com/diskfs/go-diskfs" | |
"github.com/diskfs/go-diskfs/partition/mbr" | |
"go.uber.org/zap" | |
) | |
type Mount interface { | |
Mount() error | |
} | |
type Mounter struct { | |
log *zap.Logger | |
mountDir string | |
mountFile string | |
} | |
func New(log *zap.Logger, mountDir, mountFile string) (*Mounter, error) { | |
for _, file := range []string{mountDir, mountFile} { | |
if _, err := os.Stat(file); os.IsNotExist(err) { | |
return nil, err | |
} | |
} | |
b := &Mounter{ | |
log: log, | |
mountDir: mountDir, | |
mountFile: mountFile, | |
} | |
return b, nil | |
} | |
func (m *Mounter) Mount() error { | |
disk, err := diskfs.Open(m.mountFile) | |
if err != nil { | |
return err | |
} | |
var offset uint32 | |
var blockSize int | |
// OFFSET=$((`fdisk -lu $IMAGE 2> /dev/null | grep -P "2\s+\**\s+[0-9]+\s+[0-9]+\s+[0-9]+\s+[0-9]+" | sed 's/\*//g' | awk '{print $2}'`)) | |
// BLOCK=$((`fdisk -lu $IMAGE 2> /dev/null | grep "^Units" | awk -F"= " '{print $2}' | awk '{print $1}'`)) | |
//spew.Dump(disk.Table.(*mbr.Table).Partitions) | |
table := disk.Table.(*mbr.Table) | |
blockSize = table.PhysicalSectorSize | |
for _, partition := range table.Partitions { | |
if !partition.Bootable && partition.Type == mbr.Linux { | |
offset = partition.Start | |
} | |
} | |
fullOffset := offset * uint32(blockSize) | |
dst := filepath.Join(m.mountDir, "/mnt") | |
err = os.MkdirAll(dst, os.ModePerm) | |
if err != nil { | |
return err | |
} | |
// sudo mount -o loop,rw,sync,offset=$(($OFFSET * $BLOCK)) $IMAGE $TMP | |
opts := fmt.Sprintf("rw,sync,offset=%d", fullOffset) | |
if err := syscall.Mount(m.mountFile, dst, "", syscall.MS_BIND, opts); err != nil { | |
m.log.Error("Failed to bind mount subdir", zap.String("mountFile", m.mountFile), zap.String("dst", dst)) | |
return err | |
} | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment