-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin.go
More file actions
525 lines (456 loc) · 12.6 KB
/
Copy pathplugin.go
File metadata and controls
525 lines (456 loc) · 12.6 KB
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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
package main
import (
"encoding/json"
"fmt"
"io"
"log"
"net"
"net/http"
"path/filepath"
"regexp"
)
// VolumePlugin implements the Docker volume plugin protocol.
type VolumePlugin struct {
state *PluginState
mountBase string
}
func NewVolumePlugin(state *PluginState, mountBase string) *VolumePlugin {
return &VolumePlugin{
state: state,
mountBase: mountBase,
}
}
func (vp *VolumePlugin) save() {
if err := vp.state.Save(); err != nil {
log.Printf("save state error: %v", err)
}
}
// --- Docker Plugin Protocol handlers ---
// ping is called by Docker to check plugin health.
func (vp *VolumePlugin) ping(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, "OK")
}
// proto advertises the plugin protocol version.
func (vp *VolumePlugin) proto(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/vnd.docker.plugins.http.v1.+")
w.WriteHeader(http.StatusOK)
}
// activate handles /Plugin.Activate and advertises implemented interfaces.
func (vp *VolumePlugin) activate(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{
"Implements": []string{"VolumeDriver"},
})
}
// capabilities handles /VolumeDriver.Capabilities.
func (vp *VolumePlugin) capabilities(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{
"Capabilities": map[string]any{
"Scope": "local",
},
})
}
// path handles /VolumeDriver.Path: return a volume's mount path without mounting.
func (vp *VolumePlugin) path(w http.ResponseWriter, r *http.Request) {
req, err := parsePathRequest(r)
if err != nil {
badRequest(w, fmt.Sprintf("parse request: %v", err))
return
}
vol, ok := vp.state.GetVolume(req.name)
if !ok {
notFound(w, fmt.Sprintf("volume %s not found", req.name))
return
}
lun, ok := vp.state.GetLUN(vol.Portal, vol.IQN)
mountpoint := filepath.Join(vp.mountBase, lunDirName(vol.Portal, vol.IQN))
if ok && lun.MountPoint != "" {
mountpoint = lun.MountPoint
}
writeJSON(w, http.StatusOK, map[string]any{"Mountpoint": mountpoint})
}
// Create handles /VolumeDriver.Create: validate driver_opts and ensure the
// LUN is logged in and mounted.
func (vp *VolumePlugin) create(w http.ResponseWriter, r *http.Request) {
req, err := parseCreateRequest(r)
if err != nil {
badRequest(w, fmt.Sprintf("parse request: %v", err))
return
}
portal, iqn := req.opts["portal"], req.opts["iqn"]
if err := validatePortal(portal); err != nil {
badRequest(w, err.Error())
return
}
if err := validateIQN(iqn); err != nil {
badRequest(w, err.Error())
return
}
// If LUN is already mounted, just register the volume name.
lun, ok := vp.state.GetLUN(portal, iqn)
if ok {
mounted, _ := isMounted(lun.MountPoint)
if mounted {
vp.state.PutVolume(req.name, &VolumeEntry{
Portal: portal,
IQN: iqn,
FSType: req.opts["fs_type"],
})
vp.save()
writeJSON(w, http.StatusOK, emptyMap())
return
}
}
// Ensure full mount chain: login → resolve → mount.
info, err := EnsureMount(vp.mountBase, portal, iqn, req.opts["fs_type"])
if err != nil {
badRequest(w, fmt.Sprintf("mount LUN: %v", err))
return
}
vp.state.UpsertLUN(portal, iqn, func(lun *LUNState) {
lun.Portal = portal
lun.IQN = iqn
lun.DevicePath = info.DevicePath
lun.MountPoint = info.LUNDir
lun.Formatted = info.IsFormatted
})
vp.state.PutVolume(req.name, &VolumeEntry{
Portal: portal,
IQN: iqn,
FSType: req.opts["fs_type"],
})
vp.save()
writeJSON(w, http.StatusOK, emptyMap())
}
// Get handles /VolumeDriver.Get: return info about a single volume.
func (vp *VolumePlugin) get(w http.ResponseWriter, r *http.Request) {
req, err := parseGetRequest(r)
if err != nil {
badRequest(w, fmt.Sprintf("parse request: %v", err))
return
}
// Look up volume by name from our stored mappings.
vol, ok := vp.state.GetVolume(req.name)
if !ok {
notFound(w, fmt.Sprintf("volume %s not found", req.name))
return
}
lun, ok := vp.state.GetLUN(vol.Portal, vol.IQN)
mountpoint := filepath.Join(vp.mountBase, lunDirName(vol.Portal, vol.IQN))
if ok && lun.MountPoint != "" {
mountpoint = lun.MountPoint
}
writeJSON(w, http.StatusOK, map[string]any{
"Volume": map[string]any{
"Name": req.name,
"Mountpoint": mountpoint,
"Status": map[string]any{},
},
})
}
// ListVolumes returns all volumes managed by this plugin on this node.
func (vp *VolumePlugin) list(w http.ResponseWriter, r *http.Request) {
volumes := make([]map[string]any, 0)
for name, vol := range vp.state.ListVolumes() {
lun, ok := vp.state.GetLUN(vol.Portal, vol.IQN)
mountpoint := ""
if ok {
mountpoint = lun.MountPoint
}
volumes = append(volumes, map[string]any{
"Name": name,
"Mountpoint": mountpoint,
})
}
writeJSON(w, http.StatusOK, map[string]any{
"Volumes": volumes,
"Err": "",
})
}
// Mount handles /VolumeDriver.Mount: ensure the volume is accessible and
// return the mount path. Increments the per-LUN ref count.
func (vp *VolumePlugin) mount(w http.ResponseWriter, r *http.Request) {
req, err := parseMountRequest(r)
if err != nil {
badRequest(w, fmt.Sprintf("parse request: %v", err))
return
}
// Look up volume by name from stored mappings.
vol, ok := vp.state.GetVolume(req.name)
if !ok {
badRequest(w, fmt.Sprintf("mount: volume %s not found", req.name))
return
}
portal, iqn := vol.Portal, vol.IQN
fsType := vol.FSType
lun, ok := vp.state.GetLUN(portal, iqn)
needsMount := !ok
if ok {
mounted, _ := isMounted(lun.MountPoint)
if !mounted {
needsMount = true
}
}
if needsMount {
info, err := EnsureMount(vp.mountBase, portal, iqn, fsType)
if err != nil {
badRequest(w, fmt.Sprintf("mount LUN: %v", err))
return
}
vp.state.UpsertLUN(portal, iqn, func(lun *LUNState) {
lun.Portal = portal
lun.IQN = iqn
lun.DevicePath = info.DevicePath
lun.MountPoint = info.LUNDir
lun.Formatted = info.IsFormatted
})
vp.save()
lun, _ = vp.state.GetLUN(portal, iqn)
}
if _, ok := vp.state.IncrRef(portal, iqn); !ok {
badRequest(w, fmt.Sprintf("mount: LUN %s@%s disappeared from state", portal, iqn))
return
}
vp.save()
writeJSON(w, http.StatusOK, map[string]any{
"Mountpoint": lun.MountPoint,
})
}
// Unmount handles /VolumeDriver.Unmount: decrement ref count, possibly
// unmount+logout.
func (vp *VolumePlugin) unmount(w http.ResponseWriter, r *http.Request) {
req, err := parseUnmountRequest(r)
if err != nil {
badRequest(w, fmt.Sprintf("parse request: %v", err))
return
}
// Look up volume by name.
vol, ok := vp.state.GetVolume(req.name)
if !ok {
// Volume not tracked; nothing to do.
writeJSON(w, http.StatusOK, emptyMap())
return
}
portal, iqn := vol.Portal, vol.IQN
ref, ok := vp.state.DecrRef(portal, iqn)
if !ok {
writeJSON(w, http.StatusOK, emptyMap())
return
}
vp.save()
if ref <= 0 {
if err := UnmountLUN(vp.mountBase, portal, iqn); err != nil {
log.Printf("unmount error: %v", err)
}
vp.state.DeleteLUN(portal, iqn)
vp.save()
}
writeJSON(w, http.StatusOK, emptyMap())
}
// Destroy handles /VolumeDriver.Remove: remove volume mapping and unmount if
// no other volumes reference this LUN.
func (vp *VolumePlugin) destroy(w http.ResponseWriter, r *http.Request) {
req, err := parseDestroyRequest(r)
if err != nil {
badRequest(w, fmt.Sprintf("parse request: %v", err))
return
}
// Look up volume by name.
vol, ok := vp.state.GetVolume(req.name)
if !ok {
writeJSON(w, http.StatusOK, emptyMap())
return
}
portal, iqn := vol.Portal, vol.IQN
// Remove volume mapping.
vp.state.DeleteVolume(req.name)
// Check if any other volumes still reference this LUN.
hasOtherRefs := false
for _, v := range vp.state.ListVolumes() {
if v.Portal == portal && v.IQN == iqn {
hasOtherRefs = true
break
}
}
if !hasOtherRefs {
if err := UnmountLUN(vp.mountBase, portal, iqn); err != nil {
log.Printf("destroy unmount error: %v", err)
}
vp.state.DeleteLUN(portal, iqn)
}
vp.save()
writeJSON(w, http.StatusOK, emptyMap())
}
// --- Validation helpers ---
var iqnRegex = regexp.MustCompile(`^iqn\.\d{4}-\d{2}\.[a-zA-Z0-9][-a-zA-Z0-9]*(?:\.[a-zA-Z0-9][-a-zA-Z0-9]*)*:[a-zA-Z0-9._-]+$`)
func validatePortal(portal string) error {
if portal == "" {
return fmt.Errorf("portal is required")
}
host, port, err := net.SplitHostPort(portal)
if err != nil {
return fmt.Errorf("invalid portal format %q (expected host:port): %v", portal, err)
}
if host == "" {
return fmt.Errorf("portal host is empty")
}
if port == "" {
return fmt.Errorf("portal port is empty")
}
for i := 0; i < len(port); i++ {
if port[i] < '0' || port[i] > '9' {
return fmt.Errorf("portal port %q is not numeric", port)
}
}
return nil
}
func validateIQN(iqn string) error {
if iqn == "" {
return fmt.Errorf("iqn is required")
}
if !iqnRegex.MatchString(iqn) {
return fmt.Errorf("invalid IQN format %q", iqn)
}
return nil
}
// --- Request parsing helpers ---
type createRequest struct {
name string
opts map[string]string
}
type getRequest struct {
name string
opts map[string]string
}
type pathRequest struct {
name string
opts map[string]string
}
type mountRequest struct {
name string
id string
opts map[string]string
}
type unmountRequest struct {
name string
id string
opts map[string]string
}
type destroyRequest struct {
name string
opts map[string]string
}
func parseCreateRequest(r *http.Request) (*createRequest, error) {
body, err := io.ReadAll(r.Body)
if err != nil {
return nil, err
}
var raw struct {
Name string `json:"Name"`
Opts map[string]string `json:"Opts"`
StatusCode int `json:"StatusCode"`
}
if err := json.Unmarshal(body, &raw); err != nil {
return nil, err
}
return &createRequest{name: raw.Name, opts: raw.Opts}, nil
}
func parseGetRequest(r *http.Request) (*getRequest, error) {
body, err := io.ReadAll(r.Body)
if err != nil {
return nil, err
}
var raw struct {
Name string `json:"Name"`
Opts map[string]string `json:"Opts"`
StatusCode int `json:"StatusCode"`
}
if err := json.Unmarshal(body, &raw); err != nil {
return nil, err
}
return &getRequest{name: raw.Name, opts: raw.Opts}, nil
}
func parsePathRequest(r *http.Request) (*pathRequest, error) {
body, err := io.ReadAll(r.Body)
if err != nil {
return nil, err
}
var raw struct {
Name string `json:"Name"`
Opts map[string]string `json:"Opts"`
StatusCode int `json:"StatusCode"`
}
if err := json.Unmarshal(body, &raw); err != nil {
return nil, err
}
return &pathRequest{name: raw.Name, opts: raw.Opts}, nil
}
func parseMountRequest(r *http.Request) (*mountRequest, error) {
body, err := io.ReadAll(r.Body)
if err != nil {
return nil, err
}
var raw struct {
Name string `json:"Name"`
ID string `json:"ID"`
Opts map[string]string `json:"Opts"`
StatusCode int `json:"StatusCode"`
}
if err := json.Unmarshal(body, &raw); err != nil {
return nil, err
}
return &mountRequest{name: raw.Name, id: raw.ID, opts: raw.Opts}, nil
}
func parseUnmountRequest(r *http.Request) (*unmountRequest, error) {
body, err := io.ReadAll(r.Body)
if err != nil {
return nil, err
}
var raw struct {
Name string `json:"Name"`
ID string `json:"ID"`
Opts map[string]string `json:"Opts"`
StatusCode int `json:"StatusCode"`
}
if err := json.Unmarshal(body, &raw); err != nil {
return nil, err
}
return &unmountRequest{name: raw.Name, id: raw.ID, opts: raw.Opts}, nil
}
func parseDestroyRequest(r *http.Request) (*destroyRequest, error) {
body, err := io.ReadAll(r.Body)
if err != nil {
return nil, err
}
var raw struct {
Name string `json:"Name"`
Opts map[string]string `json:"Opts"`
StatusCode int `json:"StatusCode"`
}
if err := json.Unmarshal(body, &raw); err != nil {
return nil, err
}
return &destroyRequest{name: raw.Name, opts: raw.Opts}, nil
}
// --- HTTP helper functions ---
func writeJSON(w http.ResponseWriter, code int, v any) {
if v == nil {
v = emptyMap()
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
json.NewEncoder(w).Encode(v)
}
func badRequest(w http.ResponseWriter, msg string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]any{"Err": msg})
}
func notFound(w http.ResponseWriter, msg string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusNotFound)
json.NewEncoder(w).Encode(map[string]any{"Err": msg})
}
func emptyMap() map[string]any {
return map[string]any{}
}