-
Notifications
You must be signed in to change notification settings - Fork 138
/
smb.go
278 lines (245 loc) · 8.83 KB
/
smb.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
/*
Copyright 2019 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 smb
import (
"fmt"
"strings"
"time"
"github.com/container-storage-interface/spec/lib/go/csi"
"k8s.io/klog/v2"
mount "k8s.io/mount-utils"
csicommon "github.com/kubernetes-csi/csi-driver-smb/pkg/csi-common"
"github.com/kubernetes-csi/csi-driver-smb/pkg/mounter"
azcache "sigs.k8s.io/cloud-provider-azure/pkg/cache"
)
const (
DefaultDriverName = "smb.csi.k8s.io"
usernameField = "username"
passwordField = "password"
sourceField = "source"
subDirField = "subdir"
domainField = "domain"
mountOptionsField = "mountoptions"
paramOnDelete = "ondelete"
defaultDomainName = "AZURE"
pvcNameKey = "csi.storage.k8s.io/pvc/name"
pvcNamespaceKey = "csi.storage.k8s.io/pvc/namespace"
pvNameKey = "csi.storage.k8s.io/pv/name"
pvcNameMetadata = "${pvc.metadata.name}"
pvcNamespaceMetadata = "${pvc.metadata.namespace}"
pvNameMetadata = "${pv.metadata.name}"
DefaultKrb5CCName = "krb5cc_"
DefaultKrb5CacheDirectory = "/var/lib/kubelet/kerberos/"
retain = "retain"
archive = "archive"
fileMode = "file_mode"
dirMode = "dir_mode"
defaultFileMode = "0777"
defaultDirMode = "0777"
)
var supportedOnDeleteValues = []string{"", "delete", retain, archive}
// DriverOptions defines driver parameters specified in driver deployment
type DriverOptions struct {
NodeID string
DriverName string
EnableGetVolumeStats bool
// this only applies to Windows node
RemoveSMBMappingDuringUnmount bool
WorkingMountDir string
VolStatsCacheExpireInMinutes int
Krb5CacheDirectory string
Krb5Prefix string
DefaultOnDeletePolicy string
RemoveArchivedVolumePath bool
}
// Driver implements all interfaces of CSI drivers
type Driver struct {
csicommon.CSIDriver
// Embed UnimplementedXXXServer to ensure the driver returns Unimplemented for any
// new RPC methods that might be introduced in future versions of the spec.
csi.UnimplementedControllerServer
csi.UnimplementedIdentityServer
csi.UnimplementedNodeServer
mounter *mount.SafeFormatAndMount
// A map storing all volumes with ongoing operations so that additional operations
// for that same volume (as defined by VolumeID) return an Aborted error
volumeLocks *volumeLocks
workingMountDir string
enableGetVolumeStats bool
// a timed cache storing volume stats <volumeID, volumeStats>
volStatsCache azcache.Resource
// a timed cache storing volume deletion records <volumeID, "">
volDeletionCache azcache.Resource
// this only applies to Windows node
removeSMBMappingDuringUnmount bool
krb5CacheDirectory string
krb5Prefix string
defaultOnDeletePolicy string
removeArchivedVolumePath bool
}
// NewDriver Creates a NewCSIDriver object. Assumes vendor version is equal to driver version &
// does not support optional driver plugin info manifest field. Refer to CSI spec for more details.
func NewDriver(options *DriverOptions) *Driver {
driver := Driver{}
driver.Name = options.DriverName
driver.Version = driverVersion
driver.NodeID = options.NodeID
driver.enableGetVolumeStats = options.EnableGetVolumeStats
driver.removeSMBMappingDuringUnmount = options.RemoveSMBMappingDuringUnmount
driver.removeArchivedVolumePath = options.RemoveArchivedVolumePath
driver.workingMountDir = options.WorkingMountDir
driver.volumeLocks = newVolumeLocks()
driver.krb5CacheDirectory = options.Krb5CacheDirectory
if driver.krb5CacheDirectory == "" {
driver.krb5CacheDirectory = DefaultKrb5CacheDirectory
}
driver.krb5Prefix = options.Krb5Prefix
if driver.krb5Prefix == "" {
driver.krb5Prefix = DefaultKrb5CCName
}
if options.VolStatsCacheExpireInMinutes <= 0 {
options.VolStatsCacheExpireInMinutes = 10 // default expire in 10 minutes
}
var err error
getter := func(_ string) (interface{}, error) { return nil, nil }
if driver.volStatsCache, err = azcache.NewTimedCache(time.Duration(options.VolStatsCacheExpireInMinutes)*time.Minute, getter, false); err != nil {
klog.Fatalf("%v", err)
}
if driver.volDeletionCache, err = azcache.NewTimedCache(time.Minute, getter, false); err != nil {
klog.Fatalf("%v", err)
}
return &driver
}
// Run driver initialization
func (d *Driver) Run(endpoint, _ string, testMode bool) {
versionMeta, err := GetVersionYAML(d.Name)
if err != nil {
klog.Fatalf("%v", err)
}
klog.V(2).Infof("\nDRIVER INFORMATION:\n-------------------\n%s\n\nStreaming logs below:", versionMeta)
d.mounter, err = mounter.NewSafeMounter(d.removeSMBMappingDuringUnmount)
if err != nil {
klog.Fatalf("Failed to get safe mounter. Error: %v", err)
}
// Initialize default library driver
d.AddControllerServiceCapabilities(
[]csi.ControllerServiceCapability_RPC_Type{
csi.ControllerServiceCapability_RPC_CREATE_DELETE_VOLUME,
csi.ControllerServiceCapability_RPC_SINGLE_NODE_MULTI_WRITER,
csi.ControllerServiceCapability_RPC_CLONE_VOLUME,
csi.ControllerServiceCapability_RPC_EXPAND_VOLUME,
})
d.AddVolumeCapabilityAccessModes([]csi.VolumeCapability_AccessMode_Mode{
csi.VolumeCapability_AccessMode_SINGLE_NODE_WRITER,
csi.VolumeCapability_AccessMode_SINGLE_NODE_READER_ONLY,
csi.VolumeCapability_AccessMode_SINGLE_NODE_SINGLE_WRITER,
csi.VolumeCapability_AccessMode_SINGLE_NODE_MULTI_WRITER,
csi.VolumeCapability_AccessMode_MULTI_NODE_READER_ONLY,
csi.VolumeCapability_AccessMode_MULTI_NODE_SINGLE_WRITER,
csi.VolumeCapability_AccessMode_MULTI_NODE_MULTI_WRITER,
})
nodeCap := []csi.NodeServiceCapability_RPC_Type{
csi.NodeServiceCapability_RPC_STAGE_UNSTAGE_VOLUME,
csi.NodeServiceCapability_RPC_SINGLE_NODE_MULTI_WRITER,
csi.NodeServiceCapability_RPC_VOLUME_MOUNT_GROUP,
}
if d.enableGetVolumeStats {
nodeCap = append(nodeCap, csi.NodeServiceCapability_RPC_GET_VOLUME_STATS)
}
d.AddNodeServiceCapabilities(nodeCap)
s := csicommon.NewNonBlockingGRPCServer()
// Driver d act as IdentityServer, ControllerServer and NodeServer
s.Start(endpoint, d, d, d, testMode)
s.Wait()
}
func IsCorruptedDir(dir string) bool {
_, pathErr := mount.PathExists(dir)
return pathErr != nil && mount.IsCorruptedMnt(pathErr)
}
// getMountOptions get mountOptions value from a map
func getMountOptions(context map[string]string) string {
for k, v := range context {
switch strings.ToLower(k) {
case mountOptionsField:
return v
}
}
return ""
}
func hasGuestMountOptions(options []string) bool {
for _, v := range options {
if v == "guest" {
return true
}
}
return false
}
// setKeyValueInMap set key/value pair in map
// key in the map is case insensitive, if key already exists, overwrite existing value
func setKeyValueInMap(m map[string]string, key, value string) {
if m == nil {
return
}
for k := range m {
if strings.EqualFold(k, key) {
m[k] = value
return
}
}
m[key] = value
}
// replaceWithMap replace key with value for str
func replaceWithMap(str string, m map[string]string) string {
for k, v := range m {
if k != "" {
str = strings.ReplaceAll(str, k, v)
}
}
return str
}
func validateOnDeleteValue(onDelete string) error {
for _, v := range supportedOnDeleteValues {
if strings.EqualFold(v, onDelete) {
return nil
}
}
return fmt.Errorf("invalid value %s for OnDelete, supported values are %v", onDelete, supportedOnDeleteValues)
}
// appendMountOptions appends extra mount options to the given mount options
func appendMountOptions(mountOptions []string, extraMountOptions map[string]string) []string {
// stores the mount options already included in mountOptions
included := make(map[string]bool)
for _, mountOption := range mountOptions {
for k := range extraMountOptions {
if strings.HasPrefix(mountOption, k) {
included[k] = true
}
}
}
allMountOptions := mountOptions
for k, v := range extraMountOptions {
if _, isIncluded := included[k]; !isIncluded {
if v != "" {
allMountOptions = append(allMountOptions, fmt.Sprintf("%s=%s", k, v))
} else {
allMountOptions = append(allMountOptions, k)
}
}
}
return allMountOptions
}
// getRootDir returns the root directory of the given directory
func getRootDir(path string) string {
parts := strings.Split(path, "/")
return parts[0]
}