-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathnfs.go
113 lines (93 loc) · 2.38 KB
/
nfs.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
105
106
107
108
109
110
111
112
113
package main
import (
"fmt"
"io/ioutil"
"os"
"os/exec"
"regexp"
"strings"
)
func ensureNFS(home string) error {
addr, err := getNetAddress()
if err != nil {
return err
}
mask, _ := getNetMask()
export := fmt.Sprintf("%s -network %s -mask %s -alldirs -maproot=root:wheel", home, addr, mask)
if _, err = os.Stat("/etc/exports"); os.IsNotExist(err) {
err := ioutil.WriteFile("/etc/exports", []byte(""), 0644)
if err != nil {
return err
}
}
rawExports, err := ioutil.ReadFile("/etc/exports")
if err != nil {
return err
}
needsExport := true
for _, line := range strings.Split(string(rawExports), "\n") {
if strings.HasPrefix(line, export) {
needsExport = false
break
}
}
if needsExport {
file, err := os.OpenFile("/etc/exports", os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
return err
}
defer file.Close()
_, err = file.WriteString(export + "\n")
if err != nil {
return err
}
}
output, err := exec.Command("nfsd", "checkexports").Output()
if err != nil {
return fmt.Errorf("There was a problem updating the /etc/exports file, please resolve the issue and run 'sudo nfsd restart'\n%s", string(output))
}
output, _ = exec.Command("nfsd", "status").Output()
enabled := false
running := false
for _, line := range strings.Split(string(output), "\n") {
if strings.Contains(line, "is enabled") {
enabled = true
} else if strings.Contains(line, "is running") {
running = true
}
}
if !enabled {
output, err = exec.Command("nfsd", "enable").Output()
} else if !running {
output, err = exec.Command("nfsd", "start").Output()
} else {
output, err = exec.Command("nfsd", "restart").Output()
}
if err != nil {
return fmt.Errorf(string(output))
}
return nil
}
func removeNFS(home string) error {
addr, err := getNetAddress()
if err != nil {
return err
}
mask, _ := getNetMask()
export := fmt.Sprintf("%s -network %s -mask %s -alldirs -maproot=root:wheel", home, addr, mask)
rawExports, err := ioutil.ReadFile("/etc/exports")
if err != nil {
return err
}
exportMatcher := regexp.MustCompile(fmt.Sprintf("(?m)^%s\n?$", export))
newExports := exportMatcher.ReplaceAllString(string(rawExports), "")
err = ioutil.WriteFile("/etc/exports", []byte(newExports), 0644)
if err != nil {
return err
}
output, err := exec.Command("nfsd", "restart").Output()
if err != nil {
return fmt.Errorf(string(output))
}
return nil
}