diff --git a/.golangci.yaml b/.golangci.yaml new file mode 100644 index 0000000..4794261 --- /dev/null +++ b/.golangci.yaml @@ -0,0 +1,75 @@ +version: '2' +linters: + default: none + enable: + - asasalint + - asciicheck + - bidichk + - bodyclose + - canonicalheader + - contextcheck + - copyloopvar + - decorder + - dogsled + - dupword + - durationcheck + - errcheck + - errchkjson + - errname + - exhaustive + - exptostd + - forbidigo + - ginkgolinter + - gocheckcompilerdirectives + - gochecksumtype + - gocritic + - goheader + - goprintffuncname + - gosec + - gosmopolitan + - govet + - grouper + - importas + - ineffassign + - interfacebloat + - intrange + - loggercheck + - makezero + - mirror + - misspell + - modernize + - musttag + - nakedret + - nilerr + - nilnil + - noctx + - nolintlint + - nosprintfhostport + - predeclared + - promlinter + - protogetter + - reassign + - sloglint + - staticcheck + - tagalign + - testableexamples + - unconvert + - unparam + - unused + - usestdlibvars + - usetesting + - wastedassign +formatters: + enable: [gci, gofmt] + settings: + gci: + sections: + - standard # Standard section: captures all standard packages. + - default # Default section: contains all imports that could not be matched to another section type. + - localmodule # Local module section: contains all local packages. + - blank # Blank section: contains all blank imports. This section is not present unless explicitly enabled. + - dot # Dot section: contains all dot imports. This section is not present unless explicitly enabled. + custom-order: true + exclusions: + generated: lax + paths: [third_party, builtin$, examples$] diff --git a/Dockerfile b/Dockerfile index f1f395a..39396a5 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,6 +1,7 @@ FROM --platform=$BUILDPLATFORM golang:1.27.3 AS builder ARG TARGETOS ARG TARGETARCH +ARG VERSION=dev WORKDIR /app @@ -11,11 +12,12 @@ RUN go mod download COPY main.go main.go COPY controllers/ controllers/ -RUN CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build -a -o probemgr main.go +RUN CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} \ + go build -a -ldflags "-s -w -X main.version=${VERSION}" -o probe-controller main.go FROM gcr.io/distroless/static:nonroot WORKDIR / -COPY --from=builder /app/probemgr . +COPY --from=builder /app/probe-controller . USER 65532:65532 -ENTRYPOINT ["/probemgr"] +ENTRYPOINT ["/probe-controller"] diff --git a/Makefile b/Makefile index 0414345..55fbdbf 100644 --- a/Makefile +++ b/Makefile @@ -1,9 +1,49 @@ -.DEFAULT_GOAL=help -SHELL:=/bin/bash +# See: https://clarkgrubb.com/makefile-style-guide +MAKEFLAGS += --warn-undefined-variables --no-builtin-rules +SHELL := /usr/bin/env bash + +# The `--norc` option prevents "PS1: unbound" errors. +# If Bash thinks it is being run with its standard input connected to a network +# connection (such as via SSH or via Docker), it reads and executes commands +# from ~/.bashrc, regardless of whether it thinks it is in interactive mode. +# Bash does not set PS1 in non-interactive environments. But on Ubuntu 24.04 the +# default /etc/bash.bashrc file assumes that PS1 is set. +# +# See https://www.gnu.org/software/bash/manual/bash.html#Invoked-by-remote-shell-daemon +.SHELLFLAGS := --norc -euo pipefail -c +.DEFAULT_GOAL := help +.DELETE_ON_ERROR: +.SUFFIXES: + +# Set empty value for MAKECMDGOALS to prevent the "warning: undefined variable 'MAKECMDGOALS'" +# warning from happening when running make without arguments +MAKECMDGOALS ?= + +## +# Git and versioning information +## + +git_version := $(shell git describe --tags --always --match='v*' --abbrev=14 --dirty) +VERSION ?= $(git_version) + +## +# Global vars and dirs +## +bin_dir := _bin + +$(bin_dir): + @mkdir -p $@ + +go_srcs := $(shell find . -name '*.go' -not -name '*_test.go' -not -path './$(bin_dir)/*') +binary := $(bin_dir)/probe-controller +ldflags := -s -w -X main.version=$(VERSION) ##@ Linting and static checks -.PHONY: vet +.PHONY: lint vet + +lint: ## Run golangci-lint + @golangci-lint run vet: ## Run go vet @go vet ./... @@ -13,21 +53,29 @@ vet: ## Run go vet .PHONY: test test-cov-html test: vet ## Run tests - @go test ./... -cover + @go test -cover ./... test-cov-html: vet ## Run test coverage - @go test ./... -covermode=count -coverprofile=coverage.out \ + @go test -covermode=count -coverprofile=coverage.out ./... \ && go tool cover -html=coverage.out ##@ Build -.PHONY: docker lint-docker +.PHONY: build bake clean lint-docker -lint-docker: - @hadolint Dockerfile +build: $(binary) ## Build binary locally + +$(binary): $(go_srcs) go.mod go.sum | $(bin_dir) + @CGO_ENABLED=0 go build -ldflags "$(ldflags)" -o $@ main.go -bake: lint-docker - @docker buildx bake image-local +bake: lint-docker ## Bake Docker image locally + @VERSION=$(VERSION) docker buildx bake image-local + +clean: ## Clean all temporary files + @rm -rfv $(bin_dir) coverage.out + +lint-docker: ## Run hadolint + @hadolint Dockerfile ##@ Helpers diff --git a/controllers/httproute_controller.go b/controllers/httproute_controller.go index 2ae2454..ebbb11a 100644 --- a/controllers/httproute_controller.go +++ b/controllers/httproute_controller.go @@ -3,10 +3,11 @@ package controllers import ( "bytes" "context" + "crypto/sha256" + "encoding/hex" "encoding/json" "fmt" "net/http" - "strconv" "time" ctrl "sigs.k8s.io/controller-runtime" @@ -63,9 +64,8 @@ func (r *HTTPRouteWatcher) Reconcile(ctx context.Context, req ctrl.Request) (ctr return ctrl.Result{}, nil } - // Check if trigger annotation is enabled + // If annotation was removed, clean up the finalizer if route.Annotations[triggerAnnotation] != "true" { - // If annotation was removed, clean up the finalizer if controllerutil.ContainsFinalizer(&route, finalizerName) { controllerutil.RemoveFinalizer(&route, finalizerName) return ctrl.Result{}, r.Update(ctx, &route) @@ -83,15 +83,18 @@ func (r *HTTPRouteWatcher) Reconcile(ctx context.Context, req ctrl.Request) (ctr } // Prevent dupe API calls on status-only updates - // TODO: hash spec fields to account for domain changes - currentGen := strconv.FormatInt(route.Generation, 10) - lastSyncedGen := route.Annotations[lastSyncedAnnotation] - if currentGen == lastSyncedGen { + currentHash, err := computeSpecHash(route.Spec) + if err != nil { + return ctrl.Result{}, err + } + + lastSyncedHash := route.Annotations[lastSyncedAnnotation] + if currentHash == lastSyncedHash { return ctrl.Result{}, nil } eventType := "UPDATED" - if lastSyncedGen == "" { + if lastSyncedHash == "" { eventType = "CREATED" } @@ -110,7 +113,7 @@ func (r *HTTPRouteWatcher) Reconcile(ctx context.Context, req ctrl.Request) (ctr if route.Annotations == nil { route.Annotations = make(map[string]string) } - route.Annotations[lastSyncedAnnotation] = currentGen + route.Annotations[lastSyncedAnnotation] = currentHash if err := r.Update(ctx, &route); err != nil { return ctrl.Result{}, err } @@ -153,6 +156,16 @@ func (r *HTTPRouteWatcher) callExternalAPI(ctx context.Context, payload WebhookP return nil } +// encode payload and return a 16-char hex digest +func computeSpecHash(spec gatewayv1.HTTPRouteSpec) (string, error) { + data, err := json.Marshal(spec) + if err != nil { + return "", fmt.Errorf("failed to marshal HTTPRoute spec: %w", err) + } + sum := sha256.Sum256(data) + return hex.EncodeToString(sum[:8]), nil +} + func (r *HTTPRouteWatcher) SetupWithManager(mgr ctrl.Manager) error { return ctrl.NewControllerManagedBy(mgr). For(&gatewayv1.HTTPRoute{}). diff --git a/controllers/httproute_controller_test.go b/controllers/httproute_controller_test.go index 4f98fc9..f3fbd8c 100644 --- a/controllers/httproute_controller_test.go +++ b/controllers/httproute_controller_test.go @@ -8,9 +8,7 @@ import ( "sync" "testing" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/types" clientgoscheme "k8s.io/client-go/kubernetes/scheme" "k8s.io/client-go/rest" ctrl "sigs.k8s.io/controller-runtime" @@ -93,13 +91,10 @@ func TestHTTPRouteWatcher_Lifecycle(t *testing.T) { ctx := context.Background() route := &gatewayv1.HTTPRoute{ - ObjectMeta: metav1.ObjectMeta{ - Name: "my-route", - Namespace: "default", - Generation: 1, - Annotations: map[string]string{ - triggerAnnotation: "true", - }, + Name: "my-route", + Namespace: "default", + Annotations: map[string]string{ + triggerAnnotation: "true", }, Spec: gatewayv1.HTTPRouteSpec{ Hostnames: []gatewayv1.Hostname{"app.example.com"}, @@ -108,7 +103,8 @@ func TestHTTPRouteWatcher_Lifecycle(t *testing.T) { env := newTestEnv(t, route) req := ctrl.Request{ - NamespacedName: types.NamespacedName{Name: "my-route", Namespace: "default"}, + Name: "my-route", + Namespace: "default", } // --- TEST: CREATE --- @@ -130,10 +126,19 @@ func TestHTTPRouteWatcher_Lifecycle(t *testing.T) { } // --- TEST: SKIP NOOP --- - events = env.recordedEvents() + var statusRoute gatewayv1.HTTPRoute + _ = env.client.Get(ctx, req.NamespacedName, &statusRoute) + statusRoute.Status.Parents = []gatewayv1.RouteParentStatus{ + { + ParentRef: gatewayv1.ParentReference{Name: "my-gateway"}, + }, + } + _ = env.client.Status().Update(ctx, &statusRoute) + if _, err := env.reconciler.Reconcile(ctx, req); err != nil { t.Fatalf("status reconcile failed: %v", err) } + events = env.recordedEvents() if len(events) != 1 { t.Fatalf("expected no duplicate call on same generation, got %d events", len(events)) } @@ -141,7 +146,6 @@ func TestHTTPRouteWatcher_Lifecycle(t *testing.T) { // --- TEST: UPDATE --- var updatedRoute gatewayv1.HTTPRoute _ = env.client.Get(ctx, req.NamespacedName, &updatedRoute) - updatedRoute.Generation = 2 // API server increments generation updatedRoute.Spec.Hostnames = []gatewayv1.Hostname{"www.example.com"} _ = env.client.Update(ctx, &updatedRoute) @@ -177,19 +181,15 @@ func TestHTTPRouteWatcher_AnnotationRemoved_CleansUpFinalizer(t *testing.T) { ctx := context.Background() route := &gatewayv1.HTTPRoute{ - ObjectMeta: metav1.ObjectMeta{ - Name: "untracked-route", - Namespace: "default", - Finalizers: []string{finalizerName}, - Annotations: map[string]string{ - lastSyncedAnnotation: "1", - }, - }, + Name: "untracked-route", + Namespace: "default", + Finalizers: []string{finalizerName}, } env := newTestEnv(t, route) req := ctrl.Request{ - NamespacedName: types.NamespacedName{Name: "untracked-route", Namespace: "default"}, + Name: "untracked-route", + Namespace: "default", } // --- TEST: Remove finalizer without calling external API --- @@ -235,13 +235,10 @@ func TestHTTPRouteWatcher_ErrorsAndAuth(t *testing.T) { { name: "API 500 on create returns error and does not stamp generation", route: &gatewayv1.HTTPRoute{ - ObjectMeta: metav1.ObjectMeta{ - Name: "fail-create", - Namespace: "default", - Generation: 1, - Finalizers: []string{finalizerName}, - Annotations: map[string]string{triggerAnnotation: "true"}, - }, + Name: "fail-create", + Namespace: "default", + Finalizers: []string{finalizerName}, + Annotations: map[string]string{triggerAnnotation: "true"}, }, apiStatusCode: http.StatusInternalServerError, wantErr: true, @@ -250,12 +247,10 @@ func TestHTTPRouteWatcher_ErrorsAndAuth(t *testing.T) { { name: "API 500 on delete returns error and keeps finalizer", route: &gatewayv1.HTTPRoute{ - ObjectMeta: metav1.ObjectMeta{ - Name: "fail-delete", - Namespace: "default", - Finalizers: []string{finalizerName}, - Annotations: map[string]string{triggerAnnotation: "true"}, - }, + Name: "fail-delete", + Namespace: "default", + Finalizers: []string{finalizerName}, + Annotations: map[string]string{triggerAnnotation: "true"}, }, deleteBeforeSync: true, apiStatusCode: http.StatusInternalServerError, @@ -265,13 +260,10 @@ func TestHTTPRouteWatcher_ErrorsAndAuth(t *testing.T) { { name: "invalid external URL returns request error", route: &gatewayv1.HTTPRoute{ - ObjectMeta: metav1.ObjectMeta{ - Name: "bad-url", - Namespace: "default", - Generation: 1, - Finalizers: []string{finalizerName}, - Annotations: map[string]string{triggerAnnotation: "true"}, - }, + Name: "bad-url", + Namespace: "default", + Finalizers: []string{finalizerName}, + Annotations: map[string]string{triggerAnnotation: "true"}, }, overrideURL: "://invalid-url", wantErr: true, @@ -280,13 +272,10 @@ func TestHTTPRouteWatcher_ErrorsAndAuth(t *testing.T) { { name: "sends Bearer token when APIToken is configured", route: &gatewayv1.HTTPRoute{ - ObjectMeta: metav1.ObjectMeta{ - Name: "auth-route", - Namespace: "default", - Generation: 1, - Finalizers: []string{finalizerName}, - Annotations: map[string]string{triggerAnnotation: "true"}, - }, + Name: "auth-route", + Namespace: "default", + Finalizers: []string{finalizerName}, + Annotations: map[string]string{triggerAnnotation: "true"}, }, apiStatusCode: http.StatusOK, apiToken: "super-secret-token", @@ -302,7 +291,8 @@ func TestHTTPRouteWatcher_ErrorsAndAuth(t *testing.T) { var env *testEnv req := ctrl.Request{ - NamespacedName: types.NamespacedName{Name: "missing-route", Namespace: "default"}, + Name: "missing-route", + Namespace: "default", } if tc.route != nil { diff --git a/docker-bake.hcl b/docker-bake.hcl index daf650a..b10031b 100644 --- a/docker-bake.hcl +++ b/docker-bake.hcl @@ -1,7 +1,7 @@ target "docker-metadata-action" {} variable "APP" { - default = "prober" + default = "probe-controller" } variable "VERSION" { @@ -9,11 +9,11 @@ variable "VERSION" { } variable "SOURCE" { - default = "https://github.com/cilindrox/probe-controller" + default = "https://github.com/cilindrox/${APP}" } variable "REGISTRY" { - default = "ghcr.io/cilindrox/probe-controller" + default = "ghcr.io/cilindrox" } group "default" { diff --git a/main.go b/main.go index 6aeb7f4..b42e13f 100644 --- a/main.go +++ b/main.go @@ -2,11 +2,11 @@ package main import ( "flag" + "fmt" "net/http" "os" "time" - "github.com/cilindrox/probe-controller/controllers" "k8s.io/apimachinery/pkg/runtime" utilruntime "k8s.io/apimachinery/pkg/util/runtime" clientgoscheme "k8s.io/client-go/kubernetes/scheme" @@ -15,11 +15,14 @@ import ( "sigs.k8s.io/controller-runtime/pkg/log/zap" metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server" gatewayv1 "sigs.k8s.io/gateway-api/apis/v1" + + "github.com/cilindrox/probe-controller/controllers" ) var ( scheme = runtime.NewScheme() setupLog = ctrl.Log.WithName("setup") + version = "dev" ) // Register k8s types and Gateway API v1 @@ -33,16 +36,22 @@ func main() { var metricsAddr string var probeAddr string var enableLeaderElection bool + var showVersion bool flag.StringVar(&apiURL, "api-url", "", "External API URL.") - flag.StringVar(&metricsAddr, "metrics-bind-address", ":8080", "The adress the metric endpoint binds to.") + 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.") + flag.BoolVar(&showVersion, "version", false, "Print version and exit.") flag.Parse() - apiToken := os.Getenv("EXTERNAL_API_TOKEN") + if showVersion { + _, _ = fmt.Fprintln(os.Stdout, version) + os.Exit(0) + } ctrl.SetLogger(zap.New(zap.UseDevMode(true))) + setupLog.Info("initializing the controller", "version", version) mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{ Scheme: scheme, @@ -56,6 +65,7 @@ func main() { os.Exit(1) } + apiToken := os.Getenv("EXTERNAL_API_TOKEN") // Register the HTTPRouteWatcher reconciler if err = (&controllers.HTTPRouteWatcher{ Client: mgr.GetClient(),