Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

operator/pkg: unit test init and deinit #5613

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 := util.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 = util.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
168 changes: 168 additions & 0 deletions operator/pkg/deinit_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
/*
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/util"
"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 := util.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() {
util.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{
SecretRef: &operatorv1alpha1.LocalSecretReference{
Namespace: "test",
Name: "karmada-demo",
},
},
},
tasksExpected: DefaultDeInitTasks,
mockFunc: func() {
util.ClientFactory = func(*rest.Config) (clientset.Interface, error) {
return fakeclientset.NewSimpleClientset(), nil
}
util.BuildClientFromSecretRefFactory = func(clientset.Interface, *operatorv1alpha1.LocalSecretReference) (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() {
util.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)
}
})
}
}
47 changes: 26 additions & 21 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,14 +72,12 @@ 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 !util.IsInCluster(opt.Karmada.Spec.HostCluster) && opt.Karmada.Spec.Components.KarmadaAPIServer.ServiceType == corev1.ServiceTypeClusterIP {
Expand All @@ -81,7 +96,7 @@ func (opt *InitOptions) Validate() error {
}
}

return utilerrors.NewAggregate(errs)
return nil
}

// InitOpt defines a type of function to set InitOptions values.
Expand Down Expand Up @@ -111,23 +126,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 +146,7 @@ func newRunData(opt *InitOptions) (*initData, error) {
return nil, err
}

localClusterClient, err := clientset.NewForConfig(opt.Kubeconfig)
localClusterClient, err := util.ClientFactory(opt.Kubeconfig)
if err != nil {
return nil, fmt.Errorf("error when creating local cluster client, err: %w", err)
}
Expand All @@ -152,7 +157,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 = util.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 Down
Loading
Loading