From 357829f9391537e5d13ccdc5b5837b0b812d42e3 Mon Sep 17 00:00:00 2001 From: "Cody W. Eilar" Date: Fri, 10 Mar 2023 09:47:23 -0800 Subject: [PATCH] Add to ability to start controller with config file Signed-off-by: Cody W. Eilar --- LICENSES | 248 ------------ cmd/controller/app/controller.go | 31 +- cmd/controller/app/options/globalflags.go | 36 ++ cmd/controller/app/options/options.go | 377 ++++-------------- cmd/controller/app/options/options_test.go | 14 +- cmd/controller/app/start.go | 210 +++++++--- cmd/controller/main.go | 2 +- cmd/webhook/app/webhook.go | 19 +- go.mod | 1 + go.sum | 4 + hack/k8s-codegen.sh | 4 + internal/apis/config/controller/doc.go | 21 + .../apis/config/controller/fuzzer/fuzzer.go | 88 ++++ .../apis/config/controller/install/install.go | 33 ++ .../controller/install/roundtrip_test.go | 29 ++ internal/apis/config/controller/register.go | 46 +++ .../apis/config/controller/scheme/scheme.go | 40 ++ internal/apis/config/controller/types.go | 201 ++++++++++ .../config/controller/v1alpha1/conversion.go | 17 + .../config/controller/v1alpha1/defaults.go | 300 ++++++++++++++ .../apis/config/controller/v1alpha1/doc.go | 23 ++ .../config/controller/v1alpha1/register.go | 44 ++ .../v1alpha1/zz_generated.conversion.go | 140 +++++++ .../v1alpha1/zz_generated.defaults.go | 41 ++ .../controller/validation/validation.go | 70 ++++ .../controller/zz_generated.deepcopy.go | 133 ++++++ pkg/apis/config/controller/doc.go | 22 + pkg/apis/config/controller/v1alpha1/doc.go | 20 + .../config/controller/v1alpha1/register.go | 56 +++ pkg/apis/config/controller/v1alpha1/types.go | 196 +++++++++ .../v1alpha1/zz_generated.deepcopy.go | 133 ++++++ pkg/controller/configfile/configfile.go | 39 ++ pkg/util/configfile/configfile.go | 106 +++++ .../configfile/configfile_test.go | 34 +- pkg/webhook/configfile/configfile.go | 105 +---- 35 files changed, 2154 insertions(+), 729 deletions(-) delete mode 100644 LICENSES create mode 100644 cmd/controller/app/options/globalflags.go create mode 100644 internal/apis/config/controller/doc.go create mode 100644 internal/apis/config/controller/fuzzer/fuzzer.go create mode 100644 internal/apis/config/controller/install/install.go create mode 100644 internal/apis/config/controller/install/roundtrip_test.go create mode 100644 internal/apis/config/controller/register.go create mode 100644 internal/apis/config/controller/scheme/scheme.go create mode 100644 internal/apis/config/controller/types.go create mode 100644 internal/apis/config/controller/v1alpha1/conversion.go create mode 100644 internal/apis/config/controller/v1alpha1/defaults.go create mode 100644 internal/apis/config/controller/v1alpha1/doc.go create mode 100644 internal/apis/config/controller/v1alpha1/register.go create mode 100644 internal/apis/config/controller/v1alpha1/zz_generated.conversion.go create mode 100644 internal/apis/config/controller/v1alpha1/zz_generated.defaults.go create mode 100644 internal/apis/config/controller/validation/validation.go create mode 100644 internal/apis/config/controller/zz_generated.deepcopy.go create mode 100644 pkg/apis/config/controller/doc.go create mode 100644 pkg/apis/config/controller/v1alpha1/doc.go create mode 100644 pkg/apis/config/controller/v1alpha1/register.go create mode 100644 pkg/apis/config/controller/v1alpha1/types.go create mode 100644 pkg/apis/config/controller/v1alpha1/zz_generated.deepcopy.go create mode 100644 pkg/controller/configfile/configfile.go create mode 100644 pkg/util/configfile/configfile.go rename pkg/{webhook => util}/configfile/configfile_test.go (67%) diff --git a/LICENSES b/LICENSES deleted file mode 100644 index ffab14a768c..00000000000 --- a/LICENSES +++ /dev/null @@ -1,248 +0,0 @@ -cloud.google.com/go/compute/metadata,https://github.com/googleapis/google-cloud-go/blob/compute/metadata/v0.2.3/compute/metadata/LICENSE,Apache-2.0 -github.com/Azure/azure-sdk-for-go,https://github.com/Azure/azure-sdk-for-go/blob/v67.3.0/LICENSE.txt,MIT -github.com/Azure/go-autorest/autorest,https://github.com/Azure/go-autorest/blob/autorest/v0.11.28/autorest/LICENSE,Apache-2.0 -github.com/Azure/go-autorest/autorest/adal,https://github.com/Azure/go-autorest/blob/autorest/adal/v0.9.21/autorest/adal/LICENSE,Apache-2.0 -github.com/Azure/go-autorest/autorest/date,https://github.com/Azure/go-autorest/blob/autorest/date/v0.3.0/autorest/date/LICENSE,Apache-2.0 -github.com/Azure/go-autorest/autorest/to,https://github.com/Azure/go-autorest/blob/autorest/to/v0.4.0/autorest/to/LICENSE,Apache-2.0 -github.com/Azure/go-autorest/autorest/validation,https://github.com/Azure/go-autorest/blob/autorest/validation/v0.3.1/autorest/validation/LICENSE,Apache-2.0 -github.com/Azure/go-autorest/logger,https://github.com/Azure/go-autorest/blob/logger/v0.2.1/logger/LICENSE,Apache-2.0 -github.com/Azure/go-autorest/tracing,https://github.com/Azure/go-autorest/blob/tracing/v0.6.0/tracing/LICENSE,Apache-2.0 -github.com/Azure/go-ntlmssp,https://github.com/Azure/go-ntlmssp/blob/cb9428e4ac1e/LICENSE,MIT -github.com/BurntSushi/toml,https://github.com/BurntSushi/toml/blob/v1.2.1/COPYING,MIT -github.com/MakeNowJust/heredoc,https://github.com/MakeNowJust/heredoc/blob/v1.0.0/LICENSE,MIT -github.com/Masterminds/goutils,https://github.com/Masterminds/goutils/blob/v1.1.1/LICENSE.txt,Apache-2.0 -github.com/Masterminds/semver/v3,https://github.com/Masterminds/semver/blob/v3.2.0/LICENSE.txt,MIT -github.com/Masterminds/sprig/v3,https://github.com/Masterminds/sprig/blob/v3.2.3/LICENSE.txt,MIT -github.com/Masterminds/squirrel,https://github.com/Masterminds/squirrel/blob/v1.5.3/LICENSE.txt,MIT -github.com/NYTimes/gziphandler,https://github.com/NYTimes/gziphandler/blob/v1.1.1/LICENSE,Apache-2.0 -github.com/Venafi/vcert/v4,https://github.com/jetstack/vcert/blob/3aa3dfd6613d/LICENSE,Apache-2.0 -github.com/akamai/AkamaiOPEN-edgegrid-golang,https://github.com/akamai/AkamaiOPEN-edgegrid-golang/blob/v1.2.2/LICENSE,Apache-2.0 -github.com/antlr/antlr4/runtime/Go/antlr,https://github.com/antlr/antlr4/blob/runtime/Go/antlr/v1.4.10/runtime/Go/antlr/LICENSE,BSD-3-Clause -github.com/armon/go-metrics,https://github.com/armon/go-metrics/blob/v0.3.9/LICENSE,MIT -github.com/armon/go-radix,https://github.com/armon/go-radix/blob/v1.0.0/LICENSE,MIT -github.com/asaskevich/govalidator,https://github.com/asaskevich/govalidator/blob/21a406dcc535/LICENSE,MIT -github.com/aws/aws-sdk-go,https://github.com/aws/aws-sdk-go/blob/v1.44.179/LICENSE.txt,Apache-2.0 -github.com/aws/aws-sdk-go/internal/sync/singleflight,https://github.com/aws/aws-sdk-go/blob/v1.44.179/internal/sync/singleflight/LICENSE,BSD-3-Clause -github.com/beorn7/perks/quantile,https://github.com/beorn7/perks/blob/v1.0.1/LICENSE,MIT -github.com/blang/semver/v4,https://github.com/blang/semver/blob/v4.0.0/v4/LICENSE,MIT -github.com/cenkalti/backoff/v3,https://github.com/cenkalti/backoff/blob/v3.0.0/LICENSE,MIT -github.com/cenkalti/backoff/v4,https://github.com/cenkalti/backoff/blob/v4.1.3/LICENSE,MIT -github.com/cert-manager/cert-manager,https://github.com/cert-manager/cert-manager/blob/HEAD/LICENSE,Apache-2.0 -github.com/cert-manager/cert-manager/pkg/issuer/acme/dns/azuredns,https://github.com/cert-manager/cert-manager/blob/HEAD/pkg/issuer/acme/dns/azuredns/LICENSE,MIT -github.com/cert-manager/cert-manager/pkg/issuer/acme/dns/clouddns,https://github.com/cert-manager/cert-manager/blob/HEAD/pkg/issuer/acme/dns/clouddns/LICENSE,MIT -github.com/cert-manager/cert-manager/pkg/issuer/acme/dns/cloudflare,https://github.com/cert-manager/cert-manager/blob/HEAD/pkg/issuer/acme/dns/cloudflare/LICENSE,MIT -github.com/cert-manager/cert-manager/pkg/issuer/acme/dns/route53,https://github.com/cert-manager/cert-manager/blob/HEAD/pkg/issuer/acme/dns/route53/LICENSE,MIT -github.com/cert-manager/cert-manager/pkg/issuer/acme/dns/util,https://github.com/cert-manager/cert-manager/blob/HEAD/pkg/issuer/acme/dns/util/LICENSE,MIT -github.com/cespare/xxhash/v2,https://github.com/cespare/xxhash/blob/v2.2.0/LICENSE.txt,MIT -github.com/chai2010/gettext-go,https://github.com/chai2010/gettext-go/blob/v1.0.2/LICENSE,BSD-3-Clause -github.com/cloudflare/cloudflare-go,https://github.com/cloudflare/cloudflare-go/blob/v0.58.1/LICENSE,BSD-3-Clause -github.com/containerd/containerd,https://github.com/containerd/containerd/blob/v1.6.18/LICENSE,Apache-2.0 -github.com/coreos/go-semver/semver,https://github.com/coreos/go-semver/blob/v0.3.0/LICENSE,Apache-2.0 -github.com/coreos/go-systemd/v22,https://github.com/coreos/go-systemd/blob/v22.3.2/LICENSE,Apache-2.0 -github.com/cpu/goacmedns,https://github.com/cpu/goacmedns/blob/v0.1.1/LICENSE,MIT -github.com/cyphar/filepath-securejoin,https://github.com/cyphar/filepath-securejoin/blob/v0.2.3/LICENSE,BSD-3-Clause -github.com/davecgh/go-spew/spew,https://github.com/davecgh/go-spew/blob/v1.1.1/LICENSE,ISC -github.com/digitalocean/godo,https://github.com/digitalocean/godo/blob/v1.93.0/LICENSE.txt,MIT -github.com/docker/cli/cli/config,https://github.com/docker/cli/blob/v20.10.21/LICENSE,Apache-2.0 -github.com/docker/distribution,https://github.com/docker/distribution/blob/v2.8.1/LICENSE,Apache-2.0 -github.com/docker/docker,https://github.com/docker/docker/blob/v20.10.21/LICENSE,Apache-2.0 -github.com/docker/docker-credential-helpers,https://github.com/docker/docker-credential-helpers/blob/v0.7.0/LICENSE,MIT -github.com/docker/go-connections,https://github.com/docker/go-connections/blob/v0.4.0/LICENSE,Apache-2.0 -github.com/docker/go-metrics,https://github.com/docker/go-metrics/blob/v0.0.1/LICENSE,Apache-2.0 -github.com/docker/go-units,https://github.com/docker/go-units/blob/v0.4.0/LICENSE,Apache-2.0 -github.com/emicklei/go-restful/v3,https://github.com/emicklei/go-restful/blob/v3.9.0/LICENSE,MIT -github.com/evanphx/json-patch,https://github.com/evanphx/json-patch/blob/v5.6.0/LICENSE,BSD-3-Clause -github.com/evanphx/json-patch/v5,https://github.com/evanphx/json-patch/blob/v5.6.0/v5/LICENSE,BSD-3-Clause -github.com/exponent-io/jsonpath,https://github.com/exponent-io/jsonpath/blob/d6023ce2651d/LICENSE,MIT -github.com/fatih/camelcase,https://github.com/fatih/camelcase/blob/v1.0.0/LICENSE.md,MIT -github.com/fatih/color,https://github.com/fatih/color/blob/v1.13.0/LICENSE.md,MIT -github.com/felixge/httpsnoop,https://github.com/felixge/httpsnoop/blob/v1.0.3/LICENSE.txt,MIT -github.com/fsnotify/fsnotify,https://github.com/fsnotify/fsnotify/blob/v1.6.0/LICENSE,BSD-3-Clause -github.com/go-asn1-ber/asn1-ber,https://github.com/go-asn1-ber/asn1-ber/blob/v1.5.4/LICENSE,MIT -github.com/go-errors/errors,https://github.com/go-errors/errors/blob/v1.0.1/LICENSE.MIT,MIT -github.com/go-gorp/gorp/v3,https://github.com/go-gorp/gorp/blob/v3.0.2/LICENSE,MIT -github.com/go-ldap/ldap/v3,https://github.com/go-ldap/ldap/blob/v3.4.4/v3/LICENSE,MIT -github.com/go-logr/logr,https://github.com/go-logr/logr/blob/v1.2.3/LICENSE,Apache-2.0 -github.com/go-logr/stdr,https://github.com/go-logr/stdr/blob/v1.2.2/LICENSE,Apache-2.0 -github.com/go-openapi/jsonpointer,https://github.com/go-openapi/jsonpointer/blob/v0.19.6/LICENSE,Apache-2.0 -github.com/go-openapi/jsonreference,https://github.com/go-openapi/jsonreference/blob/v0.20.1/LICENSE,Apache-2.0 -github.com/go-openapi/swag,https://github.com/go-openapi/swag/blob/v0.22.3/LICENSE,Apache-2.0 -github.com/gobwas/glob,https://github.com/gobwas/glob/blob/v0.2.3/LICENSE,MIT -github.com/gogo/protobuf,https://github.com/gogo/protobuf/blob/v1.3.2/LICENSE,BSD-3-Clause -github.com/golang-jwt/jwt/v4,https://github.com/golang-jwt/jwt/blob/v4.2.0/LICENSE,MIT -github.com/golang/groupcache/lru,https://github.com/golang/groupcache/blob/41bb18bfe9da/LICENSE,Apache-2.0 -github.com/golang/protobuf,https://github.com/golang/protobuf/blob/v1.5.2/LICENSE,BSD-3-Clause -github.com/golang/snappy,https://github.com/golang/snappy/blob/v0.0.4/LICENSE,BSD-3-Clause -github.com/google/btree,https://github.com/google/btree/blob/v1.0.1/LICENSE,Apache-2.0 -github.com/google/cel-go,https://github.com/google/cel-go/blob/v0.12.5/LICENSE,Apache-2.0 -github.com/google/gnostic,https://github.com/google/gnostic/blob/v0.6.9/LICENSE,Apache-2.0 -github.com/google/go-cmp/cmp,https://github.com/google/go-cmp/blob/v0.5.9/LICENSE,BSD-3-Clause -github.com/google/go-querystring/query,https://github.com/google/go-querystring/blob/v1.1.0/LICENSE,BSD-3-Clause -github.com/google/gofuzz,https://github.com/google/gofuzz/blob/v1.2.0/LICENSE,Apache-2.0 -github.com/google/shlex,https://github.com/google/shlex/blob/e7afc7fbc510/COPYING,Apache-2.0 -github.com/google/uuid,https://github.com/google/uuid/blob/v1.3.0/LICENSE,BSD-3-Clause -github.com/googleapis/enterprise-certificate-proxy/client,https://github.com/googleapis/enterprise-certificate-proxy/blob/v0.2.1/LICENSE,Apache-2.0 -github.com/googleapis/gax-go/v2,https://github.com/googleapis/gax-go/blob/v2.7.0/v2/LICENSE,BSD-3-Clause -github.com/gorilla/mux,https://github.com/gorilla/mux/blob/v1.8.0/LICENSE,BSD-3-Clause -github.com/gosuri/uitable,https://github.com/gosuri/uitable/blob/v0.0.4/LICENSE,MIT -github.com/gosuri/uitable/util/wordwrap,https://github.com/gosuri/uitable/blob/v0.0.4/util/wordwrap/LICENSE.md,MIT -github.com/gregjones/httpcache,https://github.com/gregjones/httpcache/blob/9cad4c3443a7/LICENSE.txt,MIT -github.com/grpc-ecosystem/go-grpc-prometheus,https://github.com/grpc-ecosystem/go-grpc-prometheus/blob/v1.2.0/LICENSE,Apache-2.0 -github.com/grpc-ecosystem/grpc-gateway/v2,https://github.com/grpc-ecosystem/grpc-gateway/blob/v2.7.0/LICENSE.txt,BSD-3-Clause -github.com/hashicorp/errwrap,https://github.com/hashicorp/errwrap/blob/v1.1.0/LICENSE,MPL-2.0 -github.com/hashicorp/go-cleanhttp,https://github.com/hashicorp/go-cleanhttp/blob/v0.5.2/LICENSE,MPL-2.0 -github.com/hashicorp/go-hclog,https://github.com/hashicorp/go-hclog/blob/v1.2.0/LICENSE,MIT -github.com/hashicorp/go-immutable-radix,https://github.com/hashicorp/go-immutable-radix/blob/v1.3.1/LICENSE,MPL-2.0 -github.com/hashicorp/go-multierror,https://github.com/hashicorp/go-multierror/blob/v1.1.1/LICENSE,MPL-2.0 -github.com/hashicorp/go-plugin,https://github.com/hashicorp/go-plugin/blob/v1.4.5/LICENSE,MPL-2.0 -github.com/hashicorp/go-retryablehttp,https://github.com/hashicorp/go-retryablehttp/blob/v0.7.2/LICENSE,MPL-2.0 -github.com/hashicorp/go-rootcerts,https://github.com/hashicorp/go-rootcerts/blob/v1.0.2/LICENSE,MPL-2.0 -github.com/hashicorp/go-secure-stdlib/mlock,https://github.com/hashicorp/go-secure-stdlib/blob/mlock/v0.1.1/mlock/LICENSE,MPL-2.0 -github.com/hashicorp/go-secure-stdlib/parseutil,https://github.com/hashicorp/go-secure-stdlib/blob/parseutil/v0.1.6/parseutil/LICENSE,MPL-2.0 -github.com/hashicorp/go-secure-stdlib/strutil,https://github.com/hashicorp/go-secure-stdlib/blob/strutil/v0.1.2/strutil/LICENSE,MPL-2.0 -github.com/hashicorp/go-sockaddr,https://github.com/hashicorp/go-sockaddr/blob/v1.0.2/LICENSE,MPL-2.0 -github.com/hashicorp/go-uuid,https://github.com/hashicorp/go-uuid/blob/v1.0.2/LICENSE,MPL-2.0 -github.com/hashicorp/go-version,https://github.com/hashicorp/go-version/blob/v1.2.0/LICENSE,MPL-2.0 -github.com/hashicorp/golang-lru,https://github.com/hashicorp/golang-lru/blob/v0.5.4/LICENSE,MPL-2.0 -github.com/hashicorp/hcl,https://github.com/hashicorp/hcl/blob/v1.0.0/LICENSE,MPL-2.0 -github.com/hashicorp/vault/api,https://github.com/hashicorp/vault/blob/api/v1.8.2/api/LICENSE,MPL-2.0 -github.com/hashicorp/vault/sdk,https://github.com/hashicorp/vault/blob/sdk/v0.6.2/sdk/LICENSE,MPL-2.0 -github.com/hashicorp/yamux,https://github.com/hashicorp/yamux/blob/3520598351bb/LICENSE,MPL-2.0 -github.com/huandu/xstrings,https://github.com/huandu/xstrings/blob/v1.3.3/LICENSE,MIT -github.com/imdario/mergo,https://github.com/imdario/mergo/blob/v0.3.12/LICENSE,BSD-3-Clause -github.com/jmespath/go-jmespath,https://github.com/jmespath/go-jmespath/blob/v0.4.0/LICENSE,Apache-2.0 -github.com/jmoiron/sqlx,https://github.com/jmoiron/sqlx/blob/v1.3.5/LICENSE,MIT -github.com/josharian/intern,https://github.com/josharian/intern/blob/v1.0.0/license.md,MIT -github.com/json-iterator/go,https://github.com/json-iterator/go/blob/v1.1.12/LICENSE,MIT -github.com/klauspost/compress,https://github.com/klauspost/compress/blob/v1.15.15/LICENSE,Apache-2.0 -github.com/klauspost/compress/internal/snapref,https://github.com/klauspost/compress/blob/v1.15.15/internal/snapref/LICENSE,BSD-3-Clause -github.com/klauspost/compress/zstd/internal/xxhash,https://github.com/klauspost/compress/blob/v1.15.15/zstd/internal/xxhash/LICENSE.txt,MIT -github.com/kr/pretty,https://github.com/kr/pretty/blob/v0.3.1/License,MIT -github.com/kr/text,https://github.com/kr/text/blob/v0.2.0/License,MIT -github.com/lann/builder,https://github.com/lann/builder/blob/47ae307949d0/LICENSE,MIT -github.com/lann/ps,https://github.com/lann/ps/blob/62de8c46ede0/LICENSE,MIT -github.com/lib/pq,https://github.com/lib/pq/blob/v1.10.7/LICENSE.md,MIT -github.com/liggitt/tabwriter,https://github.com/liggitt/tabwriter/blob/89fcab3d43de/LICENSE,BSD-3-Clause -github.com/mailru/easyjson,https://github.com/mailru/easyjson/blob/v0.7.7/LICENSE,MIT -github.com/mattn/go-colorable,https://github.com/mattn/go-colorable/blob/v0.1.12/LICENSE,MIT -github.com/mattn/go-isatty,https://github.com/mattn/go-isatty/blob/v0.0.14/LICENSE,MIT -github.com/mattn/go-runewidth,https://github.com/mattn/go-runewidth/blob/v0.0.13/LICENSE,MIT -github.com/matttproud/golang_protobuf_extensions/pbutil,https://github.com/matttproud/golang_protobuf_extensions/blob/v1.0.4/LICENSE,Apache-2.0 -github.com/miekg/dns,https://github.com/miekg/dns/blob/v1.1.50/LICENSE,BSD-3-Clause -github.com/mitchellh/copystructure,https://github.com/mitchellh/copystructure/blob/v1.2.0/LICENSE,MIT -github.com/mitchellh/go-homedir,https://github.com/mitchellh/go-homedir/blob/v1.1.0/LICENSE,MIT -github.com/mitchellh/go-testing-interface,https://github.com/mitchellh/go-testing-interface/blob/v1.0.0/LICENSE,MIT -github.com/mitchellh/go-wordwrap,https://github.com/mitchellh/go-wordwrap/blob/v1.0.0/LICENSE.md,MIT -github.com/mitchellh/mapstructure,https://github.com/mitchellh/mapstructure/blob/v1.5.0/LICENSE,MIT -github.com/mitchellh/reflectwalk,https://github.com/mitchellh/reflectwalk/blob/v1.0.2/LICENSE,MIT -github.com/moby/locker,https://github.com/moby/locker/blob/v1.0.1/LICENSE,Apache-2.0 -github.com/moby/spdystream,https://github.com/moby/spdystream/blob/v0.2.0/LICENSE,Apache-2.0 -github.com/moby/term,https://github.com/moby/term/blob/1aeaba878587/LICENSE,Apache-2.0 -github.com/modern-go/concurrent,https://github.com/modern-go/concurrent/blob/bacd9c7ef1dd/LICENSE,Apache-2.0 -github.com/modern-go/reflect2,https://github.com/modern-go/reflect2/blob/v1.0.2/LICENSE,Apache-2.0 -github.com/monochromegane/go-gitignore,https://github.com/monochromegane/go-gitignore/blob/205db1a8cc00/LICENSE,MIT -github.com/morikuni/aec,https://github.com/morikuni/aec/blob/v1.0.0/LICENSE,MIT -github.com/munnerz/goautoneg,https://github.com/munnerz/goautoneg/blob/a7dc8b61c822/LICENSE,BSD-3-Clause -github.com/oklog/run,https://github.com/oklog/run/blob/v1.0.0/LICENSE,Apache-2.0 -github.com/onsi/ginkgo/v2,https://github.com/onsi/ginkgo/blob/v2.7.0/LICENSE,MIT -github.com/onsi/gomega,https://github.com/onsi/gomega/blob/v1.24.2/LICENSE,MIT -github.com/opencontainers/go-digest,https://github.com/opencontainers/go-digest/blob/v1.0.0/LICENSE,Apache-2.0 -github.com/opencontainers/image-spec/specs-go,https://github.com/opencontainers/image-spec/blob/v1.1.0-rc2/LICENSE,Apache-2.0 -github.com/patrickmn/go-cache,https://github.com/patrickmn/go-cache/blob/v2.1.0/LICENSE,MIT -github.com/pavlo-v-chernykh/keystore-go/v4,https://github.com/pavlo-v-chernykh/keystore-go/blob/v4.4.1/LICENSE,MIT -github.com/peterbourgon/diskv,https://github.com/peterbourgon/diskv/blob/v2.0.1/LICENSE,MIT -github.com/pierrec/lz4,https://github.com/pierrec/lz4/blob/v2.5.2/LICENSE,BSD-3-Clause -github.com/pkg/errors,https://github.com/pkg/errors/blob/v0.9.1/LICENSE,BSD-2-Clause -github.com/prometheus/client_golang/prometheus,https://github.com/prometheus/client_golang/blob/v1.14.0/LICENSE,Apache-2.0 -github.com/prometheus/client_model/go,https://github.com/prometheus/client_model/blob/v0.3.0/LICENSE,Apache-2.0 -github.com/prometheus/common,https://github.com/prometheus/common/blob/v0.37.0/LICENSE,Apache-2.0 -github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg,https://github.com/prometheus/common/blob/v0.37.0/internal/bitbucket.org/ww/goautoneg/README.txt,BSD-3-Clause -github.com/prometheus/procfs,https://github.com/prometheus/procfs/blob/v0.8.0/LICENSE,Apache-2.0 -github.com/rivo/uniseg,https://github.com/rivo/uniseg/blob/v0.2.0/LICENSE.txt,MIT -github.com/rogpeppe/go-internal/fmtsort,https://github.com/rogpeppe/go-internal/blob/v1.9.0/LICENSE,BSD-3-Clause -github.com/rubenv/sql-migrate,https://github.com/rubenv/sql-migrate/blob/v1.2.0/LICENSE,MIT -github.com/rubenv/sql-migrate/sqlparse,https://github.com/rubenv/sql-migrate/blob/v1.2.0/sqlparse/LICENSE,MIT -github.com/russross/blackfriday/v2,https://github.com/russross/blackfriday/blob/v2.1.0/LICENSE.txt,BSD-2-Clause -github.com/ryanuber/go-glob,https://github.com/ryanuber/go-glob/blob/v1.0.0/LICENSE,MIT -github.com/sergi/go-diff/diffmatchpatch,https://github.com/sergi/go-diff/blob/v1.3.1/LICENSE,MIT -github.com/shopspring/decimal,https://github.com/shopspring/decimal/blob/v1.2.0/LICENSE,MIT -github.com/sirupsen/logrus,https://github.com/sirupsen/logrus/blob/v1.9.0/LICENSE,MIT -github.com/spf13/cast,https://github.com/spf13/cast/blob/v1.4.1/LICENSE,MIT -github.com/spf13/cobra,https://github.com/spf13/cobra/blob/v1.6.1/LICENSE.txt,Apache-2.0 -github.com/spf13/pflag,https://github.com/spf13/pflag/blob/v1.0.5/LICENSE,BSD-3-Clause -github.com/stoewer/go-strcase,https://github.com/stoewer/go-strcase/blob/v1.2.0/LICENSE,MIT -github.com/xeipuuv/gojsonpointer,https://github.com/xeipuuv/gojsonpointer/blob/4e3ac2762d5f/LICENSE-APACHE-2.0.txt,Apache-2.0 -github.com/xeipuuv/gojsonreference,https://github.com/xeipuuv/gojsonreference/blob/bd5ef7bd5415/LICENSE-APACHE-2.0.txt,Apache-2.0 -github.com/xeipuuv/gojsonschema,https://github.com/xeipuuv/gojsonschema/blob/v1.2.0/LICENSE-APACHE-2.0.txt,Apache-2.0 -github.com/xlab/treeprint,https://github.com/xlab/treeprint/blob/v1.1.0/LICENSE,MIT -github.com/youmark/pkcs8,https://github.com/youmark/pkcs8/blob/1326539a0a0a/LICENSE,MIT -go.etcd.io/etcd/api/v3,https://github.com/etcd-io/etcd/blob/api/v3.5.5/api/LICENSE,Apache-2.0 -go.etcd.io/etcd/client/pkg/v3,https://github.com/etcd-io/etcd/blob/client/pkg/v3.5.5/client/pkg/LICENSE,Apache-2.0 -go.etcd.io/etcd/client/v3,https://github.com/etcd-io/etcd/blob/client/v3.5.5/client/v3/LICENSE,Apache-2.0 -go.opencensus.io,https://github.com/census-instrumentation/opencensus-go/blob/v0.24.0/LICENSE,Apache-2.0 -go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc,https://github.com/open-telemetry/opentelemetry-go-contrib/blob/instrumentation/google.golang.org/grpc/otelgrpc/v0.35.0/instrumentation/google.golang.org/grpc/otelgrpc/LICENSE,Apache-2.0 -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp,https://github.com/open-telemetry/opentelemetry-go-contrib/blob/instrumentation/net/http/otelhttp/v0.35.0/instrumentation/net/http/otelhttp/LICENSE,Apache-2.0 -go.opentelemetry.io/otel,https://github.com/open-telemetry/opentelemetry-go/blob/v1.10.0/LICENSE,Apache-2.0 -go.opentelemetry.io/otel/exporters/otlp/internal/retry,https://github.com/open-telemetry/opentelemetry-go/blob/exporters/otlp/internal/retry/v1.10.0/exporters/otlp/internal/retry/LICENSE,Apache-2.0 -go.opentelemetry.io/otel/exporters/otlp/otlptrace,https://github.com/open-telemetry/opentelemetry-go/blob/exporters/otlp/otlptrace/v1.10.0/exporters/otlp/otlptrace/LICENSE,Apache-2.0 -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc,https://github.com/open-telemetry/opentelemetry-go/blob/exporters/otlp/otlptrace/otlptracegrpc/v1.10.0/exporters/otlp/otlptrace/otlptracegrpc/LICENSE,Apache-2.0 -go.opentelemetry.io/otel/metric,https://github.com/open-telemetry/opentelemetry-go/blob/metric/v0.31.0/metric/LICENSE,Apache-2.0 -go.opentelemetry.io/otel/sdk,https://github.com/open-telemetry/opentelemetry-go/blob/sdk/v1.10.0/sdk/LICENSE,Apache-2.0 -go.opentelemetry.io/otel/trace,https://github.com/open-telemetry/opentelemetry-go/blob/trace/v1.10.0/trace/LICENSE,Apache-2.0 -go.opentelemetry.io/proto/otlp,https://github.com/open-telemetry/opentelemetry-proto-go/blob/otlp/v0.19.0/otlp/LICENSE,Apache-2.0 -go.starlark.net,https://github.com/google/starlark-go/blob/8dd3e2ee1dd5/LICENSE,BSD-3-Clause -go.uber.org/atomic,https://github.com/uber-go/atomic/blob/v1.9.0/LICENSE.txt,MIT -go.uber.org/multierr,https://github.com/uber-go/multierr/blob/v1.6.0/LICENSE.txt,MIT -go.uber.org/zap,https://github.com/uber-go/zap/blob/v1.24.0/LICENSE.txt,MIT -golang.org/x/crypto,https://cs.opensource.google/go/x/crypto/+/v0.5.0:LICENSE,BSD-3-Clause -golang.org/x/net,https://cs.opensource.google/go/x/net/+/v0.7.0:LICENSE,BSD-3-Clause -golang.org/x/oauth2,https://cs.opensource.google/go/x/oauth2/+/v0.4.0:LICENSE,BSD-3-Clause -golang.org/x/sync,https://cs.opensource.google/go/x/sync/+/v0.1.0:LICENSE,BSD-3-Clause -golang.org/x/sys,https://cs.opensource.google/go/x/sys/+/v0.5.0:LICENSE,BSD-3-Clause -golang.org/x/term,https://cs.opensource.google/go/x/term/+/v0.5.0:LICENSE,BSD-3-Clause -golang.org/x/text,https://cs.opensource.google/go/x/text/+/v0.7.0:LICENSE,BSD-3-Clause -golang.org/x/time/rate,https://cs.opensource.google/go/x/time/+/v0.3.0:LICENSE,BSD-3-Clause -gomodules.xyz/jsonpatch/v2,https://github.com/gomodules/jsonpatch/blob/v2.2.0/v2/LICENSE,Apache-2.0 -google.golang.org/api,https://github.com/googleapis/google-api-go-client/blob/v0.108.0/LICENSE,BSD-3-Clause -google.golang.org/api/internal/third_party/uritemplates,https://github.com/googleapis/google-api-go-client/blob/v0.108.0/internal/third_party/uritemplates/LICENSE,BSD-3-Clause -google.golang.org/genproto,https://github.com/googleapis/go-genproto/blob/c8e22ba71e44/LICENSE,Apache-2.0 -google.golang.org/grpc,https://github.com/grpc/grpc-go/blob/v1.53.0/LICENSE,Apache-2.0 -google.golang.org/protobuf,https://github.com/protocolbuffers/protobuf-go/blob/v1.28.1/LICENSE,BSD-3-Clause -gopkg.in/inf.v0,https://github.com/go-inf/inf/blob/v0.9.1/LICENSE,BSD-3-Clause -gopkg.in/ini.v1,https://github.com/go-ini/ini/blob/v1.62.0/LICENSE,Apache-2.0 -gopkg.in/natefinch/lumberjack.v2,https://github.com/natefinch/lumberjack/blob/v2.0.0/LICENSE,MIT -gopkg.in/square/go-jose.v2,https://github.com/square/go-jose/blob/v2.5.1/LICENSE,Apache-2.0 -gopkg.in/square/go-jose.v2/json,https://github.com/square/go-jose/blob/v2.5.1/json/LICENSE,BSD-3-Clause -gopkg.in/yaml.v2,https://github.com/go-yaml/yaml/blob/v2.4.0/LICENSE,Apache-2.0 -gopkg.in/yaml.v3,https://github.com/go-yaml/yaml/blob/v3.0.1/LICENSE,MIT -helm.sh/helm/v3,https://github.com/helm/helm/blob/v3.11.1/LICENSE,Apache-2.0 -k8s.io/api,https://github.com/kubernetes/api/blob/v0.26.0/LICENSE,Apache-2.0 -k8s.io/apiextensions-apiserver/pkg,https://github.com/kubernetes/apiextensions-apiserver/blob/v0.26.0/LICENSE,Apache-2.0 -k8s.io/apimachinery/pkg,https://github.com/kubernetes/apimachinery/blob/v0.26.0/LICENSE,Apache-2.0 -k8s.io/apimachinery/third_party/forked/golang,https://github.com/kubernetes/apimachinery/blob/v0.26.0/third_party/forked/golang/LICENSE,BSD-3-Clause -k8s.io/apiserver,https://github.com/kubernetes/apiserver/blob/v0.26.0/LICENSE,Apache-2.0 -k8s.io/cli-runtime/pkg,https://github.com/kubernetes/cli-runtime/blob/v0.26.0/LICENSE,Apache-2.0 -k8s.io/client-go,https://github.com/kubernetes/client-go/blob/v0.26.0/LICENSE,Apache-2.0 -k8s.io/client-go/third_party/forked/golang/template,https://github.com/kubernetes/client-go/blob/v0.26.0/third_party/forked/golang/LICENSE,BSD-3-Clause -k8s.io/component-base,https://github.com/kubernetes/component-base/blob/v0.26.0/LICENSE,Apache-2.0 -k8s.io/klog/v2,https://github.com/kubernetes/klog/blob/v2.80.1/LICENSE,Apache-2.0 -k8s.io/kms/apis,https://github.com/kubernetes/kms/blob/v0.26.0/LICENSE,Apache-2.0 -k8s.io/kube-aggregator/pkg/apis/apiregistration,https://github.com/kubernetes/kube-aggregator/blob/v0.26.0/LICENSE,Apache-2.0 -k8s.io/kube-openapi/pkg,https://github.com/kubernetes/kube-openapi/blob/3758b55a6596/LICENSE,Apache-2.0 -k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json,https://github.com/kubernetes/kube-openapi/blob/3758b55a6596/pkg/internal/third_party/go-json-experiment/json/LICENSE,BSD-3-Clause -k8s.io/kube-openapi/pkg/validation/spec,https://github.com/kubernetes/kube-openapi/blob/3758b55a6596/pkg/validation/spec/LICENSE,Apache-2.0 -k8s.io/kubectl/pkg,https://github.com/kubernetes/kubectl/blob/v0.26.0/LICENSE,Apache-2.0 -k8s.io/utils,https://github.com/kubernetes/utils/blob/99ec85e7a448/LICENSE,Apache-2.0 -k8s.io/utils/internal/third_party/forked/golang,https://github.com/kubernetes/utils/blob/99ec85e7a448/internal/third_party/forked/golang/LICENSE,BSD-3-Clause -oras.land/oras-go/pkg,https://github.com/oras-project/oras-go/blob/v1.2.2/LICENSE,Apache-2.0 -sigs.k8s.io/apiserver-network-proxy/konnectivity-client,https://github.com/kubernetes-sigs/apiserver-network-proxy/blob/konnectivity-client/v0.0.33/konnectivity-client/LICENSE,Apache-2.0 -sigs.k8s.io/controller-runtime,https://github.com/kubernetes-sigs/controller-runtime/blob/v0.14.1/LICENSE,Apache-2.0 -sigs.k8s.io/gateway-api,https://github.com/kubernetes-sigs/gateway-api/blob/v0.6.0/LICENSE,Apache-2.0 -sigs.k8s.io/json,https://github.com/kubernetes-sigs/json/blob/f223a00ba0e2/LICENSE,Apache-2.0 -sigs.k8s.io/kustomize/api,https://github.com/kubernetes-sigs/kustomize/blob/api/v0.12.1/api/LICENSE,Apache-2.0 -sigs.k8s.io/kustomize/kyaml,https://github.com/kubernetes-sigs/kustomize/blob/kyaml/v0.13.9/kyaml/LICENSE,Apache-2.0 -sigs.k8s.io/kustomize/kyaml/internal/forked/github.com/go-yaml/yaml,https://github.com/kubernetes-sigs/kustomize/blob/kyaml/v0.13.9/kyaml/internal/forked/github.com/go-yaml/yaml/LICENSE,MIT -sigs.k8s.io/kustomize/kyaml/internal/forked/github.com/qri-io/starlib/util,https://github.com/kubernetes-sigs/kustomize/blob/kyaml/v0.13.9/kyaml/internal/forked/github.com/qri-io/starlib/util/LICENSE,MIT -sigs.k8s.io/structured-merge-diff/v4,https://github.com/kubernetes-sigs/structured-merge-diff/blob/v4.2.3/LICENSE,Apache-2.0 -sigs.k8s.io/yaml,https://github.com/kubernetes-sigs/yaml/blob/v1.3.0/LICENSE,MIT -software.sslmate.com/src/go-pkcs12,https://github.com/SSLMate/go-pkcs12/blob/v0.2.0/LICENSE,BSD-3-Clause diff --git a/cmd/controller/app/controller.go b/cmd/controller/app/controller.go index 61c006513ed..7de814a123a 100644 --- a/cmd/controller/app/controller.go +++ b/cmd/controller/app/controller.go @@ -35,6 +35,7 @@ import ( "k8s.io/utils/clock" "github.com/cert-manager/cert-manager/cmd/controller/app/options" + config "github.com/cert-manager/cert-manager/internal/apis/config/controller" cmdutil "github.com/cert-manager/cert-manager/internal/cmd/util" "github.com/cert-manager/cert-manager/internal/controller/feature" "github.com/cert-manager/cert-manager/pkg/acme/accounts" @@ -47,7 +48,7 @@ import ( "github.com/cert-manager/cert-manager/pkg/util/profiling" ) -func Run(opts *options.ControllerOptions, stopCh <-chan struct{}) error { +func Run(opts *config.ControllerConfiguration, stopCh <-chan struct{}) error { rootCtx, cancelContext := context.WithCancel(cmdutil.ContextWithStopCh(context.Background(), stopCh)) defer cancelContext() rootCtx = logf.NewContext(rootCtx, logf.Log, "controller") @@ -66,7 +67,7 @@ func Run(opts *options.ControllerOptions, stopCh <-chan struct{}) error { return err } - enabledControllers := opts.EnabledControllers() + enabledControllers := options.EnabledControllers(opts) log.Info(fmt.Sprintf("enabled controllers: %s", enabledControllers.List())) // Start metrics server @@ -96,7 +97,7 @@ func Run(opts *options.ControllerOptions, stopCh <-chan struct{}) error { }) // Start profiler if it is enabled - if opts.EnablePprof { + if *opts.EnablePprof { profilerLn, err := net.Listen("tcp", opts.PprofAddress) if err != nil { return fmt.Errorf("failed to listen on profiler address %s: %v", opts.PprofAddress, err) @@ -129,7 +130,7 @@ func Run(opts *options.ControllerOptions, stopCh <-chan struct{}) error { } elected := make(chan struct{}) - if opts.LeaderElect { + if *opts.LeaderElect { g.Go(func() error { log.V(logf.InfoLevel).Info("starting leader election") ctx, err := ctxFactory.Build("leader-election") @@ -229,7 +230,7 @@ func Run(opts *options.ControllerOptions, stopCh <-chan struct{}) error { // buildControllerContextFactory builds a new controller ContextFactory which // can build controller contexts for each component. -func buildControllerContextFactory(ctx context.Context, opts *options.ControllerOptions) (*controller.ContextFactory, error) { +func buildControllerContextFactory(ctx context.Context, opts *config.ControllerConfiguration) (*controller.ContextFactory, error) { log := logf.FromContext(ctx) nameservers := opts.DNS01RecursiveNameservers @@ -261,13 +262,13 @@ func buildControllerContextFactory(ctx context.Context, opts *options.Controller return nil, fmt.Errorf("error parsing ACMEHTTP01SolverResourceLimitsMemory: %w", err) } - ACMEHTTP01SolverRunAsNonRoot := opts.ACMEHTTP01SolverRunAsNonRoot + ACMEHTTP01SolverRunAsNonRoot := *opts.ACMEHTTP01SolverRunAsNonRoot acmeAccountRegistry := accounts.NewDefaultRegistry() ctxFactory, err := controller.NewContextFactory(ctx, controller.ContextOptions{ - Kubeconfig: opts.Kubeconfig, - KubernetesAPIQPS: opts.KubernetesAPIQPS, - KubernetesAPIBurst: opts.KubernetesAPIBurst, + Kubeconfig: opts.KubeConfig, + KubernetesAPIQPS: *opts.KubernetesAPIQPS, + KubernetesAPIBurst: *opts.KubernetesAPIBurst, APIServerHost: opts.APIServerHost, Namespace: opts.Namespace, @@ -287,18 +288,18 @@ func buildControllerContextFactory(ctx context.Context, opts *options.Controller DNS01Nameservers: nameservers, DNS01CheckRetryPeriod: opts.DNS01CheckRetryPeriod, - DNS01CheckAuthoritative: !opts.DNS01RecursiveNameserversOnly, + DNS01CheckAuthoritative: !*opts.DNS01RecursiveNameserversOnly, AccountRegistry: acmeAccountRegistry, }, SchedulerOptions: controller.SchedulerOptions{ - MaxConcurrentChallenges: opts.MaxConcurrentChallenges, + MaxConcurrentChallenges: *opts.MaxConcurrentChallenges, }, IssuerOptions: controller.IssuerOptions{ - ClusterIssuerAmbientCredentials: opts.ClusterIssuerAmbientCredentials, - IssuerAmbientCredentials: opts.IssuerAmbientCredentials, + ClusterIssuerAmbientCredentials: *opts.ClusterIssuerAmbientCredentials, + IssuerAmbientCredentials: *opts.IssuerAmbientCredentials, ClusterResourceNamespace: opts.ClusterResourceNamespace, }, @@ -310,7 +311,7 @@ func buildControllerContextFactory(ctx context.Context, opts *options.Controller }, CertificateOptions: controller.CertificateOptions{ - EnableOwnerRef: opts.EnableCertificateOwnerRef, + EnableOwnerRef: *opts.EnableCertificateOwnerRef, CopiedAnnotationPrefixes: opts.CopiedAnnotationPrefixes, }, }) @@ -321,7 +322,7 @@ func buildControllerContextFactory(ctx context.Context, opts *options.Controller return ctxFactory, nil } -func startLeaderElection(ctx context.Context, opts *options.ControllerOptions, leaderElectionClient kubernetes.Interface, recorder record.EventRecorder, callbacks leaderelection.LeaderCallbacks) error { +func startLeaderElection(ctx context.Context, opts *config.ControllerConfiguration, leaderElectionClient kubernetes.Interface, recorder record.EventRecorder, callbacks leaderelection.LeaderCallbacks) error { // Identity used to distinguish between multiple controller manager instances id, err := os.Hostname() if err != nil { diff --git a/cmd/controller/app/options/globalflags.go b/cmd/controller/app/options/globalflags.go new file mode 100644 index 00000000000..5498e3b01aa --- /dev/null +++ b/cmd/controller/app/options/globalflags.go @@ -0,0 +1,36 @@ +/* +Copyright 2021 The cert-manager 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 options + +import ( + "flag" + "os" + + "github.com/spf13/pflag" + + "github.com/cert-manager/cert-manager/pkg/logs" +) + +func AddGlobalFlags(fs *pflag.FlagSet) { + addKlogFlags(fs) +} + +func addKlogFlags(fs *pflag.FlagSet) { + local := flag.NewFlagSet(os.Args[0], flag.ExitOnError) + logs.InitLogs(local) + fs.AddGoFlagSet(local) +} diff --git a/cmd/controller/app/options/options.go b/cmd/controller/app/options/options.go index 5606f8839a4..301c7fa866e 100644 --- a/cmd/controller/app/options/options.go +++ b/cmd/controller/app/options/options.go @@ -17,414 +17,185 @@ limitations under the License. package options import ( - "errors" "fmt" - "net" "strings" - "time" - "github.com/spf13/pflag" "k8s.io/apimachinery/pkg/util/sets" - cmdutil "github.com/cert-manager/cert-manager/internal/cmd/util" + "github.com/spf13/pflag" + + config "github.com/cert-manager/cert-manager/internal/apis/config/controller" + configscheme "github.com/cert-manager/cert-manager/internal/apis/config/controller/scheme" + defaults "github.com/cert-manager/cert-manager/internal/apis/config/controller/v1alpha1" "github.com/cert-manager/cert-manager/internal/controller/feature" - cm "github.com/cert-manager/cert-manager/pkg/apis/certmanager" - challengescontroller "github.com/cert-manager/cert-manager/pkg/controller/acmechallenges" - orderscontroller "github.com/cert-manager/cert-manager/pkg/controller/acmeorders" + configv1alpha1 "github.com/cert-manager/cert-manager/pkg/apis/config/controller/v1alpha1" shimgatewaycontroller "github.com/cert-manager/cert-manager/pkg/controller/certificate-shim/gateways" - shimingresscontroller "github.com/cert-manager/cert-manager/pkg/controller/certificate-shim/ingresses" - cracmecontroller "github.com/cert-manager/cert-manager/pkg/controller/certificaterequests/acme" - crapprovercontroller "github.com/cert-manager/cert-manager/pkg/controller/certificaterequests/approver" - crcacontroller "github.com/cert-manager/cert-manager/pkg/controller/certificaterequests/ca" - crselfsignedcontroller "github.com/cert-manager/cert-manager/pkg/controller/certificaterequests/selfsigned" - crvaultcontroller "github.com/cert-manager/cert-manager/pkg/controller/certificaterequests/vault" - crvenaficontroller "github.com/cert-manager/cert-manager/pkg/controller/certificaterequests/venafi" - "github.com/cert-manager/cert-manager/pkg/controller/certificates/issuing" - "github.com/cert-manager/cert-manager/pkg/controller/certificates/keymanager" - certificatesmetricscontroller "github.com/cert-manager/cert-manager/pkg/controller/certificates/metrics" - "github.com/cert-manager/cert-manager/pkg/controller/certificates/readiness" - "github.com/cert-manager/cert-manager/pkg/controller/certificates/requestmanager" - "github.com/cert-manager/cert-manager/pkg/controller/certificates/revisionmanager" - "github.com/cert-manager/cert-manager/pkg/controller/certificates/trigger" - csracmecontroller "github.com/cert-manager/cert-manager/pkg/controller/certificatesigningrequests/acme" - csrcacontroller "github.com/cert-manager/cert-manager/pkg/controller/certificatesigningrequests/ca" - csrselfsignedcontroller "github.com/cert-manager/cert-manager/pkg/controller/certificatesigningrequests/selfsigned" - csrvaultcontroller "github.com/cert-manager/cert-manager/pkg/controller/certificatesigningrequests/vault" - csrvenaficontroller "github.com/cert-manager/cert-manager/pkg/controller/certificatesigningrequests/venafi" - clusterissuerscontroller "github.com/cert-manager/cert-manager/pkg/controller/clusterissuers" - issuerscontroller "github.com/cert-manager/cert-manager/pkg/controller/issuers" + logf "github.com/cert-manager/cert-manager/pkg/logs" - "github.com/cert-manager/cert-manager/pkg/util" utilfeature "github.com/cert-manager/cert-manager/pkg/util/feature" ) -type ControllerOptions struct { - APIServerHost string - Kubeconfig string - KubernetesAPIQPS float32 - KubernetesAPIBurst int - - ClusterResourceNamespace string - Namespace string - - LeaderElect bool - LeaderElectionNamespace string - LeaderElectionLeaseDuration time.Duration - LeaderElectionRenewDeadline time.Duration - LeaderElectionRetryPeriod time.Duration - - controllers []string - - ACMEHTTP01SolverImage string - ACMEHTTP01SolverResourceRequestCPU string - ACMEHTTP01SolverResourceRequestMemory string - ACMEHTTP01SolverResourceLimitsCPU string - ACMEHTTP01SolverResourceLimitsMemory string - ACMEHTTP01SolverRunAsNonRoot bool - // Allows specifying a list of custom nameservers to perform HTTP01 checks on. - ACMEHTTP01SolverNameservers []string - - ClusterIssuerAmbientCredentials bool - IssuerAmbientCredentials bool - - // Default issuer/certificates details consumed by ingress-shim - DefaultIssuerName string - DefaultIssuerKind string - DefaultIssuerGroup string - DefaultAutoCertificateAnnotations []string - - // Allows specifying a list of custom nameservers to perform DNS checks on. - DNS01RecursiveNameservers []string - // Allows controlling if recursive nameservers are only used for all checks. - // Normally authoritative nameservers are used for checking propagation. - DNS01RecursiveNameserversOnly bool - - EnableCertificateOwnerRef bool - - MaxConcurrentChallenges int - - // The host and port address, separated by a ':', that the Prometheus server - // should expose metrics on. - MetricsListenAddress string - // PprofAddress is the address on which Go profiler will run. Should be - // in form :. - PprofAddress string - // EnablePprof determines whether pprof should be enabled. - EnablePprof bool - - // DNSO1CheckRetryPeriod is the period of time after which to check if - // challenge URL can be reached by cert-manager controller. This is used - // for both DNS-01 and HTTP-01 challenges. - DNS01CheckRetryPeriod time.Duration - - // Annotations copied Certificate -> CertificateRequest, - // CertificateRequest -> Order. Slice of string literals that are - // treated as prefixes for annotation keys. - CopiedAnnotationPrefixes []string +// ControllerFlags defines options that can only be configured via flags. +type ControllerFlags struct { + // Path to a file containing a ControllerConfiguration resource + Config string } -const ( - defaultAPIServerHost = "" - defaultKubeconfig = "" - defaultKubernetesAPIQPS float32 = 20 - defaultKubernetesAPIBurst = 50 - - defaultClusterResourceNamespace = "kube-system" - defaultNamespace = "" - - defaultClusterIssuerAmbientCredentials = true - defaultIssuerAmbientCredentials = false - - defaultTLSACMEIssuerName = "" - defaultTLSACMEIssuerKind = "Issuer" - defaultTLSACMEIssuerGroup = cm.GroupName - defaultEnableCertificateOwnerRef = false - - defaultDNS01RecursiveNameserversOnly = false - - defaultMaxConcurrentChallenges = 60 - - defaultPrometheusMetricsServerAddress = "0.0.0.0:9402" - - // default time period to wait between checking DNS01 and HTTP01 challenge propagation - defaultDNS01CheckRetryPeriod = 10 * time.Second -) +func NewControllerFlags() *ControllerFlags { + return &ControllerFlags{} +} -var ( - defaultACMEHTTP01SolverImage = fmt.Sprintf("quay.io/jetstack/cert-manager-acmesolver:%s", util.AppVersion) - defaultACMEHTTP01SolverResourceRequestCPU = "10m" - defaultACMEHTTP01SolverResourceRequestMemory = "64Mi" - defaultACMEHTTP01SolverResourceLimitsCPU = "100m" - defaultACMEHTTP01SolverResourceLimitsMemory = "64Mi" - defaultACMEHTTP01SolverRunAsNonRoot = true - - defaultAutoCertificateAnnotations = []string{"kubernetes.io/tls-acme"} - - allControllers = []string{ - issuerscontroller.ControllerName, - clusterissuerscontroller.ControllerName, - certificatesmetricscontroller.ControllerName, - shimingresscontroller.ControllerName, - shimgatewaycontroller.ControllerName, - orderscontroller.ControllerName, - challengescontroller.ControllerName, - cracmecontroller.CRControllerName, - crapprovercontroller.ControllerName, - crcacontroller.CRControllerName, - crselfsignedcontroller.CRControllerName, - crvaultcontroller.CRControllerName, - crvenaficontroller.CRControllerName, - // certificate controllers - trigger.ControllerName, - issuing.ControllerName, - keymanager.ControllerName, - requestmanager.ControllerName, - readiness.ControllerName, - revisionmanager.ControllerName, - } +func (f *ControllerFlags) AddFlags(fs *pflag.FlagSet) { + fs.StringVar(&f.Config, "config", "", "Path to a file containing a ControllerConfiguration object used to configure the controller") +} - defaultEnabledControllers = []string{ - issuerscontroller.ControllerName, - clusterissuerscontroller.ControllerName, - certificatesmetricscontroller.ControllerName, - shimingresscontroller.ControllerName, - orderscontroller.ControllerName, - challengescontroller.ControllerName, - cracmecontroller.CRControllerName, - crapprovercontroller.ControllerName, - crcacontroller.CRControllerName, - crselfsignedcontroller.CRControllerName, - crvaultcontroller.CRControllerName, - crvenaficontroller.CRControllerName, - // certificate controllers - trigger.ControllerName, - issuing.ControllerName, - keymanager.ControllerName, - requestmanager.ControllerName, - readiness.ControllerName, - revisionmanager.ControllerName, - } +func ValidateControllerFlags(f *ControllerFlags) error { + // No validation needed today + return nil +} - experimentalCertificateSigningRequestControllers = []string{ - csracmecontroller.CSRControllerName, - csrcacontroller.CSRControllerName, - csrselfsignedcontroller.CSRControllerName, - csrvenaficontroller.CSRControllerName, - csrvaultcontroller.CSRControllerName, - } - // Annotations that will be copied from Certificate to CertificateRequest and to Order. - // By default, copy all annotations except for the ones applied by kubectl, fluxcd, argocd. - defaultCopiedAnnotationPrefixes = []string{ - "*", - "-kubectl.kubernetes.io/", - "-fluxcd.io/", - "-argocd.argoproj.io/", +func NewControllerConfiguration() (*config.ControllerConfiguration, error) { + scheme, _, err := configscheme.NewSchemeAndCodecs() + if err != nil { + return nil, err } -) - -func NewControllerOptions() *ControllerOptions { - return &ControllerOptions{ - APIServerHost: defaultAPIServerHost, - ClusterResourceNamespace: defaultClusterResourceNamespace, - KubernetesAPIQPS: defaultKubernetesAPIQPS, - KubernetesAPIBurst: defaultKubernetesAPIBurst, - Namespace: defaultNamespace, - LeaderElect: cmdutil.DefaultLeaderElect, - LeaderElectionNamespace: cmdutil.DefaultLeaderElectionNamespace, - LeaderElectionLeaseDuration: cmdutil.DefaultLeaderElectionLeaseDuration, - LeaderElectionRenewDeadline: cmdutil.DefaultLeaderElectionRenewDeadline, - LeaderElectionRetryPeriod: cmdutil.DefaultLeaderElectionRetryPeriod, - controllers: defaultEnabledControllers, - ClusterIssuerAmbientCredentials: defaultClusterIssuerAmbientCredentials, - IssuerAmbientCredentials: defaultIssuerAmbientCredentials, - DefaultIssuerName: defaultTLSACMEIssuerName, - DefaultIssuerKind: defaultTLSACMEIssuerKind, - DefaultIssuerGroup: defaultTLSACMEIssuerGroup, - DefaultAutoCertificateAnnotations: defaultAutoCertificateAnnotations, - ACMEHTTP01SolverNameservers: []string{}, - DNS01RecursiveNameservers: []string{}, - DNS01RecursiveNameserversOnly: defaultDNS01RecursiveNameserversOnly, - EnableCertificateOwnerRef: defaultEnableCertificateOwnerRef, - MetricsListenAddress: defaultPrometheusMetricsServerAddress, - DNS01CheckRetryPeriod: defaultDNS01CheckRetryPeriod, - EnablePprof: cmdutil.DefaultEnableProfiling, - PprofAddress: cmdutil.DefaultProfilerAddr, + versioned := &configv1alpha1.ControllerConfiguration{} + scheme.Default(versioned) + config := &config.ControllerConfiguration{} + if err := scheme.Convert(versioned, config, nil); err != nil { + return nil, err } + return config, nil } -func (s *ControllerOptions) AddFlags(fs *pflag.FlagSet) { - fs.StringVar(&s.APIServerHost, "master", defaultAPIServerHost, ""+ +func AddConfigFlags(fs *pflag.FlagSet, c *config.ControllerConfiguration) { + fs.StringVar(&c.APIServerHost, "master", c.APIServerHost, ""+ "Optional apiserver host address to connect to. If not specified, autoconfiguration "+ "will be attempted.") - fs.StringVar(&s.Kubeconfig, "kubeconfig", defaultKubeconfig, ""+ + fs.StringVar(&c.KubeConfig, "kubeconfig", c.KubeConfig, ""+ "Paths to a kubeconfig. Only required if out-of-cluster.") - fs.Float32Var(&s.KubernetesAPIQPS, "kube-api-qps", defaultKubernetesAPIQPS, "indicates the maximum queries-per-second requests to the Kubernetes apiserver") - fs.IntVar(&s.KubernetesAPIBurst, "kube-api-burst", defaultKubernetesAPIBurst, "the maximum burst queries-per-second of requests sent to the Kubernetes apiserver") - fs.StringVar(&s.ClusterResourceNamespace, "cluster-resource-namespace", defaultClusterResourceNamespace, ""+ + fs.Float32Var(c.KubernetesAPIQPS, "kube-api-qps", *c.KubernetesAPIQPS, "indicates the maximum queries-per-second requests to the Kubernetes apiserver") + fs.IntVar(c.KubernetesAPIBurst, "kube-api-burst", *c.KubernetesAPIBurst, "the maximum burst queries-per-second of requests sent to the Kubernetes apiserver") + fs.StringVar(&c.ClusterResourceNamespace, "cluster-resource-namespace", c.ClusterResourceNamespace, ""+ "Namespace to store resources owned by cluster scoped resources such as ClusterIssuer in. "+ "This must be specified if ClusterIssuers are enabled.") - fs.StringVar(&s.Namespace, "namespace", defaultNamespace, ""+ + fs.StringVar(&c.Namespace, "namespace", c.Namespace, ""+ "If set, this limits the scope of cert-manager to a single namespace and ClusterIssuers are disabled. "+ "If not specified, all namespaces will be watched") - fs.BoolVar(&s.LeaderElect, "leader-elect", cmdutil.DefaultLeaderElect, ""+ + fs.BoolVar(c.LeaderElect, "leader-elect", *c.LeaderElect, ""+ "If true, cert-manager will perform leader election between instances to ensure no more "+ "than one instance of cert-manager operates at a time") - fs.StringVar(&s.LeaderElectionNamespace, "leader-election-namespace", cmdutil.DefaultLeaderElectionNamespace, ""+ + fs.StringVar(&c.LeaderElectionNamespace, "leader-election-namespace", c.LeaderElectionNamespace, ""+ "Namespace used to perform leader election. Only used if leader election is enabled") - fs.DurationVar(&s.LeaderElectionLeaseDuration, "leader-election-lease-duration", cmdutil.DefaultLeaderElectionLeaseDuration, ""+ + fs.DurationVar(&c.LeaderElectionLeaseDuration, "leader-election-lease-duration", c.LeaderElectionLeaseDuration, ""+ "The duration that non-leader candidates will wait after observing a leadership "+ "renewal until attempting to acquire leadership of a led but unrenewed leader "+ "slot. This is effectively the maximum duration that a leader can be stopped "+ "before it is replaced by another candidate. This is only applicable if leader "+ "election is enabled.") - fs.DurationVar(&s.LeaderElectionRenewDeadline, "leader-election-renew-deadline", cmdutil.DefaultLeaderElectionRenewDeadline, ""+ + fs.DurationVar(&c.LeaderElectionRenewDeadline, "leader-election-renew-deadline", c.LeaderElectionRenewDeadline, ""+ "The interval between attempts by the acting master to renew a leadership slot "+ "before it stops leading. This must be less than or equal to the lease duration. "+ "This is only applicable if leader election is enabled.") - fs.DurationVar(&s.LeaderElectionRetryPeriod, "leader-election-retry-period", cmdutil.DefaultLeaderElectionRetryPeriod, ""+ + fs.DurationVar(&c.LeaderElectionRetryPeriod, "leader-election-retry-period", c.LeaderElectionRetryPeriod, ""+ "The duration the clients should wait between attempting acquisition and renewal "+ "of a leadership. This is only applicable if leader election is enabled.") - fs.StringSliceVar(&s.controllers, "controllers", []string{"*"}, fmt.Sprintf(""+ + fs.StringSliceVar(&c.Controllers, "controllers", c.Controllers, fmt.Sprintf(""+ "A list of controllers to enable. '--controllers=*' enables all "+ "on-by-default controllers, '--controllers=foo' enables just the controller "+ "named 'foo', '--controllers=*,-foo' disables the controller named "+ "'foo'.\nAll controllers: %s", - strings.Join(allControllers, ", "))) + strings.Join(defaults.AllControllers, ", "))) // HTTP-01 solver pod configuration via flags is a now deprecated // mechanism- please use pod template instead when adding any new // configuration options // https://github.com/cert-manager/cert-manager/blob/f1d7c432763100c3fb6eb6a1654d29060b479b3c/pkg/apis/acme/v1/types_issuer.go#L270 // These flags however will not be deprecated for backwards compatibility purposes. - fs.StringVar(&s.ACMEHTTP01SolverImage, "acme-http01-solver-image", defaultACMEHTTP01SolverImage, ""+ + fs.StringVar(&c.ACMEHTTP01SolverImage, "acme-http01-solver-image", c.ACMEHTTP01SolverImage, ""+ "The docker image to use to solve ACME HTTP01 challenges. You most likely will not "+ "need to change this parameter unless you are testing a new feature or developing cert-manager.") - fs.StringVar(&s.ACMEHTTP01SolverResourceRequestCPU, "acme-http01-solver-resource-request-cpu", defaultACMEHTTP01SolverResourceRequestCPU, ""+ + fs.StringVar(&c.ACMEHTTP01SolverResourceRequestCPU, "acme-http01-solver-resource-request-cpu", c.ACMEHTTP01SolverResourceRequestCPU, ""+ "Defines the resource request CPU size when spawning new ACME HTTP01 challenge solver pods.") - fs.StringVar(&s.ACMEHTTP01SolverResourceRequestMemory, "acme-http01-solver-resource-request-memory", defaultACMEHTTP01SolverResourceRequestMemory, ""+ + fs.StringVar(&c.ACMEHTTP01SolverResourceRequestMemory, "acme-http01-solver-resource-request-memory", c.ACMEHTTP01SolverResourceRequestMemory, ""+ "Defines the resource request Memory size when spawning new ACME HTTP01 challenge solver pods.") - fs.StringVar(&s.ACMEHTTP01SolverResourceLimitsCPU, "acme-http01-solver-resource-limits-cpu", defaultACMEHTTP01SolverResourceLimitsCPU, ""+ + fs.StringVar(&c.ACMEHTTP01SolverResourceLimitsCPU, "acme-http01-solver-resource-limits-cpu", c.ACMEHTTP01SolverResourceLimitsCPU, ""+ "Defines the resource limits CPU size when spawning new ACME HTTP01 challenge solver pods.") - fs.StringVar(&s.ACMEHTTP01SolverResourceLimitsMemory, "acme-http01-solver-resource-limits-memory", defaultACMEHTTP01SolverResourceLimitsMemory, ""+ + fs.StringVar(&c.ACMEHTTP01SolverResourceLimitsMemory, "acme-http01-solver-resource-limits-memory", c.ACMEHTTP01SolverResourceLimitsMemory, ""+ "Defines the resource limits Memory size when spawning new ACME HTTP01 challenge solver pods.") - fs.BoolVar(&s.ACMEHTTP01SolverRunAsNonRoot, "acme-http01-solver-run-as-non-root", defaultACMEHTTP01SolverRunAsNonRoot, ""+ + fs.BoolVar(c.ACMEHTTP01SolverRunAsNonRoot, "acme-http01-solver-run-as-non-root", *c.ACMEHTTP01SolverRunAsNonRoot, ""+ "Defines the ability to run the http01 solver as root for troubleshooting issues") - fs.StringSliceVar(&s.ACMEHTTP01SolverNameservers, "acme-http01-solver-nameservers", - []string{}, "A list of comma separated dns server endpoints used for "+ + fs.StringSliceVar(&c.ACMEHTTP01SolverNameservers, "acme-http01-solver-nameservers", + c.ACMEHTTP01SolverNameservers, "A list of comma separated dns server endpoints used for "+ "ACME HTTP01 check requests. This should be a list containing host and "+ "port, for example 8.8.8.8:53,8.8.4.4:53") - fs.BoolVar(&s.ClusterIssuerAmbientCredentials, "cluster-issuer-ambient-credentials", defaultClusterIssuerAmbientCredentials, ""+ + fs.BoolVar(c.ClusterIssuerAmbientCredentials, "cluster-issuer-ambient-credentials", *c.ClusterIssuerAmbientCredentials, ""+ "Whether a cluster-issuer may make use of ambient credentials for issuers. 'Ambient Credentials' are credentials drawn from the environment, metadata services, or local files which are not explicitly configured in the ClusterIssuer API object. "+ "When this flag is enabled, the following sources for credentials are also used: "+ "AWS - All sources the Go SDK defaults to, notably including any EC2 IAM roles available via instance metadata.") - fs.BoolVar(&s.IssuerAmbientCredentials, "issuer-ambient-credentials", defaultIssuerAmbientCredentials, ""+ + fs.BoolVar(c.IssuerAmbientCredentials, "issuer-ambient-credentials", *c.IssuerAmbientCredentials, ""+ "Whether an issuer may make use of ambient credentials. 'Ambient Credentials' are credentials drawn from the environment, metadata services, or local files which are not explicitly configured in the Issuer API object. "+ "When this flag is enabled, the following sources for credentials are also used: "+ "AWS - All sources the Go SDK defaults to, notably including any EC2 IAM roles available via instance metadata.") - fs.StringSliceVar(&s.DefaultAutoCertificateAnnotations, "auto-certificate-annotations", defaultAutoCertificateAnnotations, ""+ + fs.StringSliceVar(&c.DefaultAutoCertificateAnnotations, "auto-certificate-annotations", c.DefaultAutoCertificateAnnotations, ""+ "The annotation consumed by the ingress-shim controller to indicate a ingress is requesting a certificate") - fs.StringVar(&s.DefaultIssuerName, "default-issuer-name", defaultTLSACMEIssuerName, ""+ + fs.StringVar(&c.DefaultIssuerName, "default-issuer-name", c.DefaultIssuerName, ""+ "Name of the Issuer to use when the tls is requested but issuer name is not specified on the ingress resource.") - fs.StringVar(&s.DefaultIssuerKind, "default-issuer-kind", defaultTLSACMEIssuerKind, ""+ + fs.StringVar(&c.DefaultIssuerKind, "default-issuer-kind", c.DefaultIssuerKind, ""+ "Kind of the Issuer to use when the tls is requested but issuer kind is not specified on the ingress resource.") - fs.StringVar(&s.DefaultIssuerGroup, "default-issuer-group", defaultTLSACMEIssuerGroup, ""+ + fs.StringVar(&c.DefaultIssuerGroup, "default-issuer-group", c.DefaultIssuerGroup, ""+ "Group of the Issuer to use when the tls is requested but issuer group is not specified on the ingress resource.") - fs.StringSliceVar(&s.DNS01RecursiveNameservers, "dns01-recursive-nameservers", - []string{}, "A list of comma separated dns server endpoints used for "+ + fs.StringSliceVar(&c.DNS01RecursiveNameservers, "dns01-recursive-nameservers", + c.DNS01RecursiveNameservers, "A list of comma separated dns server endpoints used for "+ "DNS01 check requests. This should be a list containing host and "+ "port, for example 8.8.8.8:53,8.8.4.4:53") - fs.BoolVar(&s.DNS01RecursiveNameserversOnly, "dns01-recursive-nameservers-only", - defaultDNS01RecursiveNameserversOnly, + fs.BoolVar(c.DNS01RecursiveNameserversOnly, "dns01-recursive-nameservers-only", + *c.DNS01RecursiveNameserversOnly, "When true, cert-manager will only ever query the configured DNS resolvers "+ "to perform the ACME DNS01 self check. This is useful in DNS constrained "+ "environments, where access to authoritative nameservers is restricted. "+ "Enabling this option could cause the DNS01 self check to take longer "+ "due to caching performed by the recursive nameservers.") - fs.BoolVar(&s.EnableCertificateOwnerRef, "enable-certificate-owner-ref", defaultEnableCertificateOwnerRef, ""+ + fs.BoolVar(c.EnableCertificateOwnerRef, "enable-certificate-owner-ref", *c.EnableCertificateOwnerRef, ""+ "Whether to set the certificate resource as an owner of secret where the tls certificate is stored. "+ "When this flag is enabled, the secret will be automatically removed when the certificate resource is deleted.") - fs.StringSliceVar(&s.CopiedAnnotationPrefixes, "copied-annotation-prefixes", defaultCopiedAnnotationPrefixes, "Specify which annotations should/shouldn't be copied"+ + fs.StringSliceVar(&c.CopiedAnnotationPrefixes, "copied-annotation-prefixes", c.CopiedAnnotationPrefixes, "Specify which annotations should/shouldn't be copied"+ "from Certificate to CertificateRequest and Order, as well as from CertificateSigningRequest to Order, by passing a list of annotation key prefixes."+ "A prefix starting with a dash(-) specifies an annotation that shouldn't be copied. Example: '*,-kubectl.kuberenetes.io/'- all annotations"+ "will be copied apart from the ones where the key is prefixed with 'kubectl.kubernetes.io/'.") - fs.IntVar(&s.MaxConcurrentChallenges, "max-concurrent-challenges", defaultMaxConcurrentChallenges, ""+ + fs.IntVar(c.MaxConcurrentChallenges, "max-concurrent-challenges", *c.MaxConcurrentChallenges, ""+ "The maximum number of challenges that can be scheduled as 'processing' at once.") - fs.DurationVar(&s.DNS01CheckRetryPeriod, "dns01-check-retry-period", defaultDNS01CheckRetryPeriod, ""+ + fs.DurationVar(&c.DNS01CheckRetryPeriod, "dns01-check-retry-period", c.DNS01CheckRetryPeriod, ""+ "The duration the controller should wait between a propagation check. Despite the name, this flag is used to configure the wait period for both DNS01 and HTTP01 challenge propagation checks. For DNS01 challenges the propagation check verifies that a TXT record with the challenge token has been created. For HTTP01 challenges the propagation check verifies that the challenge token is served at the challenge URL."+ "This should be a valid duration string, for example 180s or 1h") - fs.StringVar(&s.MetricsListenAddress, "metrics-listen-address", defaultPrometheusMetricsServerAddress, ""+ + fs.StringVar(&c.MetricsListenAddress, "metrics-listen-address", c.MetricsListenAddress, ""+ "The host and port that the metrics endpoint should listen on.") - fs.BoolVar(&s.EnablePprof, "enable-profiling", cmdutil.DefaultEnableProfiling, ""+ + fs.BoolVar(c.EnablePprof, "enable-profiling", *c.EnablePprof, ""+ "Enable profiling for controller.") - fs.StringVar(&s.PprofAddress, "profiler-address", cmdutil.DefaultProfilerAddr, + fs.StringVar(&c.PprofAddress, "profiler-address", c.PprofAddress, "The host and port that Go profiler should listen on, i.e localhost:6060. Ensure that profiler is not exposed on a public address. Profiler will be served at /debug/pprof.") } -func (o *ControllerOptions) Validate() error { - if len(o.DefaultIssuerKind) == 0 { - return errors.New("the --default-issuer-kind flag must not be empty") - } - - if o.KubernetesAPIBurst <= 0 { - return fmt.Errorf("invalid value for kube-api-burst: %v must be higher than 0", o.KubernetesAPIBurst) - } - - if o.KubernetesAPIQPS <= 0 { - return fmt.Errorf("invalid value for kube-api-qps: %v must be higher than 0", o.KubernetesAPIQPS) - } - - if float32(o.KubernetesAPIBurst) < o.KubernetesAPIQPS { - return fmt.Errorf("invalid value for kube-api-burst: %v must be higher or equal to kube-api-qps: %v", o.KubernetesAPIQPS, o.KubernetesAPIQPS) - } - - for _, server := range append(o.DNS01RecursiveNameservers, o.ACMEHTTP01SolverNameservers...) { - // ensure all servers have a port number - _, _, err := net.SplitHostPort(server) - if err != nil { - return fmt.Errorf("invalid DNS server (%v): %v", err, server) - } - } - - errs := []error{} - allControllersSet := sets.NewString(allControllers...) - for _, controller := range o.controllers { - if controller == "*" { - continue - } - - controller = strings.TrimPrefix(controller, "-") - if !allControllersSet.Has(controller) { - errs = append(errs, fmt.Errorf("%q is not in the list of known controllers", controller)) - } - } - - if len(errs) > 0 { - return fmt.Errorf("validation failed for '--controllers': %v", errs) - } - - return nil -} - -func (o *ControllerOptions) EnabledControllers() sets.String { +func EnabledControllers(o *config.ControllerConfiguration) sets.String { var disabled []string enabled := sets.NewString() - for _, controller := range o.controllers { + for _, controller := range o.Controllers { switch { case controller == "*": - enabled = enabled.Insert(defaultEnabledControllers...) + enabled = enabled.Insert(defaults.DefaultEnabledControllers...) case strings.HasPrefix(controller, "-"): disabled = append(disabled, strings.TrimPrefix(controller, "-")) default: @@ -436,7 +207,7 @@ func (o *ControllerOptions) EnabledControllers() sets.String { if utilfeature.DefaultFeatureGate.Enabled(feature.ExperimentalCertificateSigningRequestControllers) { logf.Log.Info("enabling all experimental certificatesigningrequest controllers") - enabled = enabled.Insert(experimentalCertificateSigningRequestControllers...) + enabled = enabled.Insert(defaults.ExperimentalCertificateSigningRequestControllers...) } if utilfeature.DefaultFeatureGate.Enabled(feature.ExperimentalGatewayAPISupport) { diff --git a/cmd/controller/app/options/options_test.go b/cmd/controller/app/options/options_test.go index 3a0ca143928..7afcb6d3186 100644 --- a/cmd/controller/app/options/options_test.go +++ b/cmd/controller/app/options/options_test.go @@ -20,6 +20,10 @@ import ( "testing" "k8s.io/apimachinery/pkg/util/sets" + + config "github.com/cert-manager/cert-manager/internal/apis/config/controller" + defaults "github.com/cert-manager/cert-manager/internal/apis/config/controller/v1alpha1" + //"github.com/cert-manager/cert-manager/pkg/apis/config/controller/v1alpha1" ) func TestEnabledControllers(t *testing.T) { @@ -41,21 +45,21 @@ func TestEnabledControllers(t *testing.T) { }, "if all default controllers enabled, return all default controllers": { controllers: []string{"*"}, - expEnabled: sets.NewString(defaultEnabledControllers...), + expEnabled: sets.NewString(defaults.DefaultEnabledControllers...), }, "if all controllers enabled, some diabled, return all controllers with disabled": { controllers: []string{"*", "-clusterissuers", "-issuers"}, - expEnabled: sets.NewString(defaultEnabledControllers...).Delete("clusterissuers", "issuers"), + expEnabled: sets.NewString(defaults.DefaultEnabledControllers...).Delete("clusterissuers", "issuers"), }, } for name, test := range tests { t.Run(name, func(t *testing.T) { - o := ControllerOptions{ - controllers: test.controllers, + o := config.ControllerConfiguration{ + Controllers: test.controllers, } - got := o.EnabledControllers() + got := EnabledControllers(&o) if !got.Equal(test.expEnabled) { t.Errorf("got unexpected enabled, exp=%s got=%s", test.expEnabled, got) diff --git a/cmd/controller/app/start.go b/cmd/controller/app/start.go index 08784260a4f..c33fa9c6862 100644 --- a/cmd/controller/app/start.go +++ b/cmd/controller/app/start.go @@ -17,48 +17,47 @@ limitations under the License. package app import ( + "context" "fmt" + "os" + "path/filepath" "github.com/spf13/cobra" - utilerrors "k8s.io/apimachinery/pkg/util/errors" - _ "k8s.io/client-go/plugin/pkg/client/auth" + "github.com/spf13/pflag" + "k8s.io/apimachinery/pkg/runtime/serializer" + cliflag "k8s.io/component-base/cli/flag" "github.com/cert-manager/cert-manager/cmd/controller/app/options" - _ "github.com/cert-manager/cert-manager/pkg/controller/acmechallenges" - _ "github.com/cert-manager/cert-manager/pkg/controller/acmeorders" - _ "github.com/cert-manager/cert-manager/pkg/controller/certificate-shim/gateways" - _ "github.com/cert-manager/cert-manager/pkg/controller/certificate-shim/ingresses" - _ "github.com/cert-manager/cert-manager/pkg/controller/certificates/trigger" - _ "github.com/cert-manager/cert-manager/pkg/controller/clusterissuers" - _ "github.com/cert-manager/cert-manager/pkg/controller/issuers" - _ "github.com/cert-manager/cert-manager/pkg/issuer/acme" - _ "github.com/cert-manager/cert-manager/pkg/issuer/ca" - _ "github.com/cert-manager/cert-manager/pkg/issuer/selfsigned" - _ "github.com/cert-manager/cert-manager/pkg/issuer/vault" - _ "github.com/cert-manager/cert-manager/pkg/issuer/venafi" + config "github.com/cert-manager/cert-manager/internal/apis/config/controller" + "github.com/cert-manager/cert-manager/internal/apis/config/controller/scheme" + cmdutil "github.com/cert-manager/cert-manager/internal/cmd/util" + controllerconfigfile "github.com/cert-manager/cert-manager/pkg/controller/configfile" logf "github.com/cert-manager/cert-manager/pkg/logs" "github.com/cert-manager/cert-manager/pkg/util" + "github.com/cert-manager/cert-manager/pkg/util/configfile" utilfeature "github.com/cert-manager/cert-manager/pkg/util/feature" ) -type CertManagerControllerOptions struct { - ControllerOptions *options.ControllerOptions -} +const componentController = "controller" -func NewCertManagerControllerOptions() *CertManagerControllerOptions { - o := &CertManagerControllerOptions{ - ControllerOptions: options.NewControllerOptions(), - } +func NewServerCommand(stopCh <-chan struct{}) *cobra.Command { + ctx := cmdutil.ContextWithStopCh(context.Background(), stopCh) + log := logf.Log - return o -} + ctx = logf.NewContext(ctx, log, componentController) -// NewCommandStartCertManagerController is a CLI handler for starting cert-manager -func NewCommandStartCertManagerController(stopCh <-chan struct{}) *cobra.Command { - o := NewCertManagerControllerOptions() + cleanFlagSet := pflag.NewFlagSet(componentController, pflag.ContinueOnError) + // Replaces all instances of `_` in flag names with `-` + cleanFlagSet.SetNormalizeFunc(cliflag.WordSepNormalizeFunc) + controllerFlags := options.NewControllerFlags() + controllerConfig, err := options.NewControllerConfiguration() + if err != nil { + log.Error(err, "Failed to create new controller configuration") + os.Exit(1) + } cmd := &cobra.Command{ - Use: "cert-manager-controller", + Use: componentController, Short: fmt.Sprintf("Automated TLS controller for Kubernetes (%s) (%s)", util.AppVersion, util.AppGitCommit), Long: ` cert-manager is a Kubernetes addon to automate the management and issuance of @@ -66,36 +65,157 @@ TLS certificates from various issuing sources. It will ensure certificates are valid and up to date periodically, and attempt to renew certificates at an appropriate time before expiry.`, + // The controller has special flag parsing requirements to handle precedence of providing + // configuration via versioned configuration files and flag values. + // Setting DisableFlagParsing=true prevents Cobra from interfering with flag parsing + // at all, and instead we handle it all in the RunE below. + DisableFlagParsing: true, + Run: func(cmd *cobra.Command, args []string) { + // initial flag parse, since we disable cobra's flag parsing + if err := cleanFlagSet.Parse(args); err != nil { + log.Error(err, "Failed to parse controller flag") + cmd.Usage() + os.Exit(1) + } - RunE: func(cmd *cobra.Command, args []string) error { - if err := o.Validate(args); err != nil { - return fmt.Errorf("error validating options: %s", err) + // check if there are non-flag arguments in the command line + cmds := cleanFlagSet.Args() + if len(cmds) > 0 { + log.Error(nil, "Unknown command", "command", cmds[0]) + cmd.Usage() + os.Exit(1) } - logf.Log.V(logf.InfoLevel).Info("starting controller", "version", util.AppVersion, "git-commit", util.AppGitCommit) - if err := o.RunCertManagerController(stopCh); err != nil { - cmd.SilenceUsage = true // Don't display usage information when exiting because of an error - return err + // short-circuit on help + help, err := cleanFlagSet.GetBool("help") + if err != nil { + log.Info(`"help" flag is non-bool, programmer error, please correct`) + os.Exit(1) + } + if help { + cmd.Help() } - return nil + // set feature gates from initial flags-based config + if err := utilfeature.DefaultMutableFeatureGate.SetFromMap(controllerConfig.FeatureGates); err != nil { + log.Error(err, "Failed to set feature gates from initial flags-based config") + os.Exit(1) + } + + if err := options.ValidateControllerFlags(controllerFlags); err != nil { + log.Error(err, "Failed to validate controller flags") + os.Exit(1) + } + + if configFile := controllerFlags.Config; len(configFile) > 0 { + controllerConfig, err = loadConfigFile(configFile) + if err != nil { + log.Error(err, "Failed to load controller config file", "path", configFile) + os.Exit(1) + } + + if err := controllerConfigFlagPrecedence(controllerConfig, args); err != nil { + log.Error(err, "Failed to merge flags with config file values") + os.Exit(1) + } + // update feature gates based on new config + if err := utilfeature.DefaultMutableFeatureGate.SetFromMap(controllerConfig.FeatureGates); err != nil { + log.Error(err, "Failed to set feature gates from config file") + os.Exit(1) + } + } + + // Start the controller + if err := Run(controllerConfig, stopCh); err != nil { + log.Error(err, "Failed to run the controller") + os.Exit(1) + } }, - SilenceErrors: true, // Errors are already logged when calling cmd.Execute() } - flags := cmd.Flags() - o.ControllerOptions.AddFlags(flags) - utilfeature.DefaultMutableFeatureGate.AddFlag(flags) + controllerFlags.AddFlags(cleanFlagSet) + options.AddConfigFlags(cleanFlagSet, controllerConfig) + options.AddGlobalFlags(cleanFlagSet) + + cleanFlagSet.BoolP("help", "h", false, fmt.Sprintf("help for %s", cmd.Name())) + + // ugly, but necessary, because Cobra's default UsageFunc and HelpFunc pollute the flagset with global flags + const usageFmt = "Usage:\n %s\n\nFlags:\n%s" + cmd.SetUsageFunc(func(cmd *cobra.Command) error { + fmt.Fprintf(cmd.OutOrStderr(), usageFmt, cmd.UseLine(), cleanFlagSet.FlagUsagesWrapped(2)) + return nil + }) + cmd.SetHelpFunc(func(cmd *cobra.Command, args []string) { + fmt.Fprintf(cmd.OutOrStdout(), "%s\n\n"+usageFmt, cmd.Long, cmd.UseLine(), cleanFlagSet.FlagUsagesWrapped(2)) + }) return cmd } -func (o CertManagerControllerOptions) Validate(args []string) error { - errors := []error{} - errors = append(errors, o.ControllerOptions.Validate()) - return utilerrors.NewAggregate(errors) +// newFlagSetWithGlobals constructs a new pflag.FlagSet with global flags registered +// on it. +func newFlagSetWithGlobals() *pflag.FlagSet { + fs := pflag.NewFlagSet("", pflag.ExitOnError) + // set the normalize func, similar to k8s.io/component-base/cli//flags.go:InitFlags + fs.SetNormalizeFunc(cliflag.WordSepNormalizeFunc) + // explicitly add flags from libs that register global flags + options.AddGlobalFlags(fs) + return fs +} + +// newFakeFlagSet constructs a pflag.FlagSet with the same flags as fs, but where +// all values have noop Set implementations +func newFakeFlagSet(fs *pflag.FlagSet) *pflag.FlagSet { + ret := pflag.NewFlagSet("", pflag.ExitOnError) + ret.SetNormalizeFunc(fs.GetNormalizeFunc()) + fs.VisitAll(func(f *pflag.Flag) { + ret.VarP(cliflag.NoOp{}, f.Name, f.Shorthand, f.Usage) + }) + return ret +} + +// controllerConfigFlagPrecedence re-parses flags over the ControllerConfiguration object. +// We must enforce flag precedence by re-parsing the command line into the new object. +// This is necessary to preserve backwards-compatibility across binary upgrades. +// See issue #56171 for more details. +func controllerConfigFlagPrecedence(cfg *config.ControllerConfiguration, args []string) error { + // We use a throwaway controllerFlags and a fake global flagset to avoid double-parses, + // as some Set implementations accumulate values from multiple flag invocations. + fs := newFakeFlagSet(newFlagSetWithGlobals()) + // register throwaway KubeletFlags + options.NewControllerFlags().AddFlags(fs) + // register new ControllerConfiguration + options.AddConfigFlags(fs, cfg) + // re-parse flags + if err := fs.Parse(args); err != nil { + return err + } + return nil } -func (o CertManagerControllerOptions) RunCertManagerController(stopCh <-chan struct{}) error { - return Run(o.ControllerOptions, stopCh) +func loadConfigFile(name string) (*config.ControllerConfiguration, error) { + const errFmt = "failed to load controller config file %s, error %v" + // compute absolute path based on current working dir + controllerConfigFile, err := filepath.Abs(name) + if err != nil { + return nil, fmt.Errorf(errFmt, name, err) + } + _, controllerCodec, err := scheme.NewSchemeAndCodecs(serializer.EnableStrict) + if err != nil { + return nil, fmt.Errorf(errFmt, name, err) + } + loader, err := configfile.NewConfigurationFSLoader(nil, controllerconfigfile.ControllerConfigurationPathRefs, controllerCodec, controllerConfigFile) + if err != nil { + return nil, fmt.Errorf(errFmt, name, err) + } + c, err := loader.Load() + if err != nil { + return nil, fmt.Errorf(errFmt, name, err) + } + cfg, ok := c.(*config.ControllerConfiguration) + if !ok { + return nil, fmt.Errorf(errFmt, name, "could not decode configuration as a controllerConfiguration.") + } + + return cfg, nil } diff --git a/cmd/controller/main.go b/cmd/controller/main.go index 6f80cdf429d..223e5a6cf55 100644 --- a/cmd/controller/main.go +++ b/cmd/controller/main.go @@ -31,7 +31,7 @@ func main() { logf.InitLogs(flag.CommandLine) defer logf.FlushLogs() - cmd := app.NewCommandStartCertManagerController(stopCh) + cmd := app.NewServerCommand(stopCh) cmd.Flags().AddGoFlagSet(flag.CommandLine) flag.CommandLine.Parse([]string{}) diff --git a/cmd/webhook/app/webhook.go b/cmd/webhook/app/webhook.go index 41aca7cca71..b3c3a6fb0d7 100644 --- a/cmd/webhook/app/webhook.go +++ b/cmd/webhook/app/webhook.go @@ -24,16 +24,19 @@ import ( "github.com/spf13/cobra" "github.com/spf13/pflag" + "k8s.io/apimachinery/pkg/runtime/serializer" cliflag "k8s.io/component-base/cli/flag" "github.com/cert-manager/cert-manager/cmd/webhook/app/options" config "github.com/cert-manager/cert-manager/internal/apis/config/webhook" + "github.com/cert-manager/cert-manager/internal/apis/config/webhook/scheme" cmdutil "github.com/cert-manager/cert-manager/internal/cmd/util" cmwebhook "github.com/cert-manager/cert-manager/internal/webhook" logf "github.com/cert-manager/cert-manager/pkg/logs" "github.com/cert-manager/cert-manager/pkg/util" + "github.com/cert-manager/cert-manager/pkg/util/configfile" utilfeature "github.com/cert-manager/cert-manager/pkg/util/feature" - "github.com/cert-manager/cert-manager/pkg/webhook/configfile" + webhookconfigfile "github.com/cert-manager/cert-manager/pkg/webhook/configfile" ) const componentWebhook = "webhook" @@ -197,13 +200,23 @@ func loadConfigFile(name string) (*config.WebhookConfiguration, error) { if err != nil { return nil, fmt.Errorf(errFmt, name, err) } - loader, err := configfile.NewFSLoader(configfile.NewRealFS(), webhookConfigFile) + //loader, err := configfile.NewFSLoader(configfile.NewRealFS(), webhookConfigFile) + _, webhookCodec, err := scheme.NewSchemeAndCodecs(serializer.EnableStrict) if err != nil { return nil, fmt.Errorf(errFmt, name, err) } - cfg, err := loader.Load() + loader, err := configfile.NewConfigurationFSLoader(nil, webhookconfigfile.WebhookConfigurationPathRefs, webhookCodec, webhookConfigFile) if err != nil { return nil, fmt.Errorf(errFmt, name, err) } + c, err := loader.Load() + if err != nil { + return nil, fmt.Errorf(errFmt, name, err) + } + cfg, ok := c.(*config.WebhookConfiguration) + if !ok { + return nil, fmt.Errorf(errFmt, name, "could not decode configuration as a WebhookConfiguration.") + } + return cfg, nil } diff --git a/go.mod b/go.mod index 3a0c73fc499..400485dab83 100644 --- a/go.mod +++ b/go.mod @@ -81,6 +81,7 @@ require ( github.com/armon/go-metrics v0.3.9 // indirect github.com/armon/go-radix v1.0.0 // indirect github.com/asaskevich/govalidator v0.0.0-20200428143746-21a406dcc535 // indirect + github.com/aunum/log v0.0.0-20200821225356-38d2e2c8b489 // indirect github.com/beorn7/perks v1.0.1 // indirect github.com/blang/semver/v4 v4.0.0 // indirect github.com/cenkalti/backoff/v3 v3.0.0 // indirect diff --git a/go.sum b/go.sum index 5bd41a1b05c..428b50f1d97 100644 --- a/go.sum +++ b/go.sum @@ -269,6 +269,7 @@ github.com/exponent-io/jsonpath v0.0.0-20151013193312-d6023ce2651d/go.mod h1:ZZM github.com/fatih/camelcase v1.0.0 h1:hxNvNX/xYBp0ovncs8WyWZrOrpBNub/JfaMvbURyft8= github.com/fatih/camelcase v1.0.0/go.mod h1:yN2Sb0lFhZJUdVvtELVWefmrXpuZESvPmqwoZc+/fpc= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= +github.com/fatih/color v1.9.0/go.mod h1:eQcE1qtQxscV5RaZvpXrrb8Drkc3/DdQ+uUYCNjL+zU= github.com/fatih/color v1.13.0 h1:8LOYc1KYPPmyKMuN8QV2DNRWNbLo6LZ0iLs8+mlH53w= github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk= github.com/fatih/structs v1.1.0 h1:Q7juDM0QtcnhCpeyLGQKyg4TOIghuNXrkL32pHAUMxo= @@ -282,6 +283,7 @@ github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4 github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= github.com/ghodss/yaml v0.0.0-20150909031657-73d445a93680/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= +github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/globalsign/mgo v0.0.0-20180905125535-1ca0a4f7cbcb/go.mod h1:xkRDCp4j0OGD1HRkm4kmhM+pmpv3AKq5SU7GMg4oO/Q= github.com/globalsign/mgo v0.0.0-20181015135952-eeefdecb41b8/go.mod h1:xkRDCp4j0OGD1HRkm4kmhM+pmpv3AKq5SU7GMg4oO/Q= @@ -683,6 +685,7 @@ github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNx github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcMEpPG5Rm84= +github.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOAqxQCu2WE= github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= github.com/mattn/go-isatty v0.0.14 h1:yVuAays6BHfxijgZPzw+3Zlu5yQgKGP2/hcQbHb7S9Y= github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= @@ -1497,6 +1500,7 @@ gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.7/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= diff --git a/hack/k8s-codegen.sh b/hack/k8s-codegen.sh index 4aa3a24dd39..e0f39d3a1ea 100755 --- a/hack/k8s-codegen.sh +++ b/hack/k8s-codegen.sh @@ -59,6 +59,8 @@ deepcopy_inputs=( internal/apis/acme \ pkg/apis/config/webhook/v1alpha1 \ internal/apis/config/webhook \ + pkg/apis/config/controller/v1alpha1 \ + internal/apis/config/controller \ pkg/apis/meta/v1 \ internal/apis/meta \ pkg/webhook/handlers/testdata/apis/testgroup/v2 \ @@ -86,6 +88,7 @@ defaulter_inputs=( internal/apis/acme/v1beta1 \ internal/apis/acme/v1 \ internal/apis/config/webhook/v1alpha1 \ + internal/apis/config/controller/v1alpha1 \ internal/apis/meta/v1 \ pkg/webhook/handlers/testdata/apis/testgroup/v2 \ pkg/webhook/handlers/testdata/apis/testgroup/v1 \ @@ -102,6 +105,7 @@ conversion_inputs=( internal/apis/acme/v1beta1 \ internal/apis/acme/v1 \ internal/apis/config/webhook/v1alpha1 \ + internal/apis/config/controller/v1alpha1 \ internal/apis/meta/v1 \ pkg/webhook/handlers/testdata/apis/testgroup/v2 \ pkg/webhook/handlers/testdata/apis/testgroup/v1 \ diff --git a/internal/apis/config/controller/doc.go b/internal/apis/config/controller/doc.go new file mode 100644 index 00000000000..b65dd808f42 --- /dev/null +++ b/internal/apis/config/controller/doc.go @@ -0,0 +1,21 @@ +/* +Copyright 2021 The cert-manager 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. +*/ + +// +k8s:deepcopy-gen=package,register + +// Package controller is the internal version of the controller config API. +// +groupName=controller.config.cert-manager.io +package controller diff --git a/internal/apis/config/controller/fuzzer/fuzzer.go b/internal/apis/config/controller/fuzzer/fuzzer.go new file mode 100644 index 00000000000..103812db692 --- /dev/null +++ b/internal/apis/config/controller/fuzzer/fuzzer.go @@ -0,0 +1,88 @@ +/* +Copyright 2021 The cert-manager 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 fuzzer + +import ( + fuzz "github.com/google/gofuzz" + runtimeserializer "k8s.io/apimachinery/pkg/runtime/serializer" + "k8s.io/utils/pointer" + + "github.com/cert-manager/cert-manager/internal/apis/config/controller" +) + +// Funcs returns the fuzzer functions for the controller config api group. +var Funcs = func(codecs runtimeserializer.CodecFactory) []interface{} { + return []interface{}{ + func(s *controller.ControllerConfiguration, c fuzz.Continue) { + c.FuzzNoCustom(s) // fuzz self without calling this function again + + // TODO: AcidLeroy: What should we do with these? The install tests seem to be failing randomly. + if s.KubernetesAPIQPS == nil { + s.KubernetesAPIQPS = pointer.Float32(10) + } + if s.KubernetesAPIBurst == nil { + s.KubernetesAPIBurst = pointer.Int(10) + } + if s.Controllers == nil { + s.Controllers = []string{"duh"} + } + if s.LeaderElect == nil { + s.LeaderElect = pointer.Bool(true) + } + if s.ACMEHTTP01SolverNameservers == nil { + s.ACMEHTTP01SolverNameservers = []string{"8.8.8.8:53"} + } + if s.ClusterIssuerAmbientCredentials == nil { + s.ClusterIssuerAmbientCredentials = pointer.Bool(true) + } + if s.IssuerAmbientCredentials == nil { + s.IssuerAmbientCredentials = pointer.Bool(true) + } + if s.DefaultAutoCertificateAnnotations == nil { + s.DefaultAutoCertificateAnnotations = []string{""} + } + if s.ACMEHTTP01SolverRunAsNonRoot == nil { + s.ACMEHTTP01SolverRunAsNonRoot = pointer.Bool(true) + } + if s.DNS01RecursiveNameservers == nil { + s.DNS01RecursiveNameservers = []string{"8.8.8.8:53"} + } + if s.DNS01RecursiveNameserversOnly == nil { + s.DNS01RecursiveNameserversOnly = pointer.Bool(true) + } + if s.CopiedAnnotationPrefixes == nil { + s.CopiedAnnotationPrefixes = []string{"*", "-kubectl.kubernetes.io/", "-fluxcd.io/", "-argocd.argoproj.io/"} + } + if s.EnableCertificateOwnerRef == nil { + s.EnableCertificateOwnerRef = pointer.Bool(true) + } + if s.EnablePprof == nil { + s.EnablePprof = pointer.Bool(true) + } + if s.MaxConcurrentChallenges == nil { + s.MaxConcurrentChallenges = pointer.Int(1) + } + if s.PprofAddress == "" { + s.PprofAddress = "something:1234" + } + if s.FeatureGates == nil { + s.FeatureGates = map[string]bool{"feature": true} + } + + }, + } +} diff --git a/internal/apis/config/controller/install/install.go b/internal/apis/config/controller/install/install.go new file mode 100644 index 00000000000..5836717f8b6 --- /dev/null +++ b/internal/apis/config/controller/install/install.go @@ -0,0 +1,33 @@ +/* +Copyright 2021 The cert-manager 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 install installs the API group, making it available as an option to +// all of the API encoding/decoding machinery. +package install + +import ( + "k8s.io/apimachinery/pkg/runtime" + utilruntime "k8s.io/apimachinery/pkg/util/runtime" + + "github.com/cert-manager/cert-manager/internal/apis/config/controller" + "github.com/cert-manager/cert-manager/internal/apis/config/controller/v1alpha1" +) + +// Install registers the API group and adds types to a scheme +func Install(scheme *runtime.Scheme) { + utilruntime.Must(controller.AddToScheme(scheme)) + utilruntime.Must(v1alpha1.AddToScheme(scheme)) +} diff --git a/internal/apis/config/controller/install/roundtrip_test.go b/internal/apis/config/controller/install/roundtrip_test.go new file mode 100644 index 00000000000..1ef6dc62464 --- /dev/null +++ b/internal/apis/config/controller/install/roundtrip_test.go @@ -0,0 +1,29 @@ +/* +Copyright 2021 The cert-manager 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 install + +import ( + "testing" + + "k8s.io/apimachinery/pkg/api/apitesting/roundtrip" + + configfuzzer "github.com/cert-manager/cert-manager/internal/apis/config/controller/fuzzer" +) + +func TestRoundTripTypes(t *testing.T) { + roundtrip.RoundTripTestForAPIGroup(t, Install, configfuzzer.Funcs) +} diff --git a/internal/apis/config/controller/register.go b/internal/apis/config/controller/register.go new file mode 100644 index 00000000000..d0a4ceb0188 --- /dev/null +++ b/internal/apis/config/controller/register.go @@ -0,0 +1,46 @@ +/* +Copyright 2021 The cert-manager 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 controller + +import ( + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + + "github.com/cert-manager/cert-manager/pkg/apis/config/controller" +) + +var ( + SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes) + AddToScheme = SchemeBuilder.AddToScheme +) + +// SchemeGroupVersion is group version used to register these objects +var SchemeGroupVersion = schema.GroupVersion{Group: controller.GroupName, Version: runtime.APIVersionInternal} + +// Resource takes an unqualified resource and returns a Group qualified GroupResource +func Resource(resource string) schema.GroupResource { + return SchemeGroupVersion.WithResource(resource).GroupResource() +} + +// Adds the list of known types to api.Scheme. +func addKnownTypes(scheme *runtime.Scheme) error { + scheme.AddKnownTypes(SchemeGroupVersion, + &ControllerConfiguration{}, + // Add new kinds to be registered here + ) + return nil +} diff --git a/internal/apis/config/controller/scheme/scheme.go b/internal/apis/config/controller/scheme/scheme.go new file mode 100644 index 00000000000..f2abc05b199 --- /dev/null +++ b/internal/apis/config/controller/scheme/scheme.go @@ -0,0 +1,40 @@ +/* +Copyright 2021 The cert-manager 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 scheme + +import ( + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/serializer" + + config "github.com/cert-manager/cert-manager/internal/apis/config/controller" + configv1alpha1 "github.com/cert-manager/cert-manager/internal/apis/config/controller/v1alpha1" +) + +// NewSchemeAndCodecs is a utility function that returns a Scheme and CodecFactory +// that understand the types in the config.cert-manager.io API group. Passing mutators allows +// for adjusting the behavior of the CodecFactory, for example enable strict decoding. +func NewSchemeAndCodecs(mutators ...serializer.CodecFactoryOptionsMutator) (*runtime.Scheme, *serializer.CodecFactory, error) { + scheme := runtime.NewScheme() + if err := config.AddToScheme(scheme); err != nil { + return nil, nil, err + } + if err := configv1alpha1.AddToScheme(scheme); err != nil { + return nil, nil, err + } + codecs := serializer.NewCodecFactory(scheme, mutators...) + return scheme, &codecs, nil +} diff --git a/internal/apis/config/controller/types.go b/internal/apis/config/controller/types.go new file mode 100644 index 00000000000..e20ed4c0b39 --- /dev/null +++ b/internal/apis/config/controller/types.go @@ -0,0 +1,201 @@ +/* +Copyright 2021 The cert-manager 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 controller + +import ( + "time" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +type ControllerConfiguration struct { + metav1.TypeMeta + + // Optional apiserver host address to connect to. If not specified, + // autoconfiguration will be attempted + APIServerHost string + + // Paths to a kubeconfig. Only required if out-of-cluster. + KubeConfig string + + // Indicates the maximum queries-per-second requests to the Kubernetes apiserver + KubernetesAPIQPS *float32 + + // The maximum burst queries-per-second of requests sent to the Kubernetes apiserver + KubernetesAPIBurst *int + + // Namespace to store resources owned by cluster scoped resources such as ClusterIssuer in. + ClusterResourceNamespace string + + // If set, this limits the scope of cert-manager to a single namespace and + // ClusterIssuers are disabled. If not specified, all namespaces will be + // watched" + Namespace string + + // If true, cert-manager will perform leader election between instances to + // ensure no more than one instance of cert-manager operates at a time + LeaderElect *bool + + //Namespace used to perform leader election. Only used if leader election is enabled + LeaderElectionNamespace string + + // The duration that non-leader candidates will wait after observing a leadership + // renewal until attempting to acquire leadership of a led but unrenewed leader + // slot. This is effectively the maximum duration that a leader can be stopped + // before it is replaced by another candidate. This is only applicable if leader + // election is enabled. + LeaderElectionLeaseDuration time.Duration + + // The interval between attempts by the acting master to renew a leadership slot + // before it stops leading. This must be less than or equal to the lease duration. + // This is only applicable if leader election is enabled. + LeaderElectionRenewDeadline time.Duration + + // The duration the clients should wait between attempting acquisition and renewal + // of a leadership. This is only applicable if leader election is enabled. + LeaderElectionRetryPeriod time.Duration + + // A list of controllers to enable. + // ['*'] enables all controllers, + // ['foo'] enables only the foo controller + // ['*', '-foo'] disables the controller named foo. + Controllers []string + + // HTTP-01 solver pod configuration via flags is a now deprecated + // mechanism- please use pod template instead when adding any new + // configuration options + // https://github.com/cert-manager/cert-manager/blob/f1d7c432763100c3fb6eb6a1654d29060b479b3c/pkg/apis/acme/v1/types_issuer.go#L270 + // These flags however will not be deprecated for backwards compatibility purposes. + // The Docker image to use to solve ACME HTTP01 challenges. You most likely + // will not need to change this parameter unless you are testing a new + // feature or developing cert-manager. + ACMEHTTP01SolverImage string + + // Defines the resource request CPU size when spawning new ACME HTTP01 + // challenge solver pods. + ACMEHTTP01SolverResourceRequestCPU string + + //Defines the resource request Memory size when spawning new ACME HTTP01 + //challenge solver pods. + ACMEHTTP01SolverResourceRequestMemory string + + //Defines the resource limits CPU size when spawning new ACME HTTP01 + //challenge solver pods. + ACMEHTTP01SolverResourceLimitsCPU string + + // Defines the resource limits Memory size when spawning new ACME HTTP01 + // challenge solver pods. + ACMEHTTP01SolverResourceLimitsMemory string + + // Defines the ability to run the http01 solver as root for troubleshooting + // issues + ACMEHTTP01SolverRunAsNonRoot *bool + + // A list of comma separated dns server endpoints used for + // ACME HTTP01 check requests. This should be a list containing host and + // port, for example ["8.8.8.8:53","8.8.4.4:53"] + // Allows specifying a list of custom nameservers to perform HTTP01 checks on. + ACMEHTTP01SolverNameservers []string + + // Whether a cluster-issuer may make use of ambient credentials for issuers. + // 'Ambient Credentials' are credentials drawn from the environment, metadata + // services, or local files which are not explicitly configured in the + // ClusterIssuer API object. When this flag is enabled, the following sources + // for credentials are also used: AWS - All sources the Go SDK defaults to, + // notably including any EC2 IAM roles available via instance metadata. + ClusterIssuerAmbientCredentials *bool + + // Whether an issuer may make use of ambient credentials. 'Ambient + // Credentials' are credentials drawn from the environment, metadata services, + // or local files which are not explicitly configured in the Issuer API + // object. When this flag is enabled, the following sources for + // credentials are also used: AWS - All sources the Go SDK defaults to, + // notably including any EC2 IAM roles available via instance metadata. + IssuerAmbientCredentials *bool + + // Default issuer/certificates details consumed by ingress-shim + // Name of the Issuer to use when the tls is requested but issuer name is + // not specified on the ingress resource. + DefaultIssuerName string + + // Kind of the Issuer to use when the TLS is requested but issuer kind is not + // specified on the ingress resource. + DefaultIssuerKind string + + // Group of the Issuer to use when the TLS is requested but issuer group is + // not specified on the ingress resource. + DefaultIssuerGroup string + + // The annotation consumed by the ingress-shim controller to indicate a ingress + // is requesting a certificate + DefaultAutoCertificateAnnotations []string + + // A list of comma separated dns server endpoints used for + // DNS01 check requests. This should be a list containing host and + // port, for example ["8.8.8.8:53","8.8.4.4:53"] + DNS01RecursiveNameservers []string + + // When true, cert-manager will only ever query the configured DNS resolvers + // to perform the ACME DNS01 self check. This is useful in DNS constrained + // environments, where access to authoritative nameservers is restricted. + // Enabling this option could cause the DNS01 self check to take longer + // due to caching performed by the recursive nameservers. + DNS01RecursiveNameserversOnly *bool + + // Whether to set the certificate resource as an owner of secret where the + // tls certificate is stored. When this flag is enabled, the secret will be + // automatically removed when the certificate resource is deleted. + EnableCertificateOwnerRef *bool + + // The maximum number of challenges that can be scheduled as 'processing' at once. + MaxConcurrentChallenges *int + + // The host and port that the metrics endpoint should listen on. + MetricsListenAddress string + + // The host and port that Go profiler should listen on, i.e localhost:6060. + // Ensure that profiler is not exposed on a public address. Profiler will be + // served at /debug/pprof. + PprofAddress string + // Enable profiling for controller. + EnablePprof *bool + + // The duration the controller should wait between a propagation check. Despite + // the name, this flag is used to configure the wait period for both DNS01 and + // HTTP01 challenge propagation checks. For DNS01 challenges the propagation + // check verifies that a TXT record with the challenge token has been created. + // For HTTP01 challenges the propagation check verifies that the challenge + // token is served at the challenge URL. This should be a valid duration + // string, for example 180s or 1h + DNS01CheckRetryPeriod time.Duration + + // Specify which annotations should/shouldn't be copied from Certificate to + // CertificateRequest and Order, as well as from CertificateSigningRequest to + // Order, by passing a list of annotation key prefixes. A prefix starting with + // a dash(-) specifies an annotation that shouldn't be copied. Example: + // '*,-kubectl.kuberenetes.io/'- all annotations will be copied apart from the + // ones where the key is prefixed with 'kubectl.kubernetes.io/'. + CopiedAnnotationPrefixes []string + + // featureGates is a map of feature names to bools that enable or disable experimental + // features. + // Default: nil + // +optional + FeatureGates map[string]bool +} diff --git a/internal/apis/config/controller/v1alpha1/conversion.go b/internal/apis/config/controller/v1alpha1/conversion.go new file mode 100644 index 00000000000..335956697c5 --- /dev/null +++ b/internal/apis/config/controller/v1alpha1/conversion.go @@ -0,0 +1,17 @@ +/* +Copyright 2021 The cert-manager 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 v1alpha1 diff --git a/internal/apis/config/controller/v1alpha1/defaults.go b/internal/apis/config/controller/v1alpha1/defaults.go new file mode 100644 index 00000000000..fe0c35f287e --- /dev/null +++ b/internal/apis/config/controller/v1alpha1/defaults.go @@ -0,0 +1,300 @@ +/* +Copyright 2021 The cert-manager Authors. + +Licensed under the Apache License, Vo.u 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 v1alpha1 + +import ( + "fmt" + + "k8s.io/apimachinery/pkg/runtime" + + "time" + + cm "github.com/cert-manager/cert-manager/pkg/apis/certmanager" + "github.com/cert-manager/cert-manager/pkg/apis/config/controller/v1alpha1" + challengescontroller "github.com/cert-manager/cert-manager/pkg/controller/acmechallenges" + orderscontroller "github.com/cert-manager/cert-manager/pkg/controller/acmeorders" + shimgatewaycontroller "github.com/cert-manager/cert-manager/pkg/controller/certificate-shim/gateways" + shimingresscontroller "github.com/cert-manager/cert-manager/pkg/controller/certificate-shim/ingresses" + cracmecontroller "github.com/cert-manager/cert-manager/pkg/controller/certificaterequests/acme" + crapprovercontroller "github.com/cert-manager/cert-manager/pkg/controller/certificaterequests/approver" + crcacontroller "github.com/cert-manager/cert-manager/pkg/controller/certificaterequests/ca" + crselfsignedcontroller "github.com/cert-manager/cert-manager/pkg/controller/certificaterequests/selfsigned" + crvaultcontroller "github.com/cert-manager/cert-manager/pkg/controller/certificaterequests/vault" + crvenaficontroller "github.com/cert-manager/cert-manager/pkg/controller/certificaterequests/venafi" + "github.com/cert-manager/cert-manager/pkg/controller/certificates/issuing" + "github.com/cert-manager/cert-manager/pkg/controller/certificates/keymanager" + certificatesmetricscontroller "github.com/cert-manager/cert-manager/pkg/controller/certificates/metrics" + "github.com/cert-manager/cert-manager/pkg/controller/certificates/readiness" + "github.com/cert-manager/cert-manager/pkg/controller/certificates/requestmanager" + "github.com/cert-manager/cert-manager/pkg/controller/certificates/revisionmanager" + "github.com/cert-manager/cert-manager/pkg/controller/certificates/trigger" + csracmecontroller "github.com/cert-manager/cert-manager/pkg/controller/certificatesigningrequests/acme" + csrcacontroller "github.com/cert-manager/cert-manager/pkg/controller/certificatesigningrequests/ca" + csrselfsignedcontroller "github.com/cert-manager/cert-manager/pkg/controller/certificatesigningrequests/selfsigned" + csrvaultcontroller "github.com/cert-manager/cert-manager/pkg/controller/certificatesigningrequests/vault" + csrvenaficontroller "github.com/cert-manager/cert-manager/pkg/controller/certificatesigningrequests/venafi" + clusterissuerscontroller "github.com/cert-manager/cert-manager/pkg/controller/clusterissuers" + issuerscontroller "github.com/cert-manager/cert-manager/pkg/controller/issuers" + "github.com/cert-manager/cert-manager/pkg/util" +) + +var ( + defaultAPIServerHost = "" + defaultKubeconfig = "" + defaultKubernetesAPIQPS float32 = 20 + defaultKubernetesAPIBurst = 50 + + defaultClusterResourceNamespace = "kube-system" + defaultNamespace = "" + + defaultLeaderElect = true + defaultLeaderElectionNamespace = "kube-system" + defaultLeaderElectionLeaseDuration = 60 * time.Second + defaultLeaderElectionRenewDeadline = 40 * time.Second + defaultLeaderElectionRetryPeriod = 15 * time.Second + + defaultEnableProfiling = false + defaultProfilerAddr = "localhost:6060" + + defaultClusterIssuerAmbientCredentials = true + defaultIssuerAmbientCredentials = false + + defaultTLSACMEIssuerName = "" + defaultTLSACMEIssuerKind = "Issuer" + defaultTLSACMEIssuerGroup = cm.GroupName + defaultEnableCertificateOwnerRef = false + + defaultDNS01RecursiveNameserversOnly = false + defaultDNS01RecursiveNameservers = []string{} + + defaultMaxConcurrentChallenges = 60 + + defaultPrometheusMetricsServerAddress = "0.0.0.0:9402" + + // default time period to wait between checking DNS01 and HTTP01 challenge propagation + defaultDNS01CheckRetryPeriod = 10 * time.Second + defaultACMEHTTP01SolverImage = fmt.Sprintf("quay.io/jetstack/cert-manager-acmesolver:%s", util.AppVersion) + defaultACMEHTTP01SolverResourceRequestCPU = "10m" + defaultACMEHTTP01SolverResourceRequestMemory = "64Mi" + defaultACMEHTTP01SolverResourceLimitsCPU = "100m" + defaultACMEHTTP01SolverResourceLimitsMemory = "64Mi" + defaultACMEHTTP01SolverRunAsNonRoot = true + defaultACMEHTTP01SolverNameservers = []string{} + + defaultAutoCertificateAnnotations = []string{"kubernetes.io/tls-acme"} + + AllControllers = []string{ + issuerscontroller.ControllerName, + clusterissuerscontroller.ControllerName, + certificatesmetricscontroller.ControllerName, + shimingresscontroller.ControllerName, + shimgatewaycontroller.ControllerName, + orderscontroller.ControllerName, + challengescontroller.ControllerName, + cracmecontroller.CRControllerName, + crapprovercontroller.ControllerName, + crcacontroller.CRControllerName, + crselfsignedcontroller.CRControllerName, + crvaultcontroller.CRControllerName, + crvenaficontroller.CRControllerName, + // certificate controllers + trigger.ControllerName, + issuing.ControllerName, + keymanager.ControllerName, + requestmanager.ControllerName, + readiness.ControllerName, + revisionmanager.ControllerName, + } + + DefaultEnabledControllers = []string{ + issuerscontroller.ControllerName, + clusterissuerscontroller.ControllerName, + certificatesmetricscontroller.ControllerName, + shimingresscontroller.ControllerName, + orderscontroller.ControllerName, + challengescontroller.ControllerName, + cracmecontroller.CRControllerName, + crapprovercontroller.ControllerName, + crcacontroller.CRControllerName, + crselfsignedcontroller.CRControllerName, + crvaultcontroller.CRControllerName, + crvenaficontroller.CRControllerName, + // certificate controllers + trigger.ControllerName, + issuing.ControllerName, + keymanager.ControllerName, + requestmanager.ControllerName, + readiness.ControllerName, + revisionmanager.ControllerName, + } + + ExperimentalCertificateSigningRequestControllers = []string{ + csracmecontroller.CSRControllerName, + csrcacontroller.CSRControllerName, + csrselfsignedcontroller.CSRControllerName, + csrvenaficontroller.CSRControllerName, + csrvaultcontroller.CSRControllerName, + } + + // Annotations that will be copied from Certificate to CertificateRequest and to Order. + // By default, copy all annotations except for the ones applied by kubectl, fluxcd, argocd. + defaultCopiedAnnotationPrefixes = []string{ + "*", + "-kubectl.kubernetes.io/", + "-fluxcd.io/", + "-argocd.argoproj.io/", + } +) + +func addDefaultingFuncs(scheme *runtime.Scheme) error { + return RegisterDefaults(scheme) +} + +func SetDefaults_ControllerConfiguration(obj *v1alpha1.ControllerConfiguration) { + if obj.APIServerHost == "" { + obj.APIServerHost = defaultAPIServerHost + } + + if obj.KubeConfig == "" { + obj.KubeConfig = defaultKubeconfig + } + + if obj.KubernetesAPIQPS == nil { + obj.KubernetesAPIQPS = &defaultKubernetesAPIQPS + } + + if obj.KubernetesAPIBurst == nil { + obj.KubernetesAPIBurst = &defaultKubernetesAPIBurst + } + + if obj.ClusterResourceNamespace == "" { + obj.ClusterResourceNamespace = defaultClusterResourceNamespace + } + + if obj.Namespace == "" { + obj.Namespace = defaultNamespace + } + + if obj.LeaderElect == nil { + obj.LeaderElect = &defaultLeaderElect + } + + if obj.LeaderElectionNamespace == "" { + obj.LeaderElectionNamespace = defaultLeaderElectionNamespace + } + + // TODO: Does it make sense to have a duration of 0? + if obj.LeaderElectionLeaseDuration == time.Duration(0) { + obj.LeaderElectionLeaseDuration = defaultLeaderElectionLeaseDuration + } + + if obj.LeaderElectionRenewDeadline == time.Duration(0) { + obj.LeaderElectionRenewDeadline = defaultLeaderElectionRenewDeadline + } + + if obj.LeaderElectionRetryPeriod == time.Duration(0) { + obj.LeaderElectionRetryPeriod = defaultLeaderElectionRetryPeriod + } + + if len(obj.Controllers) == 0 { + obj.Controllers = []string{"*"} + } + + if obj.ACMEHTTP01SolverImage == "" { + obj.ACMEHTTP01SolverImage = defaultACMEHTTP01SolverImage + } + + if obj.ACMEHTTP01SolverResourceRequestCPU == "" { + obj.ACMEHTTP01SolverResourceRequestCPU = defaultACMEHTTP01SolverResourceRequestCPU + } + + if obj.ACMEHTTP01SolverResourceRequestMemory == "" { + obj.ACMEHTTP01SolverResourceRequestMemory = defaultACMEHTTP01SolverResourceRequestMemory + } + + if obj.ACMEHTTP01SolverResourceLimitsCPU == "" { + obj.ACMEHTTP01SolverResourceLimitsCPU = defaultACMEHTTP01SolverResourceLimitsCPU + } + + if obj.ACMEHTTP01SolverResourceLimitsMemory == "" { + obj.ACMEHTTP01SolverResourceLimitsMemory = defaultACMEHTTP01SolverResourceLimitsMemory + } + + if obj.ACMEHTTP01SolverRunAsNonRoot == nil { + obj.ACMEHTTP01SolverRunAsNonRoot = &defaultACMEHTTP01SolverRunAsNonRoot + } + + if len(obj.ACMEHTTP01SolverNameservers) == 0 { + obj.ACMEHTTP01SolverNameservers = defaultACMEHTTP01SolverNameservers + } + + if obj.ClusterIssuerAmbientCredentials == nil { + obj.ClusterIssuerAmbientCredentials = &defaultClusterIssuerAmbientCredentials + } + + if obj.IssuerAmbientCredentials == nil { + obj.IssuerAmbientCredentials = &defaultIssuerAmbientCredentials + } + + if obj.DefaultIssuerName == "" { + obj.DefaultIssuerName = defaultTLSACMEIssuerName + } + + if obj.DefaultIssuerKind == "" { + obj.DefaultIssuerKind = defaultTLSACMEIssuerKind + } + + if obj.DefaultIssuerGroup == "" { + obj.DefaultIssuerGroup = defaultTLSACMEIssuerGroup + } + + if len(obj.DefaultAutoCertificateAnnotations) == 0 { + obj.DefaultAutoCertificateAnnotations = defaultAutoCertificateAnnotations + } + + if len(obj.DNS01RecursiveNameservers) == 0 { + obj.DNS01RecursiveNameservers = defaultDNS01RecursiveNameservers + } + + if obj.EnableCertificateOwnerRef == nil { + obj.EnableCertificateOwnerRef = &defaultEnableCertificateOwnerRef + } + + if obj.DNS01RecursiveNameserversOnly == nil { + obj.DNS01RecursiveNameserversOnly = &defaultDNS01RecursiveNameserversOnly + } + + if obj.MaxConcurrentChallenges == nil { + obj.MaxConcurrentChallenges = &defaultMaxConcurrentChallenges + } + + if obj.MetricsListenAddress == "" { + obj.MetricsListenAddress = defaultPrometheusMetricsServerAddress + } + + if obj.EnablePprof == nil { + obj.EnablePprof = &defaultEnableProfiling + } + + if obj.PprofAddress == "" { + obj.PprofAddress = defaultProfilerAddr + + } + + if len(obj.CopiedAnnotationPrefixes) == 0 { + obj.CopiedAnnotationPrefixes = defaultCopiedAnnotationPrefixes + } +} diff --git a/internal/apis/config/controller/v1alpha1/doc.go b/internal/apis/config/controller/v1alpha1/doc.go new file mode 100644 index 00000000000..4a7f9fe7ed1 --- /dev/null +++ b/internal/apis/config/controller/v1alpha1/doc.go @@ -0,0 +1,23 @@ +/* +Copyright 2021 The cert-manager 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. +*/ + +// +k8s:conversion-gen=github.com/cert-manager/cert-manager/internal/apis/config/controller +// +k8s:conversion-gen-external-types=github.com/cert-manager/cert-manager/pkg/apis/config/controller/v1alpha1 +// +k8s:defaulter-gen=TypeMeta +// +k8s:defaulter-gen-input=github.com/cert-manager/cert-manager/pkg/apis/config/controller/v1alpha1 + +// +groupName=controller.config.cert-manager.io +package v1alpha1 diff --git a/internal/apis/config/controller/v1alpha1/register.go b/internal/apis/config/controller/v1alpha1/register.go new file mode 100644 index 00000000000..b054e3f36df --- /dev/null +++ b/internal/apis/config/controller/v1alpha1/register.go @@ -0,0 +1,44 @@ +/* +Copyright 2021 The cert-manager 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 v1alpha1 + +import ( + "k8s.io/apimachinery/pkg/runtime/schema" + + "github.com/cert-manager/cert-manager/pkg/apis/config/controller" + "github.com/cert-manager/cert-manager/pkg/apis/config/controller/v1alpha1" +) + +// SchemeGroupVersion is group version used to register these objects +var SchemeGroupVersion = schema.GroupVersion{Group: controller.GroupName, Version: "v1alpha1"} + +// Resource takes an unqualified resource and returns a Group qualified GroupResource +func Resource(resource string) schema.GroupResource { + return SchemeGroupVersion.WithResource(resource).GroupResource() +} + +var ( + localSchemeBuilder = &v1alpha1.SchemeBuilder + AddToScheme = localSchemeBuilder.AddToScheme +) + +func init() { + // We only register manually written functions here. The registration of the + // generated functions takes place in the generated files. The separation + // makes the code compile even when the generated files are missing. + localSchemeBuilder.Register(addDefaultingFuncs) +} diff --git a/internal/apis/config/controller/v1alpha1/zz_generated.conversion.go b/internal/apis/config/controller/v1alpha1/zz_generated.conversion.go new file mode 100644 index 00000000000..ed6ced50bab --- /dev/null +++ b/internal/apis/config/controller/v1alpha1/zz_generated.conversion.go @@ -0,0 +1,140 @@ +//go:build !ignore_autogenerated +// +build !ignore_autogenerated + +/* +Copyright The cert-manager 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. +*/ + +// Code generated by conversion-gen. DO NOT EDIT. + +package v1alpha1 + +import ( + time "time" + unsafe "unsafe" + + controller "github.com/cert-manager/cert-manager/internal/apis/config/controller" + v1alpha1 "github.com/cert-manager/cert-manager/pkg/apis/config/controller/v1alpha1" + conversion "k8s.io/apimachinery/pkg/conversion" + runtime "k8s.io/apimachinery/pkg/runtime" +) + +func init() { + localSchemeBuilder.Register(RegisterConversions) +} + +// RegisterConversions adds conversion functions to the given scheme. +// Public to allow building arbitrary schemes. +func RegisterConversions(s *runtime.Scheme) error { + if err := s.AddGeneratedConversionFunc((*v1alpha1.ControllerConfiguration)(nil), (*controller.ControllerConfiguration)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1alpha1_ControllerConfiguration_To_controller_ControllerConfiguration(a.(*v1alpha1.ControllerConfiguration), b.(*controller.ControllerConfiguration), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*controller.ControllerConfiguration)(nil), (*v1alpha1.ControllerConfiguration)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_controller_ControllerConfiguration_To_v1alpha1_ControllerConfiguration(a.(*controller.ControllerConfiguration), b.(*v1alpha1.ControllerConfiguration), scope) + }); err != nil { + return err + } + return nil +} + +func autoConvert_v1alpha1_ControllerConfiguration_To_controller_ControllerConfiguration(in *v1alpha1.ControllerConfiguration, out *controller.ControllerConfiguration, s conversion.Scope) error { + out.APIServerHost = in.APIServerHost + out.KubeConfig = in.KubeConfig + out.KubernetesAPIQPS = (*float32)(unsafe.Pointer(in.KubernetesAPIQPS)) + out.KubernetesAPIBurst = (*int)(unsafe.Pointer(in.KubernetesAPIBurst)) + out.ClusterResourceNamespace = in.ClusterResourceNamespace + out.Namespace = in.Namespace + out.LeaderElect = (*bool)(unsafe.Pointer(in.LeaderElect)) + out.LeaderElectionNamespace = in.LeaderElectionNamespace + out.LeaderElectionLeaseDuration = time.Duration(in.LeaderElectionLeaseDuration) + out.LeaderElectionRenewDeadline = time.Duration(in.LeaderElectionRenewDeadline) + out.LeaderElectionRetryPeriod = time.Duration(in.LeaderElectionRetryPeriod) + out.Controllers = *(*[]string)(unsafe.Pointer(&in.Controllers)) + out.ACMEHTTP01SolverImage = in.ACMEHTTP01SolverImage + out.ACMEHTTP01SolverResourceRequestCPU = in.ACMEHTTP01SolverResourceRequestCPU + out.ACMEHTTP01SolverResourceRequestMemory = in.ACMEHTTP01SolverResourceRequestMemory + out.ACMEHTTP01SolverResourceLimitsCPU = in.ACMEHTTP01SolverResourceLimitsCPU + out.ACMEHTTP01SolverResourceLimitsMemory = in.ACMEHTTP01SolverResourceLimitsMemory + out.ACMEHTTP01SolverRunAsNonRoot = (*bool)(unsafe.Pointer(in.ACMEHTTP01SolverRunAsNonRoot)) + out.ACMEHTTP01SolverNameservers = *(*[]string)(unsafe.Pointer(&in.ACMEHTTP01SolverNameservers)) + out.ClusterIssuerAmbientCredentials = (*bool)(unsafe.Pointer(in.ClusterIssuerAmbientCredentials)) + out.IssuerAmbientCredentials = (*bool)(unsafe.Pointer(in.IssuerAmbientCredentials)) + out.DefaultIssuerName = in.DefaultIssuerName + out.DefaultIssuerKind = in.DefaultIssuerKind + out.DefaultIssuerGroup = in.DefaultIssuerGroup + out.DefaultAutoCertificateAnnotations = *(*[]string)(unsafe.Pointer(&in.DefaultAutoCertificateAnnotations)) + out.DNS01RecursiveNameservers = *(*[]string)(unsafe.Pointer(&in.DNS01RecursiveNameservers)) + out.DNS01RecursiveNameserversOnly = (*bool)(unsafe.Pointer(in.DNS01RecursiveNameserversOnly)) + out.EnableCertificateOwnerRef = (*bool)(unsafe.Pointer(in.EnableCertificateOwnerRef)) + out.MaxConcurrentChallenges = (*int)(unsafe.Pointer(in.MaxConcurrentChallenges)) + out.MetricsListenAddress = in.MetricsListenAddress + out.PprofAddress = in.PprofAddress + out.EnablePprof = (*bool)(unsafe.Pointer(in.EnablePprof)) + out.DNS01CheckRetryPeriod = time.Duration(in.DNS01CheckRetryPeriod) + out.CopiedAnnotationPrefixes = *(*[]string)(unsafe.Pointer(&in.CopiedAnnotationPrefixes)) + out.FeatureGates = *(*map[string]bool)(unsafe.Pointer(&in.FeatureGates)) + return nil +} + +// Convert_v1alpha1_ControllerConfiguration_To_controller_ControllerConfiguration is an autogenerated conversion function. +func Convert_v1alpha1_ControllerConfiguration_To_controller_ControllerConfiguration(in *v1alpha1.ControllerConfiguration, out *controller.ControllerConfiguration, s conversion.Scope) error { + return autoConvert_v1alpha1_ControllerConfiguration_To_controller_ControllerConfiguration(in, out, s) +} + +func autoConvert_controller_ControllerConfiguration_To_v1alpha1_ControllerConfiguration(in *controller.ControllerConfiguration, out *v1alpha1.ControllerConfiguration, s conversion.Scope) error { + out.APIServerHost = in.APIServerHost + out.KubeConfig = in.KubeConfig + out.KubernetesAPIQPS = (*float32)(unsafe.Pointer(in.KubernetesAPIQPS)) + out.KubernetesAPIBurst = (*int)(unsafe.Pointer(in.KubernetesAPIBurst)) + out.ClusterResourceNamespace = in.ClusterResourceNamespace + out.Namespace = in.Namespace + out.LeaderElect = (*bool)(unsafe.Pointer(in.LeaderElect)) + out.LeaderElectionNamespace = in.LeaderElectionNamespace + out.LeaderElectionLeaseDuration = time.Duration(in.LeaderElectionLeaseDuration) + out.LeaderElectionRenewDeadline = time.Duration(in.LeaderElectionRenewDeadline) + out.LeaderElectionRetryPeriod = time.Duration(in.LeaderElectionRetryPeriod) + out.Controllers = *(*[]string)(unsafe.Pointer(&in.Controllers)) + out.ACMEHTTP01SolverImage = in.ACMEHTTP01SolverImage + out.ACMEHTTP01SolverResourceRequestCPU = in.ACMEHTTP01SolverResourceRequestCPU + out.ACMEHTTP01SolverResourceRequestMemory = in.ACMEHTTP01SolverResourceRequestMemory + out.ACMEHTTP01SolverResourceLimitsCPU = in.ACMEHTTP01SolverResourceLimitsCPU + out.ACMEHTTP01SolverResourceLimitsMemory = in.ACMEHTTP01SolverResourceLimitsMemory + out.ACMEHTTP01SolverRunAsNonRoot = (*bool)(unsafe.Pointer(in.ACMEHTTP01SolverRunAsNonRoot)) + out.ACMEHTTP01SolverNameservers = *(*[]string)(unsafe.Pointer(&in.ACMEHTTP01SolverNameservers)) + out.ClusterIssuerAmbientCredentials = (*bool)(unsafe.Pointer(in.ClusterIssuerAmbientCredentials)) + out.IssuerAmbientCredentials = (*bool)(unsafe.Pointer(in.IssuerAmbientCredentials)) + out.DefaultIssuerName = in.DefaultIssuerName + out.DefaultIssuerKind = in.DefaultIssuerKind + out.DefaultIssuerGroup = in.DefaultIssuerGroup + out.DefaultAutoCertificateAnnotations = *(*[]string)(unsafe.Pointer(&in.DefaultAutoCertificateAnnotations)) + out.DNS01RecursiveNameservers = *(*[]string)(unsafe.Pointer(&in.DNS01RecursiveNameservers)) + out.DNS01RecursiveNameserversOnly = (*bool)(unsafe.Pointer(in.DNS01RecursiveNameserversOnly)) + out.EnableCertificateOwnerRef = (*bool)(unsafe.Pointer(in.EnableCertificateOwnerRef)) + out.MaxConcurrentChallenges = (*int)(unsafe.Pointer(in.MaxConcurrentChallenges)) + out.MetricsListenAddress = in.MetricsListenAddress + out.PprofAddress = in.PprofAddress + out.EnablePprof = (*bool)(unsafe.Pointer(in.EnablePprof)) + out.DNS01CheckRetryPeriod = time.Duration(in.DNS01CheckRetryPeriod) + out.CopiedAnnotationPrefixes = *(*[]string)(unsafe.Pointer(&in.CopiedAnnotationPrefixes)) + out.FeatureGates = *(*map[string]bool)(unsafe.Pointer(&in.FeatureGates)) + return nil +} + +// Convert_controller_ControllerConfiguration_To_v1alpha1_ControllerConfiguration is an autogenerated conversion function. +func Convert_controller_ControllerConfiguration_To_v1alpha1_ControllerConfiguration(in *controller.ControllerConfiguration, out *v1alpha1.ControllerConfiguration, s conversion.Scope) error { + return autoConvert_controller_ControllerConfiguration_To_v1alpha1_ControllerConfiguration(in, out, s) +} diff --git a/internal/apis/config/controller/v1alpha1/zz_generated.defaults.go b/internal/apis/config/controller/v1alpha1/zz_generated.defaults.go new file mode 100644 index 00000000000..3b429dee22f --- /dev/null +++ b/internal/apis/config/controller/v1alpha1/zz_generated.defaults.go @@ -0,0 +1,41 @@ +//go:build !ignore_autogenerated +// +build !ignore_autogenerated + +/* +Copyright The cert-manager 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. +*/ + +// Code generated by defaulter-gen. DO NOT EDIT. + +package v1alpha1 + +import ( + v1alpha1 "github.com/cert-manager/cert-manager/pkg/apis/config/controller/v1alpha1" + runtime "k8s.io/apimachinery/pkg/runtime" +) + +// RegisterDefaults adds defaulters functions to the given scheme. +// Public to allow building arbitrary schemes. +// All generated defaulters are covering - they call all nested defaulters. +func RegisterDefaults(scheme *runtime.Scheme) error { + scheme.AddTypeDefaultingFunc(&v1alpha1.ControllerConfiguration{}, func(obj interface{}) { + SetObjectDefaults_ControllerConfiguration(obj.(*v1alpha1.ControllerConfiguration)) + }) + return nil +} + +func SetObjectDefaults_ControllerConfiguration(in *v1alpha1.ControllerConfiguration) { + SetDefaults_ControllerConfiguration(in) +} diff --git a/internal/apis/config/controller/validation/validation.go b/internal/apis/config/controller/validation/validation.go new file mode 100644 index 00000000000..6e345916a1d --- /dev/null +++ b/internal/apis/config/controller/validation/validation.go @@ -0,0 +1,70 @@ +/* +Copyright 2021 The cert-manager 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 validation + +import ( + "fmt" + "net" + "strings" + + utilerrors "k8s.io/apimachinery/pkg/util/errors" + "k8s.io/apimachinery/pkg/util/sets" + + config "github.com/cert-manager/cert-manager/internal/apis/config/controller" + defaults "github.com/cert-manager/cert-manager/internal/apis/config/controller/v1alpha1" +) + +func ValidateControllerConfiguration(o *config.ControllerConfiguration) error { + var allErrors []error + if len(o.DefaultIssuerKind) == 0 { + allErrors = append(allErrors, fmt.Errorf("the --default-issuer-kind must not be empty")) + } + + if *o.KubernetesAPIBurst <= 0 { + allErrors = append(allErrors, fmt.Errorf("invalid value for kube-api-burst: %v must be higher than 0", o.KubernetesAPIBurst)) + } + + if *o.KubernetesAPIQPS <= 0 { + allErrors = append(allErrors, fmt.Errorf("invalid value for kube-api-qps: %v must be higher than 0", o.KubernetesAPIQPS)) + } + + if float32(*o.KubernetesAPIBurst) < *o.KubernetesAPIQPS { + allErrors = append(allErrors, fmt.Errorf("invalid value for kube-api-burst: %v must be higher or equal to kube-api-qps: %v", o.KubernetesAPIQPS, o.KubernetesAPIQPS)) + } + + for _, server := range append(o.DNS01RecursiveNameservers, o.ACMEHTTP01SolverNameservers...) { + // ensure all servers have a port number + _, _, err := net.SplitHostPort(server) + if err != nil { + allErrors = append(allErrors, fmt.Errorf("invalid DNS server (%v): %v", err, server)) + } + } + + allControllersSet := sets.NewString(defaults.AllControllers...) + for _, controller := range o.Controllers { + if controller == "*" { + continue + } + + controller = strings.TrimPrefix(controller, "-") + if !allControllersSet.Has(controller) { + allErrors = append(allErrors, fmt.Errorf("%q is not in the list of known controllers", controller)) + } + } + + return utilerrors.NewAggregate(allErrors) +} diff --git a/internal/apis/config/controller/zz_generated.deepcopy.go b/internal/apis/config/controller/zz_generated.deepcopy.go new file mode 100644 index 00000000000..19698ec5afb --- /dev/null +++ b/internal/apis/config/controller/zz_generated.deepcopy.go @@ -0,0 +1,133 @@ +//go:build !ignore_autogenerated +// +build !ignore_autogenerated + +/* +Copyright The cert-manager 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. +*/ + +// Code generated by deepcopy-gen. DO NOT EDIT. + +package controller + +import ( + runtime "k8s.io/apimachinery/pkg/runtime" +) + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ControllerConfiguration) DeepCopyInto(out *ControllerConfiguration) { + *out = *in + out.TypeMeta = in.TypeMeta + if in.KubernetesAPIQPS != nil { + in, out := &in.KubernetesAPIQPS, &out.KubernetesAPIQPS + *out = new(float32) + **out = **in + } + if in.KubernetesAPIBurst != nil { + in, out := &in.KubernetesAPIBurst, &out.KubernetesAPIBurst + *out = new(int) + **out = **in + } + if in.LeaderElect != nil { + in, out := &in.LeaderElect, &out.LeaderElect + *out = new(bool) + **out = **in + } + if in.Controllers != nil { + in, out := &in.Controllers, &out.Controllers + *out = make([]string, len(*in)) + copy(*out, *in) + } + if in.ACMEHTTP01SolverRunAsNonRoot != nil { + in, out := &in.ACMEHTTP01SolverRunAsNonRoot, &out.ACMEHTTP01SolverRunAsNonRoot + *out = new(bool) + **out = **in + } + if in.ACMEHTTP01SolverNameservers != nil { + in, out := &in.ACMEHTTP01SolverNameservers, &out.ACMEHTTP01SolverNameservers + *out = make([]string, len(*in)) + copy(*out, *in) + } + if in.ClusterIssuerAmbientCredentials != nil { + in, out := &in.ClusterIssuerAmbientCredentials, &out.ClusterIssuerAmbientCredentials + *out = new(bool) + **out = **in + } + if in.IssuerAmbientCredentials != nil { + in, out := &in.IssuerAmbientCredentials, &out.IssuerAmbientCredentials + *out = new(bool) + **out = **in + } + if in.DefaultAutoCertificateAnnotations != nil { + in, out := &in.DefaultAutoCertificateAnnotations, &out.DefaultAutoCertificateAnnotations + *out = make([]string, len(*in)) + copy(*out, *in) + } + if in.DNS01RecursiveNameservers != nil { + in, out := &in.DNS01RecursiveNameservers, &out.DNS01RecursiveNameservers + *out = make([]string, len(*in)) + copy(*out, *in) + } + if in.DNS01RecursiveNameserversOnly != nil { + in, out := &in.DNS01RecursiveNameserversOnly, &out.DNS01RecursiveNameserversOnly + *out = new(bool) + **out = **in + } + if in.EnableCertificateOwnerRef != nil { + in, out := &in.EnableCertificateOwnerRef, &out.EnableCertificateOwnerRef + *out = new(bool) + **out = **in + } + if in.MaxConcurrentChallenges != nil { + in, out := &in.MaxConcurrentChallenges, &out.MaxConcurrentChallenges + *out = new(int) + **out = **in + } + if in.EnablePprof != nil { + in, out := &in.EnablePprof, &out.EnablePprof + *out = new(bool) + **out = **in + } + if in.CopiedAnnotationPrefixes != nil { + in, out := &in.CopiedAnnotationPrefixes, &out.CopiedAnnotationPrefixes + *out = make([]string, len(*in)) + copy(*out, *in) + } + if in.FeatureGates != nil { + in, out := &in.FeatureGates, &out.FeatureGates + *out = make(map[string]bool, len(*in)) + for key, val := range *in { + (*out)[key] = val + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ControllerConfiguration. +func (in *ControllerConfiguration) DeepCopy() *ControllerConfiguration { + if in == nil { + return nil + } + out := new(ControllerConfiguration) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ControllerConfiguration) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} diff --git a/pkg/apis/config/controller/doc.go b/pkg/apis/config/controller/doc.go new file mode 100644 index 00000000000..80f0a61e463 --- /dev/null +++ b/pkg/apis/config/controller/doc.go @@ -0,0 +1,22 @@ +/* +Copyright 2021 The cert-manager 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. +*/ + +// +groupName=controller.config.cert-manager.io + +// Package controller contains types used to configure the controller +package controller + +const GroupName = "controller.config.cert-manager.io" diff --git a/pkg/apis/config/controller/v1alpha1/doc.go b/pkg/apis/config/controller/v1alpha1/doc.go new file mode 100644 index 00000000000..1188713651d --- /dev/null +++ b/pkg/apis/config/controller/v1alpha1/doc.go @@ -0,0 +1,20 @@ +/* +Copyright 2021 The cert-manager 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 v1alpha1 is the v1alpha1 version of the controller config API. +// +k8s:deepcopy-gen=package,register +// +groupName=controller.config.cert-manager.io +package v1alpha1 diff --git a/pkg/apis/config/controller/v1alpha1/register.go b/pkg/apis/config/controller/v1alpha1/register.go new file mode 100644 index 00000000000..5f50b785ffc --- /dev/null +++ b/pkg/apis/config/controller/v1alpha1/register.go @@ -0,0 +1,56 @@ +/* +Copyright 2021 The cert-manager 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 v1alpha1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + + "github.com/cert-manager/cert-manager/pkg/apis/config/controller" +) + +// SchemeGroupVersion is group version used to register these objects +var SchemeGroupVersion = schema.GroupVersion{Group: controller.GroupName, Version: "v1alpha1"} + +// Resource takes an unqualified resource and returns a Group qualified GroupResource +func Resource(resource string) schema.GroupResource { + return SchemeGroupVersion.WithResource(resource).GroupResource() +} + +var ( + SchemeBuilder runtime.SchemeBuilder + localSchemeBuilder = &SchemeBuilder + AddToScheme = localSchemeBuilder.AddToScheme +) + +func init() { + // We only register manually written functions here. The registration of the + // generated functions takes place in the generated files. The separation + // makes the code compile even when the generated files are missing. + localSchemeBuilder.Register(addKnownTypes) +} + +// Adds the list of known types to api.Scheme. +func addKnownTypes(scheme *runtime.Scheme) error { + scheme.AddKnownTypes(SchemeGroupVersion, + &ControllerConfiguration{}, + // Add new kinds to be registered here + ) + metav1.AddToGroupVersion(scheme, SchemeGroupVersion) + return nil +} diff --git a/pkg/apis/config/controller/v1alpha1/types.go b/pkg/apis/config/controller/v1alpha1/types.go new file mode 100644 index 00000000000..5476aaecc81 --- /dev/null +++ b/pkg/apis/config/controller/v1alpha1/types.go @@ -0,0 +1,196 @@ +/* +Copyright 2021 The cert-manager 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 v1alpha1 + +import ( + "time" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +type ControllerConfiguration struct { + metav1.TypeMeta `json:",inline"` + + // Optional apiserver host address to connect to. If not specified, + // autoconfiguration will be attempted + APIServerHost string `json:"apiServerHost,omitempty"` + + // Paths to a kubeconfig. Only required if out-of-cluster. + KubeConfig string `json:"kubeConfig,omitempty"` + + // Indicates the maximum queries-per-second requests to the Kubernetes apiserver + KubernetesAPIQPS *float32 `json:"kubernetesAPIQPS,omitempty"` + + // The maximum burst queries-per-second of requests sent to the Kubernetes apiserver + KubernetesAPIBurst *int `json:"kubernetesAPIBurst,omitempty"` + + // Namespace to store resources owned by cluster scoped resources such as ClusterIssuer in. + ClusterResourceNamespace string `json:"clusterResourceNamespace,omitempty"` + + // If set, this limits the scope of cert-manager to a single namespace and + // ClusterIssuers are disabled. If not specified, all namespaces will be + // watched" + Namespace string `json:"namespace,omitempty"` + + // If true, cert-manager will perform leader election between instances to + // ensure no more than one instance of cert-manager operates at a time + LeaderElect *bool `json:"leaderElect,omitempty"` + + //Namespace used to perform leader election. Only used if leader election is enabled + LeaderElectionNamespace string `json:"leaderElectionNamespace,omitempty"` + + // The duration that non-leader candidates will wait after observing a leadership + // renewal until attempting to acquire leadership of a led but unrenewed leader + // slot. This is effectively the maximum duration that a leader can be stopped + // before it is replaced by another candidate. This is only applicable if leader + // election is enabled. + LeaderElectionLeaseDuration time.Duration `json:"leaderElectionLeaseDuration,omitempty"` + + // The interval between attempts by the acting master to renew a leadership slot + // before it stops leading. This must be less than or equal to the lease duration. + // This is only applicable if leader election is enabled. + LeaderElectionRenewDeadline time.Duration `json:"leaderElectionRenewDeadline,omitempty"` + + // The duration the clients should wait between attempting acquisition and renewal + // of a leadership. This is only applicable if leader election is enabled. + LeaderElectionRetryPeriod time.Duration `json:"leaderElectionRetryPeriod,omitempty"` + + // A list of controllers to enable. + // ['*'] enables all controllers, + // ['foo'] enables only the foo controller + // ['*', '-foo'] disables the controller named foo. + Controllers []string `json:"controllers,omitempty"` + + // The Docker image to use to solve ACME HTTP01 challenges. You most likely + // will not need to change this parameter unless you are testing a new + // feature or developing cert-manager. + ACMEHTTP01SolverImage string `json:"acmeHTTP01SolverImage,omitempty"` + + // Defines the resource request CPU size when spawning new ACME HTTP01 + // challenge solver pods. + ACMEHTTP01SolverResourceRequestCPU string `json:"acmeHTTP01SolverResourceRequestCPU,omitempty"` + + //Defines the resource request Memory size when spawning new ACME HTTP01 + //challenge solver pods. + ACMEHTTP01SolverResourceRequestMemory string `json:"acmeHTTP01SolverResourceRequestMemory,omitempty"` + + //Defines the resource limits CPU size when spawning new ACME HTTP01 + //challenge solver pods. + ACMEHTTP01SolverResourceLimitsCPU string `json:"acmeHTTP01SolverResourceLimitsCPU,omitempty"` + + // Defines the resource limits Memory size when spawning new ACME HTTP01 + // challenge solver pods. + ACMEHTTP01SolverResourceLimitsMemory string `json:"acmeHTTP01SolverResourceLimitsMemory,omitempty"` + + // Defines the ability to run the http01 solver as root for troubleshooting + // issues + ACMEHTTP01SolverRunAsNonRoot *bool `json:"acmeHTTP01SolverRunAsNonRoot,omitempty"` + + // A list of comma separated dns server endpoints used for + // ACME HTTP01 check requests. This should be a list containing host and + // port, for example ["8.8.8.8:53","8.8.4.4:53"] + // Allows specifying a list of custom nameservers to perform HTTP01 checks on. + ACMEHTTP01SolverNameservers []string `json:"acmeHTTP01SolverNameservers,omitempty"` + + // Whether a cluster-issuer may make use of ambient credentials for issuers. + // 'Ambient Credentials' are credentials drawn from the environment, metadata + // services, or local files which are not explicitly configured in the + // ClusterIssuer API object. When this flag is enabled, the following sources + // for credentials are also used: AWS - All sources the Go SDK defaults to, + // notably including any EC2 IAM roles available via instance metadata. + ClusterIssuerAmbientCredentials *bool `json:"clusterIssuerAmbientCredentials,omitempty"` + + // Whether an issuer may make use of ambient credentials. 'Ambient + // Credentials' are credentials drawn from the environment, metadata services, + // or local files which are not explicitly configured in the Issuer API + // object. When this flag is enabled, the following sources for + // credentials are also used: AWS - All sources the Go SDK defaults to, + // notably including any EC2 IAM roles available via instance metadata. + IssuerAmbientCredentials *bool `json:"issuerAmbientCredentials,omitempty"` + + // Default issuer/certificates details consumed by ingress-shim + // Name of the Issuer to use when the tls is requested but issuer name is + // not specified on the ingress resource. + DefaultIssuerName string `json:"defaultIssuerName,omitempty"` + + // Kind of the Issuer to use when the TLS is requested but issuer kind is not + // specified on the ingress resource. + DefaultIssuerKind string `json:"defaultIssuerKind,omitempty"` + + // Group of the Issuer to use when the TLS is requested but issuer group is + // not specified on the ingress resource. + DefaultIssuerGroup string `json:"defaultIssuerGroup,omitempty"` + + // The annotation consumed by the ingress-shim controller to indicate a ingress + // is requesting a certificate + DefaultAutoCertificateAnnotations []string `json:"defaultAutoCertificateAnnotations,omitempty"` + + // A list of comma separated dns server endpoints used for + // DNS01 check requests. This should be a list containing host and + // port, for example ["8.8.8.8:53","8.8.4.4:53"] + DNS01RecursiveNameservers []string `json:"dns01RecursiveNameservers,omitempty"` + + // When true, cert-manager will only ever query the configured DNS resolvers + // to perform the ACME DNS01 self check. This is useful in DNS constrained + // environments, where access to authoritative nameservers is restricted. + // Enabling this option could cause the DNS01 self check to take longer + // due to caching performed by the recursive nameservers. + DNS01RecursiveNameserversOnly *bool `json:"dns01RecursiveNameserversOnly,omitempty"` + + // Whether to set the certificate resource as an owner of secret where the + // tls certificate is stored. When this flag is enabled, the secret will be + // automatically removed when the certificate resource is deleted. + EnableCertificateOwnerRef *bool `json:"enableCertificateOwnerRef,omitempty"` + + // The maximum number of challenges that can be scheduled as 'processing' at once. + MaxConcurrentChallenges *int `json:"maxConcurrentChallenges,omitempty"` + + // The host and port that the metrics endpoint should listen on. + MetricsListenAddress string `json:"metricsListenAddress,omitempty"` + + // The host and port that Go profiler should listen on, i.e localhost:6060. + // Ensure that profiler is not exposed on a public address. Profiler will be + // served at /debug/pprof. + PprofAddress string `json:"pprofAddress,omitempty"` + // Enable profiling for controller. + EnablePprof *bool `json:"enablePprof"` + + // The duration the controller should wait between a propagation check. Despite + // the name, this flag is used to configure the wait period for both DNS01 and + // HTTP01 challenge propagation checks. For DNS01 challenges the propagation + // check verifies that a TXT record with the challenge token has been created. + // For HTTP01 challenges the propagation check verifies that the challenge + // token is served at the challenge URL. This should be a valid duration + // string, for example 180s or 1h + DNS01CheckRetryPeriod time.Duration `json:"dns01CheckRetryPeriod,omitempty"` + + // Specify which annotations should/shouldn't be copied from Certificate to + // CertificateRequest and Order, as well as from CertificateSigningRequest to + // Order, by passing a list of annotation key prefixes. A prefix starting with + // a dash(-) specifies an annotation that shouldn't be copied. Example: + // '*,-kubectl.kuberenetes.io/'- all annotations will be copied apart from the + // ones where the key is prefixed with 'kubectl.kubernetes.io/'. + CopiedAnnotationPrefixes []string `json:"copiedAnnotationPrefixes,omitempty"` + + // featureGates is a map of feature names to bools that enable or disable experimental + // features. + // Default: nil + // +optional + FeatureGates map[string]bool `json:"featureGates,omitempty"` +} diff --git a/pkg/apis/config/controller/v1alpha1/zz_generated.deepcopy.go b/pkg/apis/config/controller/v1alpha1/zz_generated.deepcopy.go new file mode 100644 index 00000000000..be64bbb2a2f --- /dev/null +++ b/pkg/apis/config/controller/v1alpha1/zz_generated.deepcopy.go @@ -0,0 +1,133 @@ +//go:build !ignore_autogenerated +// +build !ignore_autogenerated + +/* +Copyright The cert-manager 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. +*/ + +// Code generated by deepcopy-gen. DO NOT EDIT. + +package v1alpha1 + +import ( + runtime "k8s.io/apimachinery/pkg/runtime" +) + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ControllerConfiguration) DeepCopyInto(out *ControllerConfiguration) { + *out = *in + out.TypeMeta = in.TypeMeta + if in.KubernetesAPIQPS != nil { + in, out := &in.KubernetesAPIQPS, &out.KubernetesAPIQPS + *out = new(float32) + **out = **in + } + if in.KubernetesAPIBurst != nil { + in, out := &in.KubernetesAPIBurst, &out.KubernetesAPIBurst + *out = new(int) + **out = **in + } + if in.LeaderElect != nil { + in, out := &in.LeaderElect, &out.LeaderElect + *out = new(bool) + **out = **in + } + if in.Controllers != nil { + in, out := &in.Controllers, &out.Controllers + *out = make([]string, len(*in)) + copy(*out, *in) + } + if in.ACMEHTTP01SolverRunAsNonRoot != nil { + in, out := &in.ACMEHTTP01SolverRunAsNonRoot, &out.ACMEHTTP01SolverRunAsNonRoot + *out = new(bool) + **out = **in + } + if in.ACMEHTTP01SolverNameservers != nil { + in, out := &in.ACMEHTTP01SolverNameservers, &out.ACMEHTTP01SolverNameservers + *out = make([]string, len(*in)) + copy(*out, *in) + } + if in.ClusterIssuerAmbientCredentials != nil { + in, out := &in.ClusterIssuerAmbientCredentials, &out.ClusterIssuerAmbientCredentials + *out = new(bool) + **out = **in + } + if in.IssuerAmbientCredentials != nil { + in, out := &in.IssuerAmbientCredentials, &out.IssuerAmbientCredentials + *out = new(bool) + **out = **in + } + if in.DefaultAutoCertificateAnnotations != nil { + in, out := &in.DefaultAutoCertificateAnnotations, &out.DefaultAutoCertificateAnnotations + *out = make([]string, len(*in)) + copy(*out, *in) + } + if in.DNS01RecursiveNameservers != nil { + in, out := &in.DNS01RecursiveNameservers, &out.DNS01RecursiveNameservers + *out = make([]string, len(*in)) + copy(*out, *in) + } + if in.DNS01RecursiveNameserversOnly != nil { + in, out := &in.DNS01RecursiveNameserversOnly, &out.DNS01RecursiveNameserversOnly + *out = new(bool) + **out = **in + } + if in.EnableCertificateOwnerRef != nil { + in, out := &in.EnableCertificateOwnerRef, &out.EnableCertificateOwnerRef + *out = new(bool) + **out = **in + } + if in.MaxConcurrentChallenges != nil { + in, out := &in.MaxConcurrentChallenges, &out.MaxConcurrentChallenges + *out = new(int) + **out = **in + } + if in.EnablePprof != nil { + in, out := &in.EnablePprof, &out.EnablePprof + *out = new(bool) + **out = **in + } + if in.CopiedAnnotationPrefixes != nil { + in, out := &in.CopiedAnnotationPrefixes, &out.CopiedAnnotationPrefixes + *out = make([]string, len(*in)) + copy(*out, *in) + } + if in.FeatureGates != nil { + in, out := &in.FeatureGates, &out.FeatureGates + *out = make(map[string]bool, len(*in)) + for key, val := range *in { + (*out)[key] = val + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ControllerConfiguration. +func (in *ControllerConfiguration) DeepCopy() *ControllerConfiguration { + if in == nil { + return nil + } + out := new(ControllerConfiguration) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ControllerConfiguration) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} diff --git a/pkg/controller/configfile/configfile.go b/pkg/controller/configfile/configfile.go new file mode 100644 index 00000000000..616b5cbbdf8 --- /dev/null +++ b/pkg/controller/configfile/configfile.go @@ -0,0 +1,39 @@ +/* +Copyright 2021 The cert-manager 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 configfile + +import ( + "fmt" + + config "github.com/cert-manager/cert-manager/internal/apis/config/controller" +) + +type Any = interface{} + +// ControllerConfigurationPathRefs returns pointers to all the ControllerConfiguration fields that contain filepaths. +// You might use this, for example, to resolve all relative paths against some common root before +// passing the configuration to the application. This method must be kept up to date as new fields are added. +func ControllerConfigurationPathRefs(cfg Any) ([]*string, error) { + c, ok := cfg.(*config.ControllerConfiguration) + if !ok { + return nil, fmt.Errorf("failed to cast object to ControllerConfiguration, unexpected type") + } + + return []*string{ + &c.KubeConfig, + }, nil +} diff --git a/pkg/util/configfile/configfile.go b/pkg/util/configfile/configfile.go new file mode 100644 index 00000000000..1266a5f5310 --- /dev/null +++ b/pkg/util/configfile/configfile.go @@ -0,0 +1,106 @@ +/* +Copyright 2021 The cert-manager 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 configfile + +import ( + "fmt" + "io/ioutil" + "path/filepath" + + "k8s.io/apimachinery/pkg/runtime/serializer" +) + +type configurationFSLoader struct { + readFileFunc func(filename string) ([]byte, error) + configurationPathRefsFunc func(decodedConfiguration Any) ([]*string, error) + codec *serializer.CodecFactory + filename string +} + +type Any = interface{} + +func (f *configurationFSLoader) Load() (Any, error) { + data, err := f.readFileFunc(f.filename) + if err != nil { + return nil, fmt.Errorf("failed to read config file %q, error: %v", f.filename, err) + } + + if len(data) == 0 { + return nil, fmt.Errorf("config file %q was empty", f.filename) + } + + cfg, err := f.decodeConfiguration(data) + if err != nil { + return nil, err + } + + // make all paths absolute + paths, err := f.configurationPathRefsFunc(cfg) + if err != nil { + return nil, err + } + resolveRelativePaths(paths, filepath.Dir(f.filename)) + return cfg, nil +} + +func NewConfigurationFSLoader(readFileFunc func(filename string) ([]byte, error), pathRefFunc func(decodedConfiguration Any) ([]*string, error), codec *serializer.CodecFactory, filename string) (*configurationFSLoader, error) { + var f func(string) ([]byte, error) + + // Default the readfile function to use ioutil.Readfile for convenience. + if readFileFunc == nil { + f = func(filename string) ([]byte, error) { + return ioutil.ReadFile(filename) + } + } else { + f = readFileFunc + } + + // If function is nil, then we default it to use empty paths. + // TODO: Maybe this should be an error instead? + if pathRefFunc == nil { + pathRefFunc = func(decodedConfiguration Any) ([]*string, error) { + return []*string{}, nil + } + } + + return &configurationFSLoader{ + readFileFunc: f, + configurationPathRefsFunc: pathRefFunc, + codec: codec, + filename: filename, + }, nil +} + +func resolveRelativePaths(paths []*string, root string) { + for _, path := range paths { + // leave empty paths alone, "no path" is a valid input + // do not attempt to resolve paths that are already absolute + if len(*path) > 0 && !filepath.IsAbs(*path) { + *path = filepath.Join(root, *path) + } + } +} + +func (f *configurationFSLoader) decodeConfiguration(data []byte) (Any, error) { + obj, _, err := f.codec.UniversalDecoder().Decode(data, nil, nil) + if err != nil { + return nil, fmt.Errorf("failed to decode: %w", err) + } + + return obj, nil + +} diff --git a/pkg/webhook/configfile/configfile_test.go b/pkg/util/configfile/configfile_test.go similarity index 67% rename from pkg/webhook/configfile/configfile_test.go rename to pkg/util/configfile/configfile_test.go index 475960b30b7..f8b21f20314 100644 --- a/pkg/webhook/configfile/configfile_test.go +++ b/pkg/util/configfile/configfile_test.go @@ -19,13 +19,23 @@ package configfile import ( "fmt" "testing" + + config "github.com/cert-manager/cert-manager/internal/apis/config/webhook" + "github.com/cert-manager/cert-manager/internal/apis/config/webhook/scheme" + "github.com/cert-manager/cert-manager/pkg/webhook/configfile" + "k8s.io/apimachinery/pkg/runtime/serializer" ) func TestFSLoader_Load(t *testing.T) { const expectedFilename = "/path/to/config/file" const kubeConfigPath = "path/to/kubeconfig/file" - loader, err := NewFSLoader(newFakeFS(func(filename string) ([]byte, error) { + _, webhookCodec, err := scheme.NewSchemeAndCodecs(serializer.EnableStrict) + if err != nil { + t.Fatal(err) + } + + loader, err := NewConfigurationFSLoader(func(filename string) ([]byte, error) { if filename != expectedFilename { t.Fatalf("unexpected filename %q passed to ReadFile", filename) return nil, fmt.Errorf("unexpected filename %q", filename) @@ -33,31 +43,25 @@ func TestFSLoader_Load(t *testing.T) { return []byte(fmt.Sprintf(`apiVersion: webhook.config.cert-manager.io/v1alpha1 kind: WebhookConfiguration kubeConfig: %s`, kubeConfigPath)), nil - }), expectedFilename) + }, configfile.WebhookConfigurationPathRefs, webhookCodec, expectedFilename) if err != nil { t.Fatal(err) } - cfg, err := loader.Load() + obj, err := loader.Load() + if err != nil { t.Fatal(err) } + cfg, ok := obj.(*config.WebhookConfiguration) + if !ok { + t.Errorf("Failed to cast Loaded object as a webhookConfiguration") + } + // the config loader will force paths to be 'absolute' if they are provided as relative. absKubeConfigPath := "/path/to/config/path/to/kubeconfig/file" if cfg.KubeConfig != absKubeConfigPath { t.Errorf("expected kubeConfig to be set to %q but got %q", absKubeConfigPath, cfg.KubeConfig) } } - -func newFakeFS(readFileFunc func(string) ([]byte, error)) Filesystem { - return fakeFS{readFileFunc: readFileFunc} -} - -type fakeFS struct { - readFileFunc func(string) ([]byte, error) -} - -func (f fakeFS) ReadFile(filename string) ([]byte, error) { - return f.readFileFunc(filename) -} diff --git a/pkg/webhook/configfile/configfile.go b/pkg/webhook/configfile/configfile.go index 102a88ba7d6..35847c129ed 100644 --- a/pkg/webhook/configfile/configfile.go +++ b/pkg/webhook/configfile/configfile.go @@ -18,107 +18,24 @@ package configfile import ( "fmt" - "io/ioutil" - "path/filepath" - - "k8s.io/apimachinery/pkg/runtime/serializer" config "github.com/cert-manager/cert-manager/internal/apis/config/webhook" - "github.com/cert-manager/cert-manager/internal/apis/config/webhook/scheme" ) -// Filesystem is an interface used to mock out calls to ReadFile -type Filesystem interface { - ReadFile(filename string) ([]byte, error) -} - -type realFS struct{} - -func (fs realFS) ReadFile(filename string) ([]byte, error) { - return ioutil.ReadFile(filename) -} - -// NewRealFS builds a Filesystem that wraps around `ioutil.ReadFile`. -func NewRealFS() Filesystem { - return realFS{} -} - -type Loader interface { - Load() (*config.WebhookConfiguration, error) -} - -type fsLoader struct { - fs Filesystem - filename string - codec *serializer.CodecFactory -} - -var _ Loader = &fsLoader{} - -func (f *fsLoader) Load() (*config.WebhookConfiguration, error) { - data, err := f.fs.ReadFile(f.filename) - if err != nil { - return nil, fmt.Errorf("failed to read webhook config file %q, error: %v", f.filename, err) - } - - if len(data) == 0 { - return nil, fmt.Errorf("webhook config file %q was empty", f.filename) - } - - cfg, err := decodeWebhookConfiguration(f.codec, data) - if err != nil { - return nil, err - } - - // make all paths absolute - resolveRelativePaths(webhookConfigurationPathRefs(cfg), filepath.Dir(f.filename)) - return cfg, nil -} - -func NewFSLoader(fs Filesystem, name string) (Loader, error) { - _, webhookCodec, err := scheme.NewSchemeAndCodecs(serializer.EnableStrict) - if err != nil { - return nil, err - } - - return &fsLoader{ - fs: fs, - filename: name, - codec: webhookCodec, - }, nil -} - -func resolveRelativePaths(paths []*string, root string) { - for _, path := range paths { - // leave empty paths alone, "no path" is a valid input - // do not attempt to resolve paths that are already absolute - if len(*path) > 0 && !filepath.IsAbs(*path) { - *path = filepath.Join(root, *path) - } - } -} - -func decodeWebhookConfiguration(codec *serializer.CodecFactory, data []byte) (*config.WebhookConfiguration, error) { - obj, gvk, err := codec.UniversalDecoder().Decode(data, nil, nil) - if err != nil { - return nil, fmt.Errorf("failed to decode: %w", err) - } - - internalObj, ok := obj.(*config.WebhookConfiguration) - if !ok { - return nil, fmt.Errorf("failed to cast object to WebhookConfiguration, unexpected type: %v", gvk) - } - - return internalObj, nil -} +type Any = interface{} // webhookConfigurationPathRefs returns pointers to all the WebhookConfiguration fields that contain filepaths. // You might use this, for example, to resolve all relative paths against some common root before // passing the configuration to the application. This method must be kept up to date as new fields are added. -func webhookConfigurationPathRefs(cfg *config.WebhookConfiguration) []*string { - return []*string{ - &cfg.TLSConfig.Filesystem.KeyFile, - &cfg.TLSConfig.Filesystem.CertFile, - &cfg.KubeConfig, +func WebhookConfigurationPathRefs(cfg Any) ([]*string, error) { + c, ok := cfg.(*config.WebhookConfiguration) + if !ok { + return nil, fmt.Errorf("failed to cast object to WebhookConfiguration, unexpected type") } + + return []*string{ + &c.TLSConfig.Filesystem.KeyFile, + &c.TLSConfig.Filesystem.CertFile, + &c.KubeConfig, + }, nil }