Skip to content

Commit

Permalink
updates based on SDK's helm-operator 1.0.0 (operator-framework#59)
Browse files Browse the repository at this point in the history
  • Loading branch information
joelanford authored Aug 12, 2020
1 parent 12b55ea commit d40d48e
Show file tree
Hide file tree
Showing 14 changed files with 250 additions and 208 deletions.
2 changes: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ RUN go mod download
# Copy the go source
COPY main.go main.go
COPY pkg/ pkg/
COPY version/ version/
COPY internal/ internal/

# Build
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 GO111MODULE=on go build -a -o helm-operator main.go
Expand Down
34 changes: 19 additions & 15 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,30 @@ else
GOBIN=$(shell go env GOBIN)
endif

# GO_BUILD_ARGS should be set when running 'go build' or 'go install'.
REPO = $(shell go list -m)
VERSION = $(shell git describe --dirty --tags --always)
GIT_COMMIT = $(shell git rev-parse HEAD)
GO_BUILD_ARGS = \
-gcflags "all=-trimpath=$(shell dirname $(shell pwd))" \
-asmflags "all=-trimpath=$(shell dirname $(shell pwd))" \
-ldflags " \
-X '$(REPO)/internal/version.Version=$(VERSION)' \
-X '$(REPO)/internal/version.GitCommit=$(GIT_COMMIT)' \
" \

all: manager

# Run tests
test: fmt vet testbin
go test -race -covermode atomic -coverprofile cover.out ./...
ENVTEST_ASSETS_DIR=$(shell pwd)/testbin
test: fmt vet
mkdir -p ${ENVTEST_ASSETS_DIR}
test -f ${ENVTEST_ASSETS_DIR}/setup-envtest.sh || curl -sSLo ${ENVTEST_ASSETS_DIR}/setup-envtest.sh https://raw.githubusercontent.com/kubernetes-sigs/controller-runtime/master/hack/setup-envtest.sh
source ${ENVTEST_ASSETS_DIR}/setup-envtest.sh; fetch_envtest_tools $(ENVTEST_ASSETS_DIR); setup_envtest_env $(ENVTEST_ASSETS_DIR); go test -race -covermode atomic -coverprofile cover.out ./...

# Build manager binary
build: fmt vet
go build -o bin/helm-operator main.go
go build $(GO_BUILD_ARGS) -o bin/helm-operator main.go

# Run go fmt against code
fmt:
Expand All @@ -32,7 +47,7 @@ lint: golangci-lint
$(GOLANGCI_LINT) run

# Build the docker image
docker-build: test
docker-build:
docker build . -t ${IMG}

# Push the docker image
Expand All @@ -51,14 +66,3 @@ GOLANGCI_LINT=$(shell go env GOPATH)/bin/golangci-lint
else
GOLANGCI_LINT=$(shell which golangci-lint)
endif

K8S_VER ?= v1.18.2
ETCD_VER ?= v3.4.3
OS=$(shell uname -s | tr '[:upper:]' '[:lower:]')
ARCH=$(shell uname -m | sed 's/x86_64/amd64/')

.PHONY: testbin
testbin:
mkdir -p testbin
[[ -x testbin/etcd ]] || curl -L https://storage.googleapis.com/etcd/${ETCD_VER}/etcd-${ETCD_VER}-${OS}-${ARCH}.tar.gz | tar zx -C testbin --strip-components=1 etcd-${ETCD_VER}-${OS}-${ARCH}/etcd
[[ -x testbin/kube-apiserver && -x testbin/kubectl ]] || curl -L https://dl.k8s.io/${K8S_VER}/kubernetes-server-${OS}-${ARCH}.tar.gz | tar zx -C testbin --strip-components=3 kubernetes/server/bin/kube-apiserver kubernetes/server/bin/kubectl
2 changes: 1 addition & 1 deletion example/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ endif

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

# Install CRDs into a cluster
install: kustomize
Expand Down
8 changes: 4 additions & 4 deletions example/config/samples/helm_v1_nginx.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ kind: Nginx
metadata:
name: nginx-sample
annotations:
helm.operator-sdk/upgrade-force: "true"
helm.operator-sdk/install-disable-hooks: "true"
helm.operator-sdk/upgrade-disable-hooks: "true"
helm.operator-sdk/uninstall-disable-hooks: "true"
helm.sdk.operatorframework.io/upgrade-force: "true"
helm.sdk.operatorframework.io/install-disable-hooks: "true"
helm.sdk.operatorframework.io/upgrade-disable-hooks: "true"
helm.sdk.operatorframework.io/uninstall-disable-hooks: "true"
spec:
replicaCount: 1
image:
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ require (
github.com/onsi/ginkgo v1.12.1
github.com/onsi/gomega v1.10.1
github.com/operator-framework/operator-lib v0.1.0
github.com/spf13/cobra v1.0.0
github.com/spf13/pflag v1.0.5
github.com/stretchr/testify v1.5.1
go.uber.org/zap v1.13.0
Expand Down
165 changes: 165 additions & 0 deletions internal/cmd/run/cmd.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
/*
Copyright 2020 The Operator-SDK 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 run

import (
"flag"
"os"
"runtime"
"time"

"github.com/spf13/cobra"
"github.com/spf13/pflag"
ctrl "sigs.k8s.io/controller-runtime"
logf "sigs.k8s.io/controller-runtime/pkg/log"
zapl "sigs.k8s.io/controller-runtime/pkg/log/zap"

"github.com/joelanford/helm-operator/internal/version"
"github.com/joelanford/helm-operator/pkg/annotation"
"github.com/joelanford/helm-operator/pkg/manager"
"github.com/joelanford/helm-operator/pkg/reconciler"
"github.com/joelanford/helm-operator/pkg/watches"
)

func NewCmd() *cobra.Command {
r := run{}
zapfs := flag.NewFlagSet("zap", flag.ExitOnError)
opts := &zapl.Options{}
opts.BindFlags(zapfs)

cmd := &cobra.Command{
Use: "run",
Short: "Run the operator",
Run: func(cmd *cobra.Command, _ []string) {
logf.SetLogger(zapl.New(zapl.UseFlagOptions(opts)))
r.run(cmd)
},
}
r.bindFlags(cmd.Flags())
cmd.Flags().AddGoFlagSet(zapfs)
return cmd
}

type run struct {
metricsAddr string
enableLeaderElection bool
leaderElectionID string
leaderElectionNamespace string

watchesFile string
defaultMaxConcurrentReconciles int
defaultReconcilePeriod time.Duration
}

func (r *run) bindFlags(fs *pflag.FlagSet) {
fs.StringVar(&r.metricsAddr, "metrics-addr", ":8080", "The address the metric endpoint binds to.")
fs.BoolVar(&r.enableLeaderElection, "enable-leader-election", false,
"Enable leader election for controller manager. Enabling this will ensure there is only one active controller manager.")
fs.StringVar(&r.leaderElectionID, "leader-election-id", "",
"Name of the configmap that is used for holding the leader lock.")
fs.StringVar(&r.leaderElectionNamespace, "leader-election-namespace", "",
"Namespace in which to create the leader election configmap for holding the leader lock (required if running locally with leader election enabled).")

fs.StringVar(&r.watchesFile, "watches-file", "./watches.yaml", "Path to watches.yaml file.")
fs.DurationVar(&r.defaultReconcilePeriod, "reconcile-period", time.Minute, "Default reconcile period for controllers (use 0 to disable periodic reconciliation)")
fs.IntVar(&r.defaultMaxConcurrentReconciles, "max-concurrent-reconciles", runtime.NumCPU(), "Default maximum number of concurrent reconciles for controllers.")
}

var log = logf.Log.WithName("cmd")

func printVersion() {
log.Info("Version",
"Go Version", runtime.Version(),
"GOOS", runtime.GOOS,
"GOARCH", runtime.GOARCH,
"helm-operator", version.Version)
}

func (r *run) run(cmd *cobra.Command) {
printVersion()

// Deprecated: OPERATOR_NAME environment variable is an artifact of the legacy operator-sdk project scaffolding.
// Flag `--leader-election-id` should be used instead.
if operatorName, found := os.LookupEnv("OPERATOR_NAME"); found {
log.Info("environment variable OPERATOR_NAME has been deprecated, use --leader-election-id instead.")
if cmd.Flags().Lookup("leader-election-id").Changed {
log.Info("ignoring OPERATOR_NAME environment variable since --leader-election-id is set")
} else {
r.leaderElectionID = operatorName
}
}

options := ctrl.Options{
MetricsBindAddress: r.metricsAddr,
LeaderElection: r.enableLeaderElection,
LeaderElectionID: r.leaderElectionID,
LeaderElectionNamespace: r.leaderElectionNamespace,
NewClient: manager.NewDelegatingClientFunc(),
}
manager.ConfigureWatchNamespaces(&options, log)
mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), options)
if err != nil {
log.Error(err, "unable to start manager")
os.Exit(1)
}

ws, err := watches.Load(r.watchesFile)
if err != nil {
log.Error(err, "unable to load watches.yaml", "path", r.watchesFile)
os.Exit(1)
}

for _, w := range ws {
reconcilePeriod := r.defaultReconcilePeriod
if w.ReconcilePeriod != nil {
reconcilePeriod = w.ReconcilePeriod.Duration
}

maxConcurrentReconciles := r.defaultMaxConcurrentReconciles
if w.MaxConcurrentReconciles != nil {
maxConcurrentReconciles = *w.MaxConcurrentReconciles
}

r, err := reconciler.New(
reconciler.WithChart(*w.Chart),
reconciler.WithGroupVersionKind(w.GroupVersionKind),
reconciler.WithOverrideValues(w.OverrideValues),
reconciler.SkipDependentWatches(w.WatchDependentResources != nil && !*w.WatchDependentResources),
reconciler.WithMaxConcurrentReconciles(maxConcurrentReconciles),
reconciler.WithReconcilePeriod(reconcilePeriod),
reconciler.WithInstallAnnotations(annotation.DefaultInstallAnnotations...),
reconciler.WithUpgradeAnnotations(annotation.DefaultUpgradeAnnotations...),
reconciler.WithUninstallAnnotations(annotation.DefaultUninstallAnnotations...),
)
if err != nil {
log.Error(err, "unable to create helm reconciler", "controller", "Helm")
os.Exit(1)
}

if err := r.SetupWithManager(mgr); err != nil {
log.Error(err, "unable to create controller", "controller", "Helm")
os.Exit(1)
}
log.Info("configured watch", "gvk", w.GroupVersionKind, "chartPath", w.ChartPath, "maxConcurrentReconciles", maxConcurrentReconciles, "reconcilePeriod", reconcilePeriod)
}

log.Info("starting manager")
if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil {
log.Error(err, "problem running manager")
os.Exit(1)
}
}
42 changes: 42 additions & 0 deletions internal/cmd/version/cmd.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/*
Copyright 2020 The Operator-SDK 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 version

import (
"fmt"
"runtime"

"github.com/spf13/cobra"

"github.com/joelanford/helm-operator/internal/version"
)

func NewCmd() *cobra.Command {
versionCmd := &cobra.Command{
Use: "version",
Short: "Prints the version of helm-operator",
Run: func(cmd *cobra.Command, args []string) {
run()
},
}
return versionCmd
}

func run() {
fmt.Printf("helm-operator version: %q, commit: %q, go version: %q, GOOS: %q, GOARCH: %q\n",
version.Version, version.GitCommit, runtime.Version(), runtime.GOOS, runtime.GOARCH)
}
5 changes: 3 additions & 2 deletions version/version.go → internal/version/version.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ limitations under the License.

package version

const (
Version = "0.0.0+git"
var (
Version = "unknown"
GitCommit = "unknown"
)
Loading

0 comments on commit d40d48e

Please sign in to comment.