blob: ab9549d68c89965e010fa7a6a5652c04b8355969 [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"
Lorenz Brun0db90ba2020-04-06 14:04:52 +020028 "golang.org/x/sys/unix"
29 "google.golang.org/grpc"
30 "google.golang.org/grpc/codes"
31 "google.golang.org/grpc/status"
Lorenz Brun65702192023-08-31 16:27:38 +020032 "google.golang.org/protobuf/types/known/wrapperspb"
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 }
Lorenz Brund1c392a2023-07-06 19:10:56 +0200108 if err := os.MkdirAll(req.TargetPath, 0700); err != nil {
109 return nil, status.Errorf(codes.Internal, "unable to create requested target path: %v", err)
110 }
Lorenz Brun0db90ba2020-04-06 14:04:52 +0200111 switch req.VolumeCapability.AccessType.(type) {
112 case *csi.VolumeCapability_Mount:
Lorenz Brun37050122021-03-30 14:00:27 +0200113 err := unix.Mount(volumePath, req.TargetPath, "", unix.MS_BIND, "")
114 switch {
115 case err == unix.ENOENT:
116 return nil, status.Error(codes.NotFound, "volume not found")
117 case err != nil:
118 return nil, status.Errorf(codes.Unavailable, "failed to bind-mount volume: %v", err)
119 }
120
121 if req.Readonly {
122 err := unix.Mount(volumePath, req.TargetPath, "", unix.MS_BIND|unix.MS_REMOUNT|unix.MS_RDONLY, "")
123 if err != nil {
124 _ = unix.Unmount(req.TargetPath, 0) // Best-effort
125 return nil, status.Errorf(codes.Unavailable, "failed to remount volume: %v", err)
126 }
127 }
128 case *csi.VolumeCapability_Block:
129 f, err := os.OpenFile(volumePath, os.O_RDWR, 0)
130 if err != nil {
131 return nil, status.Errorf(codes.Unavailable, "failed to open block volume: %v", err)
132 }
133 defer f.Close()
134 var flags uint32 = loop.FlagDirectIO
135 if req.Readonly {
136 flags |= loop.FlagReadOnly
137 }
138 loopdev, err := loop.Create(f, loop.Config{Flags: flags})
139 if err != nil {
140 return nil, status.Errorf(codes.Unavailable, "failed to create loop device: %v", err)
141 }
142 loopdevNum, err := loopdev.Dev()
143 if err != nil {
144 loopdev.Remove()
145 return nil, status.Errorf(codes.Internal, "device number not available: %v", err)
146 }
147 if err := unix.Mknod(req.TargetPath, unix.S_IFBLK|0640, int(loopdevNum)); err != nil {
148 loopdev.Remove()
149 return nil, status.Errorf(codes.Unavailable, "failed to create device node at target path: %v", err)
150 }
151 loopdev.Close()
Lorenz Brun0db90ba2020-04-06 14:04:52 +0200152 default:
153 return nil, status.Error(codes.InvalidArgument, "unsupported access type")
154 }
155
Lorenz Brun0db90ba2020-04-06 14:04:52 +0200156 return &csi.NodePublishVolumeResponse{}, nil
157}
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200158
Lorenz Brun37050122021-03-30 14:00:27 +0200159func (s *csiPluginServer) NodeUnpublishVolume(ctx context.Context, req *csi.NodeUnpublishVolumeRequest) (*csi.NodeUnpublishVolumeResponse, error) {
160 loopdev, err := loop.Open(req.TargetPath)
161 if err == nil {
162 defer loopdev.Close()
163 // We have a block device
164 if err := loopdev.Remove(); err != nil {
165 return nil, status.Errorf(codes.Unavailable, "failed to remove loop device: %v", err)
166 }
167 if err := os.Remove(req.TargetPath); err != nil && !os.IsNotExist(err) {
168 return nil, status.Errorf(codes.Unavailable, "failed to remove device inode: %v", err)
169 }
170 return &csi.NodeUnpublishVolumeResponse{}, nil
171 }
172 // Otherwise try a normal unmount
Lorenz Brun0db90ba2020-04-06 14:04:52 +0200173 if err := unix.Unmount(req.TargetPath, 0); err != nil {
174 return nil, status.Errorf(codes.Unavailable, "failed to unmount volume: %v", err)
175 }
176 return &csi.NodeUnpublishVolumeResponse{}, nil
177}
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200178
179func (*csiPluginServer) NodeGetVolumeStats(ctx context.Context, req *csi.NodeGetVolumeStatsRequest) (*csi.NodeGetVolumeStatsResponse, error) {
Lorenz Brun0db90ba2020-04-06 14:04:52 +0200180 quota, err := fsquota.GetQuota(req.VolumePath)
181 if os.IsNotExist(err) {
182 return nil, status.Error(codes.NotFound, "volume does not exist at this path")
183 } else if err != nil {
184 return nil, status.Errorf(codes.Unavailable, "failed to get quota: %v", err)
185 }
186
187 return &csi.NodeGetVolumeStatsResponse{
188 Usage: []*csi.VolumeUsage{
189 {
190 Total: int64(quota.Bytes),
191 Unit: csi.VolumeUsage_BYTES,
192 Used: int64(quota.BytesUsed),
193 Available: int64(quota.Bytes - quota.BytesUsed),
194 },
195 {
196 Total: int64(quota.Inodes),
197 Unit: csi.VolumeUsage_INODES,
198 Used: int64(quota.InodesUsed),
199 Available: int64(quota.Inodes - quota.InodesUsed),
200 },
201 },
202 }, nil
203}
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200204
Lorenz Brun37050122021-03-30 14:00:27 +0200205func (s *csiPluginServer) NodeExpandVolume(ctx context.Context, req *csi.NodeExpandVolumeRequest) (*csi.NodeExpandVolumeResponse, error) {
Lorenz Brun0db90ba2020-04-06 14:04:52 +0200206 if req.CapacityRange.LimitBytes <= 0 {
207 return nil, status.Error(codes.InvalidArgument, "invalid expanded volume size: at or below zero bytes")
208 }
Lorenz Brun37050122021-03-30 14:00:27 +0200209 loopdev, err := loop.Open(req.VolumePath)
210 if err == nil {
211 defer loopdev.Close()
212 volumePath := filepath.Join(s.VolumesDirectory.FullPath(), req.VolumeId)
213 imageFile, err := os.OpenFile(volumePath, os.O_RDWR, 0)
214 if err != nil {
215 return nil, status.Errorf(codes.Unavailable, "failed to open block volume backing file: %v", err)
216 }
217 defer imageFile.Close()
218 if err := unix.Fallocate(int(imageFile.Fd()), 0, 0, req.CapacityRange.LimitBytes); err != nil {
219 return nil, status.Errorf(codes.Unavailable, "failed to expand volume using fallocate: %v", err)
220 }
221 if err := loopdev.RefreshSize(); err != nil {
222 return nil, status.Errorf(codes.Unavailable, "failed to refresh loop device size: %v", err)
223 }
224 return &csi.NodeExpandVolumeResponse{CapacityBytes: req.CapacityRange.LimitBytes}, nil
225 }
Lorenz Brun0db90ba2020-04-06 14:04:52 +0200226 if err := fsquota.SetQuota(req.VolumePath, uint64(req.CapacityRange.LimitBytes), 0); err != nil {
227 return nil, status.Errorf(codes.Unavailable, "failed to update quota: %v", err)
228 }
229 return &csi.NodeExpandVolumeResponse{CapacityBytes: req.CapacityRange.LimitBytes}, nil
230}
231
232func rpcCapability(cap csi.NodeServiceCapability_RPC_Type) *csi.NodeServiceCapability {
233 return &csi.NodeServiceCapability{
234 Type: &csi.NodeServiceCapability_Rpc{
235 Rpc: &csi.NodeServiceCapability_RPC{Type: cap},
236 },
237 }
238}
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200239
240func (*csiPluginServer) NodeGetCapabilities(ctx context.Context, req *csi.NodeGetCapabilitiesRequest) (*csi.NodeGetCapabilitiesResponse, error) {
Lorenz Brun0db90ba2020-04-06 14:04:52 +0200241 return &csi.NodeGetCapabilitiesResponse{
242 Capabilities: []*csi.NodeServiceCapability{
243 rpcCapability(csi.NodeServiceCapability_RPC_EXPAND_VOLUME),
244 rpcCapability(csi.NodeServiceCapability_RPC_GET_VOLUME_STATS),
245 },
246 }, nil
247}
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200248
249func (*csiPluginServer) NodeGetInfo(ctx context.Context, req *csi.NodeGetInfoRequest) (*csi.NodeGetInfoResponse, error) {
Lorenz Brun0db90ba2020-04-06 14:04:52 +0200250 hostname, err := os.Hostname()
251 if err != nil {
252 return nil, status.Errorf(codes.Unavailable, "failed to get node identity: %v", err)
253 }
254 return &csi.NodeGetInfoResponse{
255 NodeId: hostname,
256 }, nil
257}
258
259// CSI Identity endpoints
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200260func (*csiPluginServer) GetPluginInfo(ctx context.Context, req *csi.GetPluginInfoRequest) (*csi.GetPluginInfoResponse, error) {
Lorenz Brun0db90ba2020-04-06 14:04:52 +0200261 return &csi.GetPluginInfoResponse{
Serge Bazanski662b5b32020-12-21 13:49:00 +0100262 Name: "dev.monogon.metropolis.vfs",
Lorenz Brun0db90ba2020-04-06 14:04:52 +0200263 VendorVersion: "0.0.1", // TODO(lorenz): Maybe stamp?
264 }, nil
265}
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200266
267func (*csiPluginServer) GetPluginCapabilities(ctx context.Context, req *csi.GetPluginCapabilitiesRequest) (*csi.GetPluginCapabilitiesResponse, error) {
Lorenz Brun0db90ba2020-04-06 14:04:52 +0200268 return &csi.GetPluginCapabilitiesResponse{
269 Capabilities: []*csi.PluginCapability{
270 {
271 Type: &csi.PluginCapability_VolumeExpansion_{
272 VolumeExpansion: &csi.PluginCapability_VolumeExpansion{
273 Type: csi.PluginCapability_VolumeExpansion_ONLINE,
274 },
275 },
276 },
277 },
278 }, nil
279}
280
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200281func (s *csiPluginServer) Probe(ctx context.Context, req *csi.ProbeRequest) (*csi.ProbeResponse, error) {
Lorenz Brun65702192023-08-31 16:27:38 +0200282 return &csi.ProbeResponse{Ready: &wrapperspb.BoolValue{Value: true}}, nil
Lorenz Brun0db90ba2020-04-06 14:04:52 +0200283}
284
285// Registration endpoints
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200286func (s *csiPluginServer) GetInfo(ctx context.Context, req *pluginregistration.InfoRequest) (*pluginregistration.PluginInfo, error) {
Lorenz Brun0db90ba2020-04-06 14:04:52 +0200287 return &pluginregistration.PluginInfo{
Lorenz Brun4e090352021-03-17 17:44:41 +0100288 Type: pluginregistration.CSIPlugin,
Serge Bazanski662b5b32020-12-21 13:49:00 +0100289 Name: "dev.monogon.metropolis.vfs",
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200290 Endpoint: s.KubeletDirectory.Plugins.VFS.FullPath(),
Lorenz Brun0db90ba2020-04-06 14:04:52 +0200291 SupportedVersions: []string{"1.2"}, // Keep in sync with container-storage-interface/spec package version
292 }, nil
293}
294
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200295func (s *csiPluginServer) NotifyRegistrationStatus(ctx context.Context, req *pluginregistration.RegistrationStatus) (*pluginregistration.RegistrationStatusResponse, error) {
Lorenz Brun0db90ba2020-04-06 14:04:52 +0200296 if req.Error != "" {
Serge Bazanskic7359672020-10-30 16:38:57 +0100297 s.logger.Warningf("Kubelet failed registering CSI plugin: %v", req.Error)
Lorenz Brun0db90ba2020-04-06 14:04:52 +0200298 }
299 return &pluginregistration.RegistrationStatusResponse{}, nil
300}