blob: efd8af4332a56634985eaf010864f2511456461b [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
42// Derived from K8s spec for acceptable names, but shortened to 130 characters to avoid issues with
43// maximum path length. We don't provision longer names so this applies only if you manually create
44// a volume with a name of more than 130 characters.
Lorenz Brun37050122021-03-30 14:00:27 +020045var acceptableNames = regexp.MustCompile("^[a-z][a-z0-9-.]{0,128}[a-z0-9]$")
Lorenz Brun0db90ba2020-04-06 14:04:52 +020046
Serge Bazanskic2c7ad92020-07-13 17:20:09 +020047type csiPluginServer struct {
Lorenz Brun37050122021-03-30 14:00:27 +020048 *csi.UnimplementedNodeServer
Serge Bazanskic2c7ad92020-07-13 17:20:09 +020049 KubeletDirectory *localstorage.DataKubernetesKubeletDirectory
50 VolumesDirectory *localstorage.DataVolumesDirectory
Lorenz Brun0db90ba2020-04-06 14:04:52 +020051
Serge Bazanskic7359672020-10-30 16:38:57 +010052 logger logtree.LeveledLogger
Lorenz Brun0db90ba2020-04-06 14:04:52 +020053}
54
Serge Bazanskic2c7ad92020-07-13 17:20:09 +020055func (s *csiPluginServer) Run(ctx context.Context) error {
56 s.logger = supervisor.Logger(ctx)
Lorenz Brun0db90ba2020-04-06 14:04:52 +020057
Serge Bazanskic2c7ad92020-07-13 17:20:09 +020058 pluginListener, err := net.ListenUnix("unix", &net.UnixAddr{Name: s.KubeletDirectory.Plugins.VFS.FullPath(), Net: "unix"})
59 if err != nil {
60 return fmt.Errorf("failed to listen on CSI socket: %w", err)
Lorenz Brun0db90ba2020-04-06 14:04:52 +020061 }
Serge Bazanskic2c7ad92020-07-13 17:20:09 +020062 pluginListener.SetUnlinkOnClose(true)
63
64 pluginServer := grpc.NewServer()
65 csi.RegisterIdentityServer(pluginServer, s)
66 csi.RegisterNodeServer(pluginServer, s)
67 // Enable graceful shutdown since we don't have long-running RPCs and most of them shouldn't and can't be
68 // cancelled anyways.
69 if err := supervisor.Run(ctx, "csi-node", supervisor.GRPCServer(pluginServer, pluginListener, true)); err != nil {
70 return err
71 }
72
73 registrationListener, err := net.ListenUnix("unix", &net.UnixAddr{Name: s.KubeletDirectory.PluginsRegistry.VFSReg.FullPath(), Net: "unix"})
74 if err != nil {
75 return fmt.Errorf("failed to listen on CSI registration socket: %w", err)
76 }
77 registrationListener.SetUnlinkOnClose(true)
78
79 registrationServer := grpc.NewServer()
80 pluginregistration.RegisterRegistrationServer(registrationServer, s)
81 if err := supervisor.Run(ctx, "registration", supervisor.GRPCServer(registrationServer, registrationListener, true)); err != nil {
82 return err
83 }
84 supervisor.Signal(ctx, supervisor.SignalHealthy)
85 supervisor.Signal(ctx, supervisor.SignalDone)
86 return nil
Lorenz Brun0db90ba2020-04-06 14:04:52 +020087}
88
Serge Bazanskic2c7ad92020-07-13 17:20:09 +020089func (s *csiPluginServer) NodePublishVolume(ctx context.Context, req *csi.NodePublishVolumeRequest) (*csi.NodePublishVolumeResponse, error) {
Lorenz Brun0db90ba2020-04-06 14:04:52 +020090 if !acceptableNames.MatchString(req.VolumeId) {
91 return nil, status.Error(codes.InvalidArgument, "invalid characters in volume id")
92 }
Serge Bazanskic2c7ad92020-07-13 17:20:09 +020093
94 // TODO(q3k): move this logic to localstorage?
95 volumePath := filepath.Join(s.VolumesDirectory.FullPath(), req.VolumeId)
96
Lorenz Brun0db90ba2020-04-06 14:04:52 +020097 switch req.VolumeCapability.AccessMode.Mode {
98 case csi.VolumeCapability_AccessMode_SINGLE_NODE_WRITER:
99 case csi.VolumeCapability_AccessMode_SINGLE_NODE_READER_ONLY:
100 default:
101 return nil, status.Error(codes.InvalidArgument, "unsupported access mode")
102 }
103 switch req.VolumeCapability.AccessType.(type) {
104 case *csi.VolumeCapability_Mount:
Lorenz Brun37050122021-03-30 14:00:27 +0200105 err := unix.Mount(volumePath, req.TargetPath, "", unix.MS_BIND, "")
106 switch {
107 case err == unix.ENOENT:
108 return nil, status.Error(codes.NotFound, "volume not found")
109 case err != nil:
110 return nil, status.Errorf(codes.Unavailable, "failed to bind-mount volume: %v", err)
111 }
112
113 if req.Readonly {
114 err := unix.Mount(volumePath, req.TargetPath, "", unix.MS_BIND|unix.MS_REMOUNT|unix.MS_RDONLY, "")
115 if err != nil {
116 _ = unix.Unmount(req.TargetPath, 0) // Best-effort
117 return nil, status.Errorf(codes.Unavailable, "failed to remount volume: %v", err)
118 }
119 }
120 case *csi.VolumeCapability_Block:
121 f, err := os.OpenFile(volumePath, os.O_RDWR, 0)
122 if err != nil {
123 return nil, status.Errorf(codes.Unavailable, "failed to open block volume: %v", err)
124 }
125 defer f.Close()
126 var flags uint32 = loop.FlagDirectIO
127 if req.Readonly {
128 flags |= loop.FlagReadOnly
129 }
130 loopdev, err := loop.Create(f, loop.Config{Flags: flags})
131 if err != nil {
132 return nil, status.Errorf(codes.Unavailable, "failed to create loop device: %v", err)
133 }
134 loopdevNum, err := loopdev.Dev()
135 if err != nil {
136 loopdev.Remove()
137 return nil, status.Errorf(codes.Internal, "device number not available: %v", err)
138 }
139 if err := unix.Mknod(req.TargetPath, unix.S_IFBLK|0640, int(loopdevNum)); err != nil {
140 loopdev.Remove()
141 return nil, status.Errorf(codes.Unavailable, "failed to create device node at target path: %v", err)
142 }
143 loopdev.Close()
Lorenz Brun0db90ba2020-04-06 14:04:52 +0200144 default:
145 return nil, status.Error(codes.InvalidArgument, "unsupported access type")
146 }
147
Lorenz Brun0db90ba2020-04-06 14:04:52 +0200148 return &csi.NodePublishVolumeResponse{}, nil
149}
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200150
Lorenz Brun37050122021-03-30 14:00:27 +0200151func (s *csiPluginServer) NodeUnpublishVolume(ctx context.Context, req *csi.NodeUnpublishVolumeRequest) (*csi.NodeUnpublishVolumeResponse, error) {
152 loopdev, err := loop.Open(req.TargetPath)
153 if err == nil {
154 defer loopdev.Close()
155 // We have a block device
156 if err := loopdev.Remove(); err != nil {
157 return nil, status.Errorf(codes.Unavailable, "failed to remove loop device: %v", err)
158 }
159 if err := os.Remove(req.TargetPath); err != nil && !os.IsNotExist(err) {
160 return nil, status.Errorf(codes.Unavailable, "failed to remove device inode: %v", err)
161 }
162 return &csi.NodeUnpublishVolumeResponse{}, nil
163 }
164 // Otherwise try a normal unmount
Lorenz Brun0db90ba2020-04-06 14:04:52 +0200165 if err := unix.Unmount(req.TargetPath, 0); err != nil {
166 return nil, status.Errorf(codes.Unavailable, "failed to unmount volume: %v", err)
167 }
168 return &csi.NodeUnpublishVolumeResponse{}, nil
169}
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200170
171func (*csiPluginServer) NodeGetVolumeStats(ctx context.Context, req *csi.NodeGetVolumeStatsRequest) (*csi.NodeGetVolumeStatsResponse, error) {
Lorenz Brun0db90ba2020-04-06 14:04:52 +0200172 quota, err := fsquota.GetQuota(req.VolumePath)
173 if os.IsNotExist(err) {
174 return nil, status.Error(codes.NotFound, "volume does not exist at this path")
175 } else if err != nil {
176 return nil, status.Errorf(codes.Unavailable, "failed to get quota: %v", err)
177 }
178
179 return &csi.NodeGetVolumeStatsResponse{
180 Usage: []*csi.VolumeUsage{
181 {
182 Total: int64(quota.Bytes),
183 Unit: csi.VolumeUsage_BYTES,
184 Used: int64(quota.BytesUsed),
185 Available: int64(quota.Bytes - quota.BytesUsed),
186 },
187 {
188 Total: int64(quota.Inodes),
189 Unit: csi.VolumeUsage_INODES,
190 Used: int64(quota.InodesUsed),
191 Available: int64(quota.Inodes - quota.InodesUsed),
192 },
193 },
194 }, nil
195}
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200196
Lorenz Brun37050122021-03-30 14:00:27 +0200197func (s *csiPluginServer) NodeExpandVolume(ctx context.Context, req *csi.NodeExpandVolumeRequest) (*csi.NodeExpandVolumeResponse, error) {
Lorenz Brun0db90ba2020-04-06 14:04:52 +0200198 if req.CapacityRange.LimitBytes <= 0 {
199 return nil, status.Error(codes.InvalidArgument, "invalid expanded volume size: at or below zero bytes")
200 }
Lorenz Brun37050122021-03-30 14:00:27 +0200201 loopdev, err := loop.Open(req.VolumePath)
202 if err == nil {
203 defer loopdev.Close()
204 volumePath := filepath.Join(s.VolumesDirectory.FullPath(), req.VolumeId)
205 imageFile, err := os.OpenFile(volumePath, os.O_RDWR, 0)
206 if err != nil {
207 return nil, status.Errorf(codes.Unavailable, "failed to open block volume backing file: %v", err)
208 }
209 defer imageFile.Close()
210 if err := unix.Fallocate(int(imageFile.Fd()), 0, 0, req.CapacityRange.LimitBytes); err != nil {
211 return nil, status.Errorf(codes.Unavailable, "failed to expand volume using fallocate: %v", err)
212 }
213 if err := loopdev.RefreshSize(); err != nil {
214 return nil, status.Errorf(codes.Unavailable, "failed to refresh loop device size: %v", err)
215 }
216 return &csi.NodeExpandVolumeResponse{CapacityBytes: req.CapacityRange.LimitBytes}, nil
217 }
Lorenz Brun0db90ba2020-04-06 14:04:52 +0200218 if err := fsquota.SetQuota(req.VolumePath, uint64(req.CapacityRange.LimitBytes), 0); err != nil {
219 return nil, status.Errorf(codes.Unavailable, "failed to update quota: %v", err)
220 }
221 return &csi.NodeExpandVolumeResponse{CapacityBytes: req.CapacityRange.LimitBytes}, nil
222}
223
224func rpcCapability(cap csi.NodeServiceCapability_RPC_Type) *csi.NodeServiceCapability {
225 return &csi.NodeServiceCapability{
226 Type: &csi.NodeServiceCapability_Rpc{
227 Rpc: &csi.NodeServiceCapability_RPC{Type: cap},
228 },
229 }
230}
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200231
232func (*csiPluginServer) NodeGetCapabilities(ctx context.Context, req *csi.NodeGetCapabilitiesRequest) (*csi.NodeGetCapabilitiesResponse, error) {
Lorenz Brun0db90ba2020-04-06 14:04:52 +0200233 return &csi.NodeGetCapabilitiesResponse{
234 Capabilities: []*csi.NodeServiceCapability{
235 rpcCapability(csi.NodeServiceCapability_RPC_EXPAND_VOLUME),
236 rpcCapability(csi.NodeServiceCapability_RPC_GET_VOLUME_STATS),
237 },
238 }, nil
239}
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200240
241func (*csiPluginServer) NodeGetInfo(ctx context.Context, req *csi.NodeGetInfoRequest) (*csi.NodeGetInfoResponse, error) {
Lorenz Brun0db90ba2020-04-06 14:04:52 +0200242 hostname, err := os.Hostname()
243 if err != nil {
244 return nil, status.Errorf(codes.Unavailable, "failed to get node identity: %v", err)
245 }
246 return &csi.NodeGetInfoResponse{
247 NodeId: hostname,
248 }, nil
249}
250
251// CSI Identity endpoints
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200252func (*csiPluginServer) GetPluginInfo(ctx context.Context, req *csi.GetPluginInfoRequest) (*csi.GetPluginInfoResponse, error) {
Lorenz Brun0db90ba2020-04-06 14:04:52 +0200253 return &csi.GetPluginInfoResponse{
Serge Bazanski662b5b32020-12-21 13:49:00 +0100254 Name: "dev.monogon.metropolis.vfs",
Lorenz Brun0db90ba2020-04-06 14:04:52 +0200255 VendorVersion: "0.0.1", // TODO(lorenz): Maybe stamp?
256 }, nil
257}
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200258
259func (*csiPluginServer) GetPluginCapabilities(ctx context.Context, req *csi.GetPluginCapabilitiesRequest) (*csi.GetPluginCapabilitiesResponse, error) {
Lorenz Brun0db90ba2020-04-06 14:04:52 +0200260 return &csi.GetPluginCapabilitiesResponse{
261 Capabilities: []*csi.PluginCapability{
262 {
263 Type: &csi.PluginCapability_VolumeExpansion_{
264 VolumeExpansion: &csi.PluginCapability_VolumeExpansion{
265 Type: csi.PluginCapability_VolumeExpansion_ONLINE,
266 },
267 },
268 },
269 },
270 }, nil
271}
272
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200273func (s *csiPluginServer) Probe(ctx context.Context, req *csi.ProbeRequest) (*csi.ProbeResponse, error) {
274 return &csi.ProbeResponse{Ready: &wrappers.BoolValue{Value: true}}, nil
Lorenz Brun0db90ba2020-04-06 14:04:52 +0200275}
276
277// Registration endpoints
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200278func (s *csiPluginServer) GetInfo(ctx context.Context, req *pluginregistration.InfoRequest) (*pluginregistration.PluginInfo, error) {
Lorenz Brun0db90ba2020-04-06 14:04:52 +0200279 return &pluginregistration.PluginInfo{
Lorenz Brun4e090352021-03-17 17:44:41 +0100280 Type: pluginregistration.CSIPlugin,
Serge Bazanski662b5b32020-12-21 13:49:00 +0100281 Name: "dev.monogon.metropolis.vfs",
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200282 Endpoint: s.KubeletDirectory.Plugins.VFS.FullPath(),
Lorenz Brun0db90ba2020-04-06 14:04:52 +0200283 SupportedVersions: []string{"1.2"}, // Keep in sync with container-storage-interface/spec package version
284 }, nil
285}
286
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200287func (s *csiPluginServer) NotifyRegistrationStatus(ctx context.Context, req *pluginregistration.RegistrationStatus) (*pluginregistration.RegistrationStatusResponse, error) {
Lorenz Brun0db90ba2020-04-06 14:04:52 +0200288 if req.Error != "" {
Serge Bazanskic7359672020-10-30 16:38:57 +0100289 s.logger.Warningf("Kubelet failed registering CSI plugin: %v", req.Error)
Lorenz Brun0db90ba2020-04-06 14:04:52 +0200290 }
291 return &pluginregistration.RegistrationStatusResponse{}, nil
292}