blob: 0e9e4194bc37ab0194caf986cd95c49d47051828 [file] [log] [blame]
Lorenz Brunb15abad2020-04-16 11:17:12 +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 "errors"
22 "fmt"
23 "io/ioutil"
24 "os"
25 "path/filepath"
26
Lorenz Brunb15abad2020-04-16 11:17:12 +020027 "go.uber.org/zap"
Lorenz Brunb15abad2020-04-16 11:17:12 +020028 v1 "k8s.io/api/core/v1"
29 storagev1 "k8s.io/api/storage/v1"
30 apierrs "k8s.io/apimachinery/pkg/api/errors"
31 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
32 "k8s.io/client-go/informers"
33 coreinformers "k8s.io/client-go/informers/core/v1"
34 storageinformers "k8s.io/client-go/informers/storage/v1"
35 "k8s.io/client-go/kubernetes"
36 "k8s.io/client-go/kubernetes/scheme"
37 typedcorev1 "k8s.io/client-go/kubernetes/typed/core/v1"
38 "k8s.io/client-go/tools/cache"
39 "k8s.io/client-go/tools/record"
40 ref "k8s.io/client-go/tools/reference"
41 "k8s.io/client-go/util/workqueue"
Serge Bazanskic2c7ad92020-07-13 17:20:09 +020042
43 "git.monogon.dev/source/nexantic.git/core/internal/common/supervisor"
44 "git.monogon.dev/source/nexantic.git/core/internal/localstorage"
45 "git.monogon.dev/source/nexantic.git/core/pkg/fsquota"
Lorenz Brunb15abad2020-04-16 11:17:12 +020046)
47
Serge Bazanskic2c7ad92020-07-13 17:20:09 +020048// ONCHANGE(//core/internal/kubernetes/reconciler:resources_csi.go): needs to match csiProvisionerServerName declared.
49const csiProvisionerServerName = "com.nexantic.smalltown.vfs"
Lorenz Brunb15abad2020-04-16 11:17:12 +020050
Serge Bazanskic2c7ad92020-07-13 17:20:09 +020051// csiProvisionerServer is responsible for the provisioning and deprovisioning of CSI-based container volumes. It runs on all
Lorenz Brunb15abad2020-04-16 11:17:12 +020052// nodes and watches PVCs for ones assigned to the node it's running on and fulfills the provisioning request by
53// creating a directory, applying a quota and creating the corresponding PV. When the PV is released and its retention
54// policy is Delete, the directory and the PV resource are deleted.
Serge Bazanskic2c7ad92020-07-13 17:20:09 +020055type csiProvisionerServer struct {
56 NodeName string
57 Kubernetes kubernetes.Interface
58 InformerFactory informers.SharedInformerFactory
59 VolumesDirectory *localstorage.DataVolumesDirectory
60
Lorenz Brunb15abad2020-04-16 11:17:12 +020061 claimQueue workqueue.RateLimitingInterface
62 pvQueue workqueue.RateLimitingInterface
63 recorder record.EventRecorder
64 pvcInformer coreinformers.PersistentVolumeClaimInformer
65 pvInformer coreinformers.PersistentVolumeInformer
66 storageClassInformer storageinformers.StorageClassInformer
Lorenz Brunb15abad2020-04-16 11:17:12 +020067 logger *zap.Logger
68}
69
70// runCSIProvisioner runs the main provisioning machinery. It consists of a bunch of informers which keep track of
71// the events happening on the Kubernetes control plane and informs us when something happens. If anything happens to
72// PVCs or PVs, we enqueue the identifier of that resource in a work queue. Queues are being worked on by only one
73// worker to limit load and avoid complicated locking infrastructure. Failed items are requeued.
Serge Bazanskic2c7ad92020-07-13 17:20:09 +020074func (p *csiProvisionerServer) Run(ctx context.Context) error {
75 // The recorder is used to log Kubernetes events for successful or failed volume provisions. These events then
76 // show up in `kubectl describe pvc` and can be used by admins to debug issues with this provisioner.
77 eventBroadcaster := record.NewBroadcaster()
78 eventBroadcaster.StartRecordingToSink(&typedcorev1.EventSinkImpl{Interface: p.Kubernetes.CoreV1().Events("")})
79 p.recorder = eventBroadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: csiProvisionerServerName, Host: p.NodeName})
Lorenz Brunb15abad2020-04-16 11:17:12 +020080
Serge Bazanskic2c7ad92020-07-13 17:20:09 +020081 p.pvInformer = p.InformerFactory.Core().V1().PersistentVolumes()
82 p.pvcInformer = p.InformerFactory.Core().V1().PersistentVolumeClaims()
83 p.storageClassInformer = p.InformerFactory.Storage().V1().StorageClasses()
Lorenz Brunb15abad2020-04-16 11:17:12 +020084
Serge Bazanskic2c7ad92020-07-13 17:20:09 +020085 p.claimQueue = workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter())
86 p.pvQueue = workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter())
Lorenz Brunb15abad2020-04-16 11:17:12 +020087
Serge Bazanskic2c7ad92020-07-13 17:20:09 +020088 p.pvcInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
89 AddFunc: p.enqueueClaim,
90 UpdateFunc: func(old, new interface{}) {
91 p.enqueueClaim(new)
92 },
93 })
94 p.pvInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
95 AddFunc: p.enqueuePV,
96 UpdateFunc: func(old, new interface{}) {
97 p.enqueuePV(new)
98 },
99 })
100 p.logger = supervisor.Logger(ctx)
Lorenz Brunb15abad2020-04-16 11:17:12 +0200101
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200102 go p.pvcInformer.Informer().Run(ctx.Done())
103 go p.pvInformer.Informer().Run(ctx.Done())
104 go p.storageClassInformer.Informer().Run(ctx.Done())
Lorenz Brunb15abad2020-04-16 11:17:12 +0200105
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200106 // These will self-terminate once the queues are shut down
107 go p.processQueueItems(p.claimQueue, func(key string) error {
108 return p.processPVC(key)
109 })
110 go p.processQueueItems(p.pvQueue, func(key string) error {
111 return p.processPV(key)
112 })
Lorenz Brunb15abad2020-04-16 11:17:12 +0200113
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200114 supervisor.Signal(ctx, supervisor.SignalHealthy)
115 <-ctx.Done()
116 p.claimQueue.ShutDown()
117 p.pvQueue.ShutDown()
118 return nil
Lorenz Brunb15abad2020-04-16 11:17:12 +0200119}
120
121// isOurPVC checks if the given PVC is is to be provisioned by this provisioner and has been scheduled onto this node
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200122func (p *csiProvisionerServer) isOurPVC(pvc *v1.PersistentVolumeClaim) bool {
123 if pvc.ObjectMeta.Annotations["volume.beta.kubernetes.io/storage-provisioner"] != csiProvisionerServerName {
124 return false
125 }
126 if pvc.ObjectMeta.Annotations["volume.kubernetes.io/selected-node"] != p.NodeName {
127 return false
128 }
129 return true
Lorenz Brunb15abad2020-04-16 11:17:12 +0200130}
131
132// isOurPV checks if the given PV has been provisioned by this provisioner and has been scheduled onto this node
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200133func (p *csiProvisionerServer) isOurPV(pv *v1.PersistentVolume) bool {
134 if pv.ObjectMeta.Annotations["pv.kubernetes.io/provisioned-by"] != csiProvisionerServerName {
135 return false
136 }
137 if pv.Spec.NodeAffinity.Required.NodeSelectorTerms[0].MatchExpressions[0].Values[0] != p.NodeName {
138 return false
139 }
140 return true
Lorenz Brunb15abad2020-04-16 11:17:12 +0200141}
142
143// enqueueClaim adds an added/changed PVC to the work queue
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200144func (p *csiProvisionerServer) enqueueClaim(obj interface{}) {
Lorenz Brunb15abad2020-04-16 11:17:12 +0200145 key, err := cache.MetaNamespaceKeyFunc(obj)
146 if err != nil {
147 p.logger.Error("Not queuing PVC because key could not be derived", zap.Error(err))
148 return
149 }
150 p.claimQueue.Add(key)
151}
152
153// enqueuePV adds an added/changed PV to the work queue
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200154func (p *csiProvisionerServer) enqueuePV(obj interface{}) {
Lorenz Brunb15abad2020-04-16 11:17:12 +0200155 key, err := cache.MetaNamespaceKeyFunc(obj)
156 if err != nil {
157 p.logger.Error("Not queuing PV because key could not be derived", zap.Error(err))
158 return
159 }
160 p.pvQueue.Add(key)
161}
162
163// processQueueItems gets items from the given work queue and calls the process function for each of them. It self-
164// terminates once the queue is shut down.
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200165func (p *csiProvisionerServer) processQueueItems(queue workqueue.RateLimitingInterface, process func(key string) error) {
Lorenz Brunb15abad2020-04-16 11:17:12 +0200166 for {
167 obj, shutdown := queue.Get()
168 if shutdown {
169 return
170 }
171
172 func(obj interface{}) {
173 defer queue.Done(obj)
174 key, ok := obj.(string)
175 if !ok {
176 queue.Forget(obj)
177 p.logger.Error("Expected string in workqueue", zap.Any("actual", obj))
178 return
179 }
180
181 if err := process(key); err != nil {
182 p.logger.Warn("Failed processing item, requeueing", zap.String("name", key),
183 zap.Int("num_requeues", queue.NumRequeues(obj)), zap.Error(err))
184 queue.AddRateLimited(obj)
185 }
186
187 queue.Forget(obj)
188 }(obj)
189 }
190}
191
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200192// volumePath gets the path where the volume is stored.
193func (p *csiProvisionerServer) volumePath(volumeID string) string {
194 return filepath.Join(p.VolumesDirectory.FullPath(), volumeID)
Lorenz Brunb15abad2020-04-16 11:17:12 +0200195}
196
197// processPVC looks at a single PVC item from the queue, determines if it needs to be provisioned and logs the
198// provisioning result to the recorder
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200199func (p *csiProvisionerServer) processPVC(key string) error {
Lorenz Brunb15abad2020-04-16 11:17:12 +0200200 namespace, name, err := cache.SplitMetaNamespaceKey(key)
201 if err != nil {
202 return fmt.Errorf("invalid resource key: %s", key)
203 }
204 pvc, err := p.pvcInformer.Lister().PersistentVolumeClaims(namespace).Get(name)
205 if apierrs.IsNotFound(err) {
206 return nil // nothing to do, no error
207 } else if err != nil {
208 return fmt.Errorf("failed to get PVC for processing: %w", err)
209 }
210
211 if !p.isOurPVC(pvc) {
212 return nil
213 }
214
215 if pvc.Status.Phase != "Pending" {
216 // If the PVC is not pending, we don't need to provision anything
217 return nil
218 }
219
220 storageClass, err := p.storageClassInformer.Lister().Get(*pvc.Spec.StorageClassName)
221 if err != nil {
222 return fmt.Errorf("")
223 }
224
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200225 if storageClass.Provisioner != csiProvisionerServerName {
Lorenz Brunb15abad2020-04-16 11:17:12 +0200226 // We're not responsible for this PVC. Can only happen if controller-manager makes a mistake
227 // setting the annotations, but we're bailing here anyways for safety.
228 return nil
229 }
230
231 err = p.provisionPVC(pvc, storageClass)
232
233 if err != nil {
234 p.recorder.Eventf(pvc, v1.EventTypeWarning, "ProvisioningFailed", "Failed to provision PV: %v", err)
235 return err
236 }
237 p.recorder.Eventf(pvc, v1.EventTypeNormal, "Provisioned", "Successfully provisioned PV")
238
239 return nil
240}
241
242// provisionPVC creates the directory where the volume lives, sets a quota for the requested amount of storage and
243// creates the PV object representing this new volume
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200244func (p *csiProvisionerServer) provisionPVC(pvc *v1.PersistentVolumeClaim, storageClass *storagev1.StorageClass) error {
Lorenz Brunb15abad2020-04-16 11:17:12 +0200245 claimRef, err := ref.GetReference(scheme.Scheme, pvc)
246 if err != nil {
247 return fmt.Errorf("failed to get reference to PVC: %w", err)
248 }
249
250 storageReq := pvc.Spec.Resources.Requests[v1.ResourceStorage]
251 if storageReq.IsZero() {
252 return fmt.Errorf("PVC is not requesting any storage, this is not supported")
253 }
254 capacity, ok := storageReq.AsInt64()
255 if !ok {
256 return fmt.Errorf("PVC requesting more than 2^63 bytes of storage, this is not supported")
257 }
258
259 if *pvc.Spec.VolumeMode == v1.PersistentVolumeBlock {
260 return fmt.Errorf("Block PVCs are not supported by Smalltown")
261 }
262
263 volumeID := "pvc-" + string(pvc.ObjectMeta.UID)
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200264 volumePath := p.volumePath(volumeID)
Lorenz Brunb15abad2020-04-16 11:17:12 +0200265
266 p.logger.Info("Creating local PV", zap.String("volume-id", volumeID))
267 if err := os.Mkdir(volumePath, 0644); err != nil && !os.IsExist(err) {
268 return fmt.Errorf("failed to create volume directory: %w", err)
269 }
270 files, err := ioutil.ReadDir(volumePath)
271 if err != nil {
272 return fmt.Errorf("failed to list files in newly-created volume: %w", err)
273 }
274 if len(files) > 0 {
275 return errors.New("newly-created volume already contains data, bailing")
276 }
277 if err := fsquota.SetQuota(volumePath, uint64(capacity), 100000); err != nil {
278 return fmt.Errorf("failed to update quota: %v", err)
279 }
280
281 vol := &v1.PersistentVolume{
282 ObjectMeta: metav1.ObjectMeta{
283 Name: volumeID,
284 Annotations: map[string]string{
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200285 "pv.kubernetes.io/provisioned-by": csiProvisionerServerName},
Lorenz Brunb15abad2020-04-16 11:17:12 +0200286 },
287 Spec: v1.PersistentVolumeSpec{
288 AccessModes: []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce},
289 Capacity: v1.ResourceList{
290 v1.ResourceStorage: storageReq, // We're always giving the exact amount
291 },
292 PersistentVolumeSource: v1.PersistentVolumeSource{
293 CSI: &v1.CSIPersistentVolumeSource{
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200294 Driver: csiProvisionerServerName,
Lorenz Brunb15abad2020-04-16 11:17:12 +0200295 VolumeHandle: volumeID,
296 },
297 },
298 ClaimRef: claimRef,
299 NodeAffinity: &v1.VolumeNodeAffinity{
300 Required: &v1.NodeSelector{
301 NodeSelectorTerms: []v1.NodeSelectorTerm{
302 {
303 MatchExpressions: []v1.NodeSelectorRequirement{
304 {
305 Key: "kubernetes.io/hostname",
306 Operator: v1.NodeSelectorOpIn,
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200307 Values: []string{p.NodeName},
Lorenz Brunb15abad2020-04-16 11:17:12 +0200308 },
309 },
310 },
311 },
312 },
313 },
314 StorageClassName: *pvc.Spec.StorageClassName,
315 PersistentVolumeReclaimPolicy: *storageClass.ReclaimPolicy,
316 },
317 }
318
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200319 _, err = p.Kubernetes.CoreV1().PersistentVolumes().Create(context.Background(), vol, metav1.CreateOptions{})
320 if err != nil && !apierrs.IsAlreadyExists(err) {
Lorenz Brunb15abad2020-04-16 11:17:12 +0200321 return fmt.Errorf("failed to create PV object: %w", err)
322 }
323 return nil
324}
325
326// processPV looks at a single PV item from the queue and checks if it has been released and needs to be deleted. If yes
327// it deletes the associated quota, directory and the PV object and logs the result to the recorder.
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200328func (p *csiProvisionerServer) processPV(key string) error {
Lorenz Brunb15abad2020-04-16 11:17:12 +0200329 _, name, err := cache.SplitMetaNamespaceKey(key)
330 if err != nil {
331 return fmt.Errorf("invalid resource key: %s", key)
332 }
333 pv, err := p.pvInformer.Lister().Get(name)
334 if apierrs.IsNotFound(err) {
335 return nil // nothing to do, no error
336 } else if err != nil {
337 return fmt.Errorf("failed to get PV for processing: %w", err)
338 }
339
340 if !p.isOurPV(pv) {
341 return nil
342 }
343 if pv.Spec.PersistentVolumeReclaimPolicy != v1.PersistentVolumeReclaimDelete || pv.Status.Phase != "Released" {
344 return nil
345 }
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200346 volumePath := p.volumePath(pv.Spec.CSI.VolumeHandle)
Lorenz Brunb15abad2020-04-16 11:17:12 +0200347
348 // Log deletes for auditing purposes
349 p.logger.Info("Deleting persistent volume", zap.String("name", pv.Spec.CSI.VolumeHandle))
350 if err := fsquota.SetQuota(volumePath, 0, 0); err != nil {
351 // We record these here manually since a successful deletion removes the PV we'd be attaching them to
352 p.recorder.Eventf(pv, v1.EventTypeWarning, "DeprovisioningFailed", "Failed to remove quota: %v", err)
353 return fmt.Errorf("failed to remove quota: %w", err)
354 }
355 err = os.RemoveAll(volumePath)
356 if os.IsNotExist(err) {
357 return nil
358 } else if err != nil {
359 p.recorder.Eventf(pv, v1.EventTypeWarning, "DeprovisioningFailed", "Failed to delete volume: %v", err)
360 return fmt.Errorf("failed to delete volume: %w", err)
361 }
362
Serge Bazanskic2c7ad92020-07-13 17:20:09 +0200363 err = p.Kubernetes.CoreV1().PersistentVolumes().Delete(context.Background(), pv.Name, metav1.DeleteOptions{})
Lorenz Brunb15abad2020-04-16 11:17:12 +0200364 if err != nil && !apierrs.IsNotFound(err) {
365 p.recorder.Eventf(pv, v1.EventTypeWarning, "DeprovisioningFailed", "Failed to delete PV object from K8s API: %v", err)
366 return fmt.Errorf("failed to delete PV object: %w", err)
367 }
368 return nil
369}