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

use client factory to create namespace #7589

Merged
merged 2 commits into from
Feb 16, 2024
Merged
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
2 changes: 2 additions & 0 deletions cmd/eksctl-anywhere/cmd/createcluster.go
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,7 @@ func (cc *createClusterOptions) createCluster(cmd *cobra.Command, _ []string) er
deps.EksdInstaller,
deps.PackageInstaller,
deps.ClusterCreator,
deps.UnAuthKubectlClient,
)
err = createWorkloadCluster.Run(ctx, clusterSpec, createValidations)

Expand All @@ -266,6 +267,7 @@ func (cc *createClusterOptions) createCluster(cmd *cobra.Command, _ []string) er

createMgmtCluster := management.NewCreate(
deps.Bootstrapper,
deps.UnAuthKubeClient,
deps.Provider,
deps.ClusterManager,
deps.GitOpsFlux,
Expand Down
11 changes: 10 additions & 1 deletion pkg/clients/kubernetes/unauth.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/utils/pointer"
"sigs.k8s.io/controller-runtime/pkg/client/apiutil"
)

Expand Down Expand Up @@ -41,7 +42,15 @@ func (c *UnAuthClient) Get(ctx context.Context, name, namespace, kubeconfig stri
return fmt.Errorf("getting kubernetes resource: %v", err)
}

return c.kubectl.Get(ctx, resourceType, kubeconfig, obj, &KubectlGetOptions{Name: name, Namespace: namespace})
var opts KubectlGetOptions

if namespace == "" {
opts = KubectlGetOptions{Name: name, ClusterScoped: pointer.Bool(true)}
} else {
opts = KubectlGetOptions{Name: name, Namespace: namespace}
}

return c.kubectl.Get(ctx, resourceType, kubeconfig, obj, &opts)
}

// KubeconfigClient returns an equivalent authenticated client.
Expand Down
12 changes: 7 additions & 5 deletions pkg/clients/kubernetes/unauth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/utils/pointer"
clusterapiv1 "sigs.k8s.io/cluster-api/api/v1beta1"
controlplanev1 "sigs.k8s.io/cluster-api/controlplane/kubeadm/api/v1beta1"
"sigs.k8s.io/controller-runtime/pkg/client"
Expand All @@ -24,30 +25,35 @@ func TestUnAuthClientGetSuccess(t *testing.T) {
namespace string
obj runtime.Object
wantResourceType string
options kubernetes.KubectlGetOptions
}{
{
name: "eksa cluster",
namespace: "eksa-system",
obj: &anywherev1.Cluster{},
wantResourceType: "Cluster.v1alpha1.anywhere.eks.amazonaws.com",
options: kubernetes.KubectlGetOptions{Name: "eksa cluster", Namespace: "eksa-system"},
},
{
name: "capi cluster",
namespace: "eksa-system",
obj: &clusterapiv1.Cluster{},
wantResourceType: "Cluster.v1beta1.cluster.x-k8s.io",
options: kubernetes.KubectlGetOptions{Name: "capi cluster", Namespace: "eksa-system"},
},
{
name: "capi kubeadm controlplane",
namespace: "eksa-system",
obj: &controlplanev1.KubeadmControlPlane{},
wantResourceType: "KubeadmControlPlane.v1beta1.controlplane.cluster.x-k8s.io",
options: kubernetes.KubectlGetOptions{Name: "capi kubeadm controlplane", Namespace: "eksa-system"},
},
{
name: "my-node",
namespace: "",
obj: &corev1.NodeList{},
wantResourceType: "Node",
options: kubernetes.KubectlGetOptions{Name: "my-node", ClusterScoped: pointer.Bool(true)},
},
}
for _, tt := range tests {
Expand All @@ -58,11 +64,7 @@ func TestUnAuthClientGetSuccess(t *testing.T) {
kubectl := mocks.NewMockKubectl(ctrl)
kubeconfig := "k.kubeconfig"

o := &kubernetes.KubectlGetOptions{
Name: tt.name,
Namespace: tt.namespace,
}
kubectl.EXPECT().Get(ctx, tt.wantResourceType, kubeconfig, tt.obj, o)
kubectl.EXPECT().Get(ctx, tt.wantResourceType, kubeconfig, tt.obj, &tt.options)

c := kubernetes.NewUnAuthClient(kubectl)
g.Expect(c.Init()).To(Succeed())
Expand Down
5 changes: 0 additions & 5 deletions pkg/clustermanager/cluster_manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -1404,11 +1404,6 @@ func (c *ClusterManager) DeletePackageResources(ctx context.Context, managementC
return c.clusterClient.DeletePackageResources(ctx, managementCluster, clusterName)
}

// CreateNamespace creates a namespace on the target cluster if it does not already exist.
func (c *ClusterManager) CreateNamespace(ctx context.Context, targetCluster *types.Cluster, namespace string) error {
return c.clusterClient.CreateNamespaceIfNotPresent(ctx, targetCluster.KubeconfigFile, namespace)
}

func (c *ClusterManager) getUpgraderImagesFromBundle(ctx context.Context, cluster *types.Cluster, cl *cluster.Spec) (*corev1.ConfigMap, error) {
upgraderImages := make(map[string]string)
for _, versionBundle := range cl.Bundles.Spec.VersionsBundles {
Expand Down
41 changes: 41 additions & 0 deletions pkg/workflows/create_prep.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package workflows

import (
"context"

corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"

"github.com/aws/eks-anywhere/pkg/workflows/interfaces"
)

// CreateNamespaceIfNotPresent creates the namespace on the cluster if it does not already exist.
func CreateNamespaceIfNotPresent(ctx context.Context, namespace, kubeconfig string, clientFactory interfaces.ClientFactory) error {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: can we find a different place for this?
Im ok if you move it in a separate pr

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i'll do it in another pr

client, err := clientFactory.BuildClientFromKubeconfig(kubeconfig)
if err != nil {
return err
}

if err := client.Get(ctx, namespace, "", &corev1.Namespace{}); err != nil && !errors.IsNotFound(err) {
return err
} else if err == nil {
return nil
}

ns := &corev1.Namespace{
TypeMeta: metav1.TypeMeta{
APIVersion: "v1",
Kind: "Namespace",
},
ObjectMeta: metav1.ObjectMeta{
Name: namespace,
},
}

if err = client.Create(ctx, ns); err != nil {
return err
}

return nil
}
123 changes: 123 additions & 0 deletions pkg/workflows/create_prep_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
package workflows_test

import (
"context"
"fmt"
"testing"

"github.com/golang/mock/gomock"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"

clientmocks "github.com/aws/eks-anywhere/pkg/clients/kubernetes/mocks"
"github.com/aws/eks-anywhere/pkg/workflows"
"github.com/aws/eks-anywhere/pkg/workflows/interfaces/mocks"
)

type createPrepTestSetup struct {
t *testing.T
ctx context.Context
client *clientmocks.MockClient
clientFactory *mocks.MockClientFactory
}

func newCreatePrepTest(t *testing.T) *createPrepTestSetup {
mockCtrl := gomock.NewController(t)
client := clientmocks.NewMockClient(mockCtrl)
clientFactory := mocks.NewMockClientFactory(mockCtrl)

return &createPrepTestSetup{
t: t,
ctx: context.Background(),
client: client,
clientFactory: clientFactory,
}
}

func newNamespace(name string) *corev1.Namespace {
return &corev1.Namespace{
TypeMeta: metav1.TypeMeta{
APIVersion: "v1",
Kind: "Namespace",
},
ObjectMeta: metav1.ObjectMeta{
Name: name,
},
}
}

func TestCreateNamespaceNotExistsSuccess(t *testing.T) {
test := newCreatePrepTest(t)
kubeconfig := "testpath"
namespace := "test-ns"

test.clientFactory.EXPECT().BuildClientFromKubeconfig(kubeconfig).Return(test.client, nil)
test.client.EXPECT().Get(test.ctx, namespace, "", &corev1.Namespace{}).Return(apierrors.NewNotFound(schema.GroupResource{Group: "", Resource: ""}, ""))
test.client.EXPECT().Create(test.ctx, newNamespace(namespace)).Return(nil)

err := workflows.CreateNamespaceIfNotPresent(test.ctx, namespace, kubeconfig, test.clientFactory)
if err != nil {
t.Fatalf("Expected nil, but got %v", err)
}
}

func TestCreateNamespaceAlreadyExistsSuccess(t *testing.T) {
test := newCreatePrepTest(t)
kubeconfig := "testpath"
namespace := "default"

test.clientFactory.EXPECT().BuildClientFromKubeconfig(kubeconfig).Return(test.client, nil)
test.client.EXPECT().Get(test.ctx, namespace, "", &corev1.Namespace{}).Return(nil)

err := workflows.CreateNamespaceIfNotPresent(test.ctx, namespace, kubeconfig, test.clientFactory)
if err != nil {
t.Fatalf("Expected nil, but got %v", err)
}
}

func TestCreateNamespaceBuildClientFail(t *testing.T) {
test := newCreatePrepTest(t)
kubeconfig := "testpath"
namespace := "test-ns"

test.clientFactory.EXPECT().BuildClientFromKubeconfig(kubeconfig).Return(test.client, fmt.Errorf(""))

err := workflows.CreateNamespaceIfNotPresent(test.ctx, namespace, kubeconfig, test.clientFactory)

if err == nil {
t.Fatalf("Expected error, but got nil")
}
}

func TestCreateNamespaceGetNamespaceFail(t *testing.T) {
test := newCreatePrepTest(t)
kubeconfig := "testpath"
namespace := "test-ns"

test.clientFactory.EXPECT().BuildClientFromKubeconfig(kubeconfig).Return(test.client, nil)
test.client.EXPECT().Get(test.ctx, namespace, "", &corev1.Namespace{}).Return(fmt.Errorf(""))

err := workflows.CreateNamespaceIfNotPresent(test.ctx, namespace, kubeconfig, test.clientFactory)

if err == nil {
t.Fatalf("Expected error, but got nil")
}
}

func TestCreateNamespaceFail(t *testing.T) {
test := newCreatePrepTest(t)
kubeconfig := "testpath"
namespace := "test-ns"

test.clientFactory.EXPECT().BuildClientFromKubeconfig(kubeconfig).Return(test.client, nil)
test.client.EXPECT().Get(test.ctx, namespace, "", &corev1.Namespace{}).Return(apierrors.NewNotFound(schema.GroupResource{Group: "", Resource: ""}, ""))
test.client.EXPECT().Create(test.ctx, newNamespace(namespace)).Return(fmt.Errorf(""))

err := workflows.CreateNamespaceIfNotPresent(test.ctx, namespace, kubeconfig, test.clientFactory)

if err == nil {
t.Fatalf("Expected error, but got nil")
}
}
1 change: 0 additions & 1 deletion pkg/workflows/interfaces/interfaces.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,6 @@ type ClusterManager interface {
GenerateAWSIAMKubeconfig(ctx context.Context, cluster *types.Cluster) error
DeletePackageResources(ctx context.Context, managementCluster *types.Cluster, clusterName string) error
CreateRegistryCredSecret(ctx context.Context, mgmt *types.Cluster) error
CreateNamespace(ctx context.Context, targetCluster *types.Cluster, namespace string) error
}

type GitOpsManager interface {
Expand Down
14 changes: 0 additions & 14 deletions pkg/workflows/interfaces/mocks/clients.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 5 additions & 1 deletion pkg/workflows/management/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
// Create is a schema for create cluster.
type Create struct {
bootstrapper interfaces.Bootstrapper
clientFactory interfaces.ClientFactory
provider providers.Provider
clusterManager interfaces.ClusterManager
gitOpsManager interfaces.GitOpsManager
Expand All @@ -24,7 +25,8 @@ type Create struct {
}

// NewCreate builds a new create construct.
func NewCreate(bootstrapper interfaces.Bootstrapper, provider providers.Provider,
func NewCreate(bootstrapper interfaces.Bootstrapper,
clientFactory interfaces.ClientFactory, provider providers.Provider,
clusterManager interfaces.ClusterManager, gitOpsManager interfaces.GitOpsManager,
writer filewriter.FileWriter, eksdInstaller interfaces.EksdInstaller,
packageInstaller interfaces.PackageInstaller,
Expand All @@ -33,6 +35,7 @@ func NewCreate(bootstrapper interfaces.Bootstrapper, provider providers.Provider
) *Create {
return &Create{
bootstrapper: bootstrapper,
clientFactory: clientFactory,
provider: provider,
clusterManager: clusterManager,
gitOpsManager: gitOpsManager,
Expand All @@ -48,6 +51,7 @@ func NewCreate(bootstrapper interfaces.Bootstrapper, provider providers.Provider
func (c *Create) Run(ctx context.Context, clusterSpec *cluster.Spec, validator interfaces.Validator) error {
commandContext := &task.CommandContext{
Bootstrapper: c.bootstrapper,
ClientFactory: c.clientFactory,
Provider: c.provider,
ClusterManager: c.clusterManager,
GitOpsManager: c.gitOpsManager,
Expand Down
2 changes: 1 addition & 1 deletion pkg/workflows/management/create_install_eksa.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ func (s *installEksaComponentsOnWorkloadTask) Run(ctx context.Context, commandCo
commandContext.ClusterSpec.Cluster.SetManagementComponentsVersion(commandContext.ClusterSpec.EKSARelease.Spec.Version)

if commandContext.ClusterSpec.Cluster.Namespace != "" {
if err := commandContext.ClusterManager.CreateNamespace(ctx, commandContext.WorkloadCluster, commandContext.ClusterSpec.Cluster.Namespace); err != nil {
if err := workflows.CreateNamespaceIfNotPresent(ctx, commandContext.ClusterSpec.Cluster.Namespace, commandContext.WorkloadCluster.KubeconfigFile, commandContext.ClientFactory); err != nil {
commandContext.SetError(err)
return &workflows.CollectMgmtClusterDiagnosticsTask{}
}
Expand Down
Loading
Loading