blob: d180b8658c3ec8215ee915d9e1d021f481154d7c [file] [log] [blame]
Lorenz Brun0db90ba2020-04-06 14:04:52 +02001// Copyright 2020 The Monogon Project Authors.
2//
3// SPDX-License-Identifier: Apache-2.0
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16
17package kubernetes
18
19import (
20 "context"
21 "fmt"
22 "net"
23 "os"
24 "path/filepath"
25 "regexp"
26
Lorenz Brun0db90ba2020-04-06 14:04:52 +020027 "github.com/container-storage-interface/spec/lib/go/csi"
28 "github.com/golang/protobuf/ptypes/wrappers"
Lorenz Brun0db90ba2020-04-06 14:04:52 +020029 "golang.org/x/sys/unix"
30 "google.golang.org/grpc"
31 "google.golang.org/grpc/codes"
32 "google.golang.org/grpc/status"
Lorenz Brun37050122021-03-30 14:00:27 +020033 "k8s.io/kubelet/pkg/apis/pluginregistration/v1"
Lorenz Brun0db90ba2020-04-06 14:04:52 +020034
Serge Bazanski31370b02021-01-07 16:31:14 +010035 "source.monogon.dev/metropolis/node/core/localstorage"
Serge Bazanski31370b02021-01-07 16:31:14 +010036 "source.monogon.dev/metropolis/pkg/fsquota"
Lorenz Brun4e090352021-03-17 17:44:41 +010037 "source.monogon.dev/metropolis/pkg/logtree"
Lorenz Brun37050122021-03-30 14:00:27 +020038 "source.monogon.dev/metropolis/pkg/loop"
Serge Bazanski31370b02021-01-07 16:31:14 +010039 "source.monogon.dev/metropolis/pkg/supervisor"
Lorenz Brun0db90ba2020-04-06 14:04:52 +020040)
41
Serge Bazanski216fe7b2021-05-21 18:36:16 +020042// Derived from K8s spec for acceptable names, but shortened to 130 characters
43// to avoid issues with maximum path length. We don't provision longer names so
44// this applies only if you manually create a volume with a name of more than
45// 130 characters.
Lorenz Brun37050122021-03-30 14:00:27 +020046var acceptableNames = regexp.MustCompile("^[a-z][a-z0-9-.]{0,128}[a-z0-9]$")
Lorenz Brun0db90ba2020-04-06 14:04:52 +020047
Serge Bazanskic2c7ad92020-07-13 17:20:09 +020048type csiPluginServer struct {
Lorenz Brun37050122021-03-30 14:00:27 +020049 *csi.UnimplementedNodeServer
Serge Bazanskic2c7ad92020-07-13 17:20:09 +020050 KubeletDirectory *localstorage.DataKubernetesKubeletDirectory
51 VolumesDirectory *localstorage.DataVolumesDirectory
Lorenz Brun0db90ba2020-04-06 14:04:52 +020052
Serge Bazanskic7359672020-10-30 16:38:57 +010053 logger logtree.LeveledLogger
Lorenz Brun0db90ba2020-04-06 14:04:52 +020054}
55
Serge Bazanskic2c7ad92020-07-13 17:20:09 +020056func (s *csiPluginServer) Run(ctx context.Context) error {
57 s.logger = supervisor.Logger(ctx)
Lorenz Brun0db90ba2020-04-06 14:04:52 +020058
Lorenz Brun4599aa22023-06-28 13:09:32 +020059 // Try to remove socket if an unclean shutdown happened.
60 os.Remove(s.KubeletDirectory.Plugins.VFS.FullPath())
61
Serge Bazanskic2c7ad92020-07-13 17:20:09 +020062 pluginListener, err := net.ListenUnix("unix", &net.UnixAddr{Name: s.KubeletDirectory.Plugins.VFS.FullPath(), Net: "unix"})
63 if err != nil {
64 return fmt.Errorf("failed to listen on CSI socket: %w", err)
Lorenz Brun0db90ba2020-04-06 14:04:52 +020065 }
Serge Bazanskic2c7ad92020-07-13 17:20:09 +020066
67 pluginServer := grpc.NewServer()
68 csi.RegisterIdentityServer(pluginServer, s)
69 csi.RegisterNodeServer(pluginServer, s)
Serge Bazanski216fe7b2021-05-21 18:36:16 +020070 // Enable graceful shutdown since we don't have long-running RPCs and most
71 // of them shouldn't and can't be cancelled anyways.
Serge Bazanskic2c7ad92020-07-13 17:20:09 +020072 if err := supervisor.Run(ctx, "csi-node", supervisor.GRPCServer(pluginServer, pluginListener, true)); err != nil {
73 return err
74 }
75
Lorenz Brun4599aa22023-06-28 13:09:32 +020076 // Try to remove socket if an unclean shutdown happened
77 os.Remove(s.KubeletDirectory.PluginsRegistry.VFSReg.FullPath())
78
Serge Bazanskic2c7ad92020-07-13 17:20:09 +020079 registrationListener, err := net.ListenUnix("unix", &net.UnixAddr{Name: s.KubeletDirectory.PluginsRegistry.VFSReg.FullPath(), Net: "unix"})
80 if err != nil {
81 return fmt.Errorf("failed to listen on CSI registration socket: %w", err)
82 }
Serge Bazanskic2c7ad92020-07-13 17:20:09 +020083
84 registrationServer := grpc.NewServer()
85 pluginregistration.RegisterRegistrationServer(registrationServer, s)
86 if err := supervisor.Run(ctx, "registration", supervisor.GRPCServer(registrationServer, registrationListener, true)); err != nil {
87 return err
88 }
89 supervisor.Signal(ctx, supervisor.SignalHealthy)
90 supervisor.Signal(ctx, supervisor.SignalDone)
91 return nil
Lorenz Brun0db90ba2020-04-06 14:04:52 +020092}
93
Serge Bazanskic2c7ad92020-07-13 17:20:09 +020094func (s *csiPluginServer) NodePublishVolume(ctx context.Context, req *csi.NodePublishVolumeRequest) (*csi.NodePublishVolumeResponse, error) {
Lorenz Brun0db90ba2020-04-06 14:04:52 +020095 if !acceptableNames.MatchString(req.VolumeId) {
96 return nil, status.Error(codes.InvalidArgument, "invalid characters in volume id")
97 }
Serge Bazanskic2c7ad92020-07-13 17:20:09 +020098
99 // TODO(q3k): move this logic to localstorage?
100 volumePath := filepath.Join(s.VolumesDirectory.FullPath(), req.VolumeId)
101
Lorenz Brun0db90ba2020-04-06 14:04:52 +0200102 switch req.VolumeCapability.AccessMode.Mode {
103 case csi.VolumeCapability_AccessMode_SINGLE_NODE_WRITER:
104 case csi.VolumeCapability_AccessMode_SINGLE_NODE_READER_ONLY:
105 default:
106 return nil, status.Error(codes.InvalidArgument, "unsupported access mode")
107 }
108 switch req.VolumeCapability.AccessType.(type) {
109 case *csi.VolumeCapability_Mount:
Lorenz Brun37050122021-03-30 14:00:27 +0200110 err := unix.Mount(volumePath, req.TargetPath, "", unix.MS_BIND, "")
111 switch {
112 case err == unix.ENOENT:
113 return nil, status.Error(codes.NotFound, "volume not found")
114 case err != nil:
115 return nil, status.Errorf(codes.Unavailable, "failed to bind-mount volume: %v", err)
116 }
117
118 if req.Readonly {
119 err := unix.Mount(volumePath, req.TargetPath, "", unix.MS_BIND|unix.MS_REMOUNT|unix.MS_RDONLY, "")
120 if err != nil {
121 _ = unix.Unmount(req.TargetPath, 0) // Best-effort
122 return nil, status.Errorf(codes.Unavailable, "failed to remount volume: %v", err)
123 }
124 }
125 case *csi.VolumeCapability_Block:
126 f, err := os.OpenFile(volumePath, os.O_RDWR, 0)
127 if err != nil {
128 return nil, status.Errorf(codes.Unavailable, "failed to open block volume: %v", err)
129 }
130 defer f.Close()
131 var flags uint32 = loop.FlagDirectIO
132 if req.Readonly {
133 flags |= loop.FlagReadOnly
134 }
135 loopdev, err := loop.Create(f, loop.Config{Flags: flags})
136 if err != nil {
137 return nil, status.Errorf(codes.Unavailable, "failed to create loop device: %v", err)
138 }
139 loopdevNum, err := loopdev.Dev()
140 if err != nil {
141 loopdev.Remove()
142 return nil, status.Errorf(codes.Internal, "device number not available: %v", err)
143 }
144 if err := unix.Mknod(req.TargetPath, unix.S_IFBLK|0640, int(loopdevNum)); err != nil {
145 loopdev.Remove()
146 return nil, status.Errorf(codes.Unavailable, "failed to create device node at target path: %v", err)
147 }
148 loopdev.Close()
Lorenz Brun0db90ba2020-04-06 14:04:52 +0200149 default:
150 return nil, status.Error(codes.InvalidArgument, "unsupported access type")
151 }
152
Lorenz Brun0db90ba2020-04-06 14:04:52 +0200153 return &csi.NodePublishVolumeResponse{}, nil
154}
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200155
Lorenz Brun37050122021-03-30 14:00:27 +0200156func (s *csiPluginServer) NodeUnpublishVolume(ctx context.Context, req *csi.NodeUnpublishVolumeRequest) (*csi.NodeUnpublishVolumeResponse, error) {
157 loopdev, err := loop.Open(req.TargetPath)
158 if err == nil {
159 defer loopdev.Close()
160 // We have a block device
161 if err := loopdev.Remove(); err != nil {
162 return nil, status.Errorf(codes.Unavailable, "failed to remove loop device: %v", err)
163 }
164 if err := os.Remove(req.TargetPath); err != nil && !os.IsNotExist(err) {
165 return nil, status.Errorf(codes.Unavailable, "failed to remove device inode: %v", err)
166 }
167 return &csi.NodeUnpublishVolumeResponse{}, nil
168 }
169 // Otherwise try a normal unmount
Lorenz Brun0db90ba2020-04-06 14:04:52 +0200170 if err := unix.Unmount(req.TargetPath, 0); err != nil {
171 return nil, status.Errorf(codes.Unavailable, "failed to unmount volume: %v", err)
172 }
173 return &csi.NodeUnpublishVolumeResponse{}, nil
174}
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200175
176func (*csiPluginServer) NodeGetVolumeStats(ctx context.Context, req *csi.NodeGetVolumeStatsRequest) (*csi.NodeGetVolumeStatsResponse, error) {
Lorenz Brun0db90ba2020-04-06 14:04:52 +0200177 quota, err := fsquota.GetQuota(req.VolumePath)
178 if os.IsNotExist(err) {
179 return nil, status.Error(codes.NotFound, "volume does not exist at this path")
180 } else if err != nil {
181 return nil, status.Errorf(codes.Unavailable, "failed to get quota: %v", err)
182 }
183
184 return &csi.NodeGetVolumeStatsResponse{
185 Usage: []*csi.VolumeUsage{
186 {
187 Total: int64(quota.Bytes),
188 Unit: csi.VolumeUsage_BYTES,
189 Used: int64(quota.BytesUsed),
190 Available: int64(quota.Bytes - quota.BytesUsed),
191 },
192 {
193 Total: int64(quota.Inodes),
194 Unit: csi.VolumeUsage_INODES,
195 Used: int64(quota.InodesUsed),
196 Available: int64(quota.Inodes - quota.InodesUsed),
197 },
198 },
199 }, nil
200}
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200201
Lorenz Brun37050122021-03-30 14:00:27 +0200202func (s *csiPluginServer) NodeExpandVolume(ctx context.Context, req *csi.NodeExpandVolumeRequest) (*csi.NodeExpandVolumeResponse, error) {
Lorenz Brun0db90ba2020-04-06 14:04:52 +0200203 if req.CapacityRange.LimitBytes <= 0 {
204 return nil, status.Error(codes.InvalidArgument, "invalid expanded volume size: at or below zero bytes")
205 }
Lorenz Brun37050122021-03-30 14:00:27 +0200206 loopdev, err := loop.Open(req.VolumePath)
207 if err == nil {
208 defer loopdev.Close()
209 volumePath := filepath.Join(s.VolumesDirectory.FullPath(), req.VolumeId)
210 imageFile, err := os.OpenFile(volumePath, os.O_RDWR, 0)
211 if err != nil {
212 return nil, status.Errorf(codes.Unavailable, "failed to open block volume backing file: %v", err)
213 }
214 defer imageFile.Close()
215 if err := unix.Fallocate(int(imageFile.Fd()), 0, 0, req.CapacityRange.LimitBytes); err != nil {
216 return nil, status.Errorf(codes.Unavailable, "failed to expand volume using fallocate: %v", err)
217 }
218 if err := loopdev.RefreshSize(); err != nil {
219 return nil, status.Errorf(codes.Unavailable, "failed to refresh loop device size: %v", err)
220 }
221 return &csi.NodeExpandVolumeResponse{CapacityBytes: req.CapacityRange.LimitBytes}, nil
222 }
Lorenz Brun0db90ba2020-04-06 14:04:52 +0200223 if err := fsquota.SetQuota(req.VolumePath, uint64(req.CapacityRange.LimitBytes), 0); err != nil {
224 return nil, status.Errorf(codes.Unavailable, "failed to update quota: %v", err)
225 }
226 return &csi.NodeExpandVolumeResponse{CapacityBytes: req.CapacityRange.LimitBytes}, nil
227}
228
229func rpcCapability(cap csi.NodeServiceCapability_RPC_Type) *csi.NodeServiceCapability {
230 return &csi.NodeServiceCapability{
231 Type: &csi.NodeServiceCapability_Rpc{
232 Rpc: &csi.NodeServiceCapability_RPC{Type: cap},
233 },
234 }
235}
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200236
237func (*csiPluginServer) NodeGetCapabilities(ctx context.Context, req *csi.NodeGetCapabilitiesRequest) (*csi.NodeGetCapabilitiesResponse, error) {
Lorenz Brun0db90ba2020-04-06 14:04:52 +0200238 return &csi.NodeGetCapabilitiesResponse{
239 Capabilities: []*csi.NodeServiceCapability{
240 rpcCapability(csi.NodeServiceCapability_RPC_EXPAND_VOLUME),
241 rpcCapability(csi.NodeServiceCapability_RPC_GET_VOLUME_STATS),
242 },
243 }, nil
244}
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200245
246func (*csiPluginServer) NodeGetInfo(ctx context.Context, req *csi.NodeGetInfoRequest) (*csi.NodeGetInfoResponse, error) {
Lorenz Brun0db90ba2020-04-06 14:04:52 +0200247 hostname, err := os.Hostname()
248 if err != nil {
249 return nil, status.Errorf(codes.Unavailable, "failed to get node identity: %v", err)
250 }
251 return &csi.NodeGetInfoResponse{
252 NodeId: hostname,
253 }, nil
254}
255
256// CSI Identity endpoints
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200257func (*csiPluginServer) GetPluginInfo(ctx context.Context, req *csi.GetPluginInfoRequest) (*csi.GetPluginInfoResponse, error) {
Lorenz Brun0db90ba2020-04-06 14:04:52 +0200258 return &csi.GetPluginInfoResponse{
Serge Bazanski662b5b32020-12-21 13:49:00 +0100259 Name: "dev.monogon.metropolis.vfs",
Lorenz Brun0db90ba2020-04-06 14:04:52 +0200260 VendorVersion: "0.0.1", // TODO(lorenz): Maybe stamp?
261 }, nil
262}
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200263
264func (*csiPluginServer) GetPluginCapabilities(ctx context.Context, req *csi.GetPluginCapabilitiesRequest) (*csi.GetPluginCapabilitiesResponse, error) {
Lorenz Brun0db90ba2020-04-06 14:04:52 +0200265 return &csi.GetPluginCapabilitiesResponse{
266 Capabilities: []*csi.PluginCapability{
267 {
268 Type: &csi.PluginCapability_VolumeExpansion_{
269 VolumeExpansion: &csi.PluginCapability_VolumeExpansion{
270 Type: csi.PluginCapability_VolumeExpansion_ONLINE,
271 },
272 },
273 },
274 },
275 }, nil
276}
277
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200278func (s *csiPluginServer) Probe(ctx context.Context, req *csi.ProbeRequest) (*csi.ProbeResponse, error) {
279 return &csi.ProbeResponse{Ready: &wrappers.BoolValue{Value: true}}, nil
Lorenz Brun0db90ba2020-04-06 14:04:52 +0200280}
281
282// Registration endpoints
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200283func (s *csiPluginServer) GetInfo(ctx context.Context, req *pluginregistration.InfoRequest) (*pluginregistration.PluginInfo, error) {
Lorenz Brun0db90ba2020-04-06 14:04:52 +0200284 return &pluginregistration.PluginInfo{
Lorenz Brun4e090352021-03-17 17:44:41 +0100285 Type: pluginregistration.CSIPlugin,
Serge Bazanski662b5b32020-12-21 13:49:00 +0100286 Name: "dev.monogon.metropolis.vfs",
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200287 Endpoint: s.KubeletDirectory.Plugins.VFS.FullPath(),
Lorenz Brun0db90ba2020-04-06 14:04:52 +0200288 SupportedVersions: []string{"1.2"}, // Keep in sync with container-storage-interface/spec package version
289 }, nil
290}
291
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200292func (s *csiPluginServer) NotifyRegistrationStatus(ctx context.Context, req *pluginregistration.RegistrationStatus) (*pluginregistration.RegistrationStatusResponse, error) {
Lorenz Brun0db90ba2020-04-06 14:04:52 +0200293 if req.Error != "" {
Serge Bazanskic7359672020-10-30 16:38:57 +0100294 s.logger.Warningf("Kubelet failed registering CSI plugin: %v", req.Error)
Lorenz Brun0db90ba2020-04-06 14:04:52 +0200295 }
296 return &pluginregistration.RegistrationStatusResponse{}, nil
297}