forked from juju/juju
/
managedfs.go
402 lines (366 loc) · 12.2 KB
/
managedfs.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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
// Copyright 2015 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package provider
import (
"bufio"
"io/ioutil"
"os"
"path"
"path/filepath"
"strings"
"unicode"
"github.com/juju/errors"
"gopkg.in/juju/names.v2"
"github.com/juju/juju/environs/context"
"github.com/juju/juju/storage"
)
const (
// defaultFilesystemType is the default filesystem type
// to create for volume-backed managed filesystems.
defaultFilesystemType = "ext4"
)
// managedFilesystemSource is an implementation of storage.FilesystemSource
// that manages filesystems on volumes attached to the host machine.
//
// managedFilesystemSource is expected to be called from a single goroutine.
type managedFilesystemSource struct {
run runCommandFunc
dirFuncs dirFuncs
volumeBlockDevices map[names.VolumeTag]storage.BlockDevice
filesystems map[names.FilesystemTag]storage.Filesystem
}
// NewManagedFilesystemSource returns a storage.FilesystemSource that manages
// filesystems on block devices on the host machine.
//
// The parameters are maps that the caller will update with information about
// block devices and filesystems created by the source. The caller must not
// update the maps during calls to the source's methods.
func NewManagedFilesystemSource(
volumeBlockDevices map[names.VolumeTag]storage.BlockDevice,
filesystems map[names.FilesystemTag]storage.Filesystem,
) storage.FilesystemSource {
return &managedFilesystemSource{
logAndExec,
&osDirFuncs{logAndExec},
volumeBlockDevices, filesystems,
}
}
// ValidateFilesystemParams is defined on storage.FilesystemSource.
func (s *managedFilesystemSource) ValidateFilesystemParams(arg storage.FilesystemParams) error {
// NOTE(axw) the parameters may be for destroying a filesystem, which
// may be called when the backing volume is detached from the machine.
// We must not perform any validation here that would fail if the
// volume is detached.
return nil
}
func (s *managedFilesystemSource) backingVolumeBlockDevice(v names.VolumeTag) (storage.BlockDevice, error) {
blockDevice, ok := s.volumeBlockDevices[v]
if !ok {
return storage.BlockDevice{}, errors.Errorf(
"backing-volume %s is not yet attached", v.Id(),
)
}
return blockDevice, nil
}
// CreateFilesystems is defined on storage.FilesystemSource.
func (s *managedFilesystemSource) CreateFilesystems(ctx context.ProviderCallContext, args []storage.FilesystemParams) ([]storage.CreateFilesystemsResult, error) {
results := make([]storage.CreateFilesystemsResult, len(args))
for i, arg := range args {
filesystem, err := s.createFilesystem(arg)
if err != nil {
results[i].Error = err
continue
}
results[i].Filesystem = filesystem
}
return results, nil
}
func (s *managedFilesystemSource) createFilesystem(arg storage.FilesystemParams) (*storage.Filesystem, error) {
blockDevice, err := s.backingVolumeBlockDevice(arg.Volume)
if err != nil {
return nil, errors.Trace(err)
}
devicePath := devicePath(blockDevice)
if isDiskDevice(devicePath) {
if err := destroyPartitions(s.run, devicePath); err != nil {
return nil, errors.Trace(err)
}
if err := createPartition(s.run, devicePath); err != nil {
return nil, errors.Trace(err)
}
devicePath = partitionDevicePath(devicePath)
}
if err := createFilesystem(s.run, devicePath); err != nil {
return nil, errors.Trace(err)
}
return &storage.Filesystem{
arg.Tag,
arg.Volume,
storage.FilesystemInfo{
arg.Tag.String(),
blockDevice.Size,
},
}, nil
}
// DestroyFilesystems is defined on storage.FilesystemSource.
func (s *managedFilesystemSource) DestroyFilesystems(ctx context.ProviderCallContext, filesystemIds []string) ([]error, error) {
// DestroyFilesystems is a no-op; there is nothing to destroy,
// since the filesystem is just data on a volume. The volume
// is destroyed separately.
return make([]error, len(filesystemIds)), nil
}
// ReleaseFilesystems is defined on storage.FilesystemSource.
func (s *managedFilesystemSource) ReleaseFilesystems(ctx context.ProviderCallContext, filesystemIds []string) ([]error, error) {
return make([]error, len(filesystemIds)), nil
}
// AttachFilesystems is defined on storage.FilesystemSource.
func (s *managedFilesystemSource) AttachFilesystems(ctx context.ProviderCallContext, args []storage.FilesystemAttachmentParams) ([]storage.AttachFilesystemsResult, error) {
results := make([]storage.AttachFilesystemsResult, len(args))
for i, arg := range args {
attachment, err := s.attachFilesystem(arg)
if err != nil {
results[i].Error = err
continue
}
results[i].FilesystemAttachment = attachment
}
return results, nil
}
func (s *managedFilesystemSource) attachFilesystem(arg storage.FilesystemAttachmentParams) (*storage.FilesystemAttachment, error) {
filesystem, ok := s.filesystems[arg.Filesystem]
if !ok {
return nil, errors.Errorf("filesystem %v is not yet provisioned", arg.Filesystem.Id())
}
blockDevice, err := s.backingVolumeBlockDevice(filesystem.Volume)
if err != nil {
return nil, errors.Trace(err)
}
devicePath := devicePath(blockDevice)
if isDiskDevice(devicePath) {
devicePath = partitionDevicePath(devicePath)
}
if err := mountFilesystem(s.run, s.dirFuncs, devicePath, arg.Path, arg.ReadOnly); err != nil {
return nil, errors.Trace(err)
}
return &storage.FilesystemAttachment{
arg.Filesystem,
arg.Machine,
storage.FilesystemAttachmentInfo{
arg.Path,
arg.ReadOnly,
},
}, nil
}
// DetachFilesystems is defined on storage.FilesystemSource.
func (s *managedFilesystemSource) DetachFilesystems(ctx context.ProviderCallContext, args []storage.FilesystemAttachmentParams) ([]error, error) {
results := make([]error, len(args))
for i, arg := range args {
if err := maybeUnmount(s.run, s.dirFuncs, arg.Path); err != nil {
results[i] = err
}
}
return results, nil
}
func destroyPartitions(run runCommandFunc, devicePath string) error {
logger.Debugf("destroying partitions on %q", devicePath)
if _, err := run("sgdisk", "--zap-all", devicePath); err != nil {
return errors.Annotate(err, "sgdisk failed")
}
return nil
}
// createPartition creates a single partition (1) on the disk with the
// specified device path.
func createPartition(run runCommandFunc, devicePath string) error {
logger.Debugf("creating partition on %q", devicePath)
if _, err := run("sgdisk", "-n", "1:0:-1", devicePath); err != nil {
return errors.Annotate(err, "sgdisk failed")
}
return nil
}
func createFilesystem(run runCommandFunc, devicePath string) error {
logger.Debugf("attempting to create filesystem on %q", devicePath)
mkfscmd := "mkfs." + defaultFilesystemType
_, err := run(mkfscmd, devicePath)
if err != nil {
return errors.Annotatef(err, "%s failed", mkfscmd)
}
logger.Infof("created filesystem on %q", devicePath)
return nil
}
func mountFilesystem(run runCommandFunc, dirFuncs dirFuncs, devicePath, mountPoint string, readOnly bool) error {
logger.Debugf("attempting to mount filesystem on %q at %q", devicePath, mountPoint)
if err := dirFuncs.mkDirAll(mountPoint, 0755); err != nil {
return errors.Annotate(err, "creating mount point")
}
mounted, mountSource, err := isMounted(dirFuncs, mountPoint)
if err != nil {
return errors.Trace(err)
}
if mounted {
logger.Debugf("filesystem on %q already mounted at %q", mountSource, mountPoint)
return nil
}
var args []string
if readOnly {
args = append(args, "-o", "ro")
}
args = append(args, devicePath, mountPoint)
if _, err := run("mount", args...); err != nil {
return errors.Annotate(err, "mount failed")
}
logger.Infof("mounted filesystem on %q at %q", devicePath, mountPoint)
// Look for the mtab entry resulting from the mount and copy it to fstab.
// This ensures the mount is available available after a reboot.
etcDir := dirFuncs.etcDir()
mtabEntry, err := extractMtabEntry(etcDir, devicePath, mountPoint)
if err != nil {
return errors.Annotate(err, "parsing /etc/mtab")
}
if mtabEntry == "" {
return nil
}
return addFstabEntry(etcDir, devicePath, mountPoint, mtabEntry)
}
// extractMtabEntry returns any /etc/mtab entry for the specified
// device path and mount point, or "" if none exists.
func extractMtabEntry(etcDir string, devicePath, mountPoint string) (string, error) {
f, err := os.Open(filepath.Join(etcDir, "mtab"))
if os.IsNotExist(err) {
return "", nil
}
if err != nil {
return "", errors.Trace(err)
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := scanner.Text()
fields := strings.Fields(line)
if len(fields) >= 2 && fields[0] == devicePath && fields[1] == mountPoint {
return line, nil
}
}
if err := scanner.Err(); err != nil {
return "", errors.Trace(err)
}
return "", nil
}
// addFstabEntry creates an entry in /etc/fstab for the specified
// device path and mount point so long as there's no existing entry already.
func addFstabEntry(etcDir string, devicePath, mountPoint, entry string) error {
f, err := os.OpenFile(filepath.Join(etcDir, "fstab"), os.O_CREATE|os.O_APPEND|os.O_RDWR, 0644)
if err != nil {
return errors.Annotate(err, "opening /etc/fstab")
}
defer f.Close()
// Ensure there's no entry there already
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := scanner.Text()
fields := strings.Fields(line)
if len(fields) >= 2 && fields[0] == devicePath && fields[1] == mountPoint {
return nil
}
}
if err := scanner.Err(); err != nil {
return errors.Trace(err)
}
// The entry will be written at the end of the fstab file.
if _, err = f.WriteString("\n" + entry + "\n"); err != nil {
return errors.Annotate(err, "writing /etc/fstab")
}
return nil
}
func maybeUnmount(run runCommandFunc, dirFuncs dirFuncs, mountPoint string) error {
mounted, _, err := isMounted(dirFuncs, mountPoint)
if err != nil {
return errors.Trace(err)
}
if !mounted {
return nil
}
logger.Debugf("attempting to unmount filesystem at %q", mountPoint)
if err := removeFstabEntry(dirFuncs.etcDir(), mountPoint); err != nil {
return errors.Annotate(err, "updating /etc/fstab failed")
}
if _, err := run("umount", mountPoint); err != nil {
return errors.Annotate(err, "umount failed")
}
logger.Infof("unmounted filesystem at %q", mountPoint)
return nil
}
// removeFstabEntry removes any existing /etc/fstab entry for
// the specified mount point.
func removeFstabEntry(etcDir string, mountPoint string) error {
fstab := filepath.Join(etcDir, "fstab")
f, err := os.Open(fstab)
if os.IsNotExist(err) {
return nil
}
if err != nil {
return errors.Trace(err)
}
defer f.Close()
scanner := bufio.NewScanner(f)
// Use a tempfile in /etc and rename when done.
newFsTab, err := ioutil.TempFile(etcDir, "juju-fstab-")
if err != nil {
return errors.Trace(err)
}
defer func() {
newFsTab.Close()
os.Remove(newFsTab.Name())
}()
if err := os.Chmod(newFsTab.Name(), 0644); err != nil {
return errors.Trace(err)
}
for scanner.Scan() {
line := scanner.Text()
fields := strings.Fields(line)
if len(fields) < 2 || fields[1] != mountPoint {
_, err := newFsTab.WriteString(line + "\n")
if err != nil {
return errors.Trace(err)
}
}
}
if err := scanner.Err(); err != nil {
return errors.Trace(err)
}
return os.Rename(newFsTab.Name(), fstab)
}
func isMounted(dirFuncs dirFuncs, mountPoint string) (bool, string, error) {
mountPointParent := filepath.Dir(mountPoint)
parentSource, err := dirFuncs.mountPointSource(mountPointParent)
if err != nil {
return false, "", errors.Trace(err)
}
source, err := dirFuncs.mountPointSource(mountPoint)
if err != nil {
return false, "", errors.Trace(err)
}
if source != parentSource {
// Already mounted.
return true, source, nil
}
return false, "", nil
}
// devicePath returns the device path for the given block device.
func devicePath(dev storage.BlockDevice) string {
return path.Join("/dev", dev.DeviceName)
}
// partitionDevicePath returns the device path for the first (and only)
// partition of the disk with the specified device path.
func partitionDevicePath(devicePath string) string {
return devicePath + "1"
}
// isDiskDevice reports whether or not the device is a full disk, as opposed
// to a partition or a loop device. We create a partition on disks to contain
// filesystems.
func isDiskDevice(devicePath string) bool {
var last rune
for _, r := range devicePath {
last = r
}
return !unicode.IsDigit(last)
}