Skip to content

Commit

Permalink
use controller-runtime NewManager for setup
Browse files Browse the repository at this point in the history
  • Loading branch information
isaaguilar committed Apr 5, 2021
1 parent b0bd276 commit d265f35
Show file tree
Hide file tree
Showing 7 changed files with 166 additions and 256 deletions.
13 changes: 12 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -106,10 +106,21 @@ deploy:
kubectl delete pod --selector name=${DEPLOYMENT} --namespace ${NAMESPACE} && sleep 4
kubectl logs -f --selector name=${DEPLOYMENT} --namespace ${NAMESPACE}

# Run go fmt against code
fmt:
go fmt ./...

# Run go vet against code
vet:
go vet ./...

# Run against the configured Kubernetes cluster in ~/.kube/config
run: fmt vet
go run cmd/manager/main.go

build: k8s-gen openapi-gen docker-build-local
build-all: build docker-build-job
push: docker-push
push-all: push docker-push-job
run: docker-build-local deploy

.PHONY: build push run docker-build docker-build-local docker-push deploy openapi-gen k8s-gen crds contoller-gen client-gen
125 changes: 50 additions & 75 deletions cmd/manager/main.go
Original file line number Diff line number Diff line change
@@ -1,113 +1,88 @@
package main

import (
"context"
"flag"
"fmt"
"os"
"runtime"

// Import all Kubernetes client auth plugins (e.g. Azure, GCP, OIDC, etc.)
_ "k8s.io/client-go/plugin/pkg/client/auth"

"github.com/isaaguilar/terraform-operator/pkg/apis"
"github.com/isaaguilar/terraform-operator/pkg/controller"
"github.com/operator-framework/operator-lib/leader"
"github.com/spf13/pflag"
"github.com/isaaguilar/terraform-operator/pkg/controllers"

"k8s.io/apimachinery/pkg/runtime"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
clientgoscheme "k8s.io/client-go/kubernetes/scheme"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client/apiutil"
"sigs.k8s.io/controller-runtime/pkg/client/config"
"sigs.k8s.io/controller-runtime/pkg/healthz"
"sigs.k8s.io/controller-runtime/pkg/log/zap"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/manager/signals"
)

var log = ctrl.Log.WithName("setup")
var (
scheme = runtime.NewScheme()
setupLog = ctrl.Log.WithName("setup")
)

func printVersion() {
log.Info(fmt.Sprintf("Go Version: %s", runtime.Version()))
log.Info(fmt.Sprintf("Go OS/Arch: %s/%s", runtime.GOOS, runtime.GOARCH))
func init() {
utilruntime.Must(clientgoscheme.AddToScheme(scheme))

utilruntime.Must(apis.AddToScheme(scheme))
// +kubebuilder:scaffold:scheme
}

func main() {
// Add the zap logger flag set to the CLI. The flag set must
// be added before calling pflag.Parse().
opts := zap.Options{}
var metricsAddr string
var enableLeaderElection bool
var probeAddr string
flag.StringVar(&metricsAddr, "metrics-bind-address", ":8080", "The address the metric endpoint binds to.")
flag.StringVar(&probeAddr, "health-probe-bind-address", ":8081", "The address the probe endpoint binds to.")
flag.BoolVar(&enableLeaderElection, "leader-elect", false,
"Enable leader election for controller manager. "+
"Enabling this will ensure there is only one active controller manager.")
opts := zap.Options{
Development: true,
}
opts.BindFlags(flag.CommandLine)
flag.Parse()

// Add flags registered by imported packages (e.g. glog and
// controller-runtime)
pflag.CommandLine.AddGoFlagSet(flag.CommandLine)

pflag.Parse()

// Use a zap logr.Logger implementation. If none of the zap
// flags are configured (or if the zap flag set is not being
// used), this defaults to a production zap logger.
//
// The logger instantiated here can be changed to any logger
// implementing the logr.Logger interface. This logger will
// be propagated through the whole operator, generating
// uniform and structured logs.
ctrl.SetLogger(zap.New(zap.UseDevMode(true)))

printVersion()

WatchNamespaceEnvVar := "WATCH_NAMESPACE"
namespace, found := os.LookupEnv(WatchNamespaceEnvVar)
if !found {
log.Error(fmt.Errorf("Failed to get watch namespace"), "")
os.Exit(1)

}

// Get a config to talk to the apiserver
cfg, err := config.GetConfig()
if err != nil {
log.Error(err, "")
os.Exit(1)
}
ctrl.SetLogger(zap.New(zap.UseFlagOptions(&opts)))

ctx := context.TODO()
// Become the leader before proceeding
err = leader.Become(ctx, "terraform-operator-lock")
mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{
Scheme: scheme,
MetricsBindAddress: metricsAddr,
Port: 9443,
HealthProbeBindAddress: probeAddr,
LeaderElection: enableLeaderElection,
LeaderElectionID: "050c8fba.isaaguilar.com",
})
if err != nil {
log.Error(err, "")
setupLog.Error(err, "unable to start manager")
os.Exit(1)
}

// Create a new Cmd to provide shared dependencies and start components
mgr, err := manager.New(cfg, manager.Options{
Namespace: namespace,
MapperProvider: apiutil.NewDiscoveryRESTMapper,
MetricsBindAddress: "0", // set to "0" to disable the metrics serving
})
if err != nil {
log.Error(err, "")
if err = (&controllers.ReconcileTerraform{
Client: mgr.GetClient(),
Log: ctrl.Log.WithName("terraform_controller"),
Recorder: mgr.GetEventRecorderFor("terraform-controller"),
Scheme: mgr.GetScheme(),
}).SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "Cluster")
os.Exit(1)
}
// +kubebuilder:scaffold:builder

log.Info("Registering Components...")

// Setup Scheme for all resources
if err := apis.AddToScheme(mgr.GetScheme()); err != nil {
log.Error(err, "")
if err := mgr.AddHealthzCheck("health", healthz.Ping); err != nil {
setupLog.Error(err, "unable to set up health check")
os.Exit(1)
}

// Setup all Controllers
if err := controller.AddToManager(mgr); err != nil {
log.Error(err, "")
if err := mgr.AddReadyzCheck("check", healthz.Ping); err != nil {
setupLog.Error(err, "unable to set up ready check")
os.Exit(1)
}

log.Info("Starting the terraform-operator controller")

// Start the Cmd
if err := mgr.Start(signals.SetupSignalHandler()); err != nil {
log.Error(err, "Manager exited non-zero")
setupLog.Info("starting manager")
if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil {
setupLog.Error(err, "problem running manager")
os.Exit(1)
}
}
3 changes: 1 addition & 2 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
module github.com/isaaguilar/terraform-operator



replace (
google.golang.org/grpc => google.golang.org/grpc v1.29.1
k8s.io/kube-state-metrics => k8s.io/kube-state-metrics v1.6.0
sigs.k8s.io/controller-tools => sigs.k8s.io/controller-tools v0.1.11-0.20190411181648-9d55346c2bde
)

replace github.com/docker/docker => github.com/moby/moby v0.7.3-0.20190826074503-38ab9da00309 // Required by Helm

replace github.com/openshift/api => github.com/openshift/api v0.0.0-20190924102528-32369d4db2ad // Required until https://github.com/operator-framework/operator-lifecycle-manager/pull/1241 is resolved

go 1.15
Expand Down
7 changes: 7 additions & 0 deletions pkg/apis/tf/v1alpha1/zz_generated.openapi.go

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

10 changes: 0 additions & 10 deletions pkg/controller/add_terraform.go

This file was deleted.

18 changes: 0 additions & 18 deletions pkg/controller/controller.go

This file was deleted.

Loading

0 comments on commit d265f35

Please sign in to comment.