-
Notifications
You must be signed in to change notification settings - Fork 19
/
driver.go
287 lines (232 loc) · 8.08 KB
/
driver.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
package btrfs // import "code.cloudfoundry.org/grootfs/store/filesystems/btrfs"
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path"
"path/filepath"
"regexp"
"strconv"
"strings"
"github.com/tscolari/lagregator"
"code.cloudfoundry.org/grootfs/groot"
"code.cloudfoundry.org/grootfs/store"
"code.cloudfoundry.org/grootfs/store/filesystems"
"code.cloudfoundry.org/grootfs/store/image_cloner"
"code.cloudfoundry.org/lager"
errorspkg "github.com/pkg/errors"
)
const (
BaseFileSystemName = "btrfs"
)
type Driver struct {
draxBinPath string
btrfsBinPath string
storePath string
}
func NewDriver(btrfsBinPath, draxBinPath, storePath string) (*Driver, error) {
if err := filesystems.CheckFSPath(storePath, filesystems.BtrfsType, BaseFileSystemName); err != nil {
return nil, err
}
return &Driver{
btrfsBinPath: btrfsBinPath,
draxBinPath: draxBinPath,
storePath: storePath,
}, nil
}
func (d *Driver) VolumePath(logger lager.Logger, id string) (string, error) {
volPath := filepath.Join(d.storePath, store.VolumesDirName, id)
_, err := os.Stat(volPath)
if err == nil {
return volPath, nil
}
return "", errorspkg.Wrapf(err, "volume does not exist `%s`", id)
}
func (d *Driver) CreateVolume(logger lager.Logger, parentID, id string) (string, error) {
logger = logger.Session("btrfs-creating-volume", lager.Data{"parentID": parentID, "id": id})
logger.Info("start")
defer logger.Info("end")
var cmd *exec.Cmd
volPath := filepath.Join(d.storePath, store.VolumesDirName, id)
if parentID == "" {
cmd = exec.Command(d.btrfsBinPath, "subvolume", "create", volPath)
} else {
parentVolPath := filepath.Join(d.storePath, store.VolumesDirName, parentID)
cmd = exec.Command(d.btrfsBinPath, "subvolume", "snapshot", parentVolPath, volPath)
}
logger.Debug("starting-btrfs", lager.Data{"path": cmd.Path, "args": cmd.Args})
if contents, err := cmd.CombinedOutput(); err != nil {
return "", errorspkg.Wrapf(err, "creating btrfs volume `%s` %s", volPath, string(contents))
}
return volPath, nil
}
func (d *Driver) CreateImage(logger lager.Logger, spec image_cloner.ImageDriverSpec) error {
logger = logger.Session("btrfs-creating-snapshot", lager.Data{"spec": spec})
logger.Info("start")
defer logger.Info("end")
toPath := filepath.Join(spec.ImagePath, "rootfs")
baseVolumePath := filepath.Join(d.storePath, store.VolumesDirName, spec.BaseVolumeIDs[len(spec.BaseVolumeIDs)-1])
cmd := exec.Command(d.btrfsBinPath, "subvolume", "snapshot", baseVolumePath, toPath)
logger.Debug("starting-btrfs", lager.Data{"path": cmd.Path, "args": cmd.Args})
if contents, err := cmd.CombinedOutput(); err != nil {
return errorspkg.Errorf(
"creating btrfs snapshot from `%s` to `%s` (%s): %s",
baseVolumePath, toPath, err, string(contents),
)
}
return d.applyDiskLimit(logger, spec)
}
func (d *Driver) Volumes(logger lager.Logger) ([]string, error) {
volumes := []string{}
existingVolumes, err := ioutil.ReadDir(path.Join(d.storePath, store.VolumesDirName))
if err != nil {
return nil, errorspkg.Wrap(err, "failed to list volumes")
}
for _, volumeInfo := range existingVolumes {
volumes = append(volumes, volumeInfo.Name())
}
return volumes, nil
}
func (d *Driver) destroyQgroup(logger lager.Logger, path string) error {
if !d.draxInPath() {
logger.Info("drax-command-not-found", lager.Data{
"warning": "could not delete quota group",
})
return nil
}
if !d.hasSUID() {
return errorspkg.New("missing the setuid bit on drax")
}
cmd := exec.Command(d.draxBinPath, "--btrfs-bin", d.btrfsBinPath, "destroy", "--volume-path", path)
stdoutBuffer := bytes.NewBuffer([]byte{})
cmd.Stdout = stdoutBuffer
cmd.Stderr = lagregator.NewRelogger(logger)
logger.Debug("starting-drax", lager.Data{"path": cmd.Path, "args": cmd.Args})
err := cmd.Run()
if err != nil {
logger.Error("drax-failed", err)
return errorspkg.Wrapf(err, "destroying quota group %s", strings.TrimSpace(stdoutBuffer.String()))
}
return nil
}
func (d *Driver) DestroyVolume(logger lager.Logger, id string) error {
logger = logger.Session("btrfs-destroying-volume", lager.Data{"volumeID": id})
logger.Info("start")
defer logger.Info("end")
return d.destroyBtrfsVolume(logger, filepath.Join(d.storePath, "volumes", id))
}
func (d *Driver) DestroyImage(logger lager.Logger, imagePath string) error {
logger = logger.Session("btrfs-destroying-image", lager.Data{"imagePath": imagePath})
logger.Info("start")
defer logger.Info("end")
return d.destroyBtrfsVolume(logger, filepath.Join(imagePath, "rootfs"))
}
func (d *Driver) destroyBtrfsVolume(logger lager.Logger, path string) error {
logger = logger.Session("destroying-subvolume", lager.Data{"path": path})
logger.Info("start")
defer logger.Info("end")
if _, err := os.Stat(path); err != nil {
return errorspkg.Wrap(err, "image path not found")
}
if err := d.destroyQgroup(logger, path); err != nil {
logger.Error("destroying-quota-groups-failed", err)
}
cmd := exec.Command(d.btrfsBinPath, "subvolume", "delete", path)
logger.Debug("starting-btrfs", lager.Data{"path": cmd.Path, "args": cmd.Args})
if contents, err := cmd.CombinedOutput(); err != nil {
logger.Error("btrfs-failed", err)
return errorspkg.Wrapf(err, "destroying volume %s", strings.TrimSpace(string(contents)))
}
return nil
}
func (d *Driver) applyDiskLimit(logger lager.Logger, spec image_cloner.ImageDriverSpec) error {
logger = logger.Session("applying-quotas", lager.Data{"spec": spec})
logger.Info("start")
defer logger.Info("end")
if spec.DiskLimit == 0 {
logger.Debug("no-need-for-quotas")
return nil
}
if !d.draxInPath() {
return errorspkg.New("drax was not found in the $PATH")
}
if !d.hasSUID() {
return errorspkg.New("missing the setuid bit on drax")
}
args := []string{
"--btrfs-bin", d.btrfsBinPath,
"limit",
"--volume-path", filepath.Join(spec.ImagePath, "rootfs"),
"--disk-limit-bytes", strconv.FormatInt(spec.DiskLimit, 10),
}
if spec.ExclusiveDiskLimit {
args = append(args, "--exclude-image-from-quota")
}
cmd := exec.Command(d.draxBinPath, args...)
stdoutBuffer := bytes.NewBuffer([]byte{})
cmd.Stdout = stdoutBuffer
cmd.Stderr = lagregator.NewRelogger(logger)
logger.Debug("starting-drax", lager.Data{"path": cmd.Path, "args": cmd.Args})
err := cmd.Run()
if err != nil {
logger.Error("drax-failed", err)
return errorspkg.Wrapf(err, " %s", strings.TrimSpace(stdoutBuffer.String()))
}
return nil
}
func (d *Driver) FetchStats(logger lager.Logger, imagePath string) (groot.VolumeStats, error) {
logger = logger.Session("btrfs-fetching-stats", lager.Data{"imagePath": imagePath})
logger.Info("start")
defer logger.Info("end")
if !d.draxInPath() {
return groot.VolumeStats{}, errorspkg.New("drax was not found in the $PATH")
}
if !d.hasSUID() {
return groot.VolumeStats{}, errorspkg.New("missing the setuid bit on drax")
}
args := []string{
"--btrfs-bin", d.btrfsBinPath,
"stats",
"--volume-path", filepath.Join(imagePath, "rootfs"),
"--force-sync",
}
cmd := exec.Command(d.draxBinPath, args...)
stdoutBuffer := bytes.NewBuffer([]byte{})
cmd.Stdout = stdoutBuffer
cmd.Stderr = lagregator.NewRelogger(logger)
err := cmd.Run()
if err != nil {
logger.Error("drax-failed", err)
return groot.VolumeStats{}, errorspkg.Wrapf(err, "%s", strings.TrimSpace(stdoutBuffer.String()))
}
usageRegexp := regexp.MustCompile(`.*\s+(\d+)\s+(\d+)$`)
usage := usageRegexp.FindStringSubmatch(strings.TrimSpace(stdoutBuffer.String()))
var stats groot.VolumeStats
if len(usage) != 3 {
logger.Error("parsing-stats-failed", errorspkg.Errorf("raw stats: %s", stdoutBuffer.String()))
return stats, errorspkg.New("could not parse stats")
}
fmt.Sscanf(usage[1], "%d", &stats.DiskUsage.TotalBytesUsed)
fmt.Sscanf(usage[2], "%d", &stats.DiskUsage.ExclusiveBytesUsed)
return stats, nil
}
func (d *Driver) draxInPath() bool {
if _, err := exec.LookPath(d.draxBinPath); err != nil {
return false
}
return true
}
func (d *Driver) hasSUID() bool {
path, err := exec.LookPath(d.draxBinPath)
if err != nil {
return false
}
// If LookPath succeeds Stat cannot fail
draxInfo, _ := os.Stat(path)
if (draxInfo.Mode() & os.ModeSetuid) == 0 {
return false
}
return true
}