diff --git a/.dockerignore b/.dockerignore index a3aab7a..7c6643f 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,3 +1,4 @@ # More info: https://docs.docker.com/engine/reference/builder/#dockerignore-file # Ignore build and test binaries. bin/ +dist/ diff --git a/.github/workflows/lint.yaml b/.github/workflows/lint.yaml new file mode 100644 index 0000000..4d05dd1 --- /dev/null +++ b/.github/workflows/lint.yaml @@ -0,0 +1,32 @@ +name: Lint + +permissions: + contents: read + +on: + push: + branches: + - main + pull_request: + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + lint: + name: Lint + runs-on: ubuntu-latest + steps: + - name: Checkout Repository + uses: actions/checkout@v4 + - name: Set Up Go + uses: actions/setup-go@v5 + with: + go-version-file: go.mod + cache-dependency-path: go.sum + - name: golangci-lint + uses: golangci/golangci-lint-action@v4 + with: + args: --timeout=30m --verbose + skip-cache: true diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml new file mode 100644 index 0000000..631c79c --- /dev/null +++ b/.github/workflows/release.yaml @@ -0,0 +1,37 @@ +name: Release + +permissions: {} + +on: + push: + tags: + - 'v*' + +jobs: + release: + runs-on: ubuntu-latest + permissions: + contents: write + id-token: write + packages: write + pull-requests: write + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 + - name: Set up Go + uses: actions/setup-go@v4 + with: + go-version-file: go.mod + cache-dependency-path: go.sum + - name: Install Syft + uses: anchore/sbom-action/download-syft@v0 + - name: Run GoReleaser + uses: goreleaser/goreleaser-action@v5 + with: + distribution: goreleaser + version: latest + args: release --clean --timeout 90m + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.gitignore b/.gitignore index 7a7feec..897eefd 100644 --- a/.gitignore +++ b/.gitignore @@ -6,6 +6,7 @@ *.so *.dylib bin/* +dist/* Dockerfile.cross # Test binary, built with `go test -c` diff --git a/.golangci.yml b/.golangci.yml index aed8644..ca69a11 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,5 +1,5 @@ run: - deadline: 5m + timeout: 5m allow-parallel-runners: true issues: diff --git a/.goreleaser.yaml b/.goreleaser.yaml new file mode 100644 index 0000000..88e27ea --- /dev/null +++ b/.goreleaser.yaml @@ -0,0 +1,118 @@ +project_name: kubedns-shepherd + +before: + hooks: + - go mod tidy + +builds: + - id: kubedns-shepherd + binary: kubedns-shepherd + main: cmd/main.go + env: + - CGO_ENABLED=0 + flags: + - -trimpath + ldflags: + - -s -w -X main.version={{ .Version }} -X main.commit={{ .Commit }} -X main.date={{ .CommitDate }} -X main.treeState={{ .IsGitDirty }} -X main.builtBy=goreleaser + goos: + - linux + goarch: + - amd64 + - arm64 + mod_timestamp: '{{ .CommitTimestamp }}' + +kos: + - build: kubedns-shepherd + main: ./cmd/... + base_image: ghcr.io/distroless/static:latest + repository: ghcr.io/eminaktas/kubedns-shepherd + tags: + - '{{ .Tag }}' + - '{{ if not .Prerelease }}latest{{ end }}' + bare: true + preserve_import_paths: false + base_import_paths: false + sbom: none + platforms: + - linux/amd64 + - linux/arm64 + labels: + io.artifacthub.package.readme-url: "https://raw.githubusercontent.com/eminaktas/kubedns-shepherd/main/README.md" + io.artifacthub.package.maintainers: '[{"name":"Emin Aktas","email":""}]' + io.artifacthub.package.license: "Apache-2.0" + org.opencontainers.image.description: "A Kubernetes controller that manages the DNS configuration for workloads" + org.opencontainers.image.created: "{{ .Date }}" + org.opencontainers.image.name: "{{ .ProjectName }}" + org.opencontainers.image.revision: "{{ .FullCommit }}" + org.opencontainers.image.version: "{{ .Version }}" + org.opencontainers.image.source: "{{ .GitURL }}" + +archives: + - name_template: >- + {{- .ProjectName }}_ + {{- title .Os }}_ + {{- if eq .Arch "amd64" }}x86_64 + {{- else if eq .Arch "386" }}i386 + {{- else }}{{ .Arch }}{{ end }} + {{- if .Arm }}v{{ .Arm }}{{ end -}} + format_overrides: + - goos: windows + format: zip + builds_info: + group: root + owner: root + files: + - README.md + - LICENSE + +sboms: + - artifacts: archive + +checksum: + name_template: "checksums.txt" + +snapshot: + name_template: "{{ incpatch .Version }}-next" + +changelog: + sort: asc + use: github + filters: + exclude: + - "^test:" + - "^test\\(" + - "^chore" + - "merge conflict" + - Merge pull request + - Merge remote-tracking branch + - Merge branch + - go mod tidy + groups: + - title: Dependency updates + regexp: '^.*?(feat|fix|chore)\(deps\)!?:.+$' + order: 300 + - title: "New Features" + regexp: '^.*?feat(\(.+\))??!?:.+$' + order: 100 + - title: "Security updates" + regexp: '^.*?sec(\(.+\))??!?:.+$' + order: 150 + - title: "Bug fixes" + regexp: '^.*?(fix|refactor)(\(.+\))??!?:.+$' + order: 200 + - title: "Documentation updates" + regexp: ^.*?docs?(\(.+\))??!?:.+$ + order: 400 + - title: "Build process updates" + regexp: ^.*?(build|ci)(\(.+\))??!?:.+$ + order: 400 + - title: Other work + order: 9999 + +release: + prerelease: auto + name_template: "v{{ .Version }}" + footer: | + **Full Changelog**: https://github.com/eminaktas/kubedns-shepherd/compare/{{ .PreviousTag }}...{{ .Tag }} + + **Container Image**: ghcr.io/eminaktas/kubedns-shepherd:{{ .Tag }} diff --git a/Dockerfile b/Dockerfile index b078298..a48973e 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,5 +1,5 @@ # Build the manager binary -FROM golang:1.20 AS builder +FROM golang:1.22 AS builder ARG TARGETOS ARG TARGETARCH diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. diff --git a/README.md b/README.md index c00a3b3..f4e6122 100644 --- a/README.md +++ b/README.md @@ -1,26 +1,19 @@ -# kubedns-shepherd -// TODO(user): Add simple overview of use/purpose +# KubeDNS Shepherd -## Description -// TODO(user): An in-depth paragraph about your project and overview of use +KubeDNS Shepherd is a Kubernetes controller that manages the DNS configuration of workloads, ensuring efficient and reliable way to configure DNS within your Kubernetes cluster. ## Getting Started -### Prerequisites -- go version v1.20.0+ -- docker version 17.03+. -- kubectl version v1.11.3+. -- Access to a Kubernetes v1.11.3+ cluster. - ### To Deploy on the cluster + **Build and push your image to the location specified by `IMG`:** ```sh make docker-build docker-push IMG=/kubedns-shepherd:tag ``` -**NOTE:** This image ought to be published in the personal registry you specified. -And it is required to have access to pull the image from the working environment. +**NOTE:** This image ought to be published in the personal registry you specified. +And it is required to have access to pull the image from the working environment. Make sure you have the proper permission to the registry if the above commands don’t work. **Install the CRDs into the cluster:** @@ -48,6 +41,7 @@ kubectl apply -k config/samples/ >**NOTE**: Ensure that the samples has default values to test it out. ### To Uninstall + **Delete the instances (CRs) from the cluster:** ```sh @@ -67,7 +61,6 @@ make undeploy ``` ## Contributing -// TODO(user): Add detailed information on how you would like others to contribute to this project **NOTE:** Run `make help` for more information on all potential `make` targets @@ -75,17 +68,4 @@ More information can be found via the [Kubebuilder Documentation](https://book.k ## License -Copyright 2024. - -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. - +This project is licensed under the [Apache-2.0 License](LICENSE). diff --git a/api/v1alpha1/dnsclass_webhook.go b/api/v1alpha1/dnsclass_webhook.go index 1776e78..16aa15f 100644 --- a/api/v1alpha1/dnsclass_webhook.go +++ b/api/v1alpha1/dnsclass_webhook.go @@ -64,27 +64,25 @@ var allowedDNSPolicies = []string{string(corev1.DNSClusterFirst), string(corev1. // ValidateCreate implements webhook.Validator so a webhook will be registered for the type func (r *DNSClass) ValidateCreate() (admission.Warnings, error) { dnsclasslog.Info("validate create", "name", r.Name) - - if !slices.Contains(allowedDNSPolicies, r.Spec.ResetDNSPolicyTo) { - return nil, fmt.Errorf("%s is not allowed for resetDNSPolicyTo. Allowed DNS Policies: %v", r.Spec.ResetDNSPolicyTo, allowedDNSPolicies) - } - return nil, nil + return r.validate() } // ValidateUpdate implements webhook.Validator so a webhook will be registered for the type func (r *DNSClass) ValidateUpdate(old runtime.Object) (admission.Warnings, error) { dnsclasslog.Info("validate update", "name", r.Name) - - if !slices.Contains(allowedDNSPolicies, r.Spec.ResetDNSPolicyTo) { - return nil, fmt.Errorf("%s is not allowed for resetDNSPolicyTo. Allowed DNS Policies: %v", r.Spec.ResetDNSPolicyTo, allowedDNSPolicies) - } - return nil, nil + return r.validate() } // ValidateDelete implements webhook.Validator so a webhook will be registered for the type func (r *DNSClass) ValidateDelete() (admission.Warnings, error) { dnsclasslog.Info("validate delete", "name", r.Name) - // Not used. return nil, nil } + +func (r *DNSClass) validate() (admission.Warnings, error) { + if !slices.Contains(allowedDNSPolicies, r.Spec.ResetDNSPolicyTo) { + return nil, fmt.Errorf("%s is not allowed for resetDNSPolicyTo. Allowed DNS Policies: %v", r.Spec.ResetDNSPolicyTo, allowedDNSPolicies) + } + return nil, nil +} diff --git a/cmd/art.txt b/cmd/art.txt new file mode 100644 index 0000000..a523766 --- /dev/null +++ b/cmd/art.txt @@ -0,0 +1,6 @@ + _ __ _ ____ _ _ ____ ____ _ _ _ +| |/ / _| |__ ___| _ \| \ | / ___| / ___|| |__ ___ _ __ | |__ ___ _ __ __| | +| ' / | | | '_ \ / _ \ | | | \| \___ \ ____\___ \| '_ \ / _ \ '_ \| '_ \ / _ \ '__/ _` | +| . \ |_| | |_) | __/ |_| | |\ |___) |_____|__) | | | | __/ |_) | | | | __/ | | (_| | +|_|\_\__,_|_.__/ \___|____/|_| \_|____/ |____/|_| |_|\___| .__/|_| |_|\___|_| \__,_| + |_| diff --git a/cmd/main.go b/cmd/main.go index 1f7710d..b7c7f96 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -19,12 +19,15 @@ package main import ( "crypto/tls" "flag" + "fmt" "os" + _ "embed" // Import all Kubernetes client auth plugins (e.g. Azure, GCP, OIDC, etc.) // to ensure that exec-entrypoint and run can make use of them. _ "k8s.io/client-go/plugin/pkg/client/auth" + goversion "github.com/caarlos0/go-version" "k8s.io/apimachinery/pkg/runtime" utilruntime "k8s.io/apimachinery/pkg/util/runtime" clientgoscheme "k8s.io/client-go/kubernetes/scheme" @@ -42,6 +45,12 @@ import ( var ( scheme = runtime.NewScheme() setupLog = ctrl.Log.WithName("setup") + + version = "" + commit = "" + treeState = "" + date = "" + builtBy = "" ) func init() { @@ -52,6 +61,7 @@ func init() { } func main() { + var printVersion bool var metricsAddr string var enableLeaderElection bool var probeAddr string @@ -60,6 +70,7 @@ func main() { var disablePodReconciling bool var maxConcurrentReconcilesForPodsReconciler int var maxConcurrentReconcilesForDNSClassReconciler int + flag.BoolVar(&printVersion, "version", false, "Prints the version") flag.StringVar(&metricsAddr, "metrics-bind-address", ":8080", "The address the metric endpoint binds to.") flag.StringVar(&probeAddr, "health-probe-bind-address", ":8081", "The address the probe endpoint binds to.") flag.BoolVar(&enableLeaderElection, "leader-elect", false, @@ -70,21 +81,25 @@ func main() { flag.BoolVar(&enableHTTP2, "enable-http2", false, "If set, HTTP/2 will be enabled for the metrics and webhook servers") flag.BoolVar(&disablePodReconciling, "disable-pod-reconciling", false, - "If set, disables dynamic DNS configuration for pods without owner references."+ + "If set, disables dynamic DNS configuration for pods without owner references. "+ "This prevents potential data loss if the controller restarts or is removed "+ "while working on a pod object, due to limitations in updating pod resources.") flag.IntVar(&maxConcurrentReconcilesForPodsReconciler, "max-concurrent-reconciles-for-pods-reconciler", 4, "Specifies the maximum number of concurrent reconciles for the Pods reconciler.") flag.IntVar(&maxConcurrentReconcilesForDNSClassReconciler, "max-concurrent-reconciles-for-dnsclass-reconciler", 2, "Specifies the maximum number of concurrent reconciles for the DNSClass reconciler.") - opts := zap.Options{ - Development: true, - } + opts := zap.Options{} opts.BindFlags(flag.CommandLine) flag.Parse() ctrl.SetLogger(zap.New(zap.UseFlagOptions(&opts))) + if printVersion { + buildVersion := buildVersion() + fmt.Println(buildVersion.String()) + os.Exit(0) + } + // if the enable-http2 flag is false (the default), http/2 should be disabled // due to its vulnerabilities. More specifically, disabling http/2 will // prevent from being vulnerable to the HTTP/2 Stream Cancelation and @@ -106,7 +121,10 @@ func main() { }) if disablePodReconciling { - setupLog.Info("disablePodReconciling is enabled. Disabled dynamic DNS configuration for pods without owner references") + setupLog.Info( + "disablePodReconciling is enabled. Disabled dynamic DNS configuration " + + "for pods without owner references", + ) } mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{ @@ -177,3 +195,35 @@ func main() { os.Exit(1) } } + +const website = "https://github.com/eminaktas/kubedns-shepherd" + +//go:embed "art.txt" +var asciiArt string + +func buildVersion() goversion.Info { + return goversion.GetVersionInfo( + goversion.WithAppDetails( + "kubedns-shepherd", + "A Kubernetes controller that manages the DNS configuration for workloads", + website), + goversion.WithASCIIName(asciiArt), + func(i *goversion.Info) { + if commit != "" { + i.GitCommit = commit + } + if treeState != "" { + i.GitTreeState = treeState + } + if date != "" { + i.BuildDate = date + } + if version != "" { + i.GitVersion = version + } + if builtBy != "" { + i.BuiltBy = builtBy + } + }, + ) +} diff --git a/config/crd/kustomization.yaml b/config/crd/kustomization.yaml index d5b4dc9..93fd691 100644 --- a/config/crd/kustomization.yaml +++ b/config/crd/kustomization.yaml @@ -13,7 +13,7 @@ patches: # [CERTMANAGER] To enable cert-manager, uncomment all the sections with [CERTMANAGER] prefix. # patches here are for enabling the CA injection for each CRD -#- path: patches/cainjection_in_dnsclasses.yaml +- path: patches/cainjection_in_dnsclasses.yaml #+kubebuilder:scaffold:crdkustomizecainjectionpatch # [WEBHOOK] To enable webhook, uncomment the following section diff --git a/config/default/kustomization.yaml b/config/default/kustomization.yaml index 72fdc81..8be1c19 100644 --- a/config/default/kustomization.yaml +++ b/config/default/kustomization.yaml @@ -22,7 +22,7 @@ resources: # crd/kustomization.yaml - ../webhook # [CERTMANAGER] To enable cert-manager, uncomment all sections with 'CERTMANAGER'. 'WEBHOOK' components are required. -#- ../certmanager +- ../certmanager # [PROMETHEUS] To enable prometheus monitor, uncomment all sections with 'PROMETHEUS'. #- ../prometheus @@ -39,104 +39,104 @@ patches: # [CERTMANAGER] To enable cert-manager, uncomment all sections with 'CERTMANAGER'. # Uncomment 'CERTMANAGER' sections in crd/kustomization.yaml to enable the CA injection in the admission webhooks. # 'CERTMANAGER' needs to be enabled to use ca injection -#- path: webhookcainjection_patch.yaml +- path: webhookcainjection_patch.yaml # [CERTMANAGER] To enable cert-manager, uncomment all sections with 'CERTMANAGER' prefix. # Uncomment the following replacements to add the cert-manager CA injection annotations -#replacements: -# - source: # Add cert-manager annotation to ValidatingWebhookConfiguration, MutatingWebhookConfiguration and CRDs -# kind: Certificate -# group: cert-manager.io -# version: v1 -# name: serving-cert # this name should match the one in certificate.yaml -# fieldPath: .metadata.namespace # namespace of the certificate CR -# targets: -# - select: -# kind: ValidatingWebhookConfiguration -# fieldPaths: -# - .metadata.annotations.[cert-manager.io/inject-ca-from] -# options: -# delimiter: '/' -# index: 0 -# create: true -# - select: -# kind: MutatingWebhookConfiguration -# fieldPaths: -# - .metadata.annotations.[cert-manager.io/inject-ca-from] -# options: -# delimiter: '/' -# index: 0 -# create: true -# - select: -# kind: CustomResourceDefinition -# fieldPaths: -# - .metadata.annotations.[cert-manager.io/inject-ca-from] -# options: -# delimiter: '/' -# index: 0 -# create: true -# - source: -# kind: Certificate -# group: cert-manager.io -# version: v1 -# name: serving-cert # this name should match the one in certificate.yaml -# fieldPath: .metadata.name -# targets: -# - select: -# kind: ValidatingWebhookConfiguration -# fieldPaths: -# - .metadata.annotations.[cert-manager.io/inject-ca-from] -# options: -# delimiter: '/' -# index: 1 -# create: true -# - select: -# kind: MutatingWebhookConfiguration -# fieldPaths: -# - .metadata.annotations.[cert-manager.io/inject-ca-from] -# options: -# delimiter: '/' -# index: 1 -# create: true -# - select: -# kind: CustomResourceDefinition -# fieldPaths: -# - .metadata.annotations.[cert-manager.io/inject-ca-from] -# options: -# delimiter: '/' -# index: 1 -# create: true -# - source: # Add cert-manager annotation to the webhook Service -# kind: Service -# version: v1 -# name: webhook-service -# fieldPath: .metadata.name # namespace of the service -# targets: -# - select: -# kind: Certificate -# group: cert-manager.io -# version: v1 -# fieldPaths: -# - .spec.dnsNames.0 -# - .spec.dnsNames.1 -# options: -# delimiter: '.' -# index: 0 -# create: true -# - source: -# kind: Service -# version: v1 -# name: webhook-service -# fieldPath: .metadata.namespace # namespace of the service -# targets: -# - select: -# kind: Certificate -# group: cert-manager.io -# version: v1 -# fieldPaths: -# - .spec.dnsNames.0 -# - .spec.dnsNames.1 -# options: -# delimiter: '.' -# index: 1 -# create: true +replacements: + - source: # Add cert-manager annotation to ValidatingWebhookConfiguration, MutatingWebhookConfiguration and CRDs + kind: Certificate + group: cert-manager.io + version: v1 + name: serving-cert # this name should match the one in certificate.yaml + fieldPath: .metadata.namespace # namespace of the certificate CR + targets: + - select: + kind: ValidatingWebhookConfiguration + fieldPaths: + - .metadata.annotations.[cert-manager.io/inject-ca-from] + options: + delimiter: '/' + index: 0 + create: true + - select: + kind: MutatingWebhookConfiguration + fieldPaths: + - .metadata.annotations.[cert-manager.io/inject-ca-from] + options: + delimiter: '/' + index: 0 + create: true + - select: + kind: CustomResourceDefinition + fieldPaths: + - .metadata.annotations.[cert-manager.io/inject-ca-from] + options: + delimiter: '/' + index: 0 + create: true + - source: + kind: Certificate + group: cert-manager.io + version: v1 + name: serving-cert # this name should match the one in certificate.yaml + fieldPath: .metadata.name + targets: + - select: + kind: ValidatingWebhookConfiguration + fieldPaths: + - .metadata.annotations.[cert-manager.io/inject-ca-from] + options: + delimiter: '/' + index: 1 + create: true + - select: + kind: MutatingWebhookConfiguration + fieldPaths: + - .metadata.annotations.[cert-manager.io/inject-ca-from] + options: + delimiter: '/' + index: 1 + create: true + - select: + kind: CustomResourceDefinition + fieldPaths: + - .metadata.annotations.[cert-manager.io/inject-ca-from] + options: + delimiter: '/' + index: 1 + create: true + - source: # Add cert-manager annotation to the webhook Service + kind: Service + version: v1 + name: webhook-service + fieldPath: .metadata.name # namespace of the service + targets: + - select: + kind: Certificate + group: cert-manager.io + version: v1 + fieldPaths: + - .spec.dnsNames.0 + - .spec.dnsNames.1 + options: + delimiter: '.' + index: 0 + create: true + - source: + kind: Service + version: v1 + name: webhook-service + fieldPath: .metadata.namespace # namespace of the service + targets: + - select: + kind: Certificate + group: cert-manager.io + version: v1 + fieldPaths: + - .spec.dnsNames.0 + - .spec.dnsNames.1 + options: + delimiter: '.' + index: 1 + create: true diff --git a/config/manager/kustomization.yaml b/config/manager/kustomization.yaml index 5c5f0b8..ad13e96 100644 --- a/config/manager/kustomization.yaml +++ b/config/manager/kustomization.yaml @@ -1,2 +1,8 @@ resources: - manager.yaml +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +images: +- name: controller + newName: controller + newTag: latest diff --git a/config/manager/manager.yaml b/config/manager/manager.yaml index ec362f4..3baabed 100644 --- a/config/manager/manager.yaml +++ b/config/manager/manager.yaml @@ -28,7 +28,7 @@ spec: selector: matchLabels: control-plane: controller-manager - replicas: 1 + replicas: 3 template: metadata: annotations: @@ -36,35 +36,8 @@ spec: labels: control-plane: controller-manager spec: - # TODO(user): Uncomment the following code to configure the nodeAffinity expression - # according to the platforms which are supported by your solution. - # It is considered best practice to support multiple architectures. You can - # build your manager image using the makefile target docker-buildx. - # affinity: - # nodeAffinity: - # requiredDuringSchedulingIgnoredDuringExecution: - # nodeSelectorTerms: - # - matchExpressions: - # - key: kubernetes.io/arch - # operator: In - # values: - # - amd64 - # - arm64 - # - ppc64le - # - s390x - # - key: kubernetes.io/os - # operator: In - # values: - # - linux securityContext: runAsNonRoot: true - # TODO(user): For common cases that do not require escalating privileges - # it is recommended to ensure that all your Pods/Containers are restrictive. - # More info: https://kubernetes.io/docs/concepts/security/pod-security-standards/#restricted - # Please uncomment the following code if your project does NOT have to work on old Kubernetes - # versions < 1.19 or on vendors versions which do NOT support this field by default (i.e. Openshift < 4.11 ). - # seccompProfile: - # type: RuntimeDefault containers: - command: - /manager @@ -89,8 +62,6 @@ spec: port: 8081 initialDelaySeconds: 5 periodSeconds: 10 - # TODO(user): Configure the resources accordingly based on the project requirements. - # More info: https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/ resources: limits: cpu: 500m diff --git a/config/rbac/role.yaml b/config/rbac/role.yaml index 3d6abd9..d19c151 100644 --- a/config/rbac/role.yaml +++ b/config/rbac/role.yaml @@ -7,7 +7,7 @@ rules: - apiGroups: - apps resources: - - daemonset + - daemonsets verbs: - get - list @@ -17,7 +17,7 @@ rules: - apiGroups: - apps resources: - - deployment + - deployments verbs: - get - list @@ -27,17 +27,7 @@ rules: - apiGroups: - apps resources: - - replicaset - verbs: - - get - - list - - patch - - update - - watch -- apiGroups: - - apps - resources: - - statefulset + - replicasets verbs: - get - list @@ -80,6 +70,14 @@ rules: - get - patch - update +- apiGroups: + - "" + resources: + - configmaps + verbs: + - get + - list + - watch - apiGroups: - "" resources: @@ -92,6 +90,8 @@ rules: resources: - pods verbs: + - create + - delete - get - list - patch diff --git a/config/samples/config_v1alpha1_dnsclass_all_namespaces.yaml b/config/samples/config_v1alpha1_dnsclass_all_namespaces.yaml index 2ca7092..51a8d49 100644 --- a/config/samples/config_v1alpha1_dnsclass_all_namespaces.yaml +++ b/config/samples/config_v1alpha1_dnsclass_all_namespaces.yaml @@ -12,7 +12,7 @@ spec: # If `all` set, the DNSClass configuration can be applied to all pods in all namespaces. # namespaces: # - all - resetDNSPolicyTo: Defaultx + resetDNSPolicyTo: Default dnsConfig: nameservers: - 10.96.0.10 diff --git a/go.mod b/go.mod index c5d1925..32dcce4 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,7 @@ module github.com/eminaktas/kubedns-shepherd go 1.22 require ( + github.com/caarlos0/go-version v0.1.1 github.com/onsi/ginkgo/v2 v2.13.0 github.com/onsi/gomega v1.29.0 gopkg.in/yaml.v2 v2.4.0 @@ -47,17 +48,17 @@ require ( github.com/prometheus/common v0.44.0 // indirect github.com/prometheus/procfs v0.10.1 // indirect github.com/spf13/pflag v1.0.5 // indirect - github.com/stretchr/testify v1.8.4 // indirect + github.com/stretchr/testify v1.9.0 // indirect go.uber.org/multierr v1.11.0 // indirect go.uber.org/zap v1.25.0 // indirect golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e // indirect - golang.org/x/net v0.19.0 // indirect + golang.org/x/net v0.20.0 // indirect golang.org/x/oauth2 v0.10.0 // indirect - golang.org/x/sys v0.15.0 // indirect - golang.org/x/term v0.15.0 // indirect + golang.org/x/sys v0.16.0 // indirect + golang.org/x/term v0.16.0 // indirect golang.org/x/text v0.14.0 // indirect golang.org/x/time v0.3.0 // indirect - golang.org/x/tools v0.16.1 // indirect + golang.org/x/tools v0.17.0 // indirect gomodules.xyz/jsonpatch/v2 v2.4.0 // indirect google.golang.org/appengine v1.6.7 // indirect google.golang.org/protobuf v1.33.0 // indirect diff --git a/go.sum b/go.sum index 7eaac5d..662333b 100644 --- a/go.sum +++ b/go.sum @@ -3,6 +3,8 @@ github.com/benbjohnson/clock v1.3.0 h1:ip6w0uFQkncKQ979AypyG0ER7mqUSBdKLOgAle/AT github.com/benbjohnson/clock v1.3.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= +github.com/caarlos0/go-version v0.1.1 h1:1bikKHkGGVIIxqCmufhSSs3hpBScgHGacrvsi8FuIfc= +github.com/caarlos0/go-version v0.1.1/go.mod h1:Ze5Qx4TsBBi5FyrSKVg1Ibc44KGV/llAaKGp86oTwZ0= github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44= github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= @@ -112,8 +114,8 @@ github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= -github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= -github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= @@ -143,8 +145,8 @@ golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLL golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= -golang.org/x/net v0.19.0 h1:zTwKpTd2XuCqf8huc7Fo2iSy+4RHPd10s4KzeTnVr1c= -golang.org/x/net v0.19.0/go.mod h1:CfAk/cbD4CthTvqiEl8NpboMuiuOYsAr/7NOjZJtv1U= +golang.org/x/net v0.20.0 h1:aCL9BSgETF1k+blQaYUBx9hJ9LOGP3gAVemcZlf1Kpo= +golang.org/x/net v0.20.0/go.mod h1:z8BVo6PvndSri0LbOE3hAn0apkU+1YvI6E70E9jsnvY= golang.org/x/oauth2 v0.10.0 h1:zHCpF2Khkwy4mMB4bv0U37YtJdTGW8jI0glAApi0Kh8= golang.org/x/oauth2 v0.10.0/go.mod h1:kTpgurOux7LqtuxjuyZa4Gj2gdezIt/jQtGnNFfypQI= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -159,11 +161,11 @@ golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc= -golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.16.0 h1:xWw16ngr6ZMtmxDyKyIgsE93KNKz5HKmMa3b8ALHidU= +golang.org/x/sys v0.16.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= -golang.org/x/term v0.15.0 h1:y/Oo/a/q3IXu26lQgl04j/gjuBDOBlx7X6Om1j2CPW4= -golang.org/x/term v0.15.0/go.mod h1:BDl952bC7+uMoWR75FIrCDx79TPU9oHkTZ9yRbYOrX0= +golang.org/x/term v0.16.0 h1:m+B6fahuftsE9qjo0VWp2FW0mB3MTJvR0BaMQrq0pmE= +golang.org/x/term v0.16.0/go.mod h1:yn7UURbUtPyrVJPGPq404EukNFxcm/foM+bV/bfcDsY= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= @@ -177,8 +179,8 @@ golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtn golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= -golang.org/x/tools v0.16.1 h1:TLyB3WofjdOEepBHAU20JdNC1Zbg87elYofWYAY5oZA= -golang.org/x/tools v0.16.1/go.mod h1:kYVVN6I1mBNoB1OX+noeBjbRk4IUEPa7JJ+TJMEooJ0= +golang.org/x/tools v0.17.0 h1:FvmRgNOcs3kOa+T20R1uhfP9F6HgG2mfxDv1vrx1Htc= +golang.org/x/tools v0.17.0/go.mod h1:xsh6VxdV005rRVaS6SSAf9oiAqljS7UZUacMZ8Bnsps= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= diff --git a/internal/controller/common.go b/internal/controller/common.go index 850afae..b3168c1 100644 --- a/internal/controller/common.go +++ b/internal/controller/common.go @@ -1,3 +1,19 @@ +/* +Copyright 2024. + +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 ( @@ -18,18 +34,33 @@ import ( // Definitions const ( // typeAvailable represents the status of the object reconciliation - typeAvailable = "Available" + TypeAvailable = "Available" // typeDegraded represents the status used when DNSClass is deleted and the finalizer operations are must to occur. - typeDegraded = "Degraded" + TypeDegraded = "Degraded" - reconcilePeriod = 1 * time.Second + ReconcilePeriod = 1 * time.Second - finalizerString = "config.kubedns-shepherd.io/finalizer" + FinalizerString = "config.kubedns-shepherd.io/finalizer" + // Annotation keys DNSConfigurationDisabled = "kubedns-shepherd.io/dns-configuration-disabled" DNSConfigured = "kubedns-shepherd.io/dns-configured" DNSClassName = "kubedns-shepherd.io/dns-class-name" IsReconciled = "kubedns-shepherd.io/is-reconciled" + + deploymentStr = "Deployment" + daemonsetStr = "DaemonSet" + statefulsetStr = "StatefulSet" + replicasetStr = "ReplicaSet" + podStr = "Pod" + + trueStr = "false" + falseStr = "false" +) + +var ( + errUnkownKind = errors.New("unknown kind") + errUnkownOwnerKind = errors.New("unknown owner kind") ) // Define a function to wait for a Pod to be deleted @@ -47,13 +78,13 @@ func waitForPodDeletion(ctx context.Context, c client.Client, podName types.Name } // Pod still exists, wait for a short duration before checking again - time.Sleep(reconcilePeriod) + time.Sleep(ReconcilePeriod) } } func getWorkloadObject(ctx context.Context, c client.Client, pod *corev1.Pod) (*Workload, error) { for _, owner := range pod.OwnerReferences { - if owner.Kind == "ReplicaSet" { + if owner.Kind == replicasetStr { var rs appsv1.ReplicaSet err := c.Get(ctx, client.ObjectKey{ Namespace: pod.Namespace, @@ -72,7 +103,7 @@ func getWorkloadObject(ctx context.Context, c client.Client, pod *corev1.Pod) (* } for _, rsOwner := range rs.OwnerReferences { - if rsOwner.Kind == "Deployment" || rsOwner.Kind == "DaemonSet" || rsOwner.Kind == "StatefulSet" { + if rsOwner.Kind == deploymentStr || rsOwner.Kind == daemonsetStr || rsOwner.Kind == statefulsetStr { return &Workload{ Name: rsOwner.Name, Namespace: pod.Namespace, @@ -80,14 +111,14 @@ func getWorkloadObject(ctx context.Context, c client.Client, pod *corev1.Pod) (* }, nil } } - } else if owner.Kind == "DaemonSet" || owner.Kind == "Deployment" || owner.Kind == "StatefulSet" { + } else if owner.Kind == daemonsetStr || owner.Kind == deploymentStr || owner.Kind == statefulsetStr { return &Workload{ Name: owner.Name, Namespace: pod.Namespace, Kind: owner.Kind, }, nil } else { - return nil, errors.New("unknown owner kind") + return nil, errUnkownOwnerKind } } @@ -116,7 +147,7 @@ func setDNSPolicyTo(obj client.Object, dnsPolicy corev1.DNSPolicy) error { o.Spec.DNSPolicy = dnsPolicy return nil default: - return errors.New("unknown kind") + return errUnkownKind } } @@ -138,24 +169,24 @@ func setDNSConfig(obj client.Object, dnsConfig *corev1.PodDNSConfig) error { o.Spec.DNSConfig = dnsConfig return nil default: - return errors.New("unknown kind") + return errUnkownKind } } func getObjectFromKindString(kind string) (client.Object, error) { switch kind { - case "Deployment": + case deploymentStr: return &appsv1.Deployment{}, nil - case "StatefulSet": + case statefulsetStr: return &appsv1.StatefulSet{}, nil - case "DaemonSet": + case daemonsetStr: return &appsv1.DaemonSet{}, nil - case "ReplicaSet": + case replicasetStr: return &appsv1.ReplicaSet{}, nil - case "Pod": + case podStr: return &corev1.Pod{}, nil default: - return nil, errors.New("unknown kind") + return nil, errUnkownKind } } @@ -213,7 +244,7 @@ func getDNSConfig(obj client.Object) *corev1.PodDNSConfig { func isDNSConfigurable(obj client.Object) bool { annotations := getAnnotations(obj) if val, ok := annotations[DNSConfigurationDisabled]; ok { - if val == "true" { + if val == trueStr { return true } } @@ -227,7 +258,7 @@ func isDNSConfigured(obj client.Object, dnsClass *corev1.PodDNSConfig) bool { dnsConfig := getDNSConfig(obj) if val, ok := annotations[DNSConfigured]; ok { - if val == "true" { + if val == trueStr { // Check if the DNS configuration is altered if dnsPolicy != corev1.DNSNone { return false @@ -261,7 +292,7 @@ func removeAnnotation(obj client.Object, key string) error { delete(o.Annotations, key) return nil default: - return errors.New("unknown kind") + return errUnkownKind } } @@ -298,7 +329,7 @@ func updateAnnotation(obj client.Object, key, value string) error { o.Annotations[key] = value return nil default: - return errors.New("unknown kind") + return errUnkownKind } } @@ -332,7 +363,7 @@ type dnsClassPredicate struct { func (*dnsClassPredicate) Create(e event.CreateEvent) bool { annotations := e.Object.GetAnnotations() if val, ok := annotations[IsReconciled]; ok { - return val == "false" + return val == falseStr } return true } diff --git a/internal/controller/common_test.go b/internal/controller/common_test.go new file mode 100644 index 0000000..2f16a99 --- /dev/null +++ b/internal/controller/common_test.go @@ -0,0 +1,17 @@ +/* +Copyright 2024. + +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 diff --git a/internal/controller/dnsclass_controller.go b/internal/controller/dnsclass_controller.go index 498cc7e..d346ffb 100644 --- a/internal/controller/dnsclass_controller.go +++ b/internal/controller/dnsclass_controller.go @@ -51,10 +51,11 @@ type DNSClassReconciler struct { //+kubebuilder:rbac:groups=config.kubedns-shepherd.io,resources=dnsclasses/status,verbs=get;update;patch //+kubebuilder:rbac:groups=config.kubedns-shepherd.io,resources=dnsclasses/finalizers,verbs=update //+kubebuilder:rbac:groups=core,resources=events,verbs=create;patch +//+kubebuilder:rbac:groups=core,resources=configmaps,verbs=get;list;watch func (r *DNSClassReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { logger := log.FromContext(ctx) - logger.Info(fmt.Sprintf("Reconciling for %s DNSClass", req.Name)) + logger.Info("Reconciling for DNSClass") dnsClass := &configv1alpha1.DNSClass{} err := r.Get(ctx, req.NamespacedName, dnsClass) @@ -74,15 +75,14 @@ func (r *DNSClassReconciler) Reconcile(ctx context.Context, req ctrl.Request) (c if annotations == nil { annotations = make(map[string]string) } - val, ok := annotations[IsReconciled] - if !ok || val == "true" { + if val, ok := annotations[IsReconciled]; !ok || val == "true" { annotations[IsReconciled] = "false" dnsClass.SetAnnotations(annotations) if err := r.Update(ctx, dnsClass); err != nil { logger.Error(err, "Failed to add annotations") return ctrl.Result{}, err } - return ctrl.Result{Requeue: true, RequeueAfter: reconcilePeriod}, nil + return ctrl.Result{Requeue: true, RequeueAfter: ReconcilePeriod}, nil } // Add default nameservers if not defined in object @@ -96,21 +96,21 @@ func (r *DNSClassReconciler) Reconcile(ctx context.Context, req ctrl.Request) (c logger.Error(err, "Failed to add nameservers") return ctrl.Result{}, err } - return ctrl.Result{Requeue: true, RequeueAfter: reconcilePeriod}, nil + return ctrl.Result{Requeue: true, RequeueAfter: ReconcilePeriod}, nil } // Set the status as Unknown when no status are available if dnsClass.Status.Conditions == nil || len(dnsClass.Status.Conditions) == 0 { - meta.SetStatusCondition(&dnsClass.Status.Conditions, metav1.Condition{Type: typeAvailable, Status: metav1.ConditionUnknown, Reason: "Reconciling", Message: "Starting reconciliation"}) + meta.SetStatusCondition(&dnsClass.Status.Conditions, metav1.Condition{Type: TypeAvailable, Status: metav1.ConditionUnknown, Reason: "Reconciling", Message: "Starting reconciliation"}) if err = r.Status().Update(ctx, dnsClass); err != nil { logger.Error(err, "Failed to update the status") return ctrl.Result{}, err } } - if !controllerutil.ContainsFinalizer(dnsClass, finalizerString) { + if !controllerutil.ContainsFinalizer(dnsClass, FinalizerString) { logger.Info("Adding Finalizer") - if ok := controllerutil.AddFinalizer(dnsClass, finalizerString); !ok { + if ok := controllerutil.AddFinalizer(dnsClass, FinalizerString); !ok { logger.Error(err, "Failed to add finalizer") return ctrl.Result{Requeue: true}, nil } @@ -120,16 +120,16 @@ func (r *DNSClassReconciler) Reconcile(ctx context.Context, req ctrl.Request) (c return ctrl.Result{}, err } - return ctrl.Result{Requeue: true, RequeueAfter: reconcilePeriod}, nil + return ctrl.Result{Requeue: true, RequeueAfter: ReconcilePeriod}, nil } if !dnsClass.DeletionTimestamp.IsZero() { - if controllerutil.ContainsFinalizer(dnsClass, finalizerString) { + if controllerutil.ContainsFinalizer(dnsClass, FinalizerString) { logger.Info("Performing Finalizer Operations before deleting DNSClass") // Add "Downgrade" status - if !meta.IsStatusConditionPresentAndEqual(dnsClass.Status.Conditions, typeDegraded, metav1.ConditionUnknown) { - meta.SetStatusCondition(&dnsClass.Status.Conditions, metav1.Condition{Type: typeDegraded, + if !meta.IsStatusConditionPresentAndEqual(dnsClass.Status.Conditions, TypeDegraded, metav1.ConditionUnknown) { + meta.SetStatusCondition(&dnsClass.Status.Conditions, metav1.Condition{Type: TypeDegraded, Status: metav1.ConditionUnknown, Reason: "Finalizing", Message: fmt.Sprintf("Performing finalizer operations for the custom resource: %s", dnsClass.Name)}) @@ -137,17 +137,17 @@ func (r *DNSClassReconciler) Reconcile(ctx context.Context, req ctrl.Request) (c logger.Error(err, "Failed to update status") return ctrl.Result{}, err } - return ctrl.Result{Requeue: true, RequeueAfter: reconcilePeriod}, nil + return ctrl.Result{Requeue: true, RequeueAfter: ReconcilePeriod}, nil } - // Revert the DNS Policy + // Reverts the DNS Configuration err := r.setDNSConfig(ctx, dnsClass, true) if err != nil { logger.Error(err, "Failed to revert the DNS Configuration") return ctrl.Result{}, err } - meta.SetStatusCondition(&dnsClass.Status.Conditions, metav1.Condition{Type: typeDegraded, + meta.SetStatusCondition(&dnsClass.Status.Conditions, metav1.Condition{Type: TypeDegraded, Status: metav1.ConditionTrue, Reason: "Finalizing", Message: "Finalizer operations were successfully accomplished"}) @@ -157,7 +157,7 @@ func (r *DNSClassReconciler) Reconcile(ctx context.Context, req ctrl.Request) (c } logger.Info("Removing Finalizer after successfully perform the operations") - if ok := controllerutil.RemoveFinalizer(dnsClass, finalizerString); !ok { + if ok := controllerutil.RemoveFinalizer(dnsClass, FinalizerString); !ok { logger.Error(err, "Failed to remove finalizer") return ctrl.Result{Requeue: true}, nil } @@ -175,7 +175,7 @@ func (r *DNSClassReconciler) Reconcile(ctx context.Context, req ctrl.Request) (c return ctrl.Result{}, err } - // Mark the resource is already reconciled with `kubedns-shepherd.io/is-reconciled=true` annotation + // Marks the resource is already reconciled with `kubedns-shepherd.io/is-reconciled=true` annotation annotations[IsReconciled] = "true" dnsClass.SetAnnotations(annotations) @@ -185,7 +185,7 @@ func (r *DNSClassReconciler) Reconcile(ctx context.Context, req ctrl.Request) (c } // The following implementation will update the status - meta.SetStatusCondition(&dnsClass.Status.Conditions, metav1.Condition{Type: typeAvailable, + meta.SetStatusCondition(&dnsClass.Status.Conditions, metav1.Condition{Type: TypeAvailable, Status: metav1.ConditionTrue, Reason: "Reconciling", Message: "DNSClass were created and Workloads DNS configurations were updated"}) @@ -229,7 +229,7 @@ func (r *DNSClassReconciler) setDNSConfig(ctx context.Context, dnsClass *configv } if r.DisablePodReconciling { - if podWorkload.Kind == "Pod" { + if podWorkload.Kind == podStr { continue } } @@ -280,7 +280,7 @@ func (r *DNSClassReconciler) configureDNSForWorkload(ctx context.Context, object return err } - if err = updateAnnotation(object, DNSConfigured, "true"); err != nil { + if err = updateAnnotation(object, DNSConfigured, trueStr); err != nil { return err } @@ -290,15 +290,17 @@ func (r *DNSClassReconciler) configureDNSForWorkload(ctx context.Context, object } // Due to the restriction of pod update, we need to delete and recreate the object - if object.GetObjectKind().GroupVersionKind().Kind == "Pod" { + if object.GetObjectKind().GroupVersionKind().Kind == podStr { if err = r.Delete(ctx, object); err != nil { return err } // Wait until pod is deleted - waitForPodDeletion(ctx, r.Client, types.NamespacedName{ + if err := waitForPodDeletion(ctx, r.Client, types.NamespacedName{ Name: object.GetName(), Namespace: object.GetNamespace(), - }) + }); err != nil { + return err + } // Remove `resourceVersion` object.SetResourceVersion("") if err = r.Create(ctx, object); err != nil { @@ -356,7 +358,7 @@ func (r *DNSClassReconciler) getNameservers(ctx context.Context) ([]string, erro return clusterDNSStringSlice, nil } - // TODO: Add more resource for detecting kube-dns endpoint. + // TODO: Add more resource for detecting kube-dns IP if needed. return nil, nil } diff --git a/internal/controller/dnsclass_controller_test.go b/internal/controller/dnsclass_controller_test.go index 6a0e465..2b279a1 100644 --- a/internal/controller/dnsclass_controller_test.go +++ b/internal/controller/dnsclass_controller_test.go @@ -25,9 +25,11 @@ import ( "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/reconcile" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" configv1alpha1 "github.com/eminaktas/kubedns-shepherd/api/v1alpha1" + "github.com/eminaktas/kubedns-shepherd/test/utils" ) var _ = Describe("DNSClass Controller", func() { @@ -37,8 +39,7 @@ var _ = Describe("DNSClass Controller", func() { ctx := context.Background() typeNamespacedName := types.NamespacedName{ - Name: resourceName, - Namespace: "default", // TODO(user):Modify as needed + Name: resourceName, } dnsclass := &configv1alpha1.DNSClass{} @@ -51,14 +52,22 @@ var _ = Describe("DNSClass Controller", func() { Name: resourceName, Namespace: "default", }, - // TODO(user): Specify other spec details if needed. + Spec: configv1alpha1.DNSClassSpec{ + DNSConfig: &corev1.PodDNSConfig{ + Nameservers: []string{"10.96.0.10"}, + Searches: []string{"svc.cluster.local"}, + Options: []corev1.PodDNSConfigOption{ + {Name: "ndots", Value: utils.StringPtr("2")}, + {Name: "edns0"}, + }, + }, + }, } Expect(k8sClient.Create(ctx, resource)).To(Succeed()) } }) AfterEach(func() { - // TODO(user): Cleanup logic after each test, like removing the resource instance. resource := &configv1alpha1.DNSClass{} err := k8sClient.Get(ctx, typeNamespacedName, resource) Expect(err).NotTo(HaveOccurred()) diff --git a/internal/controller/pods_controller.go b/internal/controller/pods_controller.go index 3caf66b..e8a0dd0 100644 --- a/internal/controller/pods_controller.go +++ b/internal/controller/pods_controller.go @@ -49,12 +49,11 @@ type PodsReconciler struct { MaxConcurrentReconcilesForPodsReconciler int } -//+kubebuilder:rbac:groups=apps,resources=deployment,verbs=get;list;watch;update;patch -//+kubebuilder:rbac:groups=apps,resources=statefulset,verbs=get;list;watch;update;patch -//+kubebuilder:rbac:groups=apps,resources=daemonset,verbs=get;list;watch;update;patch +//+kubebuilder:rbac:groups=apps,resources=deployments,verbs=get;list;watch;update;patch //+kubebuilder:rbac:groups=apps,resources=statefulsets,verbs=get;list;watch;update;patch -//+kubebuilder:rbac:groups=apps,resources=replicaset,verbs=get;list;watch;update;patch -//+kubebuilder:rbac:groups=core,resources=pods,verbs=get;list;watch;update;patch +//+kubebuilder:rbac:groups=apps,resources=daemonsets,verbs=get;list;watch;update;patch +//+kubebuilder:rbac:groups=apps,resources=replicasets,verbs=get;list;watch;update;patch +//+kubebuilder:rbac:groups=core,resources=pods,verbs=get;list;watch;update;patch;create;delete //+kubebuilder:rbac:groups=core,resources=events,verbs=create;patch func (r *PodsReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { @@ -103,7 +102,7 @@ func (r *PodsReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl. dnsClass = val break } - if val.Spec.Namespaces[0] == "all" { + if slices.Contains(val.Spec.Namespaces, "all") { dnsClass = val } } @@ -117,12 +116,12 @@ func (r *PodsReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl. // Get the latest condition count := len(dnsClass.Status.Conditions) if count == 0 { - return ctrl.Result{Requeue: true, RequeueAfter: reconcilePeriod}, nil + return ctrl.Result{Requeue: true, RequeueAfter: ReconcilePeriod}, nil } latestCondition := dnsClass.Status.Conditions[count-1] // Check if DNSClass has been marked as `Downgrade` which is used when DNSClass is being deleted. - if latestCondition.Type == typeDegraded { + if latestCondition.Type == TypeDegraded { logger.Info(fmt.Sprintf("%s DNSClass has been marked to be deleted", dnsClass.Name)) return ctrl.Result{}, nil } @@ -138,7 +137,7 @@ func (r *PodsReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl. } // Check if DNSClass condition type is Available and status is True, othewise, stop reconciling - if latestCondition.Type != typeAvailable && latestCondition.Status != v1.ConditionTrue { + if latestCondition.Type != TypeAvailable && latestCondition.Status != v1.ConditionTrue { logger.Info(fmt.Sprintf("%s DNSClass is being reconciled", dnsClass.Name)) return ctrl.Result{}, nil } @@ -153,7 +152,7 @@ func (r *PodsReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl. err = r.configureDNSForWorkload(ctx, podWorkload, dnsClass) if err != nil { logger.Error(err, fmt.Sprintf("Failed to configure %+v object", *podWorkload)) - return ctrl.Result{Requeue: true, RequeueAfter: reconcilePeriod}, nil + return ctrl.Result{Requeue: true, RequeueAfter: ReconcilePeriod}, nil } logger.Info(fmt.Sprintf("DNSConfig configured for %+v with %s DNSClass", *podWorkload, dnsClass.Name)) @@ -193,10 +192,12 @@ func (r *PodsReconciler) configureDNSForWorkload(ctx context.Context, podWorkloa return err } // Wait until pod is deleted - waitForPodDeletion(ctx, r.Client, types.NamespacedName{ + if err := waitForPodDeletion(ctx, r.Client, types.NamespacedName{ Name: podWorkload.Name, Namespace: podWorkload.Namespace, - }) + }); err != nil { + return err + } // Remove `resourceVersion` object.SetResourceVersion("") if err = r.Create(ctx, object); err != nil { diff --git a/test/e2e/e2e_test.go b/test/e2e/e2e_test.go index 0570fd8..cd722b9 100644 --- a/test/e2e/e2e_test.go +++ b/test/e2e/e2e_test.go @@ -60,7 +60,7 @@ var _ = Describe("controller", Ordered, func() { var err error // projectimage stores the name of the image used in the example - var projectimage = "example.com/kubedns-shepherd:v0.0.1" + var projectimage = "eminaktas/kubedns-shepherd:v0.0.1" By("building the manager(Operator) image") cmd := exec.Command("make", "docker-build", fmt.Sprintf("IMG=%s", projectimage)) @@ -73,7 +73,7 @@ var _ = Describe("controller", Ordered, func() { By("installing CRDs") cmd = exec.Command("make", "install") - _, err = utils.Run(cmd) + _, _ = utils.Run(cmd) By("deploying the controller-manager") cmd = exec.Command("make", "deploy", fmt.Sprintf("IMG=%s", projectimage)) diff --git a/test/utils/utils.go b/test/utils/utils.go index 7363aa5..266e063 100644 --- a/test/utils/utils.go +++ b/test/utils/utils.go @@ -138,3 +138,7 @@ func GetProjectDir() (string, error) { wd = strings.Replace(wd, "/test/e2e", "", -1) return wd, nil } + +func StringPtr(s string) *string { + return &s +}