containerized-data-importer/pkg/controller/datavolume/external-population-controller.go
alromeros 2e9a9257f9
Add support for volume populators (#2482)
* Add support for volume populators in CDI

This commit enables the use of volume populators in CDI, so datavolume-owned PVCs can be populated using custom logic.

Volume populators are CRDs used to populate volumes externally, independently of CDI. These CRDs can now be specified using the new DataSourceRef API field in the DataVolume spec.

When a DataVolume is created with a populated DataSourceRef field, the datavolume-controller creates the corresponding PVC accordingly but skips all the population-related steps. Once the PVC is bound, the DV phase changes to succeeded.

Signed-off-by: Alvaro Romero <alromero@redhat.com>

* Modify CDI test infrastructure to support testing of external populators

This commit introduces several changes to CDI ci to support the testing of DataVolumes with external populators:
* A sample volume populator is now deployed in the test infrastructure, in a similar way as bad-webserver or test-proxy. This populator will be used in functional tests from now on.
* A new test file with external population tests has been introduced in the tests directory

Signed-off-by: Alvaro Romero <alromero@redhat.com>

* Update dependencies to include lib-volume-populator library

Signed-off-by: Alvaro Romero <alromero@redhat.com>

* Add functional tests for proper coverage of external population of DataVolumes

Signed-off-by: Alvaro Romero <alromero@redhat.com>

* Minor fixes on external-population logic for DataVolumes:
* Added comments for exported structs
* Removed non-inclusive language
* Improved error messages in webhooks
* Fixed logic on datavolume-controller

Signed-off-by: Alvaro Romero <alromero@redhat.com>

* Improve DataVolume external-population logic when using the old 'DataSource' API

This commit introduces several changes into the datavolume external-population controller to improve its behavior when using the DataSource field.

It also introduces minor fixes on the generic populator logic.

Signed-off-by: Alvaro Romero <alromero@redhat.com>

* Add unit tests for external-population controller and DV admission

Signed-off-by: Alvaro Romero <alromero@redhat.com>

Signed-off-by: Alvaro Romero <alromero@redhat.com>
2023-01-17 21:56:15 +01:00

236 lines
9.6 KiB
Go

/*
Copyright 2022 The CDI Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package datavolume
import (
"context"
"fmt"
"github.com/go-logr/logr"
"github.com/pkg/errors"
corev1 "k8s.io/api/core/v1"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
cc "kubevirt.io/containerized-data-importer/pkg/controller/common"
featuregates "kubevirt.io/containerized-data-importer/pkg/feature-gates"
"sigs.k8s.io/controller-runtime/pkg/controller"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
cdiv1 "kubevirt.io/containerized-data-importer-api/pkg/apis/core/v1beta1"
)
const (
// ExternalPopulationSucceeded provides a const to indicate that the external population of the PVC has succeeded (reason)
ExternalPopulationSucceeded = "ExternalPopulationSucceeded"
// MessageExternalPopulationSucceeded provides a const to indicate that the external population of the PVC has succeeded (message)
MessageExternalPopulationSucceeded = "PVC %s successfully populated by %s"
// NoAnyVolumeDataSource provides a const to indicate that the AnyVolumeDataSource feature gate is not enabled (reason)
NoAnyVolumeDataSource = "NoAnyVolumeDataSource"
// MessageNoAnyVolumeDataSource provides a const to indicate that the AnyVolumeDataSource feature gate is not enabled (message)
MessageNoAnyVolumeDataSource = "AnyVolumeDataSource feature gate is not enabled: External population not supported"
// NoCSIDriverForExternalPopulation provides a const to indicate that no CSI drivers were found for external population (reason)
NoCSIDriverForExternalPopulation = "NoCSIDriverForExternalPopulation"
// MessageNoCSIDriverForExternalPopulation provides a const to indicate that no CSI drivers were found for external population (message)
MessageNoCSIDriverForExternalPopulation = "No CSI drivers were found: External population not supported"
populatorControllerName = "datavolume-external-population-controller"
)
// PopulatorReconciler members
type PopulatorReconciler struct {
ReconcilerBase
}
// NewPopulatorController creates a new instance of the datavolume external population controller
func NewPopulatorController(ctx context.Context, mgr manager.Manager, log logr.Logger, installerLabels map[string]string) (controller.Controller, error) {
client := mgr.GetClient()
reconciler := &PopulatorReconciler{
ReconcilerBase: ReconcilerBase{
client: client,
scheme: mgr.GetScheme(),
log: log.WithName(populatorControllerName),
recorder: mgr.GetEventRecorderFor(populatorControllerName),
featureGates: featuregates.NewFeatureGates(client),
installerLabels: installerLabels,
},
}
reconciler.Reconciler = reconciler
datavolumeController, err := controller.New(populatorControllerName, mgr, controller.Options{Reconciler: reconciler})
if err != nil {
return nil, err
}
if err := addDataVolumeControllerCommonWatches(mgr, datavolumeController, dataVolumePopulator); err != nil {
return nil, err
}
return datavolumeController, nil
}
// Reconcile loop for externally populated DataVolumes
func (r PopulatorReconciler) Reconcile(ctx context.Context, req reconcile.Request) (reconcile.Result, error) {
log := r.log.WithValues("DataVolume", req.NamespacedName)
return r.updateStatus(r.sync(log, req))
}
// If dataSourceRef is set (external populator), use an empty spec.Source field
func (r PopulatorReconciler) prepare(syncRes *dataVolumeSyncResult) error {
if !dvUsesVolumePopulator(syncRes.dv) {
return errors.Errorf("undefined population source")
}
syncRes.dvMutated.Spec.Source = &cdiv1.DataVolumeSource{}
return nil
}
// checkPopulationRequirements returns true if the PVC meets the requirements to be populated
func (r *PopulatorReconciler) checkPopulationRequirements(pvc *corev1.PersistentVolumeClaim, dv *cdiv1.DataVolume, event *Event) (bool, error) {
csiDriverAvailable, err := r.storageClassCSIDriverExists(pvc.Spec.StorageClassName)
if err != nil && !k8serrors.IsNotFound(err) {
return false, err
}
// Non-snapshot population will only work with CSI drivers
if !isSnapshotPopulation(pvc) && !csiDriverAvailable {
r.recorder.Event(pvc, corev1.EventTypeWarning, NoCSIDriverForExternalPopulation, MessageNoCSIDriverForExternalPopulation)
event.reason = NoCSIDriverForExternalPopulation
event.message = MessageNoCSIDriverForExternalPopulation
event.eventType = corev1.EventTypeWarning
return false, nil
}
return r.checkAnyVolumeDataSource(pvc, dv, event), nil
}
// checkAnyVolumeDataSource determines if the AnyVolumeDataSource feature gate is required/enabled
func (r *PopulatorReconciler) checkAnyVolumeDataSource(pvc *corev1.PersistentVolumeClaim, dv *cdiv1.DataVolume, event *Event) bool {
// We don't need the AnyVolumeDataSource feature gate if
// the PVC is externally populated by a PVC or Snapshot.
nonPopulator := isPvcPopulation(pvc) || isSnapshotPopulation(pvc)
// If the AnyVolumeDataSource feature gate is disabled, Kubernetes drops
// the contents of the dataSourceRef field. We can then determine if the
// feature is enabled or not by checking that field after creating the PVC.
enabled := pvc.Spec.DataSourceRef != nil
populationSupported := enabled || nonPopulator
if !populationSupported {
r.recorder.Event(pvc, corev1.EventTypeWarning, NoAnyVolumeDataSource, MessageNoAnyVolumeDataSource)
event.reason = NoAnyVolumeDataSource
event.message = MessageNoAnyVolumeDataSource
event.eventType = corev1.EventTypeWarning
} else {
event.reason = ExternalPopulationSucceeded
event.message = fmt.Sprintf(MessageExternalPopulationSucceeded, pvc.Name, getPopulatorName(pvc))
event.eventType = corev1.EventTypeNormal
}
return populationSupported
}
// getPopulatorName returns the name of the passed PVC's populator
func getPopulatorName(pvc *corev1.PersistentVolumeClaim) string {
var populatorName string
if pvc.Spec.DataSourceRef != nil {
populatorName = pvc.Spec.DataSourceRef.Name
} else {
populatorName = pvc.Spec.DataSource.Name
}
return populatorName
}
// dvUsesVolumePopulator returns true if the datavolume's PVC is meant to be externally populated
func dvUsesVolumePopulator(dv *cdiv1.DataVolume) bool {
return isDataSourcePopulated(dv) || isDataSourceRefPopulated(dv)
}
// isDataSourcePopulated returns true if the DataVolume has a populated DataSource field
func isDataSourcePopulated(dv *cdiv1.DataVolume) bool {
return (dv.Spec.PVC != nil && dv.Spec.PVC.DataSource != nil) ||
(dv.Spec.Storage != nil && dv.Spec.Storage.DataSource != nil)
}
// isDataSourceRefPopulated returns true if the DataVolume has a populated DataSourceRef field
func isDataSourceRefPopulated(dv *cdiv1.DataVolume) bool {
return (dv.Spec.PVC != nil && dv.Spec.PVC.DataSourceRef != nil) ||
(dv.Spec.Storage != nil && dv.Spec.Storage.DataSourceRef != nil)
}
// isPvcPopulation returns true if a PVC's population source is of PVC kind
func isPvcPopulation(pvc *corev1.PersistentVolumeClaim) bool {
return (pvc.Spec.DataSource != nil && pvc.Spec.DataSource.Kind == "PersistentVolumeClaim") ||
(pvc.Spec.DataSourceRef != nil && pvc.Spec.DataSourceRef.Kind == "PersistentVolumeClaim")
}
// isSnapshotPopulation returns true if a PVC's population source is of Snapshot kind
func isSnapshotPopulation(pvc *corev1.PersistentVolumeClaim) bool {
return (pvc.Spec.DataSource != nil && pvc.Spec.DataSource.Kind == "VolumeSnapshot") ||
(pvc.Spec.DataSourceRef != nil && pvc.Spec.DataSourceRef.Kind == "VolumeSnapshot")
}
// Generic controller functions
func (r PopulatorReconciler) updateAnnotations(dataVolume *cdiv1.DataVolume, pvc *corev1.PersistentVolumeClaim) error {
if !dvUsesVolumePopulator(dataVolume) {
return errors.Errorf("undefined population source")
}
pvc.Annotations[cc.AnnExternalPopulation] = "true"
return nil
}
func (r PopulatorReconciler) sync(log logr.Logger, req reconcile.Request) (dataVolumeSyncResult, error) {
syncRes, syncErr := r.syncExternalPopulation(log, req)
if err := r.syncUpdate(log, &syncRes); err != nil {
syncErr = err
}
return syncRes, syncErr
}
func (r PopulatorReconciler) syncExternalPopulation(log logr.Logger, req reconcile.Request) (dataVolumeSyncResult, error) {
syncRes, syncErr := r.syncCommon(log, req, nil, r.prepare)
if syncErr != nil || syncRes.result != nil {
return *syncRes, syncErr
}
if err := r.handlePvcCreation(log, syncRes, r.updateAnnotations); err != nil {
syncErr = err
}
return *syncRes, syncErr
}
func (r PopulatorReconciler) updateStatus(syncRes dataVolumeSyncResult, syncErr error) (reconcile.Result, error) {
if syncErr != nil {
return getReconcileResult(syncRes.result), syncErr
}
res, err := r.updateStatusCommon(syncRes, r.updateStatusPhase)
if err != nil {
syncErr = err
}
return res, syncErr
}
func (r PopulatorReconciler) updateStatusPhase(pvc *corev1.PersistentVolumeClaim, dataVolumeCopy *cdiv1.DataVolume, event *Event) error {
// * Population by Snapshots doesn't have additional requirements.
// * Population by PVC requires CSI drivers.
// * Population by external populators requires both CSI drivers and the AnyVolumeDataSource feature gate.
if supported, err := r.checkPopulationRequirements(pvc, dataVolumeCopy, event); err != nil {
return err
} else if supported {
dataVolumeCopy.Status.Phase = cdiv1.Succeeded
}
return nil
}