-
Notifications
You must be signed in to change notification settings - Fork 3
/
volume_driver.go
486 lines (391 loc) · 15 KB
/
volume_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
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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
package volumedriver
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"time"
"code.cloudfoundry.org/dockerdriver"
"code.cloudfoundry.org/dockerdriver/driverhttp"
"code.cloudfoundry.org/goshims/filepathshim"
"code.cloudfoundry.org/goshims/osshim"
"code.cloudfoundry.org/goshims/timeshim"
"code.cloudfoundry.org/lager/v3"
"code.cloudfoundry.org/volumedriver/internal/syncmap"
"code.cloudfoundry.org/volumedriver/mountchecker"
)
type NfsVolumeInfo struct {
Opts map[string]interface{} `json:"-"` // don't store opts
dockerdriver.VolumeInfo // see dockerdriver.resources.go
}
type OsHelper interface {
Umask(mask int) (oldmask int)
}
type VolumeDriver struct {
volumes *syncmap.SyncMap[NfsVolumeInfo]
os osshim.Os
filepath filepathshim.Filepath
time timeshim.Time
mountChecker mountchecker.MountChecker
mountPathRoot string
mounter Mounter
osHelper OsHelper
}
func NewVolumeDriver(logger lager.Logger, os osshim.Os, filepath filepathshim.Filepath, time timeshim.Time, mountChecker mountchecker.MountChecker, mountPathRoot string, mounter Mounter, oshelper OsHelper) *VolumeDriver {
d := &VolumeDriver{
volumes: syncmap.New[NfsVolumeInfo](),
os: os,
filepath: filepath,
time: time,
mountChecker: mountChecker,
mountPathRoot: mountPathRoot,
mounter: mounter,
osHelper: oshelper,
}
ctx := context.TODO()
env := driverhttp.NewHttpDriverEnv(logger, ctx)
d.restoreState(env)
return d
}
func (d *VolumeDriver) Activate(env dockerdriver.Env) dockerdriver.ActivateResponse {
return dockerdriver.ActivateResponse{
Implements: []string{"VolumeDriver"},
}
}
func (d *VolumeDriver) Create(env dockerdriver.Env, createRequest dockerdriver.CreateRequest) dockerdriver.ErrorResponse {
logger := env.Logger().Session("create")
logger.Info("start")
defer logger.Info("end")
if createRequest.Name == "" {
return dockerdriver.ErrorResponse{Err: "Missing mandatory 'volume_name'"}
}
var ok bool
if _, ok = createRequest.Opts["source"].(string); !ok {
logger.Info("mount-config-missing-source", lager.Data{"volume_name": createRequest.Name})
return dockerdriver.ErrorResponse{Err: `Missing mandatory 'source' field in 'Opts'`}
}
existing, err := d.getVolume(driverhttp.EnvWithLogger(logger, env), createRequest.Name)
if err != nil {
logger.Info("creating-volume", lager.Data{"volume_name": createRequest.Name})
logger.Info("with-opts", lager.Data{"opts": createRequest.Opts})
volInfo := NfsVolumeInfo{
VolumeInfo: dockerdriver.VolumeInfo{Name: createRequest.Name},
Opts: createRequest.Opts,
}
d.volumes.Put(createRequest.Name, volInfo)
} else {
existing.Opts = createRequest.Opts
d.volumes.Put(createRequest.Name, existing)
}
err = d.persistState(driverhttp.EnvWithLogger(logger, env))
if err != nil {
logger.Error("persist-state-failed", err)
return dockerdriver.ErrorResponse{Err: fmt.Sprintf("persist state failed when creating: %s", err.Error())}
}
return dockerdriver.ErrorResponse{}
}
func (d *VolumeDriver) List(_ dockerdriver.Env) dockerdriver.ListResponse {
listResponse := dockerdriver.ListResponse{
Volumes: []dockerdriver.VolumeInfo{},
}
for _, val := range d.volumes.Values() {
listResponse.Volumes = append(listResponse.Volumes, val.VolumeInfo)
}
listResponse.Err = ""
return listResponse
}
func (d *VolumeDriver) Mount(env dockerdriver.Env, mountRequest dockerdriver.MountRequest) dockerdriver.MountResponse {
logger := env.Logger().Session("mount", lager.Data{"volume": mountRequest.Name})
logger.Info("start")
defer logger.Info("end")
if mountRequest.Name == "" {
return dockerdriver.MountResponse{Err: "Missing mandatory 'volume_name'"}
}
volume, ok := d.volumes.Get(mountRequest.Name)
if !ok {
return dockerdriver.MountResponse{Err: fmt.Sprintf("Volume '%s' must be created before being mounted", mountRequest.Name)}
}
mountPath := d.mountPath(driverhttp.EnvWithLogger(logger, env), volume.Name)
volume.Mountpoint = mountPath
logger.Info("mounting-volume", lager.Data{"id": volume.Name, "mountpoint": mountPath})
logger.Info("mount-source", lager.Data{"source": volume.Opts["source"].(string)})
doMount := volume.MountCount < 1
volume.MountCount++
logger.Info("volume-ref-count-incremented", lager.Data{"name": volume.Name, "count": volume.MountCount})
d.volumes.Put(mountRequest.Name, volume)
if err := d.persistState(driverhttp.EnvWithLogger(logger, env)); err != nil {
logger.Error("persist-state-failed", err)
return dockerdriver.MountResponse{Err: fmt.Sprintf("persist state failed when mounting: %s", err.Error())}
}
if doMount {
mountStartTime := d.time.Now()
err := d.mount(driverhttp.EnvWithLogger(logger, env), copyOpts(volume.Opts), mountPath)
mountEndTime := d.time.Now()
mountDuration := mountEndTime.Sub(mountStartTime)
if mountDuration > 8*time.Second {
logger.Error("mount-duration-too-high", nil, lager.Data{"mount-duration-in-second": mountDuration / time.Second, "warning": "This may result in container creation failure!"})
}
switch err.(type) {
case nil:
return dockerdriver.MountResponse{Mountpoint: volume.Mountpoint}
case dockerdriver.SafeError:
errBytes, mErr := json.Marshal(err)
if mErr != nil {
logger.Error("failed-to-marshal-safeerror", mErr)
return dockerdriver.MountResponse{Err: err.Error()}
}
return dockerdriver.MountResponse{Err: string(errBytes)}
default:
return dockerdriver.MountResponse{Err: err.Error()}
}
} else {
// Check the volume to make sure it's still mounted before handing it out again.
if !d.mounter.Check(driverhttp.EnvWithLogger(logger, env), volume.Name, volume.Mountpoint) {
if err := d.mount(driverhttp.EnvWithLogger(logger, env), volume.Opts, mountPath); err != nil {
logger.Error("remount-volume-failed", err)
return dockerdriver.MountResponse{Err: fmt.Sprintf("Error remounting volume: %s", err.Error())}
}
}
return dockerdriver.MountResponse{Mountpoint: volume.Mountpoint}
}
}
func (d *VolumeDriver) Path(env dockerdriver.Env, pathRequest dockerdriver.PathRequest) dockerdriver.PathResponse {
logger := env.Logger().Session("path", lager.Data{"volume": pathRequest.Name})
if pathRequest.Name == "" {
return dockerdriver.PathResponse{Err: "Missing mandatory 'volume_name'"}
}
vol, err := d.getVolume(driverhttp.EnvWithLogger(logger, env), pathRequest.Name)
if err != nil {
logger.Error("failed-no-such-volume-found", err, lager.Data{"mountpoint": vol.Mountpoint})
return dockerdriver.PathResponse{Err: fmt.Sprintf("Volume '%s' not found", pathRequest.Name)}
}
if vol.Mountpoint == "" {
errText := "volume not previously mounted"
logger.Error("failed-mountpoint-not-assigned", errors.New(errText))
return dockerdriver.PathResponse{Err: errText}
}
return dockerdriver.PathResponse{Mountpoint: vol.Mountpoint}
}
func (d *VolumeDriver) Unmount(env dockerdriver.Env, unmountRequest dockerdriver.UnmountRequest) dockerdriver.ErrorResponse {
logger := env.Logger().Session("unmount", lager.Data{"volume": unmountRequest.Name})
logger.Info("start")
defer logger.Info("end")
if unmountRequest.Name == "" {
return dockerdriver.ErrorResponse{Err: "Missing mandatory 'volume_name'"}
}
volume, ok := d.volumes.Get(unmountRequest.Name)
if !ok {
logger.Error("failed-no-such-volume-found", fmt.Errorf("could not find volume %s", unmountRequest.Name))
return dockerdriver.ErrorResponse{Err: fmt.Sprintf("Volume '%s' not found", unmountRequest.Name)}
}
if volume.Mountpoint == "" {
errText := "volume not previously mounted"
logger.Error("failed-mountpoint-not-assigned", errors.New(errText))
return dockerdriver.ErrorResponse{Err: errText}
}
if volume.MountCount == 1 {
if err := d.unmount(driverhttp.EnvWithLogger(logger, env), unmountRequest.Name, volume.Mountpoint); err != nil {
return dockerdriver.ErrorResponse{Err: err.Error()}
}
}
volume.MountCount--
logger.Info("volume-ref-count-decremented", lager.Data{"name": volume.Name, "count": volume.MountCount})
switch volume.MountCount {
case 0:
d.volumes.Delete(unmountRequest.Name)
default:
d.volumes.Put(unmountRequest.Name, volume)
}
if err := d.persistState(driverhttp.EnvWithLogger(logger, env)); err != nil {
return dockerdriver.ErrorResponse{Err: fmt.Sprintf("failed to persist state when unmounting: %s", err.Error())}
}
return dockerdriver.ErrorResponse{}
}
func (d *VolumeDriver) Remove(env dockerdriver.Env, removeRequest dockerdriver.RemoveRequest) dockerdriver.ErrorResponse {
logger := env.Logger().Session("remove", lager.Data{"volume": removeRequest})
logger.Info("start")
defer logger.Info("end")
if removeRequest.Name == "" {
return dockerdriver.ErrorResponse{Err: "Missing mandatory 'volume_name'"}
}
vol, err := d.getVolume(driverhttp.EnvWithLogger(logger, env), removeRequest.Name)
if err != nil {
logger.Error("warning-volume-removal", fmt.Errorf("volume %s not found", removeRequest.Name))
return dockerdriver.ErrorResponse{}
}
if vol.Mountpoint != "" {
if err := d.unmount(driverhttp.EnvWithLogger(logger, env), removeRequest.Name, vol.Mountpoint); err != nil {
return dockerdriver.ErrorResponse{Err: err.Error()}
}
}
logger.Info("removing-volume", lager.Data{"name": removeRequest.Name})
d.volumes.Delete(removeRequest.Name)
if err := d.persistState(driverhttp.EnvWithLogger(logger, env)); err != nil {
return dockerdriver.ErrorResponse{Err: fmt.Sprintf("failed to persist state when removing: %s", err.Error())}
}
return dockerdriver.ErrorResponse{}
}
func (d *VolumeDriver) Get(env dockerdriver.Env, getRequest dockerdriver.GetRequest) dockerdriver.GetResponse {
volume, err := d.getVolume(env, getRequest.Name)
if err != nil {
return dockerdriver.GetResponse{Err: err.Error()}
}
return dockerdriver.GetResponse{
Volume: dockerdriver.VolumeInfo{
Name: getRequest.Name,
Mountpoint: volume.Mountpoint,
},
}
}
func (d *VolumeDriver) getVolume(env dockerdriver.Env, volumeName string) (NfsVolumeInfo, error) {
logger := env.Logger().Session("get-volume")
if vol, ok := d.volumes.Get(volumeName); ok {
logger.Info("getting-volume", lager.Data{"name": volumeName})
return vol, nil
}
return NfsVolumeInfo{}, errors.New("volume not found")
}
func (d *VolumeDriver) Capabilities(env dockerdriver.Env) dockerdriver.CapabilitiesResponse {
return dockerdriver.CapabilitiesResponse{
Capabilities: dockerdriver.CapabilityInfo{Scope: "local"},
}
}
func (d *VolumeDriver) mountPath(env dockerdriver.Env, volumeId string) string {
logger := env.Logger().Session("mount-path")
orig := d.osHelper.Umask(000)
defer d.osHelper.Umask(orig)
dir, err := d.filepath.Abs(d.mountPathRoot)
if err != nil {
logger.Fatal("abs-failed", err)
}
if err := d.os.MkdirAll(dir, os.ModePerm); err != nil {
logger.Fatal("mkdir-rootpath-failed", err)
}
return filepath.Join(dir, volumeId)
}
func (d *VolumeDriver) mount(env dockerdriver.Env, opts map[string]interface{}, mountPath string) error {
source, sourceOk := opts["source"].(string)
logger := env.Logger().Session("mount", lager.Data{"source": source, "target": mountPath})
logger.Info("start")
defer logger.Info("end")
if !sourceOk {
err := errors.New("no source information")
logger.Error("unable-to-extract-source", err)
return err
}
orig := d.osHelper.Umask(000)
defer d.osHelper.Umask(orig)
err := d.os.MkdirAll(mountPath, os.ModePerm)
if err != nil {
logger.Error("create-mountdir-failed", err)
return err
}
err = d.mounter.Mount(env, source, mountPath, opts)
if err != nil {
logger.Error("mount-failed: ", err)
rm_err := d.os.Remove(mountPath)
if rm_err != nil {
logger.Error("mountpoint-remove-failed", rm_err, lager.Data{"mount-path": mountPath})
}
}
return err
}
func (d *VolumeDriver) persistState(env dockerdriver.Env) error {
logger := env.Logger().Session("persist-state")
logger.Info("start")
defer logger.Info("end")
orig := d.osHelper.Umask(000)
defer d.osHelper.Umask(orig)
stateFile := d.mountPath(env, "driver-state.json")
stateData, err := json.Marshal(d.volumes)
if err != nil {
logger.Error("failed-to-marshall-state", err)
return err
}
err = d.os.WriteFile(stateFile, stateData, os.ModePerm)
if err != nil {
logger.Error("failed-to-write-state-file", err, lager.Data{"stateFile": stateFile})
return err
}
logger.Debug("state-saved", lager.Data{"state-file": stateFile})
return nil
}
func (d *VolumeDriver) restoreState(env dockerdriver.Env) {
logger := env.Logger().Session("restore-state")
logger.Info("start")
defer logger.Info("end")
stateFile := filepath.Join(d.mountPathRoot, "driver-state.json")
stateData, err := d.os.ReadFile(stateFile)
if err != nil {
logger.Info("failed-to-read-state-file", lager.Data{"err": err, "stateFile": stateFile})
return
}
logger.Info("state", lager.Data{"state": string(stateData)})
if err := json.Unmarshal(stateData, d.volumes); err != nil {
logger.Error("failed-to-unmarshall-state", err, lager.Data{"stateFile": stateFile})
return
}
logger.Info("state-restored", lager.Data{"state-file": stateFile})
}
func (d *VolumeDriver) unmount(env dockerdriver.Env, name string, mountPath string) error {
logger := env.Logger().Session("unmount")
logger.Info("start")
defer logger.Info("end")
exists, err := d.mountChecker.Exists(mountPath)
if err != nil {
logger.Error("failed-proc-mounts-check", err, lager.Data{"mountpoint": mountPath})
return err
}
if !exists {
err := d.os.Remove(mountPath)
if err != nil {
errText := fmt.Sprintf("Volume %s does not exist (path: %s) and unable to remove mount directory", name, mountPath)
logger.Info("mountpoint-not-found", lager.Data{"msg": errText})
return errors.New(errText)
}
errText := fmt.Sprintf("Volume %s does not exist (path: %s)", name, mountPath)
logger.Info("mountpoint-not-found", lager.Data{"msg": errText})
return errors.New(errText)
}
logger.Info("unmount-volume-folder", lager.Data{"mountpath": mountPath})
err = d.mounter.Unmount(env, mountPath)
if err != nil {
logger.Error("unmount-failed", err)
return fmt.Errorf("error unmounting volume: %s", err.Error())
}
err = d.os.Remove(mountPath)
if err != nil {
logger.Error("remove-mountpoint-failed", err)
return fmt.Errorf("error removing mountpoint: %s", err.Error())
}
logger.Info("unmounted-volume")
return nil
}
func (d *VolumeDriver) Drain(env dockerdriver.Env) error {
logger := env.Logger().Session("check-mounts")
logger.Info("start")
defer logger.Info("end")
// flush any volumes that are still in our map
for _, key := range d.volumes.Keys() {
if mount, ok := d.volumes.Get(key); ok {
if mount.Mountpoint != "" && mount.MountCount > 0 {
err := d.unmount(env, mount.Name, mount.Mountpoint)
if err != nil {
logger.Error("drain-unmount-failed", err, lager.Data{"mount-name": mount.Name, "mount-point": mount.Mountpoint})
}
}
d.volumes.Delete(key)
}
}
d.mounter.Purge(env, d.mountPathRoot)
return nil
}
func copyOpts(input map[string]any) map[string]any {
output := make(map[string]any)
for k, v := range input {
output[k] = v
}
return output
}