/
nodeserver.go
273 lines (218 loc) · 7.58 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
package h3
import (
"fmt"
"io/ioutil"
"os"
"os/exec"
"strings"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/klog"
"github.com/container-storage-interface/spec/lib/go/csi"
"golang.org/x/net/context"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/kubernetes/pkg/util/mount"
"k8s.io/kubernetes/pkg/volume/util"
csicommon "github.com/kubernetes-csi/drivers/pkg/csi-common"
)
type nodeServer struct {
*csicommon.DefaultNodeServer
mounter *mount.SafeFormatAndMount
}
type mountPoint struct {
VolumeId string
MountPath string
}
func (ns *nodeServer) NodePublishVolume(ctx context.Context, req *csi.NodePublishVolumeRequest) (*csi.NodePublishVolumeResponse, error) {
klog.Infof("NodePublishVolume: called with args %+v", *req)
targetPath := req.GetTargetPath()
notMnt, err := mount.New("").IsLikelyNotMountPoint(targetPath)
if err != nil {
if os.IsNotExist(err) {
if err := os.MkdirAll(targetPath, 0750); err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
notMnt = true
} else {
return nil, status.Error(codes.Internal, err.Error())
}
}
if !notMnt {
// testing original mount point, make sure the mount link is valid
if _, err := ioutil.ReadDir(targetPath); err == nil {
klog.Infof("already mounted to target %s", targetPath)
return &csi.NodePublishVolumeResponse{}, nil
}
// todo: mount link is invalid, now unmount and remount later (built-in functionality)
klog.Warningf("ReadDir %s failed with %v, unmount this directory", targetPath, err)
ns.mounter = &mount.SafeFormatAndMount{
Interface: mount.New(""),
Exec: mount.NewOsExec(),
}
if err := ns.mounter.Unmount(targetPath); err != nil {
klog.Errorf("Unmount directory %s failed with %v", targetPath, err)
return nil, err
}
}
mountOptions := req.GetVolumeCapability().GetMount().GetMountFlags()
if req.GetReadonly() {
mountOptions = append(mountOptions, "ro")
}
// Load default connection settings from secret
secret, e := getSecret("h3-secret")
storageUri, bucket, flags, e := extractFlags(req.GetVolumeContext(), secret)
if e != nil {
klog.Warningf("storage parameter error: %s", e)
return nil, e
}
e = Mount(storageUri, bucket, targetPath, flags)
if e != nil {
if os.IsPermission(e) {
return nil, status.Error(codes.PermissionDenied, e.Error())
}
if strings.Contains(e.Error(), "invalid argument") {
return nil, status.Error(codes.InvalidArgument, e.Error())
}
return nil, status.Error(codes.Internal, e.Error())
}
return &csi.NodePublishVolumeResponse{}, nil
}
func extractFlags(volumeContext map[string]string, secret *v1.Secret) (string, string, map[string]string, error) {
// Empty argument list
flags := make(map[string]string)
// Secret values are default, gets merged and overriden by corresponding PV values
if secret != nil && secret.Data != nil && len(secret.Data) > 0 {
// Needs byte to string casting for map values
for k, v := range secret.Data {
flags[k] = string(v)
}
} else {
klog.Infof("No csi-h3 connection defaults secret found.")
}
if len(volumeContext) > 0 {
for k, v := range volumeContext {
flags[k] = v
}
}
if e := validateFlags(flags); e != nil {
return "", "", flags, e
}
storageUri := flags["storageUri"]
bucket := flags["bucket"]
delete(flags, "storageUri")
delete(flags, "bucket")
return storageUri, bucket, flags, nil
}
func (ns *nodeServer) NodeUnpublishVolume(ctx context.Context, req *csi.NodeUnpublishVolumeRequest) (*csi.NodeUnpublishVolumeResponse, error) {
klog.Infof("NodeUnPublishVolume: called with args %+v", *req)
targetPath := req.GetTargetPath()
if len(targetPath) == 0 {
return nil, status.Error(codes.InvalidArgument, "NodeUnpublishVolume Target Path must be provided")
}
m := mount.New("")
notMnt, err := m.IsLikelyNotMountPoint(targetPath)
if err != nil && !mount.IsCorruptedMnt(err) {
return nil, status.Error(codes.Internal, err.Error())
}
if notMnt && !mount.IsCorruptedMnt(err) {
klog.Infof("Volume not mounted")
} else {
err = util.UnmountPath(req.GetTargetPath(), m)
if err != nil {
klog.Infof("Error while unmounting path: %s", err)
// This will exit and fail the NodeUnpublishVolume making it to retry unmount on the next api schedule trigger.
// Since we mount the volume with allow-non-empty now, we could skip this one too.
return nil, status.Error(codes.Internal, err.Error())
}
klog.Infof("Volume %s unmounted successfully", req.VolumeId)
}
return &csi.NodeUnpublishVolumeResponse{}, nil
}
func (ns *nodeServer) NodeUnstageVolume(ctx context.Context, req *csi.NodeUnstageVolumeRequest) (*csi.NodeUnstageVolumeResponse, error) {
klog.Infof("NodeUnstageVolume: called with args %+v", *req)
return &csi.NodeUnstageVolumeResponse{}, nil
}
func (ns *nodeServer) NodeStageVolume(ctx context.Context, req *csi.NodeStageVolumeRequest) (*csi.NodeStageVolumeResponse, error) {
klog.Infof("NodeStageVolume: called with args %+v", *req)
return &csi.NodeStageVolumeResponse{}, nil
}
func validateFlags(flags map[string]string) error {
if _, ok := flags["storageUri"]; !ok {
return status.Errorf(codes.InvalidArgument, "missing volume context value: storageUri")
}
if _, ok := flags["bucket"]; !ok {
return status.Errorf(codes.InvalidArgument, "missing volume context value: bucket")
}
return nil
}
func getSecret(secretName string) (*v1.Secret, error) {
clientset, e := GetK8sClient()
if e != nil {
return nil, status.Errorf(codes.Internal, "can not create kubernetes client: %s", e)
}
kubeconfig := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
clientcmd.NewDefaultClientConfigLoadingRules(),
&clientcmd.ConfigOverrides{},
)
namespace, _, err := kubeconfig.Namespace()
if err != nil {
return nil, status.Errorf(codes.Internal, "can't get current namespace, error %s", secretName, err)
}
klog.Infof("Loading csi-h3 connection defaults from secret %s/%s", namespace, secretName)
secret, e := clientset.CoreV1().
Secrets(namespace).
Get(secretName, metav1.GetOptions{})
if e != nil {
return nil, status.Errorf(codes.Internal, "can't load csi-h3 settings from secret %s: %s", secretName, e)
}
return secret, nil
}
// Mount routine.
func Mount(storageUri string, bucket string, targetPath string, flags map[string]string) error {
// Create bucket
command := []string{"h3cli",
"--storage",
storageUri,
"mb",
fmt.Sprintf("h3://%s", bucket)}
klog.Infof("H3 running: %s", strings.Join(command, " "))
out, err := exec.Command(command[0], command[1:]...).Output()
if err != nil {
klog.Errorf(err.Error())
// output := string(out[:])
// klog.Infof("H3 output: %s", output)
// return err
}
output := string(out[:])
klog.Infof("H3 output: %s", output)
// Back to mounting.
mountCmd := "h3fuse"
mountArgs := []string{}
// h3fuse -o storage=redis://127.0.0.1:6379 -o bucket=bucket targetPath
mountArgs = append(
mountArgs,
"-s",
"-o",
fmt.Sprintf("storage=%s", storageUri),
"-o",
fmt.Sprintf("bucket=%s", bucket),
"-o",
"allow_other",
targetPath,
)
// Other user supplied flags are ignored
// create target, os.Mkdirall is noop if it exists
err = os.MkdirAll(targetPath, 0750)
if err != nil {
return err
}
klog.Infof("executing mount command cmd=%s, storage=%s, bucket=%s, targetpath=%s", mountCmd, storageUri, bucket, targetPath)
out, err = exec.Command(mountCmd, mountArgs...).CombinedOutput()
if err != nil {
return fmt.Errorf("mounting failed: %v cmd: '%s' storage: '%s' bucket: '%s' targetpath: %s output: %q",
err, mountCmd, storageUri, bucket, targetPath, string(out))
}
return nil
}