Skip to content

Commit

Permalink
Improve Templates deletion validation
Browse files Browse the repository at this point in the history
The following rules are validated:
1. ClusterTemplate or ServiceTemplate can't be removed if it is in use by
   ManagedCluster
2. ClusterTemplate or ServiceTemplate can't be removed if the request
   was triggered by user and the template is managed by the
   TemplateManagement
3. ProviderTemplates can be removed by the controller only
  • Loading branch information
eromanova committed Oct 21, 2024
1 parent fb10d3f commit 7dbda57
Show file tree
Hide file tree
Showing 12 changed files with 485 additions and 62 deletions.
40 changes: 39 additions & 1 deletion api/v1alpha1/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,14 @@ func SetupIndexers(ctx context.Context, mgr ctrl.Manager) error {
return err
}

return SetupManagedClusterServicesIndexer(ctx, mgr)
if err := SetupManagedClusterServicesIndexer(ctx, mgr); err != nil {
return err
}

if err := SetupClusterTemplateChainIndexer(ctx, mgr); err != nil {
return err
}
return SetupServiceTemplateChainIndexer(ctx, mgr)
}

const TemplateKey = ".spec.template"
Expand Down Expand Up @@ -145,6 +152,37 @@ func ExtractServiceTemplateName(rawObj client.Object) []string {
return templates
}

const SupportedTemplateKey = ".spec.supportedTemplates[].Name"

func SetupClusterTemplateChainIndexer(ctx context.Context, mgr ctrl.Manager) error {
return mgr.GetFieldIndexer().IndexField(ctx, &ClusterTemplateChain{}, SupportedTemplateKey, ExtractSupportedTemplatesNames)
}

func SetupServiceTemplateChainIndexer(ctx context.Context, mgr ctrl.Manager) error {
return mgr.GetFieldIndexer().IndexField(ctx, &ServiceTemplateChain{}, SupportedTemplateKey, ExtractSupportedTemplatesNames)
}

func ExtractSupportedTemplatesNames(rawObj client.Object) []string {
chainSpec := TemplateChainSpec{}
ctChain, isClusterTemplateChain := rawObj.(*ClusterTemplateChain)
stChain, isServiceTemplateChain := rawObj.(*ServiceTemplateChain)
switch {
case isClusterTemplateChain:
chainSpec = ctChain.Spec
case isServiceTemplateChain:
chainSpec = stChain.Spec
default:
return nil
}

supportedTemplates := make([]string, 0, len(chainSpec.SupportedTemplates))
for _, t := range chainSpec.SupportedTemplates {
supportedTemplates = append(supportedTemplates, t.Name)
}

return supportedTemplates
}

func (c ProvidersTupled) BootstrapProvidersNames() []string {
return c.names(bootstrapProvidersType)
}
Expand Down
3 changes: 3 additions & 0 deletions api/v1alpha1/providertemplate_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ import (
)

const (
// Denotes the providertemplate resource Kind.
ProviderTemplateKind = "ProviderTemplate"

// ChartAnnotationCAPIVersion is an annotation containing the CAPI exact version in the SemVer format associated with a ProviderTemplate.
ChartAnnotationCAPIVersion = "hmc.mirantis.com/capi-version"
// ChartAnnotationCAPIVersionConstraint is an annotation containing the CAPI version constraint in the SemVer format associated with a ProviderTemplate.
Expand Down
24 changes: 21 additions & 3 deletions internal/controller/suite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,12 @@ import (
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
admissionv1 "k8s.io/api/admissionregistration/v1"
authenticationv1 "k8s.io/api/authentication/v1"
utilyaml "sigs.k8s.io/cluster-api/util/yaml"
ctrl "sigs.k8s.io/controller-runtime"
metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server"
"sigs.k8s.io/controller-runtime/pkg/webhook"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"

helmcontrollerv2 "github.com/fluxcd/helm-controller/api/v2"
sourcev1 "github.com/fluxcd/source-controller/api/v1"
Expand All @@ -55,6 +57,8 @@ import (
const (
mutatingWebhookKind = "MutatingWebhookConfiguration"
validatingWebhookKind = "ValidatingWebhookConfiguration"

hmcServiceAccountName = "hmc-controller-manager"
)

var (
Expand All @@ -63,6 +67,8 @@ var (
testEnv *envtest.Environment
ctx context.Context
cancel context.CancelFunc

userInfo = authenticationv1.UserInfo{Username: fmt.Sprintf("system:serviceaccount:hmc-system:%s", hmcServiceAccountName)}
)

func TestControllers(t *testing.T) {
Expand All @@ -83,6 +89,9 @@ var _ = BeforeSuite(func() {
)
Expect(err).NotTo(HaveOccurred())

err = os.Setenv(hmcwebhook.ServiceAccountEnvName, hmcServiceAccountName)
Expect(err).To(Succeed())

testEnv = &envtest.Environment{
CRDDirectoryPaths: []string{
filepath.Join("..", "..", "templates", "provider", "hmc", "templates", "crds"),
Expand Down Expand Up @@ -156,13 +165,19 @@ var _ = BeforeSuite(func() {
err = (&hmcwebhook.ServiceTemplateChainValidator{}).SetupWebhookWithManager(mgr)
Expect(err).NotTo(HaveOccurred())

err = (&hmcwebhook.ClusterTemplateValidator{}).SetupWebhookWithManager(mgr)
templateValidator := hmcwebhook.TemplateValidator{
InjectUserInfo: func(req *admission.Request) {
req.UserInfo = userInfo
},
}

err = (&hmcwebhook.ClusterTemplateValidator{TemplateValidator: templateValidator}).SetupWebhookWithManager(mgr)
Expect(err).NotTo(HaveOccurred())

err = (&hmcwebhook.ServiceTemplateValidator{}).SetupWebhookWithManager(mgr)
err = (&hmcwebhook.ServiceTemplateValidator{TemplateValidator: templateValidator}).SetupWebhookWithManager(mgr)
Expect(err).NotTo(HaveOccurred())

err = (&hmcwebhook.ProviderTemplateValidator{}).SetupWebhookWithManager(mgr)
err = (&hmcwebhook.ProviderTemplateValidator{TemplateValidator: templateValidator}).SetupWebhookWithManager(mgr)
Expect(err).NotTo(HaveOccurred())

go func() {
Expand All @@ -188,6 +203,9 @@ var _ = AfterSuite(func() {
cancel()
err := testEnv.Stop()
Expect(err).NotTo(HaveOccurred())

err = os.Unsetenv(hmcwebhook.ServiceAccountEnvName)
Expect(err).To(Succeed())
})

func loadWebhooks(path string) ([]*admissionv1.ValidatingWebhookConfiguration, []*admissionv1.MutatingWebhookConfiguration, error) {
Expand Down
2 changes: 1 addition & 1 deletion internal/controller/template_controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ var _ = Describe("Template Controller", func() {
err = k8sClient.Get(ctx, typeNamespacedName, providerTemplateResource)
Expect(err).NotTo(HaveOccurred())

By("Cleanup the specific resource instance ClusterTemplate")
By("Cleanup the specific resource instance ProviderTemplate")
Expect(k8sClient.Delete(ctx, providerTemplateResource)).To(Succeed())
})

Expand Down
26 changes: 13 additions & 13 deletions internal/controller/templatechain_controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -213,19 +213,6 @@ var _ = Describe("Template Chain Controller", func() {
})

AfterEach(func() {
for _, template := range []*hmcmirantiscomv1alpha1.ClusterTemplate{
ctTemplates["test"], ctTemplates["ct0"], ctTemplates["ct1"], ctTemplates["ct2"],
} {
err := k8sClient.Delete(ctx, template)
Expect(crclient.IgnoreNotFound(err)).To(Succeed())
}
for _, template := range []*hmcmirantiscomv1alpha1.ServiceTemplate{
stTemplates["test"], stTemplates["st0"], stTemplates["st1"], stTemplates["st2"],
} {
err := k8sClient.Delete(ctx, template)
Expect(crclient.IgnoreNotFound(err)).To(Succeed())
}

for _, chain := range ctChainNames {
clusterTemplateChainResource := &hmcmirantiscomv1alpha1.ClusterTemplateChain{}
err := k8sClient.Get(ctx, chain, clusterTemplateChainResource)
Expand All @@ -243,6 +230,19 @@ var _ = Describe("Template Chain Controller", func() {
Expect(k8sClient.Delete(ctx, serviceTemplateChainResource)).To(Succeed())
}

for _, template := range []*hmcmirantiscomv1alpha1.ClusterTemplate{
ctTemplates["test"], ctTemplates["ct0"], ctTemplates["ct1"], ctTemplates["ct2"],
} {
err := k8sClient.Delete(ctx, template)
Expect(crclient.IgnoreNotFound(err)).To(Succeed())
}
for _, template := range []*hmcmirantiscomv1alpha1.ServiceTemplate{
stTemplates["test"], stTemplates["st0"], stTemplates["st1"], stTemplates["st2"],
} {
err := k8sClient.Delete(ctx, template)
Expect(crclient.IgnoreNotFound(err)).To(Succeed())
}

By("Cleanup the namespace")
err := k8sClient.Get(ctx, types.NamespacedName{Name: namespace.Name}, namespace)
Expect(err).NotTo(HaveOccurred())
Expand Down
Loading

0 comments on commit 7dbda57

Please sign in to comment.