-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.go
300 lines (260 loc) · 8.31 KB
/
utils.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
/*
Copyright 2018 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 gceGCEDriver
import (
"errors"
"fmt"
"net/http"
"strings"
"context"
csi "github.com/container-storage-interface/spec/lib/go/csi"
"google.golang.org/api/googleapi"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"k8s.io/klog/v2"
)
const (
fsTypeXFS = "xfs"
)
var ProbeCSIFullMethod = "/csi.v1.Identity/Probe"
func NewVolumeCapabilityAccessMode(mode csi.VolumeCapability_AccessMode_Mode) *csi.VolumeCapability_AccessMode {
return &csi.VolumeCapability_AccessMode{Mode: mode}
}
func NewControllerServiceCapability(cap csi.ControllerServiceCapability_RPC_Type) *csi.ControllerServiceCapability {
return &csi.ControllerServiceCapability{
Type: &csi.ControllerServiceCapability_Rpc{
Rpc: &csi.ControllerServiceCapability_RPC{
Type: cap,
},
},
}
}
func NewNodeServiceCapability(cap csi.NodeServiceCapability_RPC_Type) *csi.NodeServiceCapability {
return &csi.NodeServiceCapability{
Type: &csi.NodeServiceCapability_Rpc{
Rpc: &csi.NodeServiceCapability_RPC{
Type: cap,
},
},
}
}
func logGRPC(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
if info.FullMethod == ProbeCSIFullMethod {
return handler(ctx, req)
}
// Note that secrets are not included in any RPC message. In the past protosanitizer and other log
// stripping was shown to cause a significant increase of CPU usage (see
// https://github.com/kubernetes-sigs/gcp-compute-persistent-disk-csi-driver/issues/356#issuecomment-550529004).
klog.V(4).Infof("%s called with request: %s", info.FullMethod, req)
resp, err := handler(ctx, req)
if err != nil {
klog.Errorf("%s returned with error: %v", info.FullMethod, err.Error())
} else {
cappedStr := fmt.Sprintf("%v", resp)
if len(cappedStr) > maxLogChar {
cappedStr = cappedStr[:maxLogChar] + fmt.Sprintf(" [response body too large, log capped to %d chars]", maxLogChar)
}
klog.V(4).Infof("%s returned with response: %s", info.FullMethod, cappedStr)
}
return resp, err
}
func validateVolumeCapabilities(vcs []*csi.VolumeCapability) error {
isMnt := false
isBlk := false
if vcs == nil {
return errors.New("volume capabilities is nil")
}
for _, vc := range vcs {
if err := validateVolumeCapability(vc); err != nil {
return err
}
if blk := vc.GetBlock(); blk != nil {
isBlk = true
}
if mnt := vc.GetMount(); mnt != nil {
isMnt = true
}
}
if isBlk && isMnt {
return errors.New("both mount and block volume capabilities specified")
}
return nil
}
func validateVolumeCapability(vc *csi.VolumeCapability) error {
if err := validateAccessMode(vc.GetAccessMode()); err != nil {
return err
}
blk := vc.GetBlock()
mnt := vc.GetMount()
mod := vc.GetAccessMode().GetMode()
if mnt == nil && blk == nil {
return errors.New("must specify an access type")
}
if mnt != nil && blk != nil {
return errors.New("specified both mount and block access types")
}
if mnt != nil && mod == csi.VolumeCapability_AccessMode_MULTI_NODE_MULTI_WRITER {
return errors.New("specified multi writer with mount access type")
}
return nil
}
func validateAccessMode(am *csi.VolumeCapability_AccessMode) error {
if am == nil {
return errors.New("access mode is nil")
}
switch am.GetMode() {
case csi.VolumeCapability_AccessMode_SINGLE_NODE_WRITER:
case csi.VolumeCapability_AccessMode_SINGLE_NODE_READER_ONLY:
case csi.VolumeCapability_AccessMode_MULTI_NODE_READER_ONLY:
case csi.VolumeCapability_AccessMode_MULTI_NODE_MULTI_WRITER:
default:
return fmt.Errorf("%v access mode is not supported for for PD", am.GetMode())
}
return nil
}
func getMultiWriterFromCapability(vc *csi.VolumeCapability) (bool, error) {
if vc.GetAccessMode() == nil {
return false, errors.New("access mode is nil")
}
mode := vc.GetAccessMode().GetMode()
return (mode == csi.VolumeCapability_AccessMode_MULTI_NODE_MULTI_WRITER), nil
}
func getMultiWriterFromCapabilities(vcs []*csi.VolumeCapability) (bool, error) {
if vcs == nil {
return false, errors.New("volume capabilities is nil")
}
for _, vc := range vcs {
multiWriter, err := getMultiWriterFromCapability(vc)
if err != nil {
return false, err
}
if multiWriter {
return true, nil
}
}
return false, nil
}
func getReadOnlyFromCapability(vc *csi.VolumeCapability) (bool, error) {
if vc.GetAccessMode() == nil {
return false, errors.New("access mode is nil")
}
mode := vc.GetAccessMode().GetMode()
return (mode == csi.VolumeCapability_AccessMode_MULTI_NODE_READER_ONLY ||
mode == csi.VolumeCapability_AccessMode_SINGLE_NODE_READER_ONLY), nil
}
func getReadOnlyFromCapabilities(vcs []*csi.VolumeCapability) (bool, error) {
if vcs == nil {
return false, errors.New("volume capabilities is nil")
}
for _, vc := range vcs {
readOnly, err := getReadOnlyFromCapability(vc)
if err != nil {
return false, err
}
if readOnly {
return true, nil
}
}
return false, nil
}
func collectMountOptions(fsType string, mntFlags []string) []string {
var options []string
for _, opt := range mntFlags {
options = append(options, opt)
}
// 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 == fsTypeXFS {
options = append(options, "nouuid")
}
return options
}
func containsZone(zones []string, zone string) bool {
for _, z := range zones {
if z == zone {
return true
}
}
return false
}
// CodeForError returns a pointer to the grpc error code that maps to the http
// error code for the passed in user googleapi error or context error. Returns
// codes.Internal if the given error is not a googleapi error caused by the user.
// The following http error codes are considered user errors:
// (1) http 400 Bad Request, returns grpc InvalidArgument,
// (2) http 403 Forbidden, returns grpc PermissionDenied,
// (3) http 404 Not Found, returns grpc NotFound
// (4) http 429 Too Many Requests, returns grpc ResourceExhausted
// The following errors are considered context errors:
// (1) "context deadline exceeded", returns grpc DeadlineExceeded,
// (2) "context canceled", returns grpc Canceled
func CodeForError(err error) *codes.Code {
if err == nil {
return nil
}
if errCode := existingErrorCode(err); errCode != nil {
return errCode
}
if code := isContextError(err); code != nil {
return code
}
internalErrorCode := codes.Internal
// Upwrap the error
var apiErr *googleapi.Error
if !errors.As(err, &apiErr) {
return &internalErrorCode
}
userErrors := map[int]codes.Code{
http.StatusForbidden: codes.PermissionDenied,
http.StatusBadRequest: codes.InvalidArgument,
http.StatusTooManyRequests: codes.ResourceExhausted,
http.StatusNotFound: codes.NotFound,
}
if code, ok := userErrors[apiErr.Code]; ok {
return &code
}
return &internalErrorCode
}
func existingErrorCode(err error) *codes.Code {
if err == nil {
return nil
}
if status, ok := status.FromError(err); ok {
return errCodePtr(status.Code())
}
return nil
}
// isContextError returns a pointer to the grpc error code DeadlineExceeded
// if the passed in error contains the "context deadline exceeded" string and returns
// the grpc error code Canceled if the error contains the "context canceled" string.
func isContextError(err error) *codes.Code {
if err == nil {
return nil
}
errStr := err.Error()
if strings.Contains(errStr, context.DeadlineExceeded.Error()) {
return errCodePtr(codes.DeadlineExceeded)
}
if strings.Contains(errStr, context.Canceled.Error()) {
return errCodePtr(codes.Canceled)
}
return nil
}
func errCodePtr(code codes.Code) *codes.Code {
return &code
}
func LoggedError(msg string, err error) error {
klog.Errorf(msg+"%v", err.Error())
return status.Errorf(*CodeForError(err), msg+"%v", err.Error())
}