Skip to content

Commit

Permalink
operator/pkg: test init and deinit
Browse files Browse the repository at this point in the history
In this commit, we unit test the init and deinit workflows
in the operator pkg.

Signed-off-by: Mohamed Awnallah <mohamedmohey2352@gmail.com>
  • Loading branch information
mohamedawnallah committed Sep 27, 2024
1 parent 4c8bcd4 commit 1760599
Show file tree
Hide file tree
Showing 7 changed files with 859 additions and 37 deletions.
4 changes: 2 additions & 2 deletions operator/pkg/controller/karmada/planner.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ func NewPlannerFor(karmada *operatorv1alpha1.Karmada, c client.Client, config *r
}

options := operator.NewJobInitOptions(opts...)
job = operator.NewInitJob(options)
job = operator.NewInitJob(options, operator.DefaultInitTasks)

case DeInitAction:
opts := []operator.DeInitOpt{
Expand All @@ -78,7 +78,7 @@ func NewPlannerFor(karmada *operatorv1alpha1.Karmada, c client.Client, config *r
}

options := operator.NewJobDeInitOptions(opts...)
job = operator.NewDeInitDataJob(options)
job = operator.NewDeInitDataJob(options, operator.DefaultDeInitTasks)
default:
return nil, fmt.Errorf("failed to recognize action for karmada %s", karmada.Name)
}
Expand Down
29 changes: 19 additions & 10 deletions operator/pkg/deinit.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,15 @@ import (
"github.com/karmada-io/karmada/operator/pkg/workflow"
)

var (
// DefaultDeInitTasks contains the default tasks to be executed during the deinitialization process.
DefaultDeInitTasks = []workflow.Task{
tasks.NewRemoveComponentTask(),
tasks.NewCleanupCertTask(),
tasks.NewCleanupKubeconfigTask(),
}
)

// DeInitOptions defines all the Deinit workflow options.
type DeInitOptions struct {
Name string
Expand All @@ -53,15 +62,19 @@ type deInitData struct {

// NewDeInitDataJob initializes a deInit job with a list of sub tasks. and build
// deinit runData object
func NewDeInitDataJob(opt *DeInitOptions) *workflow.Job {
func NewDeInitDataJob(opt *DeInitOptions, deInitTasks []workflow.Task) *workflow.Job {
deInitJob := workflow.NewJob()

deInitJob.AppendTask(tasks.NewRemoveComponentTask())
deInitJob.AppendTask(tasks.NewCleanupCertTask())
deInitJob.AppendTask(tasks.NewCleanupKubeconfigTask())
for _, task := range deInitTasks {
deInitJob.AppendTask(task)
}

deInitJob.SetDataInitializer(func() (workflow.RunData, error) {
localClusterClient, err := clientset.NewForConfig(opt.Kubeconfig)
if len(opt.Name) == 0 || len(opt.Namespace) == 0 {
return nil, errors.New("unexpected empty name or namespace")
}

localClusterClient, err := clientFactory(opt.Kubeconfig)
if err != nil {
return nil, fmt.Errorf("error when creating local cluster client, err: %w", err)
}
Expand All @@ -72,16 +85,12 @@ func NewDeInitDataJob(opt *DeInitOptions) *workflow.Job {
if util.IsInCluster(opt.HostCluster) {
remoteClient = localClusterClient
} else {
remoteClient, err = util.BuildClientFromSecretRef(localClusterClient, opt.HostCluster.SecretRef)
remoteClient, err = buildClientFromSecretRefFactory(localClusterClient, opt.HostCluster.SecretRef)
if err != nil {
return nil, fmt.Errorf("error when creating cluster client to install karmada, err: %w", err)
}
}

if len(opt.Name) == 0 || len(opt.Namespace) == 0 {
return nil, errors.New("unexpected empty name or namespace")
}

return &deInitData{
name: opt.Name,
namespace: opt.Namespace,
Expand Down
159 changes: 159 additions & 0 deletions operator/pkg/deinit_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
/*
Copyright 2024 The Karmada 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 karmada

import (
"fmt"
"strings"
"testing"

clientset "k8s.io/client-go/kubernetes"
fakeclientset "k8s.io/client-go/kubernetes/fake"
"k8s.io/client-go/rest"

operatorv1alpha1 "github.com/karmada-io/karmada/operator/pkg/apis/operator/v1alpha1"
"github.com/karmada-io/karmada/operator/pkg/workflow"
)

func TestNewDeInitDataJob(t *testing.T) {
tests := []struct {
name string
deInitOptions *DeInitOptions
tasksExpected []workflow.Task
}{
{
name: "NewDeInitDataJob_WithInitTasks_AllIsSubset",
deInitOptions: &DeInitOptions{
Name: "test_deinit",
Namespace: "test",
Kubeconfig: &rest.Config{},
HostCluster: &operatorv1alpha1.HostCluster{},
},
tasksExpected: DefaultDeInitTasks,
},
}

for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
deInitJob := NewDeInitDataJob(test.deInitOptions, test.tasksExpected)
err := containAllTasks(deInitJob.Tasks, test.tasksExpected)
if err != nil {
t.Errorf("unexpected error, got: %v", err)
}
})
}
}

func TestRunNewDeInitJob(t *testing.T) {
tests := []struct {
name string
deInitOptions *DeInitOptions
tasksExpected []workflow.Task
mockFunc func()
wantErr bool
errMsg string
}{
{
name: "RunNewDeInitJob_EmptyNamespace_NamespaceIsEmpty",
deInitOptions: &DeInitOptions{
Name: "test_deinit",
Kubeconfig: &rest.Config{},
HostCluster: &operatorv1alpha1.HostCluster{},
},
tasksExpected: DefaultDeInitTasks,
mockFunc: func() {},
wantErr: true,
errMsg: "unexpected empty name or namespace",
},
{
name: "RunNewDeInitJob_EmptyName_NameIsEmpty",
deInitOptions: &DeInitOptions{
Namespace: "test",
Kubeconfig: &rest.Config{},
HostCluster: &operatorv1alpha1.HostCluster{},
},
tasksExpected: DefaultDeInitTasks,
mockFunc: func() {},
wantErr: true,
errMsg: "unexpected empty name",
},
{
name: "RunNewDeInitJob_FailedToCreateLocalClusterClient_LocalClusterClientCreationError",
deInitOptions: &DeInitOptions{
Name: "test_deinit",
Namespace: "test",
Kubeconfig: &rest.Config{},
HostCluster: &operatorv1alpha1.HostCluster{},
},
tasksExpected: DefaultDeInitTasks,
mockFunc: func() {
clientFactory = func(*rest.Config) (clientset.Interface, error) {
return nil, fmt.Errorf("failed to create local cluster client")
}
},
wantErr: true,
errMsg: "failed to create local cluster client",
},
{
name: "RunNewDeInitJob_FailedToCreateRemoteClusterClient_RemoteClusterClientCreationError",
deInitOptions: &DeInitOptions{
Name: "test_deinit",
Namespace: "test",
Kubeconfig: &rest.Config{},
HostCluster: &operatorv1alpha1.HostCluster{},
},
tasksExpected: DefaultDeInitTasks,
mockFunc: func() {
clientFactory = func(*rest.Config) (clientset.Interface, error) {
return nil, fmt.Errorf("failed to create remote cluster client")
}
},
wantErr: true,
errMsg: "failed to create remote cluster client",
},
{
name: "RunNewDeInitJob_WithDeInitTasks_RunIsSuccessful",
deInitOptions: &DeInitOptions{
Name: "test_deinit",
Namespace: "test",
Kubeconfig: &rest.Config{},
HostCluster: &operatorv1alpha1.HostCluster{},
},
mockFunc: func() {
clientFactory = func(*rest.Config) (clientset.Interface, error) {
return fakeclientset.NewSimpleClientset(), nil
}
},
tasksExpected: DefaultDeInitTasks,
wantErr: false,
},
}

for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
test.mockFunc()
deInitJob := NewDeInitDataJob(test.deInitOptions, test.tasksExpected)
err := deInitJob.Run()
if (err != nil && !test.wantErr) || (err == nil && test.wantErr) {
t.Errorf("RunNewDeInitJob() = got %v error, but want %t error", err, test.wantErr)
}
if (err != nil && test.wantErr) && (!strings.Contains(err.Error(), test.errMsg)) {
t.Errorf("RunNewDeInitJob() = got %s, want %s", err.Error(), test.errMsg)
}
})
}
}
59 changes: 36 additions & 23 deletions operator/pkg/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ import (
"sync"

corev1 "k8s.io/api/core/v1"
utilerrors "k8s.io/apimachinery/pkg/util/errors"
utilversion "k8s.io/apimachinery/pkg/util/version"
clientset "k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
Expand All @@ -39,6 +38,24 @@ import (
)

var (
// DefaultInitTasks contains the default tasks to be executed during the initialization process.
DefaultInitTasks = []workflow.Task{
tasks.NewPrepareCrdsTask(),
tasks.NewCertTask(),
tasks.NewNamespaceTask(),
tasks.NewUploadCertsTask(),
tasks.NewEtcdTask(),
tasks.NewKarmadaApiserverTask(),
tasks.NewUploadKubeconfigTask(),
tasks.NewKarmadaAggregatedApiserverTask(),
tasks.NewCheckApiserverHealthTask(),
tasks.NewKarmadaResourcesTask(),
tasks.NewRBACTask(),
tasks.NewComponentTask(),
tasks.NewWaitControlPlaneTask(),
}

// defaultCrdURL is the URL for fetching CRDs.
defaultCrdURL = "https://github.com/karmada-io/karmada/releases/download/%s/crds.tar.gz"
)

Expand All @@ -55,16 +72,17 @@ type InitOptions struct {

// Validate is used to validate the initOptions before creating initJob.
func (opt *InitOptions) Validate() error {
var errs []error

if len(opt.Name) == 0 || len(opt.Namespace) == 0 {
return errors.New("unexpected empty name or namespace")
}
if opt.CRDTarball.HTTPSource != nil {
if _, err := url.Parse(opt.CRDTarball.HTTPSource.URL); err != nil {
return fmt.Errorf("unexpected invalid crds remote url %s", opt.CRDTarball.HTTPSource.URL)
return fmt.Errorf("unexpected invalid crds remote url %s, err: %w", opt.CRDTarball.HTTPSource.URL, err)
}
}
if opt.Karmada == nil || opt.Karmada.Spec.Components == nil || opt.Karmada.Spec.Components.KarmadaAPIServer == nil {
return fmt.Errorf("invalid Karmada configuration: Karmada, Karmada components, and Karmada API server must be defined")
}
if !util.IsInCluster(opt.Karmada.Spec.HostCluster) && opt.Karmada.Spec.Components.KarmadaAPIServer.ServiceType == corev1.ServiceTypeClusterIP {
return fmt.Errorf("if karmada is installed in a remote cluster, the service type of karmada-apiserver must be either NodePort or LoadBalancer")
}
Expand All @@ -73,15 +91,15 @@ func (opt *InitOptions) Validate() error {
return fmt.Errorf("unexpected karmada invalid version %s", opt.KarmadaVersion)
}

if opt.Karmada.Spec.Components.Etcd.Local != nil && opt.Karmada.Spec.Components.Etcd.Local.CommonSettings.Replicas != nil {
if opt.Karmada.Spec.Components.Etcd != nil && opt.Karmada.Spec.Components.Etcd.Local != nil && opt.Karmada.Spec.Components.Etcd.Local.CommonSettings.Replicas != nil {
replicas := *opt.Karmada.Spec.Components.Etcd.Local.CommonSettings.Replicas

if (replicas % 2) == 0 {
klog.Warningf("invalid etcd replicas %d, expected an odd number", replicas)
}
}

return utilerrors.NewAggregate(errs)
return nil
}

// InitOpt defines a type of function to set InitOptions values.
Expand Down Expand Up @@ -111,23 +129,13 @@ type initData struct {

// NewInitJob initializes a job with list of init sub-task. and build
// init runData object.
func NewInitJob(opt *InitOptions) *workflow.Job {
func NewInitJob(opt *InitOptions, initTasks []workflow.Task) *workflow.Job {
initJob := workflow.NewJob()

// add the all tasks to the init job workflow.
initJob.AppendTask(tasks.NewPrepareCrdsTask())
initJob.AppendTask(tasks.NewCertTask())
initJob.AppendTask(tasks.NewNamespaceTask())
initJob.AppendTask(tasks.NewUploadCertsTask())
initJob.AppendTask(tasks.NewEtcdTask())
initJob.AppendTask(tasks.NewKarmadaApiserverTask())
initJob.AppendTask(tasks.NewUploadKubeconfigTask())
initJob.AppendTask(tasks.NewKarmadaAggregatedApiserverTask())
initJob.AppendTask(tasks.NewCheckApiserverHealthTask())
initJob.AppendTask(tasks.NewKarmadaResourcesTask())
initJob.AppendTask(tasks.NewRBACTask())
initJob.AppendTask(tasks.NewComponentTask())
initJob.AppendTask(tasks.NewWaitControlPlaneTask())
for _, task := range initTasks {
initJob.AppendTask(task)
}

initJob.SetDataInitializer(func() (workflow.RunData, error) {
return newRunData(opt)
Expand All @@ -141,7 +149,7 @@ func newRunData(opt *InitOptions) (*initData, error) {
return nil, err
}

localClusterClient, err := clientset.NewForConfig(opt.Kubeconfig)
localClusterClient, err := clientFactory(opt.Kubeconfig)
if err != nil {
return nil, fmt.Errorf("error when creating local cluster client, err: %w", err)
}
Expand All @@ -152,7 +160,7 @@ func newRunData(opt *InitOptions) (*initData, error) {
if util.IsInCluster(opt.Karmada.Spec.HostCluster) {
remoteClient = localClusterClient
} else {
remoteClient, err = util.BuildClientFromSecretRef(localClusterClient, opt.Karmada.Spec.HostCluster.SecretRef)
remoteClient, err = buildClientFromSecretRefFactory(localClusterClient, opt.Karmada.Spec.HostCluster.SecretRef)
if err != nil {
return nil, fmt.Errorf("error when creating cluster client to install karmada, err: %w", err)
}
Expand All @@ -177,6 +185,11 @@ func newRunData(opt *InitOptions) (*initData, error) {
}
}

var hostClusterDNSDomain string
if opt.Karmada.Spec.HostCluster != nil && opt.Karmada.Spec.HostCluster.Networking != nil && opt.Karmada.Spec.HostCluster.Networking.DNSDomain != nil {
hostClusterDNSDomain = *opt.Karmada.Spec.HostCluster.Networking.DNSDomain
}

return &initData{
name: opt.Name,
namespace: opt.Namespace,
Expand All @@ -188,7 +201,7 @@ func newRunData(opt *InitOptions) (*initData, error) {
privateRegistry: privateRegistry,
components: opt.Karmada.Spec.Components,
featureGates: opt.Karmada.Spec.FeatureGates,
dnsDomain: *opt.Karmada.Spec.HostCluster.Networking.DNSDomain,
dnsDomain: hostClusterDNSDomain,
CertStore: certs.NewCertStore(),
}, nil
}
Expand Down
Loading

0 comments on commit 1760599

Please sign in to comment.