Skip to content

Commit

Permalink
Merge pull request Mirantis#380 from eromanova/tm-creation
Browse files Browse the repository at this point in the history
Handle TemplateManagement creation and removal
  • Loading branch information
Kshatrix authored Sep 25, 2024
2 parents 0c6ab14 + d3ab30a commit bcb3a7c
Show file tree
Hide file tree
Showing 12 changed files with 225 additions and 40 deletions.
6 changes: 4 additions & 2 deletions api/v1alpha1/management_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,10 @@ const (

CoreCAPIName = "capi"

ManagementName = "hmc"
ManagementFinalizer = "hmc.mirantis.com/management"
ManagementKind = "Management"
ManagementName = "hmc"
ManagementFinalizer = "hmc.mirantis.com/management"
TemplateManagementName = "hmc"
)

// ManagementSpec defines the desired state of Management
Expand Down
2 changes: 2 additions & 0 deletions api/v1alpha1/templatemanagement_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

const TemplateManagementKind = "TemplateManagement"

// TemplateManagementSpec defines the desired state of TemplateManagement
type TemplateManagementSpec struct {
// AccessRules is the list of access rules. Each AccessRule enforces
Expand Down
16 changes: 10 additions & 6 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ func main() {
insecureRegistry bool
registryCredentialsSecret string
createManagement bool
createTemplateManagement bool
createTemplates bool
hmcTemplatesChartName string
enableTelemetry bool
Expand All @@ -87,6 +88,8 @@ func main() {
"Secret containing authentication credentials for the registry.")
flag.BoolVar(&insecureRegistry, "insecure-registry", false, "Allow connecting to an HTTP registry.")
flag.BoolVar(&createManagement, "create-management", true, "Create Management object with default configuration.")
flag.BoolVar(&createTemplateManagement, "create-template-management", true,
"Create TemplateManagement object with default configuration.")
flag.BoolVar(&createTemplates, "create-templates", true, "Create HMC Templates.")
flag.StringVar(&hmcTemplatesChartName, "hmc-templates-chart-name", "hmc-templates",
"The name of the helm chart with HMC Templates.")
Expand Down Expand Up @@ -232,12 +235,13 @@ func main() {
os.Exit(1)
}
if err = mgr.Add(&controller.Poller{
Client: mgr.GetClient(),
Config: mgr.GetConfig(),
CreateManagement: createManagement,
CreateTemplates: createTemplates,
HMCTemplatesChartName: hmcTemplatesChartName,
SystemNamespace: currentNamespace,
Client: mgr.GetClient(),
Config: mgr.GetConfig(),
CreateManagement: createManagement,
CreateTemplateManagement: createTemplateManagement,
CreateTemplates: createTemplates,
HMCTemplatesChartName: hmcTemplatesChartName,
SystemNamespace: currentNamespace,
}); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "ReleaseController")
os.Exit(1)
Expand Down
74 changes: 58 additions & 16 deletions internal/controller/release_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,9 @@ type Poller struct {

Config *rest.Config

CreateManagement bool
CreateTemplates bool
CreateManagement bool
CreateTemplateManagement bool
CreateTemplates bool

HMCTemplatesChartName string
SystemNamespace string
Expand Down Expand Up @@ -89,18 +90,20 @@ func (p *Poller) Tick(ctx context.Context) error {
l.Error(err, "failed to reconcile HMC Templates")
return err
}
err = p.ensureManagement(ctx)
mgmt, err := p.getOrCreateManagement(ctx)
if err != nil {
l.Error(err, "failed to ensure default Management object")
l.Error(err, "failed to get or create Management object")
return err
}
err = p.ensureTemplateManagement(ctx, mgmt)
if err != nil {
l.Error(err, "failed to ensure default TemplateManagement object")
return err
}
return nil
}

func (p *Poller) ensureManagement(ctx context.Context) error {
if !p.CreateManagement {
return nil
}
func (p *Poller) getOrCreateManagement(ctx context.Context) (*hmc.Management, error) {
l := log.FromContext(ctx)
mgmtObj := &hmc.Management{
ObjectMeta: metav1.ObjectMeta{
Expand All @@ -113,30 +116,32 @@ func (p *Poller) ensureManagement(ctx context.Context) error {
}, mgmtObj)
if err != nil {
if !apierrors.IsNotFound(err) {
return fmt.Errorf("failed to get %s Management object", hmc.ManagementName)
return nil, fmt.Errorf("failed to get %s Management object: %w", hmc.ManagementName, err)
}
if !p.CreateManagement {
return nil, nil
}

mgmtObj.Spec.Release, err = p.getCurrentReleaseName(ctx)
if err != nil {
return err
return nil, err
}

if err := mgmtObj.Spec.SetProvidersDefaults(); err != nil {
return err
return nil, err
}

getter := helm.NewMemoryRESTClientGetter(p.Config, p.RESTMapper())
actionConfig := new(action.Configuration)
err = actionConfig.Init(getter, p.SystemNamespace, "secret", l.Info)
if err != nil {
return err
return nil, err
}

hmcConfig := make(chartutil.Values)
release, err := actionConfig.Releases.Last("hmc")
if err != nil {
if !errors.Is(err, driver.ErrReleaseNotFound) {
return err
return nil, err
}
} else {
if len(release.Config) > 0 {
Expand All @@ -152,7 +157,7 @@ func (p *Poller) ensureManagement(ctx context.Context) error {
})
rawConfig, err := json.Marshal(hmcConfig)
if err != nil {
return err
return nil, err
}
mgmtObj.Spec.Core = &hmc.Core{
HMC: hmc.Component{
Expand All @@ -164,10 +169,47 @@ func (p *Poller) ensureManagement(ctx context.Context) error {

err = p.Create(ctx, mgmtObj)
if err != nil {
return fmt.Errorf("failed to create %s Management object: %s", hmc.ManagementName, err)
return nil, fmt.Errorf("failed to create %s Management object: %s", hmc.ManagementName, err)
}
l.Info("Successfully created Management object with default configuration")
}
return mgmtObj, nil
}

func (p *Poller) ensureTemplateManagement(ctx context.Context, mgmt *hmc.Management) error {
l := log.FromContext(ctx)
if !p.CreateTemplateManagement {
return nil
}
if mgmt == nil {
return fmt.Errorf("management object is not found")
}
tmObj := &hmc.TemplateManagement{
ObjectMeta: metav1.ObjectMeta{
Name: hmc.TemplateManagementName,
OwnerReferences: []metav1.OwnerReference{
{
APIVersion: hmc.GroupVersion.String(),
Kind: mgmt.Kind,
Name: mgmt.Name,
UID: mgmt.UID,
},
},
},
}
err := p.Get(ctx, client.ObjectKey{
Name: hmc.TemplateManagementName,
}, tmObj)
if err != nil {
if !apierrors.IsNotFound(err) {
return fmt.Errorf("failed to get %s TemplateManagement object: %w", hmc.TemplateManagementName, err)
}
err = p.Create(ctx, tmObj)
if err != nil {
return fmt.Errorf("failed to create %s TemplateManagement object: %w", hmc.TemplateManagementName, err)
}
l.Info("Successfully created TemplateManagement object")
}
return nil
}

Expand Down
8 changes: 1 addition & 7 deletions internal/controller/templatemanagement_controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -198,14 +198,8 @@ var _ = Describe("Template Management Controller", func() {
Expect(k8sClient.Delete(ctx, ns)).To(Succeed())
}

tm := &hmcmirantiscomv1alpha1.TemplateManagement{}
err := k8sClient.Get(ctx, types.NamespacedName{Name: tmName}, tm)
Expect(err).NotTo(HaveOccurred())
By("Cleanup the specific resource instance TemplateManagement")
Expect(k8sClient.Delete(ctx, tm)).To(Succeed())

ctChain := &hmcmirantiscomv1alpha1.ClusterTemplateChain{}
err = k8sClient.Get(ctx, types.NamespacedName{Name: ctChainName}, ctChain)
err := k8sClient.Get(ctx, types.NamespacedName{Name: ctChainName}, ctChain)
Expect(err).NotTo(HaveOccurred())
By("Cleanup the specific resource instance ClusterTemplateChain")
Expect(k8sClient.Delete(ctx, ctChain)).To(Succeed())
Expand Down
30 changes: 28 additions & 2 deletions internal/webhook/templatemanagement_webhook.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,13 @@ package webhook

import (
"context"
"errors"
"fmt"
"sort"
"strings"

apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
Expand All @@ -31,6 +33,8 @@ import (
"github.com/Mirantis/hmc/internal/templateutil"
)

var errTemplateManagementDeletionForbidden = errors.New("TemplateManagement deletion is forbidden")

type TemplateManagementValidator struct {
client.Client
SystemNamespace string
Expand All @@ -51,7 +55,16 @@ var (
)

// ValidateCreate implements webhook.Validator so a webhook will be registered for the type.
func (*TemplateManagementValidator) ValidateCreate(_ context.Context, _ runtime.Object) (admission.Warnings, error) {
func (v *TemplateManagementValidator) ValidateCreate(ctx context.Context, _ runtime.Object) (admission.Warnings, error) {
itemsList := &metav1.PartialObjectMetadataList{}
gvk := v1alpha1.GroupVersion.WithKind(v1alpha1.TemplateManagementKind)
itemsList.SetGroupVersionKind(gvk)
if err := v.List(ctx, itemsList); err != nil {
return nil, err
}
if len(itemsList.Items) > 0 {
return nil, fmt.Errorf("TemplateManagement object already exists")
}
return nil, nil
}

Expand Down Expand Up @@ -113,7 +126,20 @@ func getManagedClustersForTemplate(ctx context.Context, cl client.Client, namesp
}

// ValidateDelete implements webhook.Validator so a webhook will be registered for the type.
func (*TemplateManagementValidator) ValidateDelete(context.Context, runtime.Object) (admission.Warnings, error) {
func (v *TemplateManagementValidator) ValidateDelete(ctx context.Context, _ runtime.Object) (admission.Warnings, error) {
partialList := &metav1.PartialObjectMetadataList{}
gvk := v1alpha1.GroupVersion.WithKind(v1alpha1.ManagementKind)
partialList.SetGroupVersionKind(gvk)
err := v.List(ctx, partialList)
if err != nil {
return nil, fmt.Errorf("failed to list Management objects: %v", err)
}
if len(partialList.Items) > 0 {
mgmt := partialList.Items[0]
if mgmt.DeletionTimestamp == nil {
return nil, errTemplateManagementDeletionForbidden
}
}
return nil, nil
}

Expand Down
108 changes: 108 additions & 0 deletions internal/webhook/templatemanagement_webhook_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,63 @@ import (
"github.com/Mirantis/hmc/api/v1alpha1"
"github.com/Mirantis/hmc/internal/utils"
"github.com/Mirantis/hmc/test/objects/managedcluster"
"github.com/Mirantis/hmc/test/objects/management"
"github.com/Mirantis/hmc/test/objects/template"
chain "github.com/Mirantis/hmc/test/objects/templatechain"
tm "github.com/Mirantis/hmc/test/objects/templatemanagement"
"github.com/Mirantis/hmc/test/scheme"
)

func TestTemplateManagementValidateCreate(t *testing.T) {
g := NewWithT(t)

ctx := context.Background()

tests := []struct {
name string
tm *v1alpha1.TemplateManagement
existingObjects []runtime.Object
err string
warnings admission.Warnings
}{
{
name: "should fail if the TemplateManagement object already exists",
tm: tm.NewTemplateManagement(tm.WithName("new")),
existingObjects: []runtime.Object{tm.NewTemplateManagement(tm.WithName(v1alpha1.TemplateManagementName))},
err: "TemplateManagement object already exists",
},
{
name: "should succeed",
tm: tm.NewTemplateManagement(tm.WithName("new")),
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := fake.NewClientBuilder().
WithScheme(scheme.Scheme).
WithRuntimeObjects(tt.existingObjects...).
WithIndex(&v1alpha1.ManagedCluster{}, v1alpha1.TemplateKey, v1alpha1.ExtractTemplateName).
Build()
validator := &TemplateManagementValidator{Client: c, SystemNamespace: utils.DefaultSystemNamespace}
warn, err := validator.ValidateCreate(ctx, tt.tm)
if tt.err != "" {
g.Expect(err).To(HaveOccurred())
if err.Error() != tt.err {
t.Fatalf("expected error '%s', got error: %s", tt.err, err.Error())
}
} else {
g.Expect(err).To(Succeed())
}
if len(tt.warnings) > 0 {
g.Expect(warn).To(Equal(tt.warnings))
} else {
g.Expect(warn).To(BeEmpty())
}
})
}
}

func TestTemplateManagementValidateUpdate(t *testing.T) {
g := NewWithT(t)

Expand Down Expand Up @@ -205,3 +256,60 @@ func TestTemplateManagementValidateUpdate(t *testing.T) {
})
}
}

func TestTemplateManagementValidateDelete(t *testing.T) {
g := NewWithT(t)

ctx := context.Background()

tmName := "test"

tests := []struct {
name string
tm *v1alpha1.TemplateManagement
existingObjects []runtime.Object
err string
warnings admission.Warnings
}{
{
name: "should fail if Management object exists and was not deleted",
tm: tm.NewTemplateManagement(tm.WithName(tmName)),
existingObjects: []runtime.Object{management.NewManagement()},
err: "TemplateManagement deletion is forbidden",
},
{
name: "should succeed if Management object is not found",
tm: tm.NewTemplateManagement(tm.WithName(tmName)),
},
{
name: "should succeed if Management object was deleted",
tm: tm.NewTemplateManagement(tm.WithName(tmName)),
existingObjects: []runtime.Object{management.NewManagement(management.WithDeletionTimestamp(metav1.Now()))},
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := fake.NewClientBuilder().
WithScheme(scheme.Scheme).
WithRuntimeObjects(tt.existingObjects...).
WithIndex(&v1alpha1.ManagedCluster{}, v1alpha1.TemplateKey, v1alpha1.ExtractTemplateName).
Build()
validator := &TemplateManagementValidator{Client: c, SystemNamespace: utils.DefaultSystemNamespace}
warn, err := validator.ValidateDelete(ctx, tt.tm)
if tt.err != "" {
g.Expect(err).To(HaveOccurred())
if err.Error() != tt.err {
t.Fatalf("expected error '%s', got error: %s", tt.err, err.Error())
}
} else {
g.Expect(err).To(Succeed())
}
if len(tt.warnings) > 0 {
g.Expect(warn).To(Equal(tt.warnings))
} else {
g.Expect(warn).To(BeEmpty())
}
})
}
}
Loading

0 comments on commit bcb3a7c

Please sign in to comment.