/
controller.go
601 lines (530 loc) · 18.8 KB
/
controller.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
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
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
/*
Package csi is CSI driver interface for OSD
Copyright 2017 Portworx
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package csi
import (
"fmt"
"github.com/portworx/kvdb"
"github.com/libopenstorage/openstorage/api"
"github.com/libopenstorage/openstorage/pkg/util"
"github.com/golang/protobuf/ptypes"
sdkVol "github.com/libopenstorage/openstorage/api/server/sdk"
csi "github.com/libopenstorage/openstorage/csi/v0.3/spec"
"github.com/sirupsen/logrus"
"golang.org/x/net/context"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
const (
volumeCapabilityMessageMultinodeVolume = "Volume is a multinode volume"
volumeCapabilityMessageNotMultinodeVolume = "Volume is not a multinode volume"
volumeCapabilityMessageReadOnlyVolume = "Volume is read only"
volumeCapabilityMessageNotReadOnlyVolume = "Volume is not read only"
defaultCSIVolumeSize = uint64(1024 * 1024 * 1024)
)
// ControllerGetCapabilities is a CSI API functions which returns to the caller
// the capabilities of the OSD CSI driver.
func (s *OsdCsiServer) ControllerGetCapabilities(
ctx context.Context,
req *csi.ControllerGetCapabilitiesRequest,
) (*csi.ControllerGetCapabilitiesResponse, error) {
// Creating and deleting volumes supported
capCreateDeleteVolume := &csi.ControllerServiceCapability{
Type: &csi.ControllerServiceCapability_Rpc{
Rpc: &csi.ControllerServiceCapability_RPC{
Type: csi.ControllerServiceCapability_RPC_CREATE_DELETE_VOLUME,
},
},
}
// Creating and deleting snapshots
capCreateDeleteSnapshot := &csi.ControllerServiceCapability{
Type: &csi.ControllerServiceCapability_Rpc{
Rpc: &csi.ControllerServiceCapability_RPC{
Type: csi.ControllerServiceCapability_RPC_CREATE_DELETE_SNAPSHOT,
},
},
}
// ListVolumes supported
capListVolumes := &csi.ControllerServiceCapability{
Type: &csi.ControllerServiceCapability_Rpc{
Rpc: &csi.ControllerServiceCapability_RPC{
Type: csi.ControllerServiceCapability_RPC_LIST_VOLUMES,
},
},
}
return &csi.ControllerGetCapabilitiesResponse{
Capabilities: []*csi.ControllerServiceCapability{
capCreateDeleteVolume,
capCreateDeleteSnapshot,
capListVolumes,
},
}, nil
}
// ControllerPublishVolume is a CSI API implements the attachment of a volume
// on to a node.
func (s *OsdCsiServer) ControllerPublishVolume(
context.Context,
*csi.ControllerPublishVolumeRequest,
) (*csi.ControllerPublishVolumeResponse, error) {
return nil, status.Error(codes.Unimplemented, "This request is not supported")
}
// ControllerUnpublishVolume is a CSI API which implements the detaching of a volume
// onto a node.
func (s *OsdCsiServer) ControllerUnpublishVolume(
context.Context,
*csi.ControllerUnpublishVolumeRequest,
) (*csi.ControllerUnpublishVolumeResponse, error) {
return nil, status.Error(codes.Unimplemented, "This request is not supported")
}
// ValidateVolumeCapabilities is a CSI API used by container orchestration systems
// to make sure a volume specification is validiated by the CSI driver.
// Note: The method used here to return errors is still not part of the spec.
// See: https://github.com/container-storage-interface/spec/pull/115
// Discussion: https://groups.google.com/forum/#!topic/kubernetes-sig-storage-wg-csi/TpTrNFbRa1I
//
func (s *OsdCsiServer) ValidateVolumeCapabilities(
ctx context.Context,
req *csi.ValidateVolumeCapabilitiesRequest,
) (*csi.ValidateVolumeCapabilitiesResponse, error) {
capabilities := req.GetVolumeCapabilities()
if capabilities == nil || len(capabilities) == 0 {
return nil, status.Error(codes.InvalidArgument, "volume_capabilities must be specified")
}
id := req.GetVolumeId()
if len(id) == 0 {
return nil, status.Error(codes.InvalidArgument, "volume_id must be specified")
}
attributes := req.GetVolumeAttributes()
// Log request
logrus.Debugf("ValidateVolumeCapabilities of id %s "+
"capabilities %#v "+
"attributes %#v ",
id,
capabilities,
attributes)
// Check ID is valid with the specified volume capabilities
volumes, err := s.driver.Inspect([]string{id})
if err != nil || len(volumes) == 0 {
return nil, status.Error(codes.NotFound, "ID not found")
}
if len(volumes) != 1 {
errs := fmt.Sprintf(
"Driver returned an unexpected number of volumes when one was expected: %d",
len(volumes))
logrus.Errorln(errs)
return nil, status.Error(codes.Internal, errs)
}
v := volumes[0]
if v.Id != id {
errs := fmt.Sprintf(
"Driver volume id [%s] does not equal requested id of: %s",
v.Id,
id)
logrus.Errorln(errs)
return nil, status.Error(codes.Internal, errs)
}
// Setup uninitialized response object
result := &csi.ValidateVolumeCapabilitiesResponse{
Supported: true,
}
// Check capability
for _, capability := range capabilities {
// Currently the CSI spec defines all storage as "file systems."
// So we do not need to check this with the volume. All we will check
// here is the validity of the capability access type.
if capability.GetMount() == nil && capability.GetBlock() == nil {
return nil, status.Error(
codes.InvalidArgument,
"Cannot have both mount and block be undefined")
}
// Check access mode is setup correctly
mode := capability.GetAccessMode()
switch {
case mode.Mode == csi.VolumeCapability_AccessMode_SINGLE_NODE_WRITER:
if v.Spec.Shared {
result.Supported = false
result.Message = volumeCapabilityMessageMultinodeVolume
break
}
if v.Readonly {
result.Supported = false
result.Message = volumeCapabilityMessageReadOnlyVolume
break
}
case mode.Mode == csi.VolumeCapability_AccessMode_SINGLE_NODE_READER_ONLY:
if v.Spec.Shared {
result.Supported = false
result.Message = volumeCapabilityMessageMultinodeVolume
break
}
if !v.Readonly {
result.Supported = false
result.Message = volumeCapabilityMessageNotReadOnlyVolume
break
}
case mode.Mode == csi.VolumeCapability_AccessMode_MULTI_NODE_READER_ONLY:
if !v.Spec.Shared {
result.Supported = false
result.Message = volumeCapabilityMessageNotMultinodeVolume
break
}
if !v.Readonly {
result.Supported = false
result.Message = volumeCapabilityMessageNotReadOnlyVolume
break
}
case mode.Mode == csi.VolumeCapability_AccessMode_MULTI_NODE_SINGLE_WRITER ||
mode.Mode == csi.VolumeCapability_AccessMode_MULTI_NODE_MULTI_WRITER:
if !v.Spec.Shared {
result.Supported = false
result.Message = volumeCapabilityMessageNotMultinodeVolume
break
}
if v.Readonly {
result.Supported = false
result.Message = volumeCapabilityMessageReadOnlyVolume
break
}
default:
return nil, status.Errorf(
codes.InvalidArgument,
"AccessMode %s is not allowed",
mode.Mode.String())
}
if !result.Supported {
return result, nil
}
}
// If we passed all the checks, then it is valid
result.Message = "Volume is supported"
return result, nil
}
// ListVolumes is a CSI API which returns to the caller all volume ids
// on this cluster. This includes ids created by CSI and ids created
// using other interfaces. This is important because the user could
// be requesting to mount a OSD volume created using non-CSI interfaces.
//
// This call does not yet implement tokens to due to the following
// issue: https://github.com/container-storage-interface/spec/issues/138
func (s *OsdCsiServer) ListVolumes(
ctx context.Context,
req *csi.ListVolumesRequest,
) (*csi.ListVolumesResponse, error) {
logrus.Debugf("ListVolumes req[%#v]", req)
// Until the issue #138 on the CSI spec is resolved we will not support
// tokenization
if req.GetMaxEntries() != 0 {
return nil, status.Error(
codes.Unimplemented,
"Driver does not support tokenization. Please see "+
"https://github.com/container-storage-interface/spec/issues/138")
}
volumes, err := s.driver.Enumerate(&api.VolumeLocator{}, nil)
if err != nil {
errs := fmt.Sprintf("Unable to get list of volumes: %s", err.Error())
logrus.Errorln(errs)
return nil, status.Error(codes.Internal, errs)
}
entries := make([]*csi.ListVolumesResponse_Entry, len(volumes))
for i, v := range volumes {
// Initialize entry
entries[i] = &csi.ListVolumesResponse_Entry{
Volume: &csi.Volume{},
}
// Required
entries[i].Volume.Id = v.Id
// This entry is optional in the API, but OSD has
// the information available to provide it
entries[i].Volume.CapacityBytes = int64(v.Spec.Size)
// Attributes. We can add or remove as needed since they
// are optional and opaque to the Container Orchestrator(CO)
// but could be used for debugging using a csi complient client.
entries[i].Volume.Attributes = osdVolumeAttributes(v)
}
return &csi.ListVolumesResponse{
Entries: entries,
}, nil
}
// osdVolumeAttributes returns the attributes of a volume as a map
// to be returned to the CSI API caller
func osdVolumeAttributes(v *api.Volume) map[string]string {
return map[string]string{
api.SpecParent: v.GetSource().GetParent(),
api.SpecSecure: fmt.Sprintf("%v", v.GetSpec().GetEncrypted()),
api.SpecShared: fmt.Sprintf("%v", v.GetSpec().GetShared()),
"readonly": fmt.Sprintf("%v", v.GetReadonly()),
"attached": v.AttachedState.String(),
"state": v.State.String(),
"error": v.GetError(),
}
}
// CreateVolume is a CSI API which creates a volume on OSD
// This function supports snapshots if the parent volume id is supplied
// in the parameters.
func (s *OsdCsiServer) CreateVolume(
ctx context.Context,
req *csi.CreateVolumeRequest,
) (*csi.CreateVolumeResponse, error) {
// Log request
logrus.Debugf("CreateVolume req[%#v]", *req)
if len(req.GetName()) == 0 {
return nil, status.Error(codes.InvalidArgument, "Name must be provided")
}
if req.GetVolumeCapabilities() == nil || len(req.GetVolumeCapabilities()) == 0 {
return nil, status.Error(codes.InvalidArgument, "Volume capabilities must be provided")
}
// Get parameters
spec, locator, source, err := s.specHandler.SpecFromOpts(req.GetParameters())
if err != nil {
e := fmt.Sprintf("Unable to get parameters: %s\n", err.Error())
logrus.Errorln(e)
return nil, status.Error(codes.InvalidArgument, e)
}
// Get Size
if req.GetCapacityRange() != nil && req.GetCapacityRange().GetRequiredBytes() != 0 {
spec.Size = uint64(req.GetCapacityRange().GetRequiredBytes())
} else {
spec.Size = defaultCSIVolumeSize
}
// Create response
volume := &csi.Volume{}
resp := &csi.CreateVolumeResponse{
Volume: volume,
}
// Check if the volume has already been created or is in process of creation
v, err := util.VolumeFromName(s.driver, req.GetName())
if err == nil {
// Check the requested arguments match that of the existing volume
if spec.Size != v.GetSpec().GetSize() {
return nil, status.Errorf(
codes.AlreadyExists,
"Existing volume has a size of %v which differs from requested size of %v",
v.GetSpec().GetSize(),
spec.Size)
}
if v.GetSpec().GetShared() != csiRequestsSharedVolume(req) {
return nil, status.Errorf(
codes.AlreadyExists,
"Existing volume has shared=%v while request is asking for shared=%v",
v.GetSpec().GetShared(),
csiRequestsSharedVolume(req))
}
if v.GetSource().GetParent() != source.GetParent() {
return nil, status.Error(codes.AlreadyExists, "Existing volume has conflicting parent value")
}
// Return information on existing volume
osdToCsiVolumeInfo(volume, v)
return resp, nil
}
// Check if this is a cloning request to create a volume from a snapshot
if req.GetVolumeContentSource().GetSnapshot() != nil {
source.Parent = req.GetVolumeContentSource().GetSnapshot().GetId()
}
// Check if the caller is asking to create a snapshot or for a new volume
var id string
if source != nil && len(source.GetParent()) != 0 {
// Get parent volume information
parent, err := util.VolumeFromName(s.driver, source.Parent)
if err != nil {
e := fmt.Sprintf("unable to get parent volume information: %s\n", err.Error())
logrus.Errorln(e)
return nil, status.Error(codes.InvalidArgument, e)
}
// Create a snapshot from the parent
id, err = s.driver.Snapshot(parent.GetId(), false, &api.VolumeLocator{
Name: req.GetName(),
},
false)
if err != nil {
e := fmt.Sprintf("unable to create snapshot: %s\n", err.Error())
logrus.Errorln(e)
return nil, status.Error(codes.Internal, e)
}
} else {
// Get Capabilities and Size
spec.Shared = csiRequestsSharedVolume(req)
// Create the volume
locator.Name = req.GetName()
// get enforced policy specs
// 0.3 Does not support user context or auth
spec, err = sdkVol.GetDefaultVolSpecs(context.Background(), spec, false /* not an update */)
if err != nil {
return nil, status.Errorf(codes.Internal, err.Error())
}
id, err = s.driver.Create(context.TODO(), locator, source, spec)
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
}
// id must have been set
v, err = util.VolumeFromName(s.driver, id)
if err != nil {
e := fmt.Sprintf("Unable to find newly created volume: %s", err.Error())
logrus.Errorln(e)
return nil, status.Error(codes.Internal, e)
}
osdToCsiVolumeInfo(volume, v)
return resp, nil
}
// DeleteVolume is a CSI API which deletes a volume
func (s *OsdCsiServer) DeleteVolume(
ctx context.Context,
req *csi.DeleteVolumeRequest,
) (*csi.DeleteVolumeResponse, error) {
// Log request
logrus.Debugf("DeleteVolume req[%#v]", *req)
// Check arguments
if len(req.GetVolumeId()) == 0 {
return nil, status.Error(codes.InvalidArgument, "Volume id must be provided")
}
// If the volume is not found, then we can return OK
volumes, err := s.driver.Inspect([]string{req.GetVolumeId()})
if (err == nil && len(volumes) == 0) ||
(err != nil && err == kvdb.ErrNotFound) {
return &csi.DeleteVolumeResponse{}, nil
} else if err != nil {
return nil, err
}
// Delete volume
err = s.driver.Delete(context.TODO(), req.GetVolumeId())
if err != nil {
e := fmt.Sprintf("Unable to delete volume with id %s: %s",
req.GetVolumeId(),
err.Error())
logrus.Errorln(e)
return nil, status.Error(codes.Internal, e)
}
return &csi.DeleteVolumeResponse{}, nil
}
func osdToCsiVolumeInfo(dest *csi.Volume, src *api.Volume) {
dest.Id = src.GetId()
dest.CapacityBytes = int64(src.Spec.GetSize())
dest.Attributes = osdVolumeAttributes(src)
}
func csiRequestsSharedVolume(req *csi.CreateVolumeRequest) bool {
for _, cap := range req.GetVolumeCapabilities() {
// Check access mode is setup correctly
mode := cap.GetAccessMode().GetMode()
if mode == csi.VolumeCapability_AccessMode_MULTI_NODE_MULTI_WRITER ||
mode == csi.VolumeCapability_AccessMode_MULTI_NODE_SINGLE_WRITER {
return true
}
}
return false
}
// CreateSnapshot is a CSI implementation to create a snapshot from the volume
func (s *OsdCsiServer) CreateSnapshot(
ctx context.Context,
req *csi.CreateSnapshotRequest,
) (*csi.CreateSnapshotResponse, error) {
if len(req.GetSourceVolumeId()) == 0 {
return nil, status.Error(codes.InvalidArgument, "Volume id must be provided")
} else if len(req.GetName()) == 0 {
return nil, status.Error(codes.InvalidArgument, "Name must be provided")
}
// Check if the snapshot with this name already exists
v, err := util.VolumeFromName(s.driver, req.GetName())
if err == nil {
// Verify the parent is the same
if req.GetSourceVolumeId() != v.GetSource().GetParent() {
return nil, status.Error(codes.AlreadyExists, "Requested snapshot already exists for another source volume id")
}
// Return current snapshot info
createdAt, err := ptypes.Timestamp(v.GetCtime())
if err != nil {
return nil, status.Errorf(codes.Internal, "Failed to get time snapshot was created: %v", err)
}
return &csi.CreateSnapshotResponse{
Snapshot: &csi.Snapshot{
Id: v.GetId(),
SourceVolumeId: v.GetSource().GetParent(),
CreatedAt: createdAt.Unix(),
Status: &csi.SnapshotStatus{
// This means that we are not uploading our snapshot
// We may add support for cloud snaps in future patches
Type: csi.SnapshotStatus_READY,
},
},
}, nil
}
// Get any labels passed in by the CO
_, locator, _, err := s.specHandler.SpecFromOpts(req.GetParameters())
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "Unable to get parameters: %v", err)
}
// Create snapshot
readonly := true
snapshotID, err := s.driver.Snapshot(req.GetSourceVolumeId(), readonly, &api.VolumeLocator{
Name: req.GetName(),
VolumeLabels: locator.GetVolumeLabels(),
}, false)
if err != nil {
if err == kvdb.ErrNotFound {
return nil, status.Errorf(codes.NotFound, "Volume id %s not found", req.GetSourceVolumeId())
}
return nil, status.Errorf(codes.Internal, "Failed to create snapshot: %v", err)
}
snapInfo, err := util.VolumeFromName(s.driver, snapshotID)
if err != nil {
return nil, status.Errorf(codes.Internal, "Failed to get information about the snapshot: %v", err)
}
createdAt, err := ptypes.Timestamp(snapInfo.GetCtime())
if err != nil {
return nil, status.Errorf(codes.Internal, "Failed to get time snapshot was created: %v", err)
}
return &csi.CreateSnapshotResponse{
Snapshot: &csi.Snapshot{
Id: snapshotID,
SourceVolumeId: req.GetSourceVolumeId(),
CreatedAt: createdAt.Unix(),
Status: &csi.SnapshotStatus{
// This means that we are not uploading our snapshot
// We may add support flow cloud snaps in future patches
Type: csi.SnapshotStatus_READY,
},
},
}, nil
}
// DeleteSnapshot is a CSI implementation to delete a snapshot
func (s *OsdCsiServer) DeleteSnapshot(
ctx context.Context,
req *csi.DeleteSnapshotRequest,
) (*csi.DeleteSnapshotResponse, error) {
if len(req.GetSnapshotId()) == 0 {
return nil, status.Error(codes.InvalidArgument, "Snapshot id must be provided")
}
// If the snapshot is not found, then we can return OK
volumes, err := s.driver.Inspect([]string{req.GetSnapshotId()})
if (err == nil && len(volumes) == 0) ||
(err != nil && err == kvdb.ErrNotFound) {
return &csi.DeleteSnapshotResponse{}, nil
} else if err != nil {
return nil, err
}
err = s.driver.Delete(context.TODO(), req.GetSnapshotId())
if err != nil {
return nil, status.Errorf(codes.Internal, "Unable to delete snapshot %s: %v",
req.GetSnapshotId(),
err)
}
return &csi.DeleteSnapshotResponse{}, nil
}
// ListSnapshots is not supported (we can add this later)
func (s *OsdCsiServer) ListSnapshots(
ctx context.Context,
req *csi.ListSnapshotsRequest,
) (*csi.ListSnapshotsResponse, error) {
// The function ListSnapshots is also not published as
// supported by this implementation
return nil, status.Error(codes.Unimplemented, "ListSnapshots is not implemented")
}