-
Notifications
You must be signed in to change notification settings - Fork 906
/
main_forkzfs.go
104 lines (82 loc) · 1.86 KB
/
main_forkzfs.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package main
import (
"bufio"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/spf13/cobra"
"golang.org/x/sys/unix"
"github.com/canonical/lxd/shared"
)
type cmdForkZFS struct {
global *cmdGlobal
}
func (c *cmdForkZFS) Command() *cobra.Command {
// Main subcommand
cmd := &cobra.Command{}
cmd.Use = "forkzfs [<arguments>...]"
cmd.Short = "Run ZFS inside a cleaned up mount namespace"
cmd.Long = `Description:
Run ZFS inside a cleaned up mount namespace
This internal command is used to run ZFS in some specific cases.
`
cmd.RunE = c.Run
cmd.Hidden = true
return cmd
}
func (c *cmdForkZFS) Run(cmd *cobra.Command, args []string) error {
// Quick checks.
if len(args) < 1 {
_ = cmd.Help()
if len(args) == 0 {
return nil
}
return fmt.Errorf("Missing required arguments")
}
// Only root should run this
if os.Geteuid() != 0 {
return fmt.Errorf("This must be run as root")
}
// Mark mount tree as private
err := unix.Mount("none", "/", "", unix.MS_REC|unix.MS_PRIVATE, "")
if err != nil {
return err
}
// Expand the mount path
absPath, err := filepath.Abs(shared.VarPath())
if err != nil {
return err
}
expPath, err := filepath.EvalSymlinks(absPath)
if err != nil {
expPath = absPath
}
// Find the source mount of the path
file, err := os.Open("/proc/self/mountinfo")
if err != nil {
return err
}
defer func() { _ = file.Close() }()
// Unmount all mounts under LXD directory
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
rows := strings.Fields(line)
if !strings.HasPrefix(rows[4], expPath) {
continue
}
_ = unix.Unmount(rows[4], unix.MNT_DETACH)
}
// Run the ZFS command
command := exec.Command("zfs", args...)
command.Stdin = os.Stdin
command.Stdout = os.Stdout
command.Stderr = os.Stderr
err = command.Run()
if err != nil {
return err
}
return nil
}