-
Notifications
You must be signed in to change notification settings - Fork 621
/
Copy pathnodeserver.go
442 lines (369 loc) · 14.8 KB
/
nodeserver.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
/*
Copyright 2017 The Kubernetes Authors.
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 cinder
import (
"context"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/container-storage-interface/spec/lib/go/csi"
"github.com/kubernetes-csi/csi-lib-utils/protosanitizer"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"k8s.io/klog/v2"
utilpath "k8s.io/utils/path"
sharedcsi "k8s.io/cloud-provider-openstack/pkg/csi"
"k8s.io/cloud-provider-openstack/pkg/csi/cinder/openstack"
"k8s.io/cloud-provider-openstack/pkg/util/blockdevice"
"k8s.io/cloud-provider-openstack/pkg/util/metadata"
"k8s.io/cloud-provider-openstack/pkg/util/mount"
mountutil "k8s.io/mount-utils"
)
type nodeServer struct {
Driver *Driver
Mount mount.IMount
Metadata metadata.IMetadata
Opts openstack.BlockStorageOpts
Topologies map[string]string
csi.UnimplementedNodeServer
}
func (ns *nodeServer) NodePublishVolume(ctx context.Context, req *csi.NodePublishVolumeRequest) (*csi.NodePublishVolumeResponse, error) {
klog.V(4).Infof("NodePublishVolume: called with args %+v", protosanitizer.StripSecrets(req))
volumeID := req.GetVolumeId()
source := req.GetStagingTargetPath()
targetPath := req.GetTargetPath()
volumeCapability := req.GetVolumeCapability()
if len(volumeID) == 0 {
return nil, status.Error(codes.InvalidArgument, "NodePublishVolume Volume ID must be provided")
}
if len(targetPath) == 0 {
return nil, status.Error(codes.InvalidArgument, "NodePublishVolume Target Path must be provided")
}
if volumeCapability == nil {
return nil, status.Error(codes.InvalidArgument, "NodePublishVolume Volume Capability must be provided")
}
ephemeralVolume := req.GetVolumeContext()[sharedcsi.VolEphemeralKey] == "true"
if ephemeralVolume {
// See https://github.com/kubernetes/cloud-provider-openstack/issues/2599
return nil, status.Error(codes.Unimplemented, "CSI inline ephemeral volumes support is removed in 1.31 release.")
}
// In case of ephemeral volume staging path not provided
if len(source) == 0 {
return nil, status.Error(codes.InvalidArgument, "NodePublishVolume Staging Target Path must be provided")
}
mountOptions := []string{"bind"}
if req.GetReadonly() {
mountOptions = append(mountOptions, "ro")
} else {
mountOptions = append(mountOptions, "rw")
}
if blk := volumeCapability.GetBlock(); blk != nil {
return nodePublishVolumeForBlock(req, ns, mountOptions)
}
m := ns.Mount
// Verify whether mounted
notMnt, err := m.IsLikelyNotMountPointAttach(targetPath)
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
// Volume Mount
if notMnt {
fsType := "ext4"
if mnt := volumeCapability.GetMount(); mnt != nil {
if mnt.FsType != "" {
fsType = mnt.FsType
}
}
// Mount
err = m.Mounter().Mount(source, targetPath, fsType, mountOptions)
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
}
return &csi.NodePublishVolumeResponse{}, nil
}
func nodePublishVolumeForBlock(req *csi.NodePublishVolumeRequest, ns *nodeServer, mountOptions []string) (*csi.NodePublishVolumeResponse, error) {
klog.V(4).Infof("NodePublishVolumeBlock: called with args %+v", protosanitizer.StripSecrets(req))
volumeID := req.GetVolumeId()
targetPath := req.GetTargetPath()
podVolumePath := filepath.Dir(targetPath)
m := ns.Mount
// Do not trust the path provided by cinder, get the real path on node
source, err := getDevicePath(volumeID, m)
if err != nil {
return nil, status.Errorf(codes.Internal, "Unable to find Device path for volume: %v", err)
}
exists, err := utilpath.Exists(utilpath.CheckFollowSymlink, podVolumePath)
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
if !exists {
if err := m.MakeDir(podVolumePath); err != nil {
return nil, status.Errorf(codes.Internal, "Could not create dir %q: %v", podVolumePath, err)
}
}
err = m.MakeFile(targetPath)
if err != nil {
return nil, status.Errorf(codes.Internal, "Error in making file %v", err)
}
if err := m.Mounter().Mount(source, targetPath, "", mountOptions); err != nil {
if removeErr := os.Remove(targetPath); removeErr != nil {
return nil, status.Errorf(codes.Internal, "Could not remove mount target %q: %v", targetPath, err)
}
return nil, status.Errorf(codes.Internal, "Could not mount %q at %q: %v", source, targetPath, err)
}
return &csi.NodePublishVolumeResponse{}, nil
}
func (ns *nodeServer) NodeUnpublishVolume(ctx context.Context, req *csi.NodeUnpublishVolumeRequest) (*csi.NodeUnpublishVolumeResponse, error) {
klog.V(4).Infof("NodeUnPublishVolume: called with args %+v", protosanitizer.StripSecrets(req))
volumeID := req.GetVolumeId()
targetPath := req.GetTargetPath()
if len(targetPath) == 0 {
return nil, status.Error(codes.InvalidArgument, "[NodeUnpublishVolume] Target Path must be provided")
}
if len(volumeID) == 0 {
return nil, status.Error(codes.InvalidArgument, "[NodeUnpublishVolume] volumeID must be provided")
}
if err := ns.Mount.UnmountPath(targetPath); err != nil {
return nil, status.Errorf(codes.Internal, "Unmount of targetpath %s failed with error %v", targetPath, err)
}
return &csi.NodeUnpublishVolumeResponse{}, nil
}
func (ns *nodeServer) NodeStageVolume(ctx context.Context, req *csi.NodeStageVolumeRequest) (*csi.NodeStageVolumeResponse, error) {
klog.V(4).Infof("NodeStageVolume: called with args %+v", protosanitizer.StripSecrets(req))
stagingTarget := req.GetStagingTargetPath()
volumeCapability := req.GetVolumeCapability()
volumeContext := req.GetVolumeContext()
volumeID := req.GetVolumeId()
if len(volumeID) == 0 {
return nil, status.Error(codes.InvalidArgument, "Volume Id not provided")
}
if len(stagingTarget) == 0 {
return nil, status.Error(codes.InvalidArgument, "Staging target not provided")
}
if volumeCapability == nil {
return nil, status.Error(codes.InvalidArgument, "NodeStageVolume Volume Capability must be provided")
}
m := ns.Mount
// Do not trust the path provided by cinder, get the real path on node
devicePath, err := getDevicePath(volumeID, m)
if err != nil {
return nil, status.Errorf(codes.Internal, "Unable to find Device path for volume: %v", err)
}
if blk := volumeCapability.GetBlock(); blk != nil {
// If block volume, do nothing
return &csi.NodeStageVolumeResponse{}, nil
}
// Verify whether mounted
notMnt, err := m.IsLikelyNotMountPointAttach(stagingTarget)
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
// Volume Mount
if notMnt {
// set default fstype is ext4
fsType := "ext4"
var options []string
if mnt := volumeCapability.GetMount(); mnt != nil {
if mnt.FsType != "" {
fsType = mnt.FsType
}
mountFlags := mnt.GetMountFlags()
options = append(options, collectMountOptions(fsType, mountFlags)...)
}
// Mount
err = ns.formatAndMountRetry(devicePath, stagingTarget, fsType, options)
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
}
if required, ok := volumeContext[ResizeRequired]; ok && strings.EqualFold(required, "true") {
r := mountutil.NewResizeFs(ns.Mount.Mounter().Exec)
needResize, err := r.NeedResize(devicePath, stagingTarget)
if err != nil {
return nil, status.Errorf(codes.Internal, "Could not determine if volume %q need to be resized: %v", volumeID, err)
}
if needResize {
klog.V(4).Infof("NodeStageVolume: Resizing volume %q created from a snapshot/volume", volumeID)
if _, err := r.Resize(devicePath, stagingTarget); err != nil {
return nil, status.Errorf(codes.Internal, "Could not resize volume %q: %v", volumeID, err)
}
}
}
return &csi.NodeStageVolumeResponse{}, nil
}
// formatAndMountRetry attempts to format and mount a device at the given path.
// If the initial mount fails, it rescans the device and retries the mount operation.
func (ns *nodeServer) formatAndMountRetry(devicePath, stagingTarget, fsType string, options []string) error {
m := ns.Mount
err := m.Mounter().FormatAndMount(devicePath, stagingTarget, fsType, options)
if err != nil {
klog.Infof("Initial format and mount failed: %v. Attempting rescan.", err)
// Attempting rescan if the initial mount fails
rescanErr := blockdevice.RescanDevice(devicePath)
if rescanErr != nil {
klog.Infof("Rescan failed: %v. Returning original mount error.", rescanErr)
return err
}
klog.Infof("Rescan succeeded, retrying format and mount")
err = m.Mounter().FormatAndMount(devicePath, stagingTarget, fsType, options)
}
return err
}
func (ns *nodeServer) NodeUnstageVolume(ctx context.Context, req *csi.NodeUnstageVolumeRequest) (*csi.NodeUnstageVolumeResponse, error) {
klog.V(4).Infof("NodeUnstageVolume: called with args %+v", protosanitizer.StripSecrets(req))
volumeID := req.GetVolumeId()
if len(volumeID) == 0 {
return nil, status.Error(codes.InvalidArgument, "Volume Id not provided")
}
stagingTargetPath := req.GetStagingTargetPath()
if len(stagingTargetPath) == 0 {
return nil, status.Error(codes.InvalidArgument, "NodeUnstageVolume Staging Target Path must be provided")
}
err := ns.Mount.UnmountPath(stagingTargetPath)
if err != nil {
return nil, status.Errorf(codes.Internal, "Unmount of targetPath %s failed with error %v", stagingTargetPath, err)
}
return &csi.NodeUnstageVolumeResponse{}, nil
}
func (ns *nodeServer) NodeGetInfo(ctx context.Context, req *csi.NodeGetInfoRequest) (*csi.NodeGetInfoResponse, error) {
nodeID, err := ns.Metadata.GetInstanceID()
if err != nil {
return nil, status.Errorf(codes.Internal, "[NodeGetInfo] unable to retrieve instance id of node %v", err)
}
nodeInfo := &csi.NodeGetInfoResponse{
NodeId: nodeID,
MaxVolumesPerNode: ns.Opts.NodeVolumeAttachLimit,
}
if !ns.Driver.withTopology {
return nodeInfo, nil
}
zone, err := ns.Metadata.GetAvailabilityZone()
if err != nil {
return nil, status.Errorf(codes.Internal, "[NodeGetInfo] Unable to retrieve availability zone of node %v", err)
}
topologyMap := make(map[string]string, len(ns.Topologies)+1)
topologyMap[topologyKey] = zone
for k, v := range ns.Topologies {
topologyMap[k] = v
}
nodeInfo.AccessibleTopology = &csi.Topology{Segments: topologyMap}
return nodeInfo, nil
}
func (ns *nodeServer) NodeGetCapabilities(ctx context.Context, req *csi.NodeGetCapabilitiesRequest) (*csi.NodeGetCapabilitiesResponse, error) {
klog.V(5).Infof("NodeGetCapabilities called with req: %#v", req)
return &csi.NodeGetCapabilitiesResponse{
Capabilities: ns.Driver.nscap,
}, nil
}
func (ns *nodeServer) NodeGetVolumeStats(_ context.Context, req *csi.NodeGetVolumeStatsRequest) (*csi.NodeGetVolumeStatsResponse, error) {
klog.V(4).Infof("NodeGetVolumeStats: called with args %+v", protosanitizer.StripSecrets(req))
volumeID := req.GetVolumeId()
if len(volumeID) == 0 {
return nil, status.Error(codes.InvalidArgument, "Volume Id not provided")
}
volumePath := req.GetVolumePath()
if len(volumePath) == 0 {
return nil, status.Error(codes.InvalidArgument, "Volume path not provided")
}
exists, err := utilpath.Exists(utilpath.CheckFollowSymlink, req.VolumePath)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to check whether volumePath exists: %v", err)
}
if !exists {
return nil, status.Errorf(codes.NotFound, "target: %s not found", volumePath)
}
stats, err := ns.Mount.GetDeviceStats(volumePath)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to get stats by path: %v", err)
}
if stats.Block {
return &csi.NodeGetVolumeStatsResponse{
Usage: []*csi.VolumeUsage{
{
Total: stats.TotalBytes,
Unit: csi.VolumeUsage_BYTES,
},
},
}, nil
}
return &csi.NodeGetVolumeStatsResponse{
Usage: []*csi.VolumeUsage{
{Total: stats.TotalBytes, Available: stats.AvailableBytes, Used: stats.UsedBytes, Unit: csi.VolumeUsage_BYTES},
{Total: stats.TotalInodes, Available: stats.AvailableInodes, Used: stats.UsedInodes, Unit: csi.VolumeUsage_INODES},
},
}, nil
}
func (ns *nodeServer) NodeExpandVolume(ctx context.Context, req *csi.NodeExpandVolumeRequest) (*csi.NodeExpandVolumeResponse, error) {
klog.V(4).Infof("NodeExpandVolume: called with args %+v", protosanitizer.StripSecrets(req))
volumeID := req.GetVolumeId()
if len(volumeID) == 0 {
return nil, status.Error(codes.InvalidArgument, "Volume ID not provided")
}
volumePath := req.GetVolumePath()
if len(volumePath) == 0 {
return nil, status.Error(codes.InvalidArgument, "Volume path not provided")
}
_, err := blockdevice.IsBlockDevice(volumePath)
if err != nil {
return nil, status.Errorf(codes.NotFound, "Failed to determine device path for volumePath %s: %v", volumePath, err)
}
output, err := ns.Mount.GetMountFs(volumePath)
if err != nil {
return nil, status.Errorf(codes.Internal, "Failed to find mount file system %s: %v", volumePath, err)
}
devicePath := strings.TrimSpace(string(output))
if devicePath == "" {
return nil, status.Error(codes.Internal, "Unable to find Device path for volume")
}
if ns.Opts.RescanOnResize {
// comparing current volume size with the expected one
newSize := req.GetCapacityRange().GetRequiredBytes()
if err := blockdevice.RescanBlockDeviceGeometry(devicePath, volumePath, newSize); err != nil {
return nil, status.Errorf(codes.Internal, "Could not verify %q volume size: %v", volumeID, err)
}
}
r := mountutil.NewResizeFs(ns.Mount.Mounter().Exec)
if _, err := r.Resize(devicePath, volumePath); err != nil {
return nil, status.Errorf(codes.Internal, "Could not resize volume %q: %v", volumeID, err)
}
return &csi.NodeExpandVolumeResponse{}, nil
}
func getDevicePath(volumeID string, m mount.IMount) (string, error) {
var devicePath string
devicePath, err := m.GetDevicePath(volumeID)
if err != nil {
klog.Warningf("Couldn't get device path from mount: %v", err)
}
if devicePath == "" {
// try to get from metadata service
klog.Info("Trying to get device path from metadata service")
devicePath, err = metadata.GetDevicePath(volumeID)
if err != nil {
klog.Errorf("Couldn't get device path from metadata service: %v", err)
return "", fmt.Errorf("couldn't get device path from metadata service: %v", err)
}
}
return devicePath, nil
}
func collectMountOptions(fsType string, mntFlags []string) []string {
var options []string
options = append(options, mntFlags...)
// By default, xfs does not allow mounting of two volumes with the same filesystem uuid.
// Force ignore this uuid to be able to mount volume + its clone / restored snapshot on the same node.
if fsType == "xfs" {
options = append(options, "nouuid")
}
return options
}