From b4dd7a09346d02fa4945585ab73be5fd2f247ff5 Mon Sep 17 00:00:00 2001 From: Enxebre Date: Wed, 17 Oct 2018 12:08:16 +0200 Subject: [PATCH] drop old machine controller and build new one --- cmd/machine-controller/Makefile | 38 ---- cmd/machine-controller/main.go | 102 ----------- cmd/manager/main.go | 74 +++++++- pkg/cloud/aws/actuators/machine/actuator.go | 7 +- ...achineproviderconfig.go => add_machine.go} | 23 ++- .../awsmachineproviderconfig_controller.go | 166 ------------------ ...ineproviderconfig_controller_suite_test.go | 71 -------- ...wsmachineproviderconfig_controller_test.go | 81 --------- 8 files changed, 88 insertions(+), 474 deletions(-) delete mode 100644 cmd/machine-controller/Makefile delete mode 100644 cmd/machine-controller/main.go rename pkg/controller/{add_awsmachineproviderconfig.go => add_machine.go} (60%) delete mode 100644 pkg/controller/awsmachineproviderconfig/awsmachineproviderconfig_controller.go delete mode 100644 pkg/controller/awsmachineproviderconfig/awsmachineproviderconfig_controller_suite_test.go delete mode 100644 pkg/controller/awsmachineproviderconfig/awsmachineproviderconfig_controller_test.go diff --git a/cmd/machine-controller/Makefile b/cmd/machine-controller/Makefile deleted file mode 100644 index 13df8fd222..0000000000 --- a/cmd/machine-controller/Makefile +++ /dev/null @@ -1,38 +0,0 @@ -# Copyright 2018 The Kubernetes 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. - -.PHONY: image - -GCR_BUCKET = k8s-cluster-api -PREFIX = gcr.io/$(GCR_BUCKET) -DEV_PREFIX ?= gcr.io/$(shell gcloud config get-value project) -NAME = aws-machine-controller -TAG = 0.0.1 - -image: - imagebuilder -t "$(PREFIX)/$(NAME):$(TAG)" -f ../../Dockerfile ../.. - -push: image - docker push "$(PREFIX)/$(NAME):$(TAG)" - $(MAKE) fix_gcs_permissions - -fix_gcs_permissions: - gsutil acl ch -u AllUsers:READ gs://artifacts.$(GCR_BUCKET).appspot.com - gsutil -m acl ch -r -u AllUsers:READ gs://artifacts.$(GCR_BUCKET).appspot.com - -dev_image: - docker build -t "$(DEV_PREFIX)/$(NAME):$(TAG)-dev" -f ../../Dockerfile ../.. - -dev_push: dev_image - docker push "$(DEV_PREFIX)/$(NAME):$(TAG)-dev" diff --git a/cmd/machine-controller/main.go b/cmd/machine-controller/main.go deleted file mode 100644 index 2821fe2e64..0000000000 --- a/cmd/machine-controller/main.go +++ /dev/null @@ -1,102 +0,0 @@ -/* -Copyright 2018 The Kubernetes 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 main - -import ( - "flag" - "os" - - "github.com/golang/glog" - "github.com/kubernetes-incubator/apiserver-builder/pkg/controller" - log "github.com/sirupsen/logrus" - "github.com/spf13/pflag" - "k8s.io/apiserver/pkg/util/logs" - "k8s.io/client-go/kubernetes" - machineactuator "sigs.k8s.io/cluster-api-provider-aws/pkg/cloud/aws/actuators/machine" - awsclient "sigs.k8s.io/cluster-api-provider-aws/pkg/cloud/aws/client" - "sigs.k8s.io/cluster-api/pkg/client/clientset_generated/clientset" - "sigs.k8s.io/cluster-api/pkg/controller/config" - "sigs.k8s.io/cluster-api/pkg/controller/machine" -// "sigs.k8s.io/cluster-api/pkg/controller/sharedinformers" -) - -var ( - logLevel string -) - -func init() { - config.ControllerConfig.AddFlags(pflag.CommandLine) - pflag.CommandLine.StringVar(&logLevel, "log-level", defaultLogLevel, "Log level (debug,info,warn,error,fatal)") -} - -const ( - controllerLogName = "awsMachine" - defaultLogLevel = "info" -) - -func main() { - // the following line exists to make glog happy, for more information, see: https://github.com/kubernetes/kubernetes/issues/17162 - flag.CommandLine.Parse([]string{}) - pflag.Parse() - - logs.InitLogs() - defer logs.FlushLogs() - - config, err := controller.GetConfig(config.ControllerConfig.Kubeconfig) - if err != nil { - glog.Fatalf("Could not create Config for talking to the apiserver: %v", err) - } - - client, err := clientset.NewForConfig(config) - if err != nil { - glog.Fatalf("Could not create client for talking to the apiserver: %v", err) - } - - kubeClient, err := kubernetes.NewForConfig(config) - if err != nil { - glog.Fatalf("Could not create kubernetes client to talk to the apiserver: %v", err) - } - - log.SetOutput(os.Stdout) - if lvl, err := log.ParseLevel(logLevel); err != nil { - log.Panic(err) - } else { - log.SetLevel(lvl) - } - - logger := log.WithField("controller", controllerLogName) - - params := machineactuator.ActuatorParams{ - ClusterClient: client, - KubeClient: kubeClient, - AwsClientBuilder: awsclient.NewClient, - Logger: logger, - } - - actuator, err := machineactuator.NewActuator(params) - if err != nil { - glog.Fatalf("Could not create AWS machine actuator: %v", err) - } - - shutdown := make(chan struct{}) - si := sharedinformers.NewSharedInformers(config, shutdown) - // If this doesn't compile, the code generator probably - // overwrote the customized NewMachineController function. - c := machine.NewMachineController(config, si, actuator) - c.Run(shutdown) - select {} -} diff --git a/cmd/manager/main.go b/cmd/manager/main.go index 26088043d0..1d074b3e4f 100644 --- a/cmd/manager/main.go +++ b/cmd/manager/main.go @@ -1,12 +1,9 @@ /* Copyright 2018 The Kubernetes 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. @@ -17,17 +14,41 @@ limitations under the License. package main import ( - "log" - _ "k8s.io/client-go/plugin/pkg/client/auth/gcp" - "sigs.k8s.io/cluster-api-provider-aws/migration/pkg/apis" - "sigs.k8s.io/cluster-api-provider-aws/migration/pkg/controller" + "sigs.k8s.io/cluster-api-provider-aws/pkg/apis" + "sigs.k8s.io/cluster-api-provider-aws/pkg/controller" "sigs.k8s.io/controller-runtime/pkg/client/config" "sigs.k8s.io/controller-runtime/pkg/manager" "sigs.k8s.io/controller-runtime/pkg/runtime/signals" + clusterapis "sigs.k8s.io/cluster-api/pkg/apis" + "sigs.k8s.io/cluster-api/pkg/client/clientset_generated/clientset" + "k8s.io/client-go/kubernetes" + machineactuator "sigs.k8s.io/cluster-api-provider-aws/pkg/cloud/aws/actuators/machine" + //"sigs.k8s.io/cluster-api-provider-aws/pkg/apis/awsproviderconfig/v1alpha1" + "github.com/golang/glog" + log "github.com/sirupsen/logrus" + awsclient "sigs.k8s.io/cluster-api-provider-aws/pkg/cloud/aws/client" + "os" + "github.com/spf13/pflag" +) + +var ( + logLevel string +) + +const ( + defaultLogLevel = "info" ) +func init() { + pflag.CommandLine.StringVar(&logLevel, "log-level", defaultLogLevel, "Log level (debug,info,warn,error,fatal)") +} + func main() { + // the following line exists to make glog happy, for more information, see: https://github.com/kubernetes/kubernetes/issues/17162 + //flag.CommandLine.Parse([]string{}) + pflag.Parse() + // Get a config to talk to the apiserver cfg, err := config.GetConfig() if err != nil { @@ -47,6 +68,11 @@ func main() { log.Fatal(err) } + if err := clusterapis.AddToScheme(mgr.GetScheme()); err != nil { + log.Fatal(err) + } + + initActuator(mgr) // Setup all Controllers if err := controller.AddToManager(mgr); err != nil { log.Fatal(err) @@ -57,3 +83,37 @@ func main() { // Start the Cmd log.Fatal(mgr.Start(signals.SetupSignalHandler())) } + +func initActuator(m manager.Manager) { + config := m.GetConfig() + client, err := clientset.NewForConfig(config) + if err != nil { + glog.Fatalf("Could not create client for talking to the apiserver: %v", err) + } + + kubeClient, err := kubernetes.NewForConfig(config) + if err != nil { + glog.Fatalf("Could not create kubernetes client to talk to the apiserver: %v", err) + } + + log.SetOutput(os.Stdout) + if lvl, err := log.ParseLevel(logLevel); err != nil { + log.Panic(err) + } else { + log.SetLevel(lvl) + } + + logger := log.WithField("controller", "awsMachine") + + params := machineactuator.ActuatorParams{ + ClusterClient: client, + KubeClient: kubeClient, + AwsClientBuilder: awsclient.NewClient, + Logger: logger, + } + + machineactuator.MachineActuator, err = machineactuator.NewActuator(params) + if err != nil { + glog.Fatalf("Could not create AWS machine actuator: %v", err) + } +} \ No newline at end of file diff --git a/pkg/cloud/aws/actuators/machine/actuator.go b/pkg/cloud/aws/actuators/machine/actuator.go index 4f4a8f7b10..e4b4b4cd41 100644 --- a/pkg/cloud/aws/actuators/machine/actuator.go +++ b/pkg/cloud/aws/actuators/machine/actuator.go @@ -32,7 +32,7 @@ import ( providerconfigv1 "sigs.k8s.io/cluster-api-provider-aws/pkg/cloud/aws/providerconfig/v1alpha1" clusterv1 "sigs.k8s.io/cluster-api/pkg/apis/cluster/v1alpha1" clusterclient "sigs.k8s.io/cluster-api/pkg/client/clientset_generated/clientset" - //clustererror "sigs.k8s.io/cluster-api/pkg/controller/error" + clustererror "sigs.k8s.io/cluster-api/pkg/controller/error" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" @@ -53,6 +53,8 @@ const ( MachineCreationFailed = "MachineCreationFailed" ) +var MachineActuator *Actuator + // Actuator is the AWS-specific actuator for the Cluster API machine controller type Actuator struct { kubeClient kubernetes.Interface @@ -117,7 +119,8 @@ func (a *Actuator) updateMachineStatus(machine *clusterv1.Machine, awsStatus *pr if !equality.Semantic.DeepEqual(machine.Status, machineCopy.Status) { mLog.Info("machine status has changed, updating") - machineCopy.Status.LastUpdated = metav1.Now() + time := metav1.Now() + machineCopy.Status.LastUpdated = &time _, err := a.clusterClient.ClusterV1alpha1().Machines(machineCopy.Namespace).UpdateStatus(machineCopy) if err != nil { diff --git a/pkg/controller/add_awsmachineproviderconfig.go b/pkg/controller/add_machine.go similarity index 60% rename from pkg/controller/add_awsmachineproviderconfig.go rename to pkg/controller/add_machine.go index 8af0a98036..1f56a16e34 100644 --- a/pkg/controller/add_awsmachineproviderconfig.go +++ b/pkg/controller/add_machine.go @@ -1,12 +1,9 @@ /* -Copyright 2018 The Kubernetes Authors. - +Copyright 2018 The Kubernetes 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. @@ -17,10 +14,22 @@ limitations under the License. package controller import ( - "sigs.k8s.io/cluster-api-provider-aws/migration/pkg/controller/awsmachineproviderconfig" + "sigs.k8s.io/cluster-api/pkg/controller/machine" + "sigs.k8s.io/controller-runtime/pkg/manager" + machineactuator "sigs.k8s.io/cluster-api-provider-aws/pkg/cloud/aws/actuators/machine" +) + +var ( + logLevel string +) + +const ( + defaultLogLevel = "info" ) func init() { // AddToManagerFuncs is a list of functions to create controllers and add them to a manager. - AddToManagerFuncs = append(AddToManagerFuncs, awsmachineproviderconfig.Add) -} + AddToManagerFuncs = append(AddToManagerFuncs, func(m manager.Manager) error { + return machine.AddWithActuator(m, machineactuator.MachineActuator) + }) +} \ No newline at end of file diff --git a/pkg/controller/awsmachineproviderconfig/awsmachineproviderconfig_controller.go b/pkg/controller/awsmachineproviderconfig/awsmachineproviderconfig_controller.go deleted file mode 100644 index a12b59ad60..0000000000 --- a/pkg/controller/awsmachineproviderconfig/awsmachineproviderconfig_controller.go +++ /dev/null @@ -1,166 +0,0 @@ -/* -Copyright 2018 The Kubernetes 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 awsmachineproviderconfig - -import ( - "context" - "log" - "reflect" - - appsv1 "k8s.io/api/apps/v1" - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/types" - awsproviderconfigv1alpha1 "sigs.k8s.io/cluster-api-provider-aws/migration/pkg/apis/awsproviderconfig/v1alpha1" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/controller" - "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" - "sigs.k8s.io/controller-runtime/pkg/handler" - "sigs.k8s.io/controller-runtime/pkg/manager" - "sigs.k8s.io/controller-runtime/pkg/reconcile" - "sigs.k8s.io/controller-runtime/pkg/source" -) - -/** -* USER ACTION REQUIRED: This is a scaffold file intended for the user to modify with their own Controller -* business logic. Delete these comments after modifying this file.* - */ - -// Add creates a new AWSMachineProviderConfig Controller and adds it to the Manager with default RBAC. The Manager will set fields on the Controller -// and Start it when the Manager is Started. -// USER ACTION REQUIRED: update cmd/manager/main.go to call this awsproviderconfig.Add(mgr) to install this Controller -func Add(mgr manager.Manager) error { - return add(mgr, newReconciler(mgr)) -} - -// newReconciler returns a new reconcile.Reconciler -func newReconciler(mgr manager.Manager) reconcile.Reconciler { - return &ReconcileAWSMachineProviderConfig{Client: mgr.GetClient(), scheme: mgr.GetScheme()} -} - -// add adds a new Controller to mgr with r as the reconcile.Reconciler -func add(mgr manager.Manager, r reconcile.Reconciler) error { - // Create a new controller - c, err := controller.New("awsmachineproviderconfig-controller", mgr, controller.Options{Reconciler: r}) - if err != nil { - return err - } - - // Watch for changes to AWSMachineProviderConfig - err = c.Watch(&source.Kind{Type: &awsproviderconfigv1alpha1.AWSMachineProviderConfig{}}, &handler.EnqueueRequestForObject{}) - if err != nil { - return err - } - - // TODO(user): Modify this to be the types you create - // Uncomment watch a Deployment created by AWSMachineProviderConfig - change this for objects you create - err = c.Watch(&source.Kind{Type: &appsv1.Deployment{}}, &handler.EnqueueRequestForOwner{ - IsController: true, - OwnerType: &awsproviderconfigv1alpha1.AWSMachineProviderConfig{}, - }) - if err != nil { - return err - } - - return nil -} - -var _ reconcile.Reconciler = &ReconcileAWSMachineProviderConfig{} - -// ReconcileAWSMachineProviderConfig reconciles a AWSMachineProviderConfig object -type ReconcileAWSMachineProviderConfig struct { - client.Client - scheme *runtime.Scheme -} - -// Reconcile reads that state of the cluster for a AWSMachineProviderConfig object and makes changes based on the state read -// and what is in the AWSMachineProviderConfig.Spec -// TODO(user): Modify this Reconcile function to implement your Controller logic. The scaffolding writes -// a Deployment as an example -// Automatically generate RBAC rules to allow the Controller to read and write Deployments -// +kubebuilder:rbac:groups=apps,resources=deployments,verbs=get;list;watch;create;update;patch;delete -// +kubebuilder:rbac:groups=awsproviderconfig.k8s.io,resources=awsmachineproviderconfigs,verbs=get;list;watch;create;update;patch;delete -func (r *ReconcileAWSMachineProviderConfig) Reconcile(request reconcile.Request) (reconcile.Result, error) { - // Fetch the AWSMachineProviderConfig instance - instance := &awsproviderconfigv1alpha1.AWSMachineProviderConfig{} - err := r.Get(context.TODO(), request.NamespacedName, instance) - if err != nil { - if errors.IsNotFound(err) { - // Object not found, return. Created objects are automatically garbage collected. - // For additional cleanup logic use finalizers. - return reconcile.Result{}, nil - } - // Error reading the object - requeue the request. - return reconcile.Result{}, err - } - - // TODO(user): Change this to be the object type created by your controller - // Define the desired Deployment object - deploy := &appsv1.Deployment{ - ObjectMeta: metav1.ObjectMeta{ - Name: instance.Name + "-deployment", - Namespace: instance.Namespace, - }, - Spec: appsv1.DeploymentSpec{ - Selector: &metav1.LabelSelector{ - MatchLabels: map[string]string{"deployment": instance.Name + "-deployment"}, - }, - Template: corev1.PodTemplateSpec{ - ObjectMeta: metav1.ObjectMeta{Labels: map[string]string{"deployment": instance.Name + "-deployment"}}, - Spec: corev1.PodSpec{ - Containers: []corev1.Container{ - { - Name: "nginx", - Image: "nginx", - }, - }, - }, - }, - }, - } - if err := controllerutil.SetControllerReference(instance, deploy, r.scheme); err != nil { - return reconcile.Result{}, err - } - - // TODO(user): Change this for the object type created by your controller - // Check if the Deployment already exists - found := &appsv1.Deployment{} - err = r.Get(context.TODO(), types.NamespacedName{Name: deploy.Name, Namespace: deploy.Namespace}, found) - if err != nil && errors.IsNotFound(err) { - log.Printf("Creating Deployment %s/%s\n", deploy.Namespace, deploy.Name) - err = r.Create(context.TODO(), deploy) - if err != nil { - return reconcile.Result{}, err - } - } else if err != nil { - return reconcile.Result{}, err - } - - // TODO(user): Change this for the object type created by your controller - // Update the found object and write the result back if there are any changes - if !reflect.DeepEqual(deploy.Spec, found.Spec) { - found.Spec = deploy.Spec - log.Printf("Updating Deployment %s/%s\n", deploy.Namespace, deploy.Name) - err = r.Update(context.TODO(), found) - if err != nil { - return reconcile.Result{}, err - } - } - return reconcile.Result{}, nil -} diff --git a/pkg/controller/awsmachineproviderconfig/awsmachineproviderconfig_controller_suite_test.go b/pkg/controller/awsmachineproviderconfig/awsmachineproviderconfig_controller_suite_test.go deleted file mode 100644 index 48c6455169..0000000000 --- a/pkg/controller/awsmachineproviderconfig/awsmachineproviderconfig_controller_suite_test.go +++ /dev/null @@ -1,71 +0,0 @@ -/* -Copyright 2018 The Kubernetes 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 awsmachineproviderconfig - -import ( - "log" - "os" - "path/filepath" - "testing" - - "github.com/onsi/gomega" - "k8s.io/client-go/kubernetes/scheme" - "k8s.io/client-go/rest" - "sigs.k8s.io/cluster-api-provider-aws/migration/pkg/apis" - "sigs.k8s.io/controller-runtime/pkg/envtest" - "sigs.k8s.io/controller-runtime/pkg/manager" - "sigs.k8s.io/controller-runtime/pkg/reconcile" -) - -var cfg *rest.Config - -func TestMain(m *testing.M) { - t := &envtest.Environment{ - CRDDirectoryPaths: []string{filepath.Join("..", "..", "..", "config", "crds")}, - } - apis.AddToScheme(scheme.Scheme) - - var err error - if cfg, err = t.Start(); err != nil { - log.Fatal(err) - } - - code := m.Run() - t.Stop() - os.Exit(code) -} - -// SetupTestReconcile returns a reconcile.Reconcile implementation that delegates to inner and -// writes the request to requests after Reconcile is finished. -func SetupTestReconcile(inner reconcile.Reconciler) (reconcile.Reconciler, chan reconcile.Request) { - requests := make(chan reconcile.Request) - fn := reconcile.Func(func(req reconcile.Request) (reconcile.Result, error) { - result, err := inner.Reconcile(req) - requests <- req - return result, err - }) - return fn, requests -} - -// StartTestManager adds recFn -func StartTestManager(mgr manager.Manager, g *gomega.GomegaWithT) chan struct{} { - stop := make(chan struct{}) - go func() { - g.Expect(mgr.Start(stop)).NotTo(gomega.HaveOccurred()) - }() - return stop -} diff --git a/pkg/controller/awsmachineproviderconfig/awsmachineproviderconfig_controller_test.go b/pkg/controller/awsmachineproviderconfig/awsmachineproviderconfig_controller_test.go deleted file mode 100644 index 14759d67c8..0000000000 --- a/pkg/controller/awsmachineproviderconfig/awsmachineproviderconfig_controller_test.go +++ /dev/null @@ -1,81 +0,0 @@ -/* -Copyright 2018 The Kubernetes 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 awsmachineproviderconfig - -import ( - "testing" - "time" - - "github.com/onsi/gomega" - "golang.org/x/net/context" - appsv1 "k8s.io/api/apps/v1" - apierrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - awsproviderconfigv1alpha1 "sigs.k8s.io/cluster-api-provider-aws/migration/pkg/apis/awsproviderconfig/v1alpha1" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/manager" - "sigs.k8s.io/controller-runtime/pkg/reconcile" -) - -var c client.Client - -var expectedRequest = reconcile.Request{NamespacedName: types.NamespacedName{Name: "foo", Namespace: "default"}} -var depKey = types.NamespacedName{Name: "foo-deployment", Namespace: "default"} - -const timeout = time.Second * 5 - -func TestReconcile(t *testing.T) { - g := gomega.NewGomegaWithT(t) - instance := &awsproviderconfigv1alpha1.AWSMachineProviderConfig{ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "default"}} - - // Setup the Manager and Controller. Wrap the Controller Reconcile function so it writes each request to a - // channel when it is finished. - mgr, err := manager.New(cfg, manager.Options{}) - g.Expect(err).NotTo(gomega.HaveOccurred()) - c = mgr.GetClient() - - recFn, requests := SetupTestReconcile(newReconciler(mgr)) - g.Expect(add(mgr, recFn)).NotTo(gomega.HaveOccurred()) - defer close(StartTestManager(mgr, g)) - - // Create the AWSMachineProviderConfig object and expect the Reconcile and Deployment to be created - err = c.Create(context.TODO(), instance) - // The instance object may not be a valid object because it might be missing some required fields. - // Please modify the instance object by adding required fields and then remove the following if statement. - if apierrors.IsInvalid(err) { - t.Logf("failed to create object, got an invalid object error: %v", err) - return - } - g.Expect(err).NotTo(gomega.HaveOccurred()) - defer c.Delete(context.TODO(), instance) - g.Eventually(requests, timeout).Should(gomega.Receive(gomega.Equal(expectedRequest))) - - deploy := &appsv1.Deployment{} - g.Eventually(func() error { return c.Get(context.TODO(), depKey, deploy) }, timeout). - Should(gomega.Succeed()) - - // Delete the Deployment and expect Reconcile to be called for Deployment deletion - g.Expect(c.Delete(context.TODO(), deploy)).NotTo(gomega.HaveOccurred()) - g.Eventually(requests, timeout).Should(gomega.Receive(gomega.Equal(expectedRequest))) - g.Eventually(func() error { return c.Get(context.TODO(), depKey, deploy) }, timeout). - Should(gomega.Succeed()) - - // Manually delete Deployment since GC isn't enabled in the test control plane - g.Expect(c.Delete(context.TODO(), deploy)).To(gomega.Succeed()) - -}