From c70ce54056b766c4c0b55ed52093c0490ebbe9e0 Mon Sep 17 00:00:00 2001 From: Camila Macedo Date: Thu, 16 May 2024 19:14:17 +0100 Subject: [PATCH] (Follow UP: 3763) - remove kustomize/v1, go/v2 and go/v3, and configurations for Project Config v2 related to legacy Kubebuilder CLI version < 3 --- pkg/config/v2/config.go | 246 -------------- pkg/config/v2/config_test.go | 315 ------------------ pkg/plugins/common/kustomize/v1/api.go | 39 --- pkg/plugins/common/kustomize/v1/create.go | 59 ---- pkg/plugins/common/kustomize/v1/init.go | 138 -------- pkg/plugins/common/kustomize/v1/plugin.go | 73 ---- .../common/kustomize/v1/scaffolds/api.go | 89 ----- .../common/kustomize/v1/scaffolds/init.go | 85 ----- .../config/certmanager/certificate.go | 86 ----- .../config/certmanager/kustomization.go | 51 --- .../config/certmanager/kustomizeconfig.go | 63 ---- .../templates/config/crd/kustomization.go | 126 ------- .../templates/config/crd/kustomizeconfig.go | 72 ---- .../crd/patches/enablecainjection_patch.go | 61 ---- .../config/crd/patches/enablewebhook_patch.go | 78 ----- .../config/kdefault/enablecainection_patch.go | 77 ----- .../config/kdefault/kustomization.go | 116 ------- .../kdefault/manager_auth_proxy_patch.go | 84 ----- .../config/kdefault/manager_config_patch.go | 53 --- .../config/kdefault/webhook_manager_patch.go | 75 ----- .../templates/config/manager/config.go | 149 --------- .../templates/config/manager/kustomization.go | 47 --- .../config/prometheus/kustomization.go | 45 --- .../templates/config/prometheus/monitor.go | 70 ---- .../config/rbac/auth_proxy_client_role.go | 60 ---- .../templates/config/rbac/auth_proxy_role.go | 68 ---- .../config/rbac/auth_proxy_role_binding.go | 63 ---- .../config/rbac/auth_proxy_service.go | 65 ---- .../templates/config/rbac/crd_editor_role.go | 83 ----- .../templates/config/rbac/crd_viewer_role.go | 79 ----- .../templates/config/rbac/kustomization.go | 63 ---- .../config/rbac/leader_election_role.go | 88 ----- .../rbac/leader_election_role_binding.go | 63 ---- .../templates/config/rbac/role_binding.go | 63 ---- .../templates/config/rbac/service_account.go | 56 ---- .../templates/config/samples/crd_sample.go | 66 ---- .../templates/config/webhook/kustomization.go | 59 ---- .../config/webhook/kustomizeconfig.go | 72 ---- .../templates/config/webhook/service.go | 67 ---- .../common/kustomize/v1/scaffolds/webhook.go | 86 ----- pkg/plugins/common/kustomize/v1/webhook.go | 39 --- .../controllers/controller_suitetest.go | 184 ---------- .../templates/api/webhook_suitetest.go | 244 -------------- .../controllers/controller_suitetest.go | 187 ----------- .../v3/scaffolds/internal/templates/main.go | 296 ---------------- .../scaffolds/internal/templates/makefile.go | 217 ------------ pkg/plugins/golang/v4/scaffolds/init.go | 8 +- 47 files changed, 3 insertions(+), 4570 deletions(-) delete mode 100644 pkg/config/v2/config.go delete mode 100644 pkg/config/v2/config_test.go delete mode 100644 pkg/plugins/common/kustomize/v1/api.go delete mode 100644 pkg/plugins/common/kustomize/v1/create.go delete mode 100644 pkg/plugins/common/kustomize/v1/init.go delete mode 100644 pkg/plugins/common/kustomize/v1/plugin.go delete mode 100644 pkg/plugins/common/kustomize/v1/scaffolds/api.go delete mode 100644 pkg/plugins/common/kustomize/v1/scaffolds/init.go delete mode 100644 pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/certmanager/certificate.go delete mode 100644 pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/certmanager/kustomization.go delete mode 100644 pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/certmanager/kustomizeconfig.go delete mode 100644 pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/crd/kustomization.go delete mode 100644 pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/crd/kustomizeconfig.go delete mode 100644 pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/crd/patches/enablecainjection_patch.go delete mode 100644 pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/crd/patches/enablewebhook_patch.go delete mode 100644 pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/kdefault/enablecainection_patch.go delete mode 100644 pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/kdefault/kustomization.go delete mode 100644 pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/kdefault/manager_auth_proxy_patch.go delete mode 100644 pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/kdefault/manager_config_patch.go delete mode 100644 pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/kdefault/webhook_manager_patch.go delete mode 100644 pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/manager/config.go delete mode 100644 pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/manager/kustomization.go delete mode 100644 pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/prometheus/kustomization.go delete mode 100644 pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/prometheus/monitor.go delete mode 100644 pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/rbac/auth_proxy_client_role.go delete mode 100644 pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/rbac/auth_proxy_role.go delete mode 100644 pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/rbac/auth_proxy_role_binding.go delete mode 100644 pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/rbac/auth_proxy_service.go delete mode 100644 pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/rbac/crd_editor_role.go delete mode 100644 pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/rbac/crd_viewer_role.go delete mode 100644 pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/rbac/kustomization.go delete mode 100644 pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/rbac/leader_election_role.go delete mode 100644 pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/rbac/leader_election_role_binding.go delete mode 100644 pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/rbac/role_binding.go delete mode 100644 pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/rbac/service_account.go delete mode 100644 pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/samples/crd_sample.go delete mode 100644 pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/webhook/kustomization.go delete mode 100644 pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/webhook/kustomizeconfig.go delete mode 100644 pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/webhook/service.go delete mode 100644 pkg/plugins/common/kustomize/v1/scaffolds/webhook.go delete mode 100644 pkg/plugins/common/kustomize/v1/webhook.go delete mode 100644 pkg/plugins/golang/v2/scaffolds/internal/templates/controllers/controller_suitetest.go delete mode 100644 pkg/plugins/golang/v3/scaffolds/internal/templates/api/webhook_suitetest.go delete mode 100644 pkg/plugins/golang/v3/scaffolds/internal/templates/controllers/controller_suitetest.go delete mode 100644 pkg/plugins/golang/v3/scaffolds/internal/templates/main.go delete mode 100644 pkg/plugins/golang/v3/scaffolds/internal/templates/makefile.go diff --git a/pkg/config/v2/config.go b/pkg/config/v2/config.go deleted file mode 100644 index 09e61e35e2..0000000000 --- a/pkg/config/v2/config.go +++ /dev/null @@ -1,246 +0,0 @@ -/* -Copyright 2022 The Kubernetes 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. -*/ - -//go:deprecated This package has been deprecated -package v2 - -import ( - "strings" - - "sigs.k8s.io/yaml" - - "sigs.k8s.io/kubebuilder/v3/pkg/config" - "sigs.k8s.io/kubebuilder/v3/pkg/model/resource" -) - -// Version is the config.Version for project configuration 2 -var Version = config.Version{Number: 2} - -type cfg struct { - // Version - Version config.Version `json:"version"` - - // String fields - Domain string `json:"domain,omitempty"` - Repository string `json:"repo,omitempty"` - - // Boolean fields - MultiGroup bool `json:"multigroup,omitempty"` - - // Resources - Gvks []resource.GVK `json:"resources,omitempty"` -} - -// New returns a new config.Config -func New() config.Config { - return &cfg{Version: Version} -} - -func init() { - config.Register(Version, New) -} - -// GetVersion implements config.Config -func (c cfg) GetVersion() config.Version { - return c.Version -} - -// GetDomain implements config.Config -func (c cfg) GetDomain() string { - return c.Domain -} - -// SetDomain implements config.Config -func (c *cfg) SetDomain(domain string) error { - c.Domain = domain - return nil -} - -// GetRepository implements config.Config -func (c cfg) GetRepository() string { - return c.Repository -} - -// SetRepository implements config.Config -func (c *cfg) SetRepository(repository string) error { - c.Repository = repository - return nil -} - -// GetProjectName implements config.Config -func (c cfg) GetProjectName() string { - return "" -} - -// SetProjectName implements config.Config -func (c *cfg) SetProjectName(string) error { - return config.UnsupportedFieldError{ - Version: Version, - Field: "project name", - } -} - -// GetPluginChain implements config.Config -func (c cfg) GetPluginChain() []string { - return []string{"go.kubebuilder.io/v2"} -} - -// SetPluginChain implements config.Config -func (c *cfg) SetPluginChain([]string) error { - return config.UnsupportedFieldError{ - Version: Version, - Field: "plugin chain", - } -} - -// IsMultiGroup implements config.Config -func (c cfg) IsMultiGroup() bool { - return c.MultiGroup -} - -// SetMultiGroup implements config.Config -func (c *cfg) SetMultiGroup() error { - c.MultiGroup = true - return nil -} - -// ClearMultiGroup implements config.Config -func (c *cfg) ClearMultiGroup() error { - c.MultiGroup = false - return nil -} - -// ResourcesLength implements config.Config -func (c cfg) ResourcesLength() int { - return len(c.Gvks) -} - -// HasResource implements config.Config -func (c cfg) HasResource(gvk resource.GVK) bool { - gvk.Domain = "" // Version 2 does not include domain per resource - - for _, trackedGVK := range c.Gvks { - if gvk.IsEqualTo(trackedGVK) { - return true - } - } - - return false -} - -// GetResource implements config.Config -func (c cfg) GetResource(gvk resource.GVK) (resource.Resource, error) { - gvk.Domain = "" // Version 2 does not include domain per resource - - for _, trackedGVK := range c.Gvks { - if gvk.IsEqualTo(trackedGVK) { - return resource.Resource{ - GVK: trackedGVK, - }, nil - } - } - - return resource.Resource{}, config.ResourceNotFoundError{GVK: gvk} -} - -// GetResources implements config.Config -func (c cfg) GetResources() ([]resource.Resource, error) { - resources := make([]resource.Resource, 0, len(c.Gvks)) - for _, gvk := range c.Gvks { - resources = append(resources, resource.Resource{ - GVK: gvk, - }) - } - - return resources, nil -} - -// AddResource implements config.Config -func (c *cfg) AddResource(res resource.Resource) error { - // As res is passed by value it is already a shallow copy, and we are only using - // fields that do not require a deep copy, so no need to make a deep copy - - res.Domain = "" // Version 2 does not include domain per resource - - if !c.HasResource(res.GVK) { - c.Gvks = append(c.Gvks, res.GVK) - } - - return nil -} - -// UpdateResource implements config.Config -func (c *cfg) UpdateResource(res resource.Resource) error { - return c.AddResource(res) -} - -// HasGroup implements config.Config -func (c cfg) HasGroup(group string) bool { - // Return true if the target group is found in the tracked resources - for _, r := range c.Gvks { - if strings.EqualFold(group, r.Group) { - return true - } - } - - // Return false otherwise - return false -} - -// ListCRDVersions implements config.Config -func (c cfg) ListCRDVersions() []string { - return make([]string, 0) -} - -// ListWebhookVersions implements config.Config -func (c cfg) ListWebhookVersions() []string { - return make([]string, 0) -} - -// DecodePluginConfig implements config.Config -func (c cfg) DecodePluginConfig(string, interface{}) error { - return config.UnsupportedFieldError{ - Version: Version, - Field: "plugins", - } -} - -// EncodePluginConfig implements config.Config -func (c cfg) EncodePluginConfig(string, interface{}) error { - return config.UnsupportedFieldError{ - Version: Version, - Field: "plugins", - } -} - -// Marshal implements config.Config -func (c cfg) MarshalYAML() ([]byte, error) { - content, err := yaml.Marshal(c) - if err != nil { - return nil, config.MarshalError{Err: err} - } - - return content, nil -} - -// Unmarshal implements config.Config -func (c *cfg) UnmarshalYAML(b []byte) error { - if err := yaml.UnmarshalStrict(b, c); err != nil { - return config.UnmarshalError{Err: err} - } - - return nil -} diff --git a/pkg/config/v2/config_test.go b/pkg/config/v2/config_test.go deleted file mode 100644 index 16b5cd5332..0000000000 --- a/pkg/config/v2/config_test.go +++ /dev/null @@ -1,315 +0,0 @@ -/* -Copyright 2022 The Kubernetes 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. -*/ - -//go:deprecated This package has been deprecated -package v2 - -import ( - "testing" - - . "github.com/onsi/ginkgo/v2" - . "github.com/onsi/gomega" - - "sigs.k8s.io/kubebuilder/v3/pkg/model/resource" -) - -func TestConfigV2(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Config V2 Suite") -} - -var _ = Describe("cfg", func() { - const ( - domain = "my.domain" - repo = "myrepo" - - otherDomain = "other.domain" - otherRepo = "otherrepo" - ) - - var c cfg - - BeforeEach(func() { - c = cfg{ - Version: Version, - Domain: domain, - Repository: repo, - } - }) - - Context("Version", func() { - It("GetVersion should return version 2", func() { - Expect(c.GetVersion().Compare(Version)).To(Equal(0)) - }) - }) - - Context("Domain", func() { - It("GetDomain should return the domain", func() { - Expect(c.GetDomain()).To(Equal(domain)) - }) - - It("SetDomain should set the domain", func() { - Expect(c.SetDomain(otherDomain)).To(Succeed()) - Expect(c.Domain).To(Equal(otherDomain)) - }) - }) - - Context("Repository", func() { - It("GetRepository should return the repository", func() { - Expect(c.GetRepository()).To(Equal(repo)) - }) - - It("SetRepository should set the repository", func() { - Expect(c.SetRepository(otherRepo)).To(Succeed()) - Expect(c.Repository).To(Equal(otherRepo)) - }) - }) - - Context("Project name", func() { - It("GetProjectName should return an empty name", func() { - Expect(c.GetProjectName()).To(Equal("")) - }) - - It("SetProjectName should fail to set the name", func() { - Expect(c.SetProjectName("name")).NotTo(Succeed()) - }) - }) - - Context("Plugin chain", func() { - It("GetPluginChain should return the only supported plugin", func() { - Expect(c.GetPluginChain()).To(Equal([]string{"go.kubebuilder.io/v2"})) - }) - - It("SetPluginChain should fail to set the plugin chain", func() { - Expect(c.SetPluginChain([]string{})).NotTo(Succeed()) - }) - }) - - Context("Multi group", func() { - It("IsMultiGroup should return false if not set", func() { - Expect(c.IsMultiGroup()).To(BeFalse()) - }) - - It("IsMultiGroup should return true if set", func() { - c.MultiGroup = true - Expect(c.IsMultiGroup()).To(BeTrue()) - }) - - It("SetMultiGroup should enable multi-group support", func() { - Expect(c.SetMultiGroup()).To(Succeed()) - Expect(c.MultiGroup).To(BeTrue()) - }) - - It("ClearMultiGroup should disable multi-group support", func() { - c.MultiGroup = true - Expect(c.ClearMultiGroup()).To(Succeed()) - Expect(c.MultiGroup).To(BeFalse()) - }) - }) - - Context("Resources", func() { - res := resource.Resource{ - GVK: resource.GVK{ - Group: "group", - Version: "v1", - Kind: "Kind", - }, - } - - DescribeTable("ResourcesLength should return the number of resources", - func(n int) { - for i := 0; i < n; i++ { - c.Gvks = append(c.Gvks, res.GVK) - } - Expect(c.ResourcesLength()).To(Equal(n)) - }, - Entry("for no resources", 0), - Entry("for one resource", 1), - Entry("for several resources", 3), - ) - - It("HasResource should return false for a non-existent resource", func() { - Expect(c.HasResource(res.GVK)).To(BeFalse()) - }) - - It("HasResource should return true for an existent resource", func() { - c.Gvks = append(c.Gvks, res.GVK) - Expect(c.HasResource(res.GVK)).To(BeTrue()) - }) - - It("GetResource should fail for a non-existent resource", func() { - _, err := c.GetResource(res.GVK) - Expect(err).To(HaveOccurred()) - }) - - It("GetResource should return an existent resource", func() { - c.Gvks = append(c.Gvks, res.GVK) - r, err := c.GetResource(res.GVK) - Expect(err).NotTo(HaveOccurred()) - Expect(r.GVK.IsEqualTo(res.GVK)).To(BeTrue()) - }) - - It("GetResources should return a slice of the tracked resources", func() { - c.Gvks = append(c.Gvks, res.GVK, res.GVK, res.GVK) - resources, err := c.GetResources() - Expect(err).NotTo(HaveOccurred()) - Expect(resources).To(Equal([]resource.Resource{res, res, res})) - }) - - It("AddResource should add the provided resource if non-existent", func() { - l := len(c.Gvks) - Expect(c.AddResource(res)).To(Succeed()) - Expect(len(c.Gvks)).To(Equal(l + 1)) - Expect(c.Gvks[0].IsEqualTo(res.GVK)).To(BeTrue()) - }) - - It("AddResource should do nothing if the resource already exists", func() { - c.Gvks = append(c.Gvks, res.GVK) - l := len(c.Gvks) - Expect(c.AddResource(res)).To(Succeed()) - Expect(len(c.Gvks)).To(Equal(l)) - }) - - It("UpdateResource should add the provided resource if non-existent", func() { - l := len(c.Gvks) - Expect(c.UpdateResource(res)).To(Succeed()) - Expect(len(c.Gvks)).To(Equal(l + 1)) - Expect(c.Gvks[0].IsEqualTo(res.GVK)).To(BeTrue()) - }) - - It("UpdateResource should do nothing if the resource already exists", func() { - c.Gvks = append(c.Gvks, res.GVK) - l := len(c.Gvks) - Expect(c.UpdateResource(res)).To(Succeed()) - Expect(len(c.Gvks)).To(Equal(l)) - }) - - It("HasGroup should return false with no tracked resources", func() { - Expect(c.HasGroup(res.Group)).To(BeFalse()) - }) - - It("HasGroup should return true with tracked resources in the same group", func() { - c.Gvks = append(c.Gvks, res.GVK) - Expect(c.HasGroup(res.Group)).To(BeTrue()) - }) - - It("HasGroup should return false with tracked resources in other group", func() { - c.Gvks = append(c.Gvks, res.GVK) - Expect(c.HasGroup("other-group")).To(BeFalse()) - }) - - It("ListCRDVersions should return an empty list", func() { - Expect(c.ListCRDVersions()).To(BeEmpty()) - }) - - It("ListWebhookVersions should return an empty list", func() { - Expect(c.ListWebhookVersions()).To(BeEmpty()) - }) - }) - - Context("Plugins", func() { - It("DecodePluginConfig should fail", func() { - Expect(c.DecodePluginConfig("", nil)).NotTo(Succeed()) - }) - - It("EncodePluginConfig should fail", func() { - Expect(c.EncodePluginConfig("", nil)).NotTo(Succeed()) - }) - }) - - Context("Persistence", func() { - var ( - // BeforeEach is called after the entries are evaluated, and therefore, c is not available - c1 = cfg{ - Version: Version, - Domain: domain, - Repository: repo, - } - c2 = cfg{ - Version: Version, - Domain: otherDomain, - Repository: otherRepo, - MultiGroup: true, - Gvks: []resource.GVK{ - {Group: "group", Version: "v1", Kind: "Kind"}, - {Group: "group", Version: "v1", Kind: "Kind2"}, - {Group: "group", Version: "v1-beta", Kind: "Kind"}, - {Group: "group2", Version: "v1", Kind: "Kind"}, - }, - } - s1 = `domain: my.domain -repo: myrepo -version: "2" -` - s2 = `domain: other.domain -multigroup: true -repo: otherrepo -resources: -- group: group - kind: Kind - version: v1 -- group: group - kind: Kind2 - version: v1 -- group: group - kind: Kind - version: v1-beta -- group: group2 - kind: Kind - version: v1 -version: "2" -` - ) - - DescribeTable("MarshalYAML should succeed", - func(c cfg, content string) { - b, err := c.MarshalYAML() - Expect(err).NotTo(HaveOccurred()) - Expect(string(b)).To(Equal(content)) - }, - Entry("for a basic configuration", c1, s1), - Entry("for a full configuration", c2, s2), - ) - DescribeTable("UnmarshalYAML should succeed", - func(content string, c cfg) { - var unmarshalled cfg - Expect(unmarshalled.UnmarshalYAML([]byte(content))).To(Succeed()) - Expect(unmarshalled.Version.Compare(c.Version)).To(Equal(0)) - Expect(unmarshalled.Domain).To(Equal(c.Domain)) - Expect(unmarshalled.Repository).To(Equal(c.Repository)) - Expect(unmarshalled.MultiGroup).To(Equal(c.MultiGroup)) - Expect(unmarshalled.Gvks).To(Equal(c.Gvks)) - }, - Entry("basic", s1, c1), - Entry("full", s2, c2), - ) - - DescribeTable("UnmarshalYAML should fail", - func(content string) { - var c cfg - Expect(c.UnmarshalYAML([]byte(content))).NotTo(Succeed()) - }, - Entry("for unknown fields", `field: 1 -version: "2"`), - ) - }) -}) - -var _ = Describe("New", func() { - It("should return a new config for project configuration 2", func() { - Expect(New().GetVersion().Compare(Version)).To(Equal(0)) - }) -}) diff --git a/pkg/plugins/common/kustomize/v1/api.go b/pkg/plugins/common/kustomize/v1/api.go deleted file mode 100644 index 708ea60e0e..0000000000 --- a/pkg/plugins/common/kustomize/v1/api.go +++ /dev/null @@ -1,39 +0,0 @@ -/* -Copyright 2022 The Kubernetes 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. -*/ - -//go:deprecated This package has been deprecated in favor of v2 -package v1 - -import ( - "sigs.k8s.io/kubebuilder/v3/pkg/machinery" - "sigs.k8s.io/kubebuilder/v3/pkg/plugin" - "sigs.k8s.io/kubebuilder/v3/pkg/plugins/common/kustomize/v1/scaffolds" -) - -var _ plugin.CreateAPISubcommand = &createAPISubcommand{} - -type createAPISubcommand struct { - createSubcommand -} - -func (p *createAPISubcommand) Scaffold(fs machinery.Filesystem) error { - if err := p.configure(); err != nil { - return err - } - scaffolder := scaffolds.NewAPIScaffolder(p.config, *p.resource, p.force) - scaffolder.InjectFS(fs) - return scaffolder.Scaffold() -} diff --git a/pkg/plugins/common/kustomize/v1/create.go b/pkg/plugins/common/kustomize/v1/create.go deleted file mode 100644 index ad2c850a12..0000000000 --- a/pkg/plugins/common/kustomize/v1/create.go +++ /dev/null @@ -1,59 +0,0 @@ -/* -Copyright 2022 The Kubernetes 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. -*/ - -//go:deprecated This package has been deprecated in favor of v2 -package v1 - -import ( - "strconv" - - "github.com/spf13/pflag" - - "sigs.k8s.io/kubebuilder/v3/pkg/config" - "sigs.k8s.io/kubebuilder/v3/pkg/model/resource" -) - -type createSubcommand struct { - config config.Config - resource *resource.Resource - - flagSet *pflag.FlagSet - - // force indicates whether to scaffold files even if they exist. - force bool -} - -func (p *createSubcommand) BindFlags(fs *pflag.FlagSet) { p.flagSet = fs } - -func (p *createSubcommand) InjectConfig(c config.Config) error { - p.config = c - return nil -} - -func (p *createSubcommand) InjectResource(res *resource.Resource) error { - p.resource = res - return nil -} - -func (p *createSubcommand) configure() (err error) { - if forceFlag := p.flagSet.Lookup("force"); forceFlag != nil { - if p.force, err = strconv.ParseBool(forceFlag.Value.String()); err != nil { - return err - } - - } - return nil -} diff --git a/pkg/plugins/common/kustomize/v1/init.go b/pkg/plugins/common/kustomize/v1/init.go deleted file mode 100644 index 251a756137..0000000000 --- a/pkg/plugins/common/kustomize/v1/init.go +++ /dev/null @@ -1,138 +0,0 @@ -/* -Copyright 2022 The Kubernetes 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. -*/ - -//go:deprecated This package has been deprecated in favor of v2 -package v1 - -import ( - "fmt" - "os" - "path/filepath" - "runtime" - "strings" - - log "github.com/sirupsen/logrus" - "github.com/spf13/pflag" - - "sigs.k8s.io/kubebuilder/v3/pkg/config" - "sigs.k8s.io/kubebuilder/v3/pkg/internal/validation" - "sigs.k8s.io/kubebuilder/v3/pkg/machinery" - "sigs.k8s.io/kubebuilder/v3/pkg/plugin" - "sigs.k8s.io/kubebuilder/v3/pkg/plugins/common/kustomize/v1/scaffolds" -) - -var _ plugin.InitSubcommand = &initSubcommand{} - -// Verify if the local environment is supported by this plugin -var supportedArchs = []string{"linux/amd64", - "linux/arm64", - "darwin/amd64"} - -type initSubcommand struct { - config config.Config - - // config options - domain string - name string -} - -func (p *initSubcommand) UpdateMetadata(cliMeta plugin.CLIMetadata, subcmdMeta *plugin.SubcommandMetadata) { - subcmdMeta.Description = fmt.Sprintf(`Initialize a common project including the following files: - - a "PROJECT" file that stores project configuration - - several YAML files for project deployment under the "config" directory - - NOTE: The kustomize/v1 plugin used to do this scaffold uses the v3 release (%s). -Therefore, darwin/arm64 is not supported since Kustomize does not provide v3 -binaries for this architecture. The currently supported architectures are %q. -More info: https://github.com/kubernetes-sigs/kustomize/issues/4612. - -`, KustomizeVersion, supportedArchs) - - subcmdMeta.Examples = fmt.Sprintf(` # Initialize a common project with your domain and name in copyright - %[1]s init --plugins common/v3 --domain example.org - - # Initialize a common project defining a specific project version - %[1]s init --plugins common/v3 --project-version 3 -`, cliMeta.CommandName) -} - -func (p *initSubcommand) BindFlags(fs *pflag.FlagSet) { - fs.StringVar(&p.domain, "domain", "my.domain", "domain for groups") - fs.StringVar(&p.name, "project-name", "", "name of this project") -} - -func (p *initSubcommand) InjectConfig(c config.Config) error { - p.config = c - - if err := p.config.SetDomain(p.domain); err != nil { - return err - } - - // Assign a default project name - if p.name == "" { - dir, err := os.Getwd() - if err != nil { - return fmt.Errorf("error getting current directory: %v", err) - } - p.name = strings.ToLower(filepath.Base(dir)) - } - // Check if the project name is a valid k8s namespace (DNS 1123 label). - if err := validation.IsDNS1123Label(p.name); err != nil { - return fmt.Errorf("project name (%s) is invalid: %v", p.name, err) - } - if err := p.config.SetProjectName(p.name); err != nil { - return err - } - - return nil -} - -func (p *initSubcommand) PreScaffold(machinery.Filesystem) error { - arch := runtime.GOARCH - // It probably will never return x86_64. However, we are here checking the support for the binaries - // So that, x86_64 means getting the Linux/amd64 binary. Then, we just keep this line to ensure - // that it complies with the same code implementation that we have in the targets. In case someone - // call the command inform the GOARCH=x86_64 then, we will properly handle the scenario - // since it will work successfully and will instal the Linux/amd64 binary via the Makefile target. - arch = strings.Replace(arch, "x86_64", "amd64", -1) - localPlatform := fmt.Sprintf("%s/%s", strings.TrimSpace(runtime.GOOS), strings.TrimSpace(arch)) - - if !hasSupportFor(localPlatform) { - log.Warnf("the platform of this environment (%s) is not suppported by kustomize v3 (%s) which is "+ - "used in this scaffold. You will be unable to download a binary for the kustomize version supported "+ - "and used by this plugin. The currently supported platforms are: %q", - localPlatform, - KustomizeVersion, - supportedArchs) - } - - return nil -} - -func hasSupportFor(localPlatform string) bool { - for _, value := range supportedArchs { - if value == localPlatform { - return true - } - } - return false -} - -func (p *initSubcommand) Scaffold(fs machinery.Filesystem) error { - scaffolder := scaffolds.NewInitScaffolder(p.config) - scaffolder.InjectFS(fs) - return scaffolder.Scaffold() -} diff --git a/pkg/plugins/common/kustomize/v1/plugin.go b/pkg/plugins/common/kustomize/v1/plugin.go deleted file mode 100644 index 492149d210..0000000000 --- a/pkg/plugins/common/kustomize/v1/plugin.go +++ /dev/null @@ -1,73 +0,0 @@ -/* -Copyright 2022 The Kubernetes 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. -*/ - -//go:deprecated This package has been deprecated in favor of v2 -package v1 - -import ( - "sigs.k8s.io/kubebuilder/v3/pkg/config" - cfgv3 "sigs.k8s.io/kubebuilder/v3/pkg/config/v3" - "sigs.k8s.io/kubebuilder/v3/pkg/plugin" - "sigs.k8s.io/kubebuilder/v3/pkg/plugins" -) - -// KustomizeVersion is the kubernetes-sigs/kustomize version to be used in the project -const KustomizeVersion = "v3.8.7" - -const pluginName = "kustomize.common." + plugins.DefaultNameQualifier - -var ( - pluginVersion = plugin.Version{Number: 1} - supportedProjectVersions = []config.Version{cfgv3.Version} -) - -var ( - _ plugin.Init = Plugin{} - _ plugin.CreateAPI = Plugin{} - _ plugin.CreateWebhook = Plugin{} -) - -// Plugin implements the plugin.Full interface -type Plugin struct { - initSubcommand - createAPISubcommand - createWebhookSubcommand -} - -// Name returns the name of the plugin -func (Plugin) Name() string { return pluginName } - -// Version returns the version of the plugin -func (Plugin) Version() plugin.Version { return pluginVersion } - -// SupportedProjectVersions returns an array with all project versions supported by the plugin -func (Plugin) SupportedProjectVersions() []config.Version { return supportedProjectVersions } - -// GetInitSubcommand will return the subcommand which is responsible for scaffolding init project -func (p Plugin) GetInitSubcommand() plugin.InitSubcommand { return &p.initSubcommand } - -// GetCreateAPISubcommand will return the subcommand which is responsible for scaffolding apis -func (p Plugin) GetCreateAPISubcommand() plugin.CreateAPISubcommand { return &p.createAPISubcommand } - -// GetCreateWebhookSubcommand will return the subcommand which is responsible for scaffolding webhooks -func (p Plugin) GetCreateWebhookSubcommand() plugin.CreateWebhookSubcommand { - return &p.createWebhookSubcommand -} - -func (p Plugin) DeprecationWarning() string { - return "This version is deprecated.The kustomize/v1 plugin used within go/v3 projects uses an old version " + - "of kustomize (v3). It is recommended that you upgrade your project to use the go/v4 and kustomize/v2 plugins." -} diff --git a/pkg/plugins/common/kustomize/v1/scaffolds/api.go b/pkg/plugins/common/kustomize/v1/scaffolds/api.go deleted file mode 100644 index c3fefbd5c3..0000000000 --- a/pkg/plugins/common/kustomize/v1/scaffolds/api.go +++ /dev/null @@ -1,89 +0,0 @@ -/* -Copyright 2022 The Kubernetes 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 scaffolds - -import ( - "fmt" - - log "github.com/sirupsen/logrus" - - "sigs.k8s.io/kubebuilder/v3/pkg/config" - "sigs.k8s.io/kubebuilder/v3/pkg/machinery" - "sigs.k8s.io/kubebuilder/v3/pkg/model/resource" - "sigs.k8s.io/kubebuilder/v3/pkg/plugins" - "sigs.k8s.io/kubebuilder/v3/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/crd" - "sigs.k8s.io/kubebuilder/v3/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/crd/patches" - "sigs.k8s.io/kubebuilder/v3/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/rbac" - "sigs.k8s.io/kubebuilder/v3/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/samples" -) - -var _ plugins.Scaffolder = &apiScaffolder{} - -// apiScaffolder contains configuration for generating scaffolding for Go type -// representing the API and controller that implements the behavior for the API. -type apiScaffolder struct { - config config.Config - resource resource.Resource - - // fs is the filesystem that will be used by the scaffolder - fs machinery.Filesystem - - // force indicates whether to scaffold files even if they exist. - force bool -} - -// NewAPIScaffolder returns a new Scaffolder for API/controller creation operations -func NewAPIScaffolder(config config.Config, res resource.Resource, force bool) plugins.Scaffolder { - return &apiScaffolder{ - config: config, - resource: res, - force: force, - } -} - -// InjectFS implements cmdutil.Scaffolder -func (s *apiScaffolder) InjectFS(fs machinery.Filesystem) { - s.fs = fs -} - -// Scaffold implements cmdutil.Scaffolder -func (s *apiScaffolder) Scaffold() error { - log.Println("Writing kustomize manifests for you to edit...") - - // Initialize the machinery.Scaffold that will write the files to disk - scaffold := machinery.NewScaffold(s.fs, - machinery.WithConfig(s.config), - machinery.WithResource(&s.resource), - ) - - // Keep track of these values before the update - if s.resource.HasAPI() { - if err := scaffold.Execute( - &samples.CRDSample{Force: s.force}, - &rbac.CRDEditorRole{}, - &rbac.CRDViewerRole{}, - &patches.EnableWebhookPatch{}, - &patches.EnableCAInjectionPatch{}, - &crd.Kustomization{}, - &crd.KustomizeConfig{}, - ); err != nil { - return fmt.Errorf("error scaffolding kustomize API manifests: %v", err) - } - } - - return nil -} diff --git a/pkg/plugins/common/kustomize/v1/scaffolds/init.go b/pkg/plugins/common/kustomize/v1/scaffolds/init.go deleted file mode 100644 index 2a160fc148..0000000000 --- a/pkg/plugins/common/kustomize/v1/scaffolds/init.go +++ /dev/null @@ -1,85 +0,0 @@ -/* -Copyright 2022 The Kubernetes 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 scaffolds - -import ( - log "github.com/sirupsen/logrus" - - "sigs.k8s.io/kubebuilder/v3/pkg/config" - "sigs.k8s.io/kubebuilder/v3/pkg/machinery" - "sigs.k8s.io/kubebuilder/v3/pkg/plugins" - "sigs.k8s.io/kubebuilder/v3/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/kdefault" - "sigs.k8s.io/kubebuilder/v3/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/manager" - "sigs.k8s.io/kubebuilder/v3/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/prometheus" - "sigs.k8s.io/kubebuilder/v3/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/rbac" -) - -const ( - imageName = "controller:latest" -) - -var _ plugins.Scaffolder = &initScaffolder{} - -type initScaffolder struct { - config config.Config - - // fs is the filesystem that will be used by the scaffolder - fs machinery.Filesystem -} - -// NewInitScaffolder returns a new Scaffolder for project initialization operations -func NewInitScaffolder(config config.Config) plugins.Scaffolder { - return &initScaffolder{ - config: config, - } -} - -// InjectFS implements cmdutil.Scaffolder -func (s *initScaffolder) InjectFS(fs machinery.Filesystem) { - s.fs = fs -} - -// Scaffold implements cmdutil.Scaffolder -func (s *initScaffolder) Scaffold() error { - log.Println("Writing kustomize manifests for you to edit...") - - // Initialize the machinery.Scaffold that will write the files to disk - scaffold := machinery.NewScaffold(s.fs, - machinery.WithConfig(s.config), - ) - - templates := []machinery.Builder{ - &rbac.Kustomization{}, - &rbac.AuthProxyRole{}, - &rbac.AuthProxyRoleBinding{}, - &rbac.AuthProxyService{}, - &rbac.AuthProxyClientRole{}, - &rbac.RoleBinding{}, - &rbac.LeaderElectionRole{}, - &rbac.LeaderElectionRoleBinding{}, - &rbac.ServiceAccount{}, - &manager.Kustomization{}, - &manager.Config{Image: imageName}, - &kdefault.Kustomization{}, - &kdefault.ManagerAuthProxyPatch{}, - &kdefault.ManagerConfigPatch{}, - &prometheus.Kustomization{}, - &prometheus.Monitor{}, - } - - return scaffold.Execute(templates...) -} diff --git a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/certmanager/certificate.go b/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/certmanager/certificate.go deleted file mode 100644 index 710f21b321..0000000000 --- a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/certmanager/certificate.go +++ /dev/null @@ -1,86 +0,0 @@ -/* -Copyright 2020 The Kubernetes 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 certmanager - -import ( - "path/filepath" - - "sigs.k8s.io/kubebuilder/v3/pkg/machinery" -) - -var _ machinery.Template = &Certificate{} - -// Certificate scaffolds a file that defines the issuer CR and the certificate CR -type Certificate struct { - machinery.TemplateMixin - machinery.ProjectNameMixin -} - -// SetTemplateDefaults implements file.Template -func (f *Certificate) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("config", "certmanager", "certificate.yaml") - } - - f.TemplateBody = certManagerTemplate - - // If file exists (ex. because a webhook was already created), skip creation. - f.IfExistsAction = machinery.SkipFile - - return nil -} - -const certManagerTemplate = `# The following manifests contain a self-signed issuer CR and a certificate CR. -# More document can be found at https://docs.cert-manager.io -# WARNING: Targets CertManager v1.0. Check https://cert-manager.io/docs/installation/upgrading/ for breaking changes. -apiVersion: cert-manager.io/v1 -kind: Issuer -metadata: - labels: - app.kubernetes.io/name: issuer - app.kubernetes.io/instance: selfsigned-issuer - app.kubernetes.io/component: certificate - app.kubernetes.io/created-by: {{ .ProjectName }} - app.kubernetes.io/part-of: {{ .ProjectName }} - app.kubernetes.io/managed-by: kustomize - name: selfsigned-issuer - namespace: system -spec: - selfSigned: {} ---- -apiVersion: cert-manager.io/v1 -kind: Certificate -metadata: - labels: - app.kubernetes.io/name: certificate - app.kubernetes.io/instance: serving-cert - app.kubernetes.io/component: certificate - app.kubernetes.io/created-by: {{ .ProjectName }} - app.kubernetes.io/part-of: {{ .ProjectName }} - app.kubernetes.io/managed-by: kustomize - name: serving-cert # this name should match the one appeared in kustomizeconfig.yaml - namespace: system -spec: - # $(SERVICE_NAME) and $(SERVICE_NAMESPACE) will be substituted by kustomize - dnsNames: - - $(SERVICE_NAME).$(SERVICE_NAMESPACE).svc - - $(SERVICE_NAME).$(SERVICE_NAMESPACE).svc.cluster.local - issuerRef: - kind: Issuer - name: selfsigned-issuer - secretName: webhook-server-cert # this secret will not be prefixed, since it's not managed by kustomize -` diff --git a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/certmanager/kustomization.go b/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/certmanager/kustomization.go deleted file mode 100644 index 2e31a62d4a..0000000000 --- a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/certmanager/kustomization.go +++ /dev/null @@ -1,51 +0,0 @@ -/* -Copyright 2020 The Kubernetes 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 certmanager - -import ( - "path/filepath" - - "sigs.k8s.io/kubebuilder/v3/pkg/machinery" -) - -var _ machinery.Template = &Kustomization{} - -// Kustomization scaffolds a file that defines the kustomization scheme for the certmanager folder -type Kustomization struct { - machinery.TemplateMixin -} - -// SetTemplateDefaults implements file.Template -func (f *Kustomization) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("config", "certmanager", "kustomization.yaml") - } - - f.TemplateBody = kustomizationTemplate - - // If file exists (ex. because a webhook was already created), skip creation. - f.IfExistsAction = machinery.SkipFile - - return nil -} - -const kustomizationTemplate = `resources: -- certificate.yaml - -configurations: -- kustomizeconfig.yaml -` diff --git a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/certmanager/kustomizeconfig.go b/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/certmanager/kustomizeconfig.go deleted file mode 100644 index c89e1f9a58..0000000000 --- a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/certmanager/kustomizeconfig.go +++ /dev/null @@ -1,63 +0,0 @@ -/* -Copyright 2020 The Kubernetes 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 certmanager - -import ( - "path/filepath" - - "sigs.k8s.io/kubebuilder/v3/pkg/machinery" -) - -var _ machinery.Template = &KustomizeConfig{} - -// KustomizeConfig scaffolds a file that configures the kustomization for the certmanager folder -type KustomizeConfig struct { - machinery.TemplateMixin -} - -// SetTemplateDefaults implements file.Template -func (f *KustomizeConfig) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("config", "certmanager", "kustomizeconfig.yaml") - } - - f.TemplateBody = kustomizeConfigTemplate - - // If file exists (ex. because a webhook was already created), skip creation. - f.IfExistsAction = machinery.SkipFile - - return nil -} - -//nolint:lll -const kustomizeConfigTemplate = `# This configuration is for teaching kustomize how to update name ref and var substitution -nameReference: -- kind: Issuer - group: cert-manager.io - fieldSpecs: - - kind: Certificate - group: cert-manager.io - path: spec/issuerRef/name - -varReference: -- kind: Certificate - group: cert-manager.io - path: spec/commonName -- kind: Certificate - group: cert-manager.io - path: spec/dnsNames -` diff --git a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/crd/kustomization.go b/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/crd/kustomization.go deleted file mode 100644 index 0dd55f5204..0000000000 --- a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/crd/kustomization.go +++ /dev/null @@ -1,126 +0,0 @@ -/* -Copyright 2020 The Kubernetes 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 crd - -import ( - "fmt" - "path/filepath" - - "sigs.k8s.io/kubebuilder/v3/pkg/machinery" -) - -var ( - _ machinery.Template = &Kustomization{} - _ machinery.Inserter = &Kustomization{} -) - -// Kustomization scaffolds a file that defines the kustomization scheme for the crd folder -type Kustomization struct { - machinery.TemplateMixin - machinery.ResourceMixin -} - -// SetTemplateDefaults implements file.Template -func (f *Kustomization) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("config", "crd", "kustomization.yaml") - } - f.Path = f.Resource.Replacer().Replace(f.Path) - - f.TemplateBody = fmt.Sprintf(kustomizationTemplate, - machinery.NewMarkerFor(f.Path, resourceMarker), - machinery.NewMarkerFor(f.Path, webhookPatchMarker), - machinery.NewMarkerFor(f.Path, caInjectionPatchMarker), - ) - - return nil -} - -//nolint:gosec to ignore false complain G101: Potential hardcoded credentials (gosec) -const ( - resourceMarker = "crdkustomizeresource" - webhookPatchMarker = "crdkustomizewebhookpatch" - caInjectionPatchMarker = "crdkustomizecainjectionpatch" -) - -// GetMarkers implements file.Inserter -func (f *Kustomization) GetMarkers() []machinery.Marker { - return []machinery.Marker{ - machinery.NewMarkerFor(f.Path, resourceMarker), - machinery.NewMarkerFor(f.Path, webhookPatchMarker), - machinery.NewMarkerFor(f.Path, caInjectionPatchMarker), - } -} - -const ( - resourceCodeFragment = `- bases/%s_%s.yaml -` - webhookPatchCodeFragment = `#- patches/webhook_in_%s.yaml -` - caInjectionPatchCodeFragment = `#- patches/cainjection_in_%s.yaml -` -) - -// GetCodeFragments implements file.Inserter -func (f *Kustomization) GetCodeFragments() machinery.CodeFragmentsMap { - fragments := make(machinery.CodeFragmentsMap, 3) - - // Generate resource code fragments - res := make([]string, 0) - res = append(res, fmt.Sprintf(resourceCodeFragment, f.Resource.QualifiedGroup(), f.Resource.Plural)) - - // Generate resource code fragments - webhookPatch := make([]string, 0) - webhookPatch = append(webhookPatch, fmt.Sprintf(webhookPatchCodeFragment, f.Resource.Plural)) - - // Generate resource code fragments - caInjectionPatch := make([]string, 0) - caInjectionPatch = append(caInjectionPatch, fmt.Sprintf(caInjectionPatchCodeFragment, f.Resource.Plural)) - - // Only store code fragments in the map if the slices are non-empty - if len(res) != 0 { - fragments[machinery.NewMarkerFor(f.Path, resourceMarker)] = res - } - if len(webhookPatch) != 0 { - fragments[machinery.NewMarkerFor(f.Path, webhookPatchMarker)] = webhookPatch - } - if len(caInjectionPatch) != 0 { - fragments[machinery.NewMarkerFor(f.Path, caInjectionPatchMarker)] = caInjectionPatch - } - - return fragments -} - -var kustomizationTemplate = `# This kustomization.yaml is not intended to be run by itself, -# since it depends on service name and namespace that are out of this kustomize package. -# It should be run by config/default -resources: -%s - -patchesStrategicMerge: -# [WEBHOOK] To enable webhook, uncomment all the sections with [WEBHOOK] prefix. -# patches here are for enabling the conversion webhook for each CRD -%s - -# [CERTMANAGER] To enable cert-manager, uncomment all the sections with [CERTMANAGER] prefix. -# patches here are for enabling the CA injection for each CRD -%s - -# the following config is for teaching kustomize how to do kustomization for CRDs. -configurations: -- kustomizeconfig.yaml -` diff --git a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/crd/kustomizeconfig.go b/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/crd/kustomizeconfig.go deleted file mode 100644 index 428bfde8b8..0000000000 --- a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/crd/kustomizeconfig.go +++ /dev/null @@ -1,72 +0,0 @@ -/* -Copyright 2020 The Kubernetes 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 crd - -import ( - "path/filepath" - - "sigs.k8s.io/kubebuilder/v3/pkg/machinery" -) - -var _ machinery.Template = &KustomizeConfig{} - -// KustomizeConfig scaffolds a file that configures the kustomization for the crd folder -type KustomizeConfig struct { - machinery.TemplateMixin - machinery.ResourceMixin -} - -// SetTemplateDefaults implements file.Template -func (f *KustomizeConfig) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("config", "crd", "kustomizeconfig.yaml") - } - - f.TemplateBody = kustomizeConfigTemplate - - return nil -} - -//nolint:lll -const kustomizeConfigTemplate = `# This file is for teaching kustomize how to substitute name and namespace reference in CRD -nameReference: -- kind: Service - version: v1 - fieldSpecs: - - kind: CustomResourceDefinition - version: {{ .Resource.API.CRDVersion }} - group: apiextensions.k8s.io - {{- if ne .Resource.API.CRDVersion "v1" }} - path: spec/conversion/webhookClientConfig/service/name - {{- else }} - path: spec/conversion/webhook/clientConfig/service/name - {{- end }} - -namespace: -- kind: CustomResourceDefinition - version: {{ .Resource.API.CRDVersion }} - group: apiextensions.k8s.io - {{- if ne .Resource.API.CRDVersion "v1" }} - path: spec/conversion/webhookClientConfig/service/namespace - {{- else }} - path: spec/conversion/webhook/clientConfig/service/namespace - {{- end }} - create: false - -varReference: -- path: metadata/annotations -` diff --git a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/crd/patches/enablecainjection_patch.go b/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/crd/patches/enablecainjection_patch.go deleted file mode 100644 index 042f2228ad..0000000000 --- a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/crd/patches/enablecainjection_patch.go +++ /dev/null @@ -1,61 +0,0 @@ -/* -Copyright 2020 The Kubernetes 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 patches - -import ( - "path/filepath" - - "sigs.k8s.io/kubebuilder/v3/pkg/machinery" -) - -var _ machinery.Template = &EnableCAInjectionPatch{} - -// EnableCAInjectionPatch scaffolds a file that defines the patch that injects CA into the CRD -type EnableCAInjectionPatch struct { - machinery.TemplateMixin - machinery.MultiGroupMixin - machinery.ResourceMixin -} - -// SetTemplateDefaults implements file.Template -func (f *EnableCAInjectionPatch) SetTemplateDefaults() error { - if f.Path == "" { - if f.MultiGroup { - f.Path = filepath.Join("config", "crd", "patches", "cainjection_in_%[group]_%[plural].yaml") - } else { - f.Path = filepath.Join("config", "crd", "patches", "cainjection_in_%[plural].yaml") - } - } - f.Path = f.Resource.Replacer().Replace(f.Path) - - f.TemplateBody = enableCAInjectionPatchTemplate - - return nil -} - -//nolint:lll -const enableCAInjectionPatchTemplate = `# The following patch adds a directive for certmanager to inject CA into the CRD -{{- if ne .Resource.API.CRDVersion "v1" }} -# CRD conversion requires k8s 1.13 or later. -{{- end }} -apiVersion: apiextensions.k8s.io/{{ .Resource.API.CRDVersion }} -kind: CustomResourceDefinition -metadata: - annotations: - cert-manager.io/inject-ca-from: $(CERTIFICATE_NAMESPACE)/$(CERTIFICATE_NAME) - name: {{ .Resource.Plural }}.{{ .Resource.QualifiedGroup }} -` diff --git a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/crd/patches/enablewebhook_patch.go b/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/crd/patches/enablewebhook_patch.go deleted file mode 100644 index 35662c647a..0000000000 --- a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/crd/patches/enablewebhook_patch.go +++ /dev/null @@ -1,78 +0,0 @@ -/* -Copyright 2020 The Kubernetes 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 patches - -import ( - "path/filepath" - - "sigs.k8s.io/kubebuilder/v3/pkg/machinery" -) - -var _ machinery.Template = &EnableWebhookPatch{} - -// EnableWebhookPatch scaffolds a file that defines the patch that enables conversion webhook for the CRD -type EnableWebhookPatch struct { - machinery.TemplateMixin - machinery.MultiGroupMixin - machinery.ResourceMixin -} - -// SetTemplateDefaults implements file.Template -func (f *EnableWebhookPatch) SetTemplateDefaults() error { - if f.Path == "" { - if f.MultiGroup { - f.Path = filepath.Join("config", "crd", "patches", "webhook_in_%[group]_%[plural].yaml") - } else { - f.Path = filepath.Join("config", "crd", "patches", "webhook_in_%[plural].yaml") - } - - } - f.Path = f.Resource.Replacer().Replace(f.Path) - - f.TemplateBody = enableWebhookPatchTemplate - - return nil -} - -const enableWebhookPatchTemplate = `# The following patch enables a conversion webhook for the CRD -{{- if ne .Resource.API.CRDVersion "v1" }} -# CRD conversion requires k8s 1.13 or later. -{{- end }} -apiVersion: apiextensions.k8s.io/{{ .Resource.API.CRDVersion }} -kind: CustomResourceDefinition -metadata: - name: {{ .Resource.Plural }}.{{ .Resource.QualifiedGroup }} -spec: - conversion: - strategy: Webhook - {{- if ne .Resource.API.CRDVersion "v1" }} - webhookClientConfig: - service: - namespace: system - name: webhook-service - path: /convert - {{- else }} - webhook: - clientConfig: - service: - namespace: system - name: webhook-service - path: /convert - conversionReviewVersions: - - {{ .Resource.API.CRDVersion }} - {{- end }} -` diff --git a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/kdefault/enablecainection_patch.go b/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/kdefault/enablecainection_patch.go deleted file mode 100644 index e52e7f8dd7..0000000000 --- a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/kdefault/enablecainection_patch.go +++ /dev/null @@ -1,77 +0,0 @@ -/* -Copyright 2020 The Kubernetes 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 kdefault - -import ( - "path/filepath" - - "sigs.k8s.io/kubebuilder/v3/pkg/machinery" -) - -var _ machinery.Template = &WebhookCAInjectionPatch{} - -// WebhookCAInjectionPatch scaffolds a file that defines the patch that adds annotation to webhooks -type WebhookCAInjectionPatch struct { - machinery.TemplateMixin - machinery.ResourceMixin - machinery.ProjectNameMixin -} - -// SetTemplateDefaults implements file.Template -func (f *WebhookCAInjectionPatch) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("config", "default", "webhookcainjection_patch.yaml") - } - - f.TemplateBody = injectCAPatchTemplate - - // If file exists (ex. because a webhook was already created), skip creation. - f.IfExistsAction = machinery.SkipFile - - return nil -} - -const injectCAPatchTemplate = `# This patch add annotation to admission webhook config and -# the variables $(CERTIFICATE_NAMESPACE) and $(CERTIFICATE_NAME) will be substituted by kustomize. -apiVersion: admissionregistration.k8s.io/{{ .Resource.Webhooks.WebhookVersion }} -kind: MutatingWebhookConfiguration -metadata: - labels: - app.kubernetes.io/name: mutatingwebhookconfiguration - app.kubernetes.io/instance: mutating-webhook-configuration - app.kubernetes.io/component: webhook - app.kubernetes.io/created-by: {{ .ProjectName }} - app.kubernetes.io/part-of: {{ .ProjectName }} - app.kubernetes.io/managed-by: kustomize - name: mutating-webhook-configuration - annotations: - cert-manager.io/inject-ca-from: $(CERTIFICATE_NAMESPACE)/$(CERTIFICATE_NAME) ---- -apiVersion: admissionregistration.k8s.io/{{ .Resource.Webhooks.WebhookVersion }} -kind: ValidatingWebhookConfiguration -metadata: - labels: - app.kubernetes.io/name: validatingwebhookconfiguration - app.kubernetes.io/instance: validating-webhook-configuration - app.kubernetes.io/component: webhook - app.kubernetes.io/created-by: {{ .ProjectName }} - app.kubernetes.io/part-of: {{ .ProjectName }} - app.kubernetes.io/managed-by: kustomize - name: validating-webhook-configuration - annotations: - cert-manager.io/inject-ca-from: $(CERTIFICATE_NAMESPACE)/$(CERTIFICATE_NAME) -` diff --git a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/kdefault/kustomization.go b/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/kdefault/kustomization.go deleted file mode 100644 index d27fd978e0..0000000000 --- a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/kdefault/kustomization.go +++ /dev/null @@ -1,116 +0,0 @@ -/* -Copyright 2020 The Kubernetes 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 kdefault - -import ( - "path/filepath" - - "sigs.k8s.io/kubebuilder/v3/pkg/machinery" -) - -var _ machinery.Template = &Kustomization{} - -// Kustomization scaffolds a file that defines the kustomization scheme for the default overlay folder -type Kustomization struct { - machinery.TemplateMixin - machinery.ProjectNameMixin -} - -// SetTemplateDefaults implements file.Template -func (f *Kustomization) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("config", "default", "kustomization.yaml") - } - - f.TemplateBody = kustomizeTemplate - - f.IfExistsAction = machinery.Error - - return nil -} - -const kustomizeTemplate = `# Adds namespace to all resources. -namespace: {{ .ProjectName }}-system - -# Value of this field is prepended to the -# names of all resources, e.g. a deployment named -# "wordpress" becomes "alices-wordpress". -# Note that it should also match with the prefix (text before '-') of the namespace -# field above. -namePrefix: {{ .ProjectName }}- - -# Labels to add to all resources and selectors. -#commonLabels: -# someName: someValue - -bases: -- ../crd -- ../rbac -- ../manager -# [WEBHOOK] To enable webhook, uncomment all the sections with [WEBHOOK] prefix including the one in -# crd/kustomization.yaml -#- ../webhook -# [CERTMANAGER] To enable cert-manager, uncomment all sections with 'CERTMANAGER'. 'WEBHOOK' components are required. -#- ../certmanager -# [PROMETHEUS] To enable prometheus monitor, uncomment all sections with 'PROMETHEUS'. -#- ../prometheus - -patchesStrategicMerge: -# Protect the /metrics endpoint by putting it behind auth. -# If you want your controller-manager to expose the /metrics -# endpoint w/o any authn/z, please comment the following line. -- manager_auth_proxy_patch.yaml - -# [WEBHOOK] To enable webhook, uncomment all the sections with [WEBHOOK] prefix including the one in -# crd/kustomization.yaml -#- manager_webhook_patch.yaml - -# [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 -#- webhookcainjection_patch.yaml - -# the following config is for teaching kustomize how to do var substitution -vars: -# [CERTMANAGER] To enable cert-manager, uncomment all sections with 'CERTMANAGER' prefix. -#- name: CERTIFICATE_NAMESPACE # namespace of the certificate CR -# objref: -# kind: Certificate -# group: cert-manager.io -# version: v1 -# name: serving-cert # this name should match the one in certificate.yaml -# fieldref: -# fieldpath: metadata.namespace -#- name: CERTIFICATE_NAME -# objref: -# kind: Certificate -# group: cert-manager.io -# version: v1 -# name: serving-cert # this name should match the one in certificate.yaml -#- name: SERVICE_NAMESPACE # namespace of the service -# objref: -# kind: Service -# version: v1 -# name: webhook-service -# fieldref: -# fieldpath: metadata.namespace -#- name: SERVICE_NAME -# objref: -# kind: Service -# version: v1 -# name: webhook-service -` diff --git a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/kdefault/manager_auth_proxy_patch.go b/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/kdefault/manager_auth_proxy_patch.go deleted file mode 100644 index 921499e214..0000000000 --- a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/kdefault/manager_auth_proxy_patch.go +++ /dev/null @@ -1,84 +0,0 @@ -/* -Copyright 2020 The Kubernetes 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 kdefault - -import ( - "path/filepath" - - "sigs.k8s.io/kubebuilder/v3/pkg/machinery" -) - -var _ machinery.Template = &ManagerAuthProxyPatch{} - -// ManagerAuthProxyPatch scaffolds a file that defines the patch that enables prometheus metrics for the manager -type ManagerAuthProxyPatch struct { - machinery.TemplateMixin -} - -// SetTemplateDefaults implements file.Template -func (f *ManagerAuthProxyPatch) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("config", "default", "manager_auth_proxy_patch.yaml") - } - - f.TemplateBody = kustomizeAuthProxyPatchTemplate - - f.IfExistsAction = machinery.Error - - return nil -} - -const kustomizeAuthProxyPatchTemplate = `# This patch inject a sidecar container which is a HTTP proxy for the -# controller manager, it performs RBAC authorization against the Kubernetes API using SubjectAccessReviews. -apiVersion: apps/v1 -kind: Deployment -metadata: - name: controller-manager - namespace: system -spec: - template: - spec: - containers: - - name: kube-rbac-proxy - securityContext: - allowPrivilegeEscalation: false - capabilities: - drop: - - "ALL" - image: gcr.io/kubebuilder/kube-rbac-proxy:v0.13.1 - args: - - "--secure-listen-address=0.0.0.0:8443" - - "--upstream=http://127.0.0.1:8080/" - - "--logtostderr=true" - - "--v=0" - ports: - - containerPort: 8443 - protocol: TCP - name: https - resources: - limits: - cpu: 500m - memory: 128Mi - requests: - cpu: 5m - memory: 64Mi - - name: manager - args: - - "--health-probe-bind-address=:8081" - - "--metrics-bind-address=127.0.0.1:8080" - - "--leader-elect" -` diff --git a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/kdefault/manager_config_patch.go b/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/kdefault/manager_config_patch.go deleted file mode 100644 index 34395fdffc..0000000000 --- a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/kdefault/manager_config_patch.go +++ /dev/null @@ -1,53 +0,0 @@ -/* -Copyright 2020 The Kubernetes 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 kdefault - -import ( - "path/filepath" - - "sigs.k8s.io/kubebuilder/v3/pkg/machinery" -) - -var _ machinery.Template = &ManagerConfigPatch{} - -// ManagerConfigPatch scaffolds a ManagerConfigPatch for a Resource -type ManagerConfigPatch struct { - machinery.TemplateMixin -} - -// SetTemplateDefaults implements input.Template -func (f *ManagerConfigPatch) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("config", "default", "manager_config_patch.yaml") - } - - f.TemplateBody = managerConfigPatchTemplate - - return nil -} - -const managerConfigPatchTemplate = `apiVersion: apps/v1 -kind: Deployment -metadata: - name: controller-manager - namespace: system -spec: - template: - spec: - containers: - - name: manager -` diff --git a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/kdefault/webhook_manager_patch.go b/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/kdefault/webhook_manager_patch.go deleted file mode 100644 index 7f993dbd31..0000000000 --- a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/kdefault/webhook_manager_patch.go +++ /dev/null @@ -1,75 +0,0 @@ -/* -Copyright 2020 The Kubernetes 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 kdefault - -import ( - "path/filepath" - - "sigs.k8s.io/kubebuilder/v3/pkg/machinery" -) - -var _ machinery.Template = &ManagerWebhookPatch{} - -// ManagerWebhookPatch scaffolds a file that defines the patch that enables webhooks on the manager -type ManagerWebhookPatch struct { - machinery.TemplateMixin - - Force bool -} - -// SetTemplateDefaults implements file.Template -func (f *ManagerWebhookPatch) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("config", "default", "manager_webhook_patch.yaml") - } - - f.TemplateBody = managerWebhookPatchTemplate - - if f.Force { - f.IfExistsAction = machinery.OverwriteFile - } else { - // If file exists (ex. because a webhook was already created), skip creation. - f.IfExistsAction = machinery.SkipFile - } - - return nil -} - -const managerWebhookPatchTemplate = `apiVersion: apps/v1 -kind: Deployment -metadata: - name: controller-manager - namespace: system -spec: - template: - spec: - containers: - - name: manager - ports: - - containerPort: 9443 - name: webhook-server - protocol: TCP - volumeMounts: - - mountPath: /tmp/k8s-webhook-server/serving-certs - name: cert - readOnly: true - volumes: - - name: cert - secret: - defaultMode: 420 - secretName: webhook-server-cert -` diff --git a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/manager/config.go b/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/manager/config.go deleted file mode 100644 index e200440fe5..0000000000 --- a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/manager/config.go +++ /dev/null @@ -1,149 +0,0 @@ -/* -Copyright 2020 The Kubernetes 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 manager - -import ( - "path/filepath" - - "sigs.k8s.io/kubebuilder/v3/pkg/machinery" -) - -var _ machinery.Template = &Config{} - -// Config scaffolds a file that defines the namespace and the manager deployment -type Config struct { - machinery.TemplateMixin - machinery.ProjectNameMixin - - // Image is controller manager image name - Image string -} - -// SetTemplateDefaults implements file.Template -func (f *Config) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("config", "manager", "manager.yaml") - } - - f.TemplateBody = configTemplate - - return nil -} - -const configTemplate = `apiVersion: v1 -kind: Namespace -metadata: - labels: - control-plane: controller-manager - app.kubernetes.io/name: namespace - app.kubernetes.io/instance: system - app.kubernetes.io/component: manager - app.kubernetes.io/created-by: {{ .ProjectName }} - app.kubernetes.io/part-of: {{ .ProjectName }} - app.kubernetes.io/managed-by: kustomize - name: system ---- -apiVersion: apps/v1 -kind: Deployment -metadata: - name: controller-manager - namespace: system - labels: - control-plane: controller-manager - app.kubernetes.io/name: deployment - app.kubernetes.io/instance: controller-manager - app.kubernetes.io/component: manager - app.kubernetes.io/created-by: {{ .ProjectName }} - app.kubernetes.io/part-of: {{ .ProjectName }} - app.kubernetes.io/managed-by: kustomize -spec: - selector: - matchLabels: - control-plane: controller-manager - replicas: 1 - template: - metadata: - annotations: - kubectl.kubernetes.io/default-container: manager - 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 - args: - - --leader-elect - image: {{ .Image }} - name: manager - securityContext: - allowPrivilegeEscalation: false - capabilities: - drop: - - "ALL" - livenessProbe: - httpGet: - path: /healthz - port: 8081 - initialDelaySeconds: 15 - periodSeconds: 20 - readinessProbe: - httpGet: - path: /readyz - 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 - memory: 128Mi - requests: - cpu: 10m - memory: 64Mi - serviceAccountName: controller-manager - terminationGracePeriodSeconds: 10 -` diff --git a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/manager/kustomization.go b/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/manager/kustomization.go deleted file mode 100644 index dcc5157905..0000000000 --- a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/manager/kustomization.go +++ /dev/null @@ -1,47 +0,0 @@ -/* -Copyright 2020 The Kubernetes 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 manager - -import ( - "path/filepath" - - "sigs.k8s.io/kubebuilder/v3/pkg/machinery" -) - -var _ machinery.Template = &Kustomization{} - -// Kustomization scaffolds a file that defines the kustomization scheme for the manager folder -type Kustomization struct { - machinery.TemplateMixin -} - -// SetTemplateDefaults implements file.Template -func (f *Kustomization) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("config", "manager", "kustomization.yaml") - } - - f.TemplateBody = kustomizeManagerTemplate - - f.IfExistsAction = machinery.Error - - return nil -} - -const kustomizeManagerTemplate = `resources: -- manager.yaml -` diff --git a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/prometheus/kustomization.go b/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/prometheus/kustomization.go deleted file mode 100644 index 76bf6e1c5e..0000000000 --- a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/prometheus/kustomization.go +++ /dev/null @@ -1,45 +0,0 @@ -/* -Copyright 2020 The Kubernetes 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 prometheus - -import ( - "path/filepath" - - "sigs.k8s.io/kubebuilder/v3/pkg/machinery" -) - -var _ machinery.Template = &Kustomization{} - -// Kustomization scaffolds a file that defines the kustomization scheme for the prometheus folder -type Kustomization struct { - machinery.TemplateMixin -} - -// SetTemplateDefaults implements file.Template -func (f *Kustomization) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("config", "prometheus", "kustomization.yaml") - } - - f.TemplateBody = kustomizationTemplate - - return nil -} - -const kustomizationTemplate = `resources: -- monitor.yaml -` diff --git a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/prometheus/monitor.go b/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/prometheus/monitor.go deleted file mode 100644 index 2a541cd5e6..0000000000 --- a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/prometheus/monitor.go +++ /dev/null @@ -1,70 +0,0 @@ -/* -Copyright 2020 The Kubernetes 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 prometheus - -import ( - "path/filepath" - - "sigs.k8s.io/kubebuilder/v3/pkg/machinery" -) - -var _ machinery.Template = &Monitor{} - -// Monitor scaffolds a file that defines the prometheus service monitor -type Monitor struct { - machinery.TemplateMixin - machinery.ProjectNameMixin -} - -// SetTemplateDefaults implements file.Template -func (f *Monitor) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("config", "prometheus", "monitor.yaml") - } - - f.TemplateBody = serviceMonitorTemplate - - return nil -} - -const serviceMonitorTemplate = ` -# Prometheus Monitor Service (Metrics) -apiVersion: monitoring.coreos.com/v1 -kind: ServiceMonitor -metadata: - labels: - control-plane: controller-manager - app.kubernetes.io/name: servicemonitor - app.kubernetes.io/instance: controller-manager-metrics-monitor - app.kubernetes.io/component: metrics - app.kubernetes.io/created-by: {{ .ProjectName }} - app.kubernetes.io/part-of: {{ .ProjectName }} - app.kubernetes.io/managed-by: kustomize - name: controller-manager-metrics-monitor - namespace: system -spec: - endpoints: - - path: /metrics - port: https - scheme: https - bearerTokenFile: /var/run/secrets/kubernetes.io/serviceaccount/token - tlsConfig: - insecureSkipVerify: true - selector: - matchLabels: - control-plane: controller-manager -` diff --git a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/rbac/auth_proxy_client_role.go b/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/rbac/auth_proxy_client_role.go deleted file mode 100644 index 680eae6375..0000000000 --- a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/rbac/auth_proxy_client_role.go +++ /dev/null @@ -1,60 +0,0 @@ -/* -Copyright 2020 The Kubernetes 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 rbac - -import ( - "path/filepath" - - "sigs.k8s.io/kubebuilder/v3/pkg/machinery" -) - -var _ machinery.Template = &AuthProxyClientRole{} - -// AuthProxyClientRole scaffolds a file that defines the role for the metrics reader -type AuthProxyClientRole struct { - machinery.TemplateMixin - machinery.ProjectNameMixin -} - -// SetTemplateDefaults implements file.Template -func (f *AuthProxyClientRole) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("config", "rbac", "auth_proxy_client_clusterrole.yaml") - } - - f.TemplateBody = clientClusterRoleTemplate - - return nil -} - -const clientClusterRoleTemplate = `apiVersion: rbac.authorization.k8s.io/v1 -kind: ClusterRole -metadata: - labels: - app.kubernetes.io/name: clusterrole - app.kubernetes.io/instance: metrics-reader - app.kubernetes.io/component: kube-rbac-proxy - app.kubernetes.io/created-by: {{ .ProjectName }} - app.kubernetes.io/part-of: {{ .ProjectName }} - app.kubernetes.io/managed-by: kustomize - name: metrics-reader -rules: -- nonResourceURLs: - - "/metrics" - verbs: - - get -` diff --git a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/rbac/auth_proxy_role.go b/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/rbac/auth_proxy_role.go deleted file mode 100644 index c08756c329..0000000000 --- a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/rbac/auth_proxy_role.go +++ /dev/null @@ -1,68 +0,0 @@ -/* -Copyright 2020 The Kubernetes 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 rbac - -import ( - "path/filepath" - - "sigs.k8s.io/kubebuilder/v3/pkg/machinery" -) - -var _ machinery.Template = &AuthProxyRole{} - -// AuthProxyRole scaffolds a file that defines the role for the auth proxy -type AuthProxyRole struct { - machinery.TemplateMixin - machinery.ProjectNameMixin -} - -// SetTemplateDefaults implements file.Template -func (f *AuthProxyRole) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("config", "rbac", "auth_proxy_role.yaml") - } - - f.TemplateBody = proxyRoleTemplate - - return nil -} - -const proxyRoleTemplate = `apiVersion: rbac.authorization.k8s.io/v1 -kind: ClusterRole -metadata: - labels: - app.kubernetes.io/name: clusterrole - app.kubernetes.io/instance: proxy-role - app.kubernetes.io/component: kube-rbac-proxy - app.kubernetes.io/created-by: {{ .ProjectName }} - app.kubernetes.io/part-of: {{ .ProjectName }} - app.kubernetes.io/managed-by: kustomize - name: proxy-role -rules: -- apiGroups: - - authentication.k8s.io - resources: - - tokenreviews - verbs: - - create -- apiGroups: - - authorization.k8s.io - resources: - - subjectaccessreviews - verbs: - - create -` diff --git a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/rbac/auth_proxy_role_binding.go b/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/rbac/auth_proxy_role_binding.go deleted file mode 100644 index c0df0d2d8c..0000000000 --- a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/rbac/auth_proxy_role_binding.go +++ /dev/null @@ -1,63 +0,0 @@ -/* -Copyright 2020 The Kubernetes 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 rbac - -import ( - "path/filepath" - - "sigs.k8s.io/kubebuilder/v3/pkg/machinery" -) - -var _ machinery.Template = &AuthProxyRoleBinding{} - -// AuthProxyRoleBinding scaffolds a file that defines the role binding for the auth proxy -type AuthProxyRoleBinding struct { - machinery.TemplateMixin - machinery.ProjectNameMixin -} - -// SetTemplateDefaults implements file.Template -func (f *AuthProxyRoleBinding) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("config", "rbac", "auth_proxy_role_binding.yaml") - } - - f.TemplateBody = proxyRoleBindinggTemplate - - return nil -} - -const proxyRoleBindinggTemplate = `apiVersion: rbac.authorization.k8s.io/v1 -kind: ClusterRoleBinding -metadata: - labels: - app.kubernetes.io/name: clusterrolebinding - app.kubernetes.io/instance: proxy-rolebinding - app.kubernetes.io/component: kube-rbac-proxy - app.kubernetes.io/created-by: {{ .ProjectName }} - app.kubernetes.io/part-of: {{ .ProjectName }} - app.kubernetes.io/managed-by: kustomize - name: proxy-rolebinding -roleRef: - apiGroup: rbac.authorization.k8s.io - kind: ClusterRole - name: proxy-role -subjects: -- kind: ServiceAccount - name: controller-manager - namespace: system -` diff --git a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/rbac/auth_proxy_service.go b/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/rbac/auth_proxy_service.go deleted file mode 100644 index beda972e91..0000000000 --- a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/rbac/auth_proxy_service.go +++ /dev/null @@ -1,65 +0,0 @@ -/* -Copyright 2020 The Kubernetes 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 rbac - -import ( - "path/filepath" - - "sigs.k8s.io/kubebuilder/v3/pkg/machinery" -) - -var _ machinery.Template = &AuthProxyService{} - -// AuthProxyService scaffolds a file that defines the service for the auth proxy -type AuthProxyService struct { - machinery.TemplateMixin - machinery.ProjectNameMixin -} - -// SetTemplateDefaults implements file.Template -func (f *AuthProxyService) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("config", "rbac", "auth_proxy_service.yaml") - } - - f.TemplateBody = authProxyServiceTemplate - - return nil -} - -const authProxyServiceTemplate = `apiVersion: v1 -kind: Service -metadata: - labels: - control-plane: controller-manager - app.kubernetes.io/name: service - app.kubernetes.io/instance: controller-manager-metrics-service - app.kubernetes.io/component: kube-rbac-proxy - app.kubernetes.io/created-by: {{ .ProjectName }} - app.kubernetes.io/part-of: {{ .ProjectName }} - app.kubernetes.io/managed-by: kustomize - name: controller-manager-metrics-service - namespace: system -spec: - ports: - - name: https - port: 8443 - protocol: TCP - targetPort: https - selector: - control-plane: controller-manager -` diff --git a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/rbac/crd_editor_role.go b/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/rbac/crd_editor_role.go deleted file mode 100644 index 6e122f3629..0000000000 --- a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/rbac/crd_editor_role.go +++ /dev/null @@ -1,83 +0,0 @@ -/* -Copyright 2020 The Kubernetes 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 rbac - -import ( - "path/filepath" - - "sigs.k8s.io/kubebuilder/v3/pkg/machinery" -) - -var _ machinery.Template = &CRDEditorRole{} - -// CRDEditorRole scaffolds a file that defines the role that allows to edit plurals -type CRDEditorRole struct { - machinery.TemplateMixin - machinery.MultiGroupMixin - machinery.ResourceMixin - machinery.ProjectNameMixin -} - -// SetTemplateDefaults implements file.Template -func (f *CRDEditorRole) SetTemplateDefaults() error { - if f.Path == "" { - if f.MultiGroup { - f.Path = filepath.Join("config", "rbac", "%[group]_%[kind]_editor_role.yaml") - } else { - f.Path = filepath.Join("config", "rbac", "%[kind]_editor_role.yaml") - } - - } - f.Path = f.Resource.Replacer().Replace(f.Path) - - f.TemplateBody = crdRoleEditorTemplate - - return nil -} - -const crdRoleEditorTemplate = `# permissions for end users to edit {{ .Resource.Plural }}. -apiVersion: rbac.authorization.k8s.io/v1 -kind: ClusterRole -metadata: - labels: - app.kubernetes.io/name: clusterrole - app.kubernetes.io/instance: {{ lower .Resource.Kind }}-editor-role - app.kubernetes.io/component: rbac - app.kubernetes.io/created-by: {{ .ProjectName }} - app.kubernetes.io/part-of: {{ .ProjectName }} - app.kubernetes.io/managed-by: kustomize - name: {{ lower .Resource.Kind }}-editor-role -rules: -- apiGroups: - - {{ .Resource.QualifiedGroup }} - resources: - - {{ .Resource.Plural }} - verbs: - - create - - delete - - get - - list - - patch - - update - - watch -- apiGroups: - - {{ .Resource.QualifiedGroup }} - resources: - - {{ .Resource.Plural }}/status - verbs: - - get -` diff --git a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/rbac/crd_viewer_role.go b/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/rbac/crd_viewer_role.go deleted file mode 100644 index ed75bb88b3..0000000000 --- a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/rbac/crd_viewer_role.go +++ /dev/null @@ -1,79 +0,0 @@ -/* -Copyright 2020 The Kubernetes 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 rbac - -import ( - "path/filepath" - - "sigs.k8s.io/kubebuilder/v3/pkg/machinery" -) - -var _ machinery.Template = &CRDViewerRole{} - -// CRDViewerRole scaffolds a file that defines the role that allows to view plurals -type CRDViewerRole struct { - machinery.TemplateMixin - machinery.MultiGroupMixin - machinery.ResourceMixin - machinery.ProjectNameMixin -} - -// SetTemplateDefaults implements file.Template -func (f *CRDViewerRole) SetTemplateDefaults() error { - if f.Path == "" { - if f.MultiGroup { - f.Path = filepath.Join("config", "rbac", "%[group]_%[kind]_viewer_role.yaml") - } else { - f.Path = filepath.Join("config", "rbac", "%[kind]_viewer_role.yaml") - } - - } - f.Path = f.Resource.Replacer().Replace(f.Path) - - f.TemplateBody = crdRoleViewerTemplate - - return nil -} - -const crdRoleViewerTemplate = `# permissions for end users to view {{ .Resource.Plural }}. -apiVersion: rbac.authorization.k8s.io/v1 -kind: ClusterRole -metadata: - labels: - app.kubernetes.io/name: clusterrole - app.kubernetes.io/instance: {{ lower .Resource.Kind }}-viewer-role - app.kubernetes.io/component: rbac - app.kubernetes.io/created-by: {{ .ProjectName }} - app.kubernetes.io/part-of: {{ .ProjectName }} - app.kubernetes.io/managed-by: kustomize - name: {{ lower .Resource.Kind }}-viewer-role -rules: -- apiGroups: - - {{ .Resource.QualifiedGroup }} - resources: - - {{ .Resource.Plural }} - verbs: - - get - - list - - watch -- apiGroups: - - {{ .Resource.QualifiedGroup }} - resources: - - {{ .Resource.Plural }}/status - verbs: - - get -` diff --git a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/rbac/kustomization.go b/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/rbac/kustomization.go deleted file mode 100644 index d3ea9b22fd..0000000000 --- a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/rbac/kustomization.go +++ /dev/null @@ -1,63 +0,0 @@ -/* -Copyright 2020 The Kubernetes 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 rbac - -import ( - "path/filepath" - - "sigs.k8s.io/kubebuilder/v3/pkg/machinery" -) - -var _ machinery.Template = &Kustomization{} - -// Kustomization scaffolds a file that defines the kustomization scheme for the rbac folder -type Kustomization struct { - machinery.TemplateMixin -} - -// SetTemplateDefaults implements file.Template -func (f *Kustomization) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("config", "rbac", "kustomization.yaml") - } - - f.TemplateBody = kustomizeRBACTemplate - - f.IfExistsAction = machinery.Error - - return nil -} - -const kustomizeRBACTemplate = `resources: -# All RBAC will be applied under this service account in -# the deployment namespace. You may comment out this resource -# if your manager will use a service account that exists at -# runtime. Be sure to update RoleBinding and ClusterRoleBinding -# subjects if changing service account names. -- service_account.yaml -- role.yaml -- role_binding.yaml -- leader_election_role.yaml -- leader_election_role_binding.yaml -# Comment the following 4 lines if you want to disable -# the auth proxy (https://github.com/brancz/kube-rbac-proxy) -# which protects your /metrics endpoint. -- auth_proxy_service.yaml -- auth_proxy_role.yaml -- auth_proxy_role_binding.yaml -- auth_proxy_client_clusterrole.yaml -` diff --git a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/rbac/leader_election_role.go b/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/rbac/leader_election_role.go deleted file mode 100644 index 79143b86cd..0000000000 --- a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/rbac/leader_election_role.go +++ /dev/null @@ -1,88 +0,0 @@ -/* -Copyright 2020 The Kubernetes 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 rbac - -import ( - "path/filepath" - - "sigs.k8s.io/kubebuilder/v3/pkg/machinery" -) - -var _ machinery.Template = &LeaderElectionRole{} - -// LeaderElectionRole scaffolds a file that defines the role that allows leader election -type LeaderElectionRole struct { - machinery.TemplateMixin - machinery.ProjectNameMixin -} - -// SetTemplateDefaults implements file.Template -func (f *LeaderElectionRole) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("config", "rbac", "leader_election_role.yaml") - } - - f.TemplateBody = leaderElectionRoleTemplate - - return nil -} - -const leaderElectionRoleTemplate = `# permissions to do leader election. -apiVersion: rbac.authorization.k8s.io/v1 -kind: Role -metadata: - labels: - app.kubernetes.io/name: role - app.kubernetes.io/instance: leader-election-role - app.kubernetes.io/component: rbac - app.kubernetes.io/created-by: {{ .ProjectName }} - app.kubernetes.io/part-of: {{ .ProjectName }} - app.kubernetes.io/managed-by: kustomize - name: leader-election-role -rules: -- apiGroups: - - "" - resources: - - configmaps - verbs: - - get - - list - - watch - - create - - update - - patch - - delete -- apiGroups: - - coordination.k8s.io - resources: - - leases - verbs: - - get - - list - - watch - - create - - update - - patch - - delete -- apiGroups: - - "" - resources: - - events - verbs: - - create - - patch -` diff --git a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/rbac/leader_election_role_binding.go b/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/rbac/leader_election_role_binding.go deleted file mode 100644 index b40b4a5fa9..0000000000 --- a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/rbac/leader_election_role_binding.go +++ /dev/null @@ -1,63 +0,0 @@ -/* -Copyright 2020 The Kubernetes 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 rbac - -import ( - "path/filepath" - - "sigs.k8s.io/kubebuilder/v3/pkg/machinery" -) - -var _ machinery.Template = &LeaderElectionRoleBinding{} - -// LeaderElectionRoleBinding scaffolds a file that defines the role binding that allows leader election -type LeaderElectionRoleBinding struct { - machinery.TemplateMixin - machinery.ProjectNameMixin -} - -// SetTemplateDefaults implements file.Template -func (f *LeaderElectionRoleBinding) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("config", "rbac", "leader_election_role_binding.yaml") - } - - f.TemplateBody = leaderElectionRoleBindingTemplate - - return nil -} - -const leaderElectionRoleBindingTemplate = `apiVersion: rbac.authorization.k8s.io/v1 -kind: RoleBinding -metadata: - labels: - app.kubernetes.io/name: rolebinding - app.kubernetes.io/instance: leader-election-rolebinding - app.kubernetes.io/component: rbac - app.kubernetes.io/created-by: {{ .ProjectName }} - app.kubernetes.io/part-of: {{ .ProjectName }} - app.kubernetes.io/managed-by: kustomize - name: leader-election-rolebinding -roleRef: - apiGroup: rbac.authorization.k8s.io - kind: Role - name: leader-election-role -subjects: -- kind: ServiceAccount - name: controller-manager - namespace: system -` diff --git a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/rbac/role_binding.go b/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/rbac/role_binding.go deleted file mode 100644 index f975ee97ac..0000000000 --- a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/rbac/role_binding.go +++ /dev/null @@ -1,63 +0,0 @@ -/* -Copyright 2020 The Kubernetes 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 rbac - -import ( - "path/filepath" - - "sigs.k8s.io/kubebuilder/v3/pkg/machinery" -) - -var _ machinery.Template = &RoleBinding{} - -// RoleBinding scaffolds a file that defines the role binding for the manager -type RoleBinding struct { - machinery.TemplateMixin - machinery.ProjectNameMixin -} - -// SetTemplateDefaults implements file.Template -func (f *RoleBinding) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("config", "rbac", "role_binding.yaml") - } - - f.TemplateBody = managerBindingTemplate - - return nil -} - -const managerBindingTemplate = `apiVersion: rbac.authorization.k8s.io/v1 -kind: ClusterRoleBinding -metadata: - labels: - app.kubernetes.io/name: clusterrolebinding - app.kubernetes.io/instance: manager-rolebinding - app.kubernetes.io/component: rbac - app.kubernetes.io/created-by: {{ .ProjectName }} - app.kubernetes.io/part-of: {{ .ProjectName }} - app.kubernetes.io/managed-by: kustomize - name: manager-rolebinding -roleRef: - apiGroup: rbac.authorization.k8s.io - kind: ClusterRole - name: manager-role -subjects: -- kind: ServiceAccount - name: controller-manager - namespace: system -` diff --git a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/rbac/service_account.go b/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/rbac/service_account.go deleted file mode 100644 index eace20658f..0000000000 --- a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/rbac/service_account.go +++ /dev/null @@ -1,56 +0,0 @@ -/* -Copyright 2022 The Kubernetes 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 rbac - -import ( - "path/filepath" - - "sigs.k8s.io/kubebuilder/v3/pkg/machinery" -) - -var _ machinery.Template = &ServiceAccount{} - -// ServiceAccount scaffolds a file that defines the service account the manager is deployed in. -type ServiceAccount struct { - machinery.TemplateMixin - machinery.ProjectNameMixin -} - -// SetTemplateDefaults implements file.Template -func (f *ServiceAccount) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("config", "rbac", "service_account.yaml") - } - - f.TemplateBody = serviceAccountTemplate - - return nil -} - -const serviceAccountTemplate = `apiVersion: v1 -kind: ServiceAccount -metadata: - labels: - app.kubernetes.io/name: serviceaccount - app.kubernetes.io/instance: controller-manager - app.kubernetes.io/component: rbac - app.kubernetes.io/created-by: {{ .ProjectName }} - app.kubernetes.io/part-of: {{ .ProjectName }} - app.kubernetes.io/managed-by: kustomize - name: controller-manager - namespace: system -` diff --git a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/samples/crd_sample.go b/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/samples/crd_sample.go deleted file mode 100644 index 06b2376d9f..0000000000 --- a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/samples/crd_sample.go +++ /dev/null @@ -1,66 +0,0 @@ -/* -Copyright 2020 The Kubernetes 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 samples - -import ( - "path/filepath" - - "sigs.k8s.io/kubebuilder/v3/pkg/machinery" -) - -var _ machinery.Template = &CRDSample{} - -// CRDSample scaffolds a file that defines a sample manifest for the CRD -type CRDSample struct { - machinery.TemplateMixin - machinery.ResourceMixin - machinery.ProjectNameMixin - - Force bool -} - -// SetTemplateDefaults implements file.Template -func (f *CRDSample) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("config", "samples", "%[group]_%[version]_%[kind].yaml") - } - f.Path = f.Resource.Replacer().Replace(f.Path) - - if f.Force { - f.IfExistsAction = machinery.OverwriteFile - } else { - f.IfExistsAction = machinery.Error - } - - f.TemplateBody = crdSampleTemplate - - return nil -} - -const crdSampleTemplate = `apiVersion: {{ .Resource.QualifiedGroup }}/{{ .Resource.Version }} -kind: {{ .Resource.Kind }} -metadata: - labels: - app.kubernetes.io/name: {{ lower .Resource.Kind }} - app.kubernetes.io/instance: {{ lower .Resource.Kind }}-sample - app.kubernetes.io/part-of: {{ .ProjectName }} - app.kubernetes.io/managed-by: kustomize - app.kubernetes.io/created-by: {{ .ProjectName }} - name: {{ lower .Resource.Kind }}-sample -spec: - # TODO(user): Add fields here -` diff --git a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/webhook/kustomization.go b/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/webhook/kustomization.go deleted file mode 100644 index 3f55f70a12..0000000000 --- a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/webhook/kustomization.go +++ /dev/null @@ -1,59 +0,0 @@ -/* -Copyright 2020 The Kubernetes 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 webhook - -import ( - "path/filepath" - - "sigs.k8s.io/kubebuilder/v3/pkg/machinery" -) - -var _ machinery.Template = &Kustomization{} - -// Kustomization scaffolds a file that defines the kustomization scheme for the webhook folder -type Kustomization struct { - machinery.TemplateMixin - machinery.ResourceMixin - - Force bool -} - -// SetTemplateDefaults implements file.Template -func (f *Kustomization) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("config", "webhook", "kustomization.yaml") - } - - f.TemplateBody = kustomizeWebhookTemplate - - if f.Force { - f.IfExistsAction = machinery.OverwriteFile - } else { - // If file exists (ex. because a webhook was already created), skip creation. - f.IfExistsAction = machinery.SkipFile - } - - return nil -} - -const kustomizeWebhookTemplate = `resources: -- manifests{{ if ne .Resource.Webhooks.WebhookVersion "v1" }}.{{ .Resource.Webhooks.WebhookVersion }}{{ end }}.yaml -- service.yaml - -configurations: -- kustomizeconfig.yaml -` diff --git a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/webhook/kustomizeconfig.go b/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/webhook/kustomizeconfig.go deleted file mode 100644 index 524f11e71c..0000000000 --- a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/webhook/kustomizeconfig.go +++ /dev/null @@ -1,72 +0,0 @@ -/* -Copyright 2020 The Kubernetes 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 webhook - -import ( - "path/filepath" - - "sigs.k8s.io/kubebuilder/v3/pkg/machinery" -) - -var _ machinery.Template = &KustomizeConfig{} - -// KustomizeConfig scaffolds a file that configures the kustomization for the webhook folder -type KustomizeConfig struct { - machinery.TemplateMixin -} - -// SetTemplateDefaults implements file.Template -func (f *KustomizeConfig) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("config", "webhook", "kustomizeconfig.yaml") - } - - f.TemplateBody = kustomizeConfigWebhookTemplate - - // If file exists (ex. because a webhook was already created), skip creation. - f.IfExistsAction = machinery.SkipFile - - return nil -} - -//nolint:lll -const kustomizeConfigWebhookTemplate = `# the following config is for teaching kustomize where to look at when substituting vars. -# It requires kustomize v2.1.0 or newer to work properly. -nameReference: -- kind: Service - version: v1 - fieldSpecs: - - kind: MutatingWebhookConfiguration - group: admissionregistration.k8s.io - path: webhooks/clientConfig/service/name - - kind: ValidatingWebhookConfiguration - group: admissionregistration.k8s.io - path: webhooks/clientConfig/service/name - -namespace: -- kind: MutatingWebhookConfiguration - group: admissionregistration.k8s.io - path: webhooks/clientConfig/service/namespace - create: true -- kind: ValidatingWebhookConfiguration - group: admissionregistration.k8s.io - path: webhooks/clientConfig/service/namespace - create: true - -varReference: -- path: metadata/annotations -` diff --git a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/webhook/service.go b/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/webhook/service.go deleted file mode 100644 index c9a292a167..0000000000 --- a/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/webhook/service.go +++ /dev/null @@ -1,67 +0,0 @@ -/* -Copyright 2020 The Kubernetes 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 webhook - -import ( - "path/filepath" - - "sigs.k8s.io/kubebuilder/v3/pkg/machinery" -) - -var _ machinery.Template = &Service{} - -// Service scaffolds a file that defines the webhook service -type Service struct { - machinery.TemplateMixin - machinery.ProjectNameMixin -} - -// SetTemplateDefaults implements file.Template -func (f *Service) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("config", "webhook", "service.yaml") - } - - f.TemplateBody = serviceTemplate - - // If file exists (ex. because a webhook was already created), skip creation. - f.IfExistsAction = machinery.SkipFile - - return nil -} - -const serviceTemplate = ` -apiVersion: v1 -kind: Service -metadata: - labels: - app.kubernetes.io/name: service - app.kubernetes.io/instance: webhook-service - app.kubernetes.io/component: webhook - app.kubernetes.io/created-by: {{ .ProjectName }} - app.kubernetes.io/part-of: {{ .ProjectName }} - app.kubernetes.io/managed-by: kustomize - name: webhook-service - namespace: system -spec: - ports: - - port: 443 - protocol: TCP - targetPort: 9443 - selector: - control-plane: controller-manager -` diff --git a/pkg/plugins/common/kustomize/v1/scaffolds/webhook.go b/pkg/plugins/common/kustomize/v1/scaffolds/webhook.go deleted file mode 100644 index 6e494f194a..0000000000 --- a/pkg/plugins/common/kustomize/v1/scaffolds/webhook.go +++ /dev/null @@ -1,86 +0,0 @@ -/* -Copyright 2022 The Kubernetes 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 scaffolds - -import ( - "fmt" - - log "github.com/sirupsen/logrus" - - "sigs.k8s.io/kubebuilder/v3/pkg/config" - "sigs.k8s.io/kubebuilder/v3/pkg/machinery" - "sigs.k8s.io/kubebuilder/v3/pkg/model/resource" - "sigs.k8s.io/kubebuilder/v3/pkg/plugins" - "sigs.k8s.io/kubebuilder/v3/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/certmanager" - "sigs.k8s.io/kubebuilder/v3/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/kdefault" - "sigs.k8s.io/kubebuilder/v3/pkg/plugins/common/kustomize/v1/scaffolds/internal/templates/config/webhook" -) - -var _ plugins.Scaffolder = &webhookScaffolder{} - -type webhookScaffolder struct { - config config.Config - resource resource.Resource - - // fs is the filesystem that will be used by the scaffolder - fs machinery.Filesystem - - // force indicates whether to scaffold files even if they exist. - force bool -} - -// NewWebhookScaffolder returns a new Scaffolder for v2 webhook creation operations -func NewWebhookScaffolder(config config.Config, resource resource.Resource, force bool) plugins.Scaffolder { - return &webhookScaffolder{ - config: config, - resource: resource, - force: force, - } -} - -// InjectFS implements cmdutil.Scaffolder -func (s *webhookScaffolder) InjectFS(fs machinery.Filesystem) { s.fs = fs } - -// Scaffold implements cmdutil.Scaffolder -func (s *webhookScaffolder) Scaffold() error { - log.Println("Writing kustomize manifests for you to edit...") - - // Initialize the machinery.Scaffold that will write the files to disk - scaffold := machinery.NewScaffold(s.fs, - machinery.WithConfig(s.config), - machinery.WithResource(&s.resource), - ) - - if err := s.config.UpdateResource(s.resource); err != nil { - return fmt.Errorf("error updating resource: %w", err) - } - - if err := scaffold.Execute( - &kdefault.WebhookCAInjectionPatch{}, - &kdefault.ManagerWebhookPatch{}, - &webhook.Kustomization{Force: s.force}, - &webhook.KustomizeConfig{}, - &webhook.Service{}, - &certmanager.Certificate{}, - &certmanager.Kustomization{}, - &certmanager.KustomizeConfig{}, - ); err != nil { - return fmt.Errorf("error scaffolding kustomize webhook manifests: %v", err) - } - - return nil -} diff --git a/pkg/plugins/common/kustomize/v1/webhook.go b/pkg/plugins/common/kustomize/v1/webhook.go deleted file mode 100644 index b971515981..0000000000 --- a/pkg/plugins/common/kustomize/v1/webhook.go +++ /dev/null @@ -1,39 +0,0 @@ -/* -Copyright 2022 The Kubernetes 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. -*/ - -//go:deprecated This package has been deprecated in favor of v2 -package v1 - -import ( - "sigs.k8s.io/kubebuilder/v3/pkg/machinery" - "sigs.k8s.io/kubebuilder/v3/pkg/plugin" - "sigs.k8s.io/kubebuilder/v3/pkg/plugins/common/kustomize/v1/scaffolds" -) - -var _ plugin.CreateWebhookSubcommand = &createWebhookSubcommand{} - -type createWebhookSubcommand struct { - createSubcommand -} - -func (p *createWebhookSubcommand) Scaffold(fs machinery.Filesystem) error { - if err := p.configure(); err != nil { - return err - } - scaffolder := scaffolds.NewWebhookScaffolder(p.config, *p.resource, p.force) - scaffolder.InjectFS(fs) - return scaffolder.Scaffold() -} diff --git a/pkg/plugins/golang/v2/scaffolds/internal/templates/controllers/controller_suitetest.go b/pkg/plugins/golang/v2/scaffolds/internal/templates/controllers/controller_suitetest.go deleted file mode 100644 index d8a0b97505..0000000000 --- a/pkg/plugins/golang/v2/scaffolds/internal/templates/controllers/controller_suitetest.go +++ /dev/null @@ -1,184 +0,0 @@ -/* -Copyright 2020 The Kubernetes 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 controllers - -import ( - "fmt" - "path/filepath" - - "sigs.k8s.io/kubebuilder/v3/pkg/machinery" -) - -var _ machinery.Template = &SuiteTest{} -var _ machinery.Inserter = &SuiteTest{} - -// SuiteTest scaffolds the file that sets up the controller tests -// nolint:maligned -type SuiteTest struct { - machinery.TemplateMixin - machinery.MultiGroupMixin - machinery.BoilerplateMixin - machinery.ResourceMixin - - // CRDDirectoryRelativePath define the Path for the CRD - CRDDirectoryRelativePath string - - Force bool -} - -// SetTemplateDefaults implements file.Template -func (f *SuiteTest) SetTemplateDefaults() error { - if f.Path == "" { - if f.MultiGroup { - f.Path = filepath.Join("controllers", "%[group]", "suite_test.go") - } else { - f.Path = filepath.Join("controllers", "suite_test.go") - } - } - f.Path = f.Resource.Replacer().Replace(f.Path) - - f.TemplateBody = fmt.Sprintf(controllerSuiteTestTemplate, - machinery.NewMarkerFor(f.Path, importMarker), - machinery.NewMarkerFor(f.Path, addSchemeMarker), - ) - - // If is multigroup the path needs to be ../../ since it has - // the group dir. - f.CRDDirectoryRelativePath = `".."` - if f.MultiGroup { - f.CRDDirectoryRelativePath = `"..", ".."` - } - - if f.Force { - f.IfExistsAction = machinery.OverwriteFile - } - - return nil -} - -const ( - importMarker = "imports" - addSchemeMarker = "scheme" -) - -// GetMarkers implements file.Inserter -func (f *SuiteTest) GetMarkers() []machinery.Marker { - return []machinery.Marker{ - machinery.NewMarkerFor(f.Path, importMarker), - machinery.NewMarkerFor(f.Path, addSchemeMarker), - } -} - -const ( - apiImportCodeFragment = `%s "%s" -` - addschemeCodeFragment = `err = %s.AddToScheme(scheme.Scheme) -Expect(err).NotTo(HaveOccurred()) - -` -) - -// GetCodeFragments implements file.Inserter -func (f *SuiteTest) GetCodeFragments() machinery.CodeFragmentsMap { - fragments := make(machinery.CodeFragmentsMap, 2) - - // Generate import code fragments - imports := make([]string, 0) - if f.Resource.Path != "" { - imports = append(imports, fmt.Sprintf(apiImportCodeFragment, f.Resource.ImportAlias(), f.Resource.Path)) - } - - // Generate add scheme code fragments - addScheme := make([]string, 0) - if f.Resource.Path != "" { - addScheme = append(addScheme, fmt.Sprintf(addschemeCodeFragment, f.Resource.ImportAlias())) - } - - // Only store code fragments in the map if the slices are non-empty - if len(imports) != 0 { - fragments[machinery.NewMarkerFor(f.Path, importMarker)] = imports - } - if len(addScheme) != 0 { - fragments[machinery.NewMarkerFor(f.Path, addSchemeMarker)] = addScheme - } - - return fragments -} - -const controllerSuiteTestTemplate = `{{ .Boilerplate }} - -package controllers - -import ( - "path/filepath" - "testing" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - "k8s.io/client-go/kubernetes/scheme" - "k8s.io/client-go/rest" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/envtest" - "sigs.k8s.io/controller-runtime/pkg/envtest/printer" - logf "sigs.k8s.io/controller-runtime/pkg/log" - "sigs.k8s.io/controller-runtime/pkg/log/zap" - %s -) - -// These tests use Ginkgo (BDD-style Go testing framework). Refer to -// http://onsi.github.io/ginkgo/ to learn more about Ginkgo. - -var cfg *rest.Config -var k8sClient client.Client -var testEnv *envtest.Environment - -func TestAPIs(t *testing.T) { - RegisterFailHandler(Fail) - - RunSpecsWithDefaultAndCustomReporters(t, - "Controller Suite", - []Reporter{printer.NewlineReporter{}}) -} - -var _ = BeforeSuite(func(done Done) { - logf.SetLogger(zap.LoggerTo(GinkgoWriter, true)) - - By("bootstrapping test environment") - testEnv = &envtest.Environment{ - CRDDirectoryPaths: []string{filepath.Join({{ .CRDDirectoryRelativePath }}, "config", "crd", "bases")}, - } - - var err error - // cfg is defined in this file globally. - cfg, err = testEnv.Start() - Expect(err).ToNot(HaveOccurred()) - Expect(cfg).ToNot(BeNil()) - - %s - - k8sClient, err = client.New(cfg, client.Options{Scheme: scheme.Scheme}) - Expect(err).ToNot(HaveOccurred()) - Expect(k8sClient).ToNot(BeNil()) - - close(done) -}, 60) - -var _ = AfterSuite(func() { - By("tearing down the test environment") - err := testEnv.Stop() - Expect(err).ToNot(HaveOccurred()) -}) -` diff --git a/pkg/plugins/golang/v3/scaffolds/internal/templates/api/webhook_suitetest.go b/pkg/plugins/golang/v3/scaffolds/internal/templates/api/webhook_suitetest.go deleted file mode 100644 index 1a580d0949..0000000000 --- a/pkg/plugins/golang/v3/scaffolds/internal/templates/api/webhook_suitetest.go +++ /dev/null @@ -1,244 +0,0 @@ -/* -Copyright 2022 The Kubernetes 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 api - -import ( - "fmt" - "path/filepath" - - "sigs.k8s.io/kubebuilder/v3/pkg/machinery" -) - -var _ machinery.Template = &WebhookSuite{} -var _ machinery.Inserter = &WebhookSuite{} - -// WebhookSuite scaffolds the file that sets up the webhook tests -type WebhookSuite struct { //nolint:maligned - machinery.TemplateMixin - machinery.MultiGroupMixin - machinery.BoilerplateMixin - machinery.ResourceMixin - - // todo: currently is not possible to know if an API was or not scaffolded. We can fix it when #1826 be addressed - WireResource bool - - // BaseDirectoryRelativePath define the Path for the base directory when it is multigroup - BaseDirectoryRelativePath string -} - -// SetTemplateDefaults implements file.Template -func (f *WebhookSuite) SetTemplateDefaults() error { - if f.Path == "" { - if f.MultiGroup { - if f.Resource.Group != "" { - f.Path = filepath.Join("apis", "%[group]", "%[version]", "webhook_suite_test.go") - } else { - f.Path = filepath.Join("apis", "%[version]", "webhook_suite_test.go") - } - } else { - f.Path = filepath.Join("api", "%[version]", "webhook_suite_test.go") - } - } - f.Path = f.Resource.Replacer().Replace(f.Path) - - f.TemplateBody = fmt.Sprintf(webhookTestSuiteTemplate, - machinery.NewMarkerFor(f.Path, importMarker), - admissionImportAlias, - machinery.NewMarkerFor(f.Path, addSchemeMarker), - machinery.NewMarkerFor(f.Path, addWebhookManagerMarker), - "%s", - "%d", - ) - - // If is multigroup the path needs to be ../../.. since it has the group dir. - f.BaseDirectoryRelativePath = `"..", ".."` - if f.MultiGroup && f.Resource.Group != "" { - f.BaseDirectoryRelativePath = `"..", "..",".."` - } - - return nil -} - -const ( - // TODO: admission webhook versions should be based on the input of the user. For More Info #1664 - admissionImportAlias = "admissionv1beta1" - admissionPath = "k8s.io/api/admission/v1beta1" - importMarker = "imports" - addWebhookManagerMarker = "webhook" - addSchemeMarker = "scheme" -) - -// GetMarkers implements file.Inserter -func (f *WebhookSuite) GetMarkers() []machinery.Marker { - return []machinery.Marker{ - machinery.NewMarkerFor(f.Path, importMarker), - machinery.NewMarkerFor(f.Path, addSchemeMarker), - machinery.NewMarkerFor(f.Path, addWebhookManagerMarker), - } -} - -const ( - apiImportCodeFragment = `%s "%s" -` - - addWebhookManagerCodeFragment = `err = (&%s{}).SetupWebhookWithManager(mgr) -Expect(err).NotTo(HaveOccurred()) - -` -) - -// GetCodeFragments implements file.Inserter -func (f *WebhookSuite) GetCodeFragments() machinery.CodeFragmentsMap { - fragments := make(machinery.CodeFragmentsMap, 3) - - // Generate import code fragments - imports := make([]string, 0) - imports = append(imports, fmt.Sprintf(apiImportCodeFragment, admissionImportAlias, admissionPath)) - - // Generate add scheme code fragments - addScheme := make([]string, 0) - - // Generate add webhookManager code fragments - addWebhookManager := make([]string, 0) - addWebhookManager = append(addWebhookManager, fmt.Sprintf(addWebhookManagerCodeFragment, f.Resource.Kind)) - - // Only store code fragments in the map if the slices are non-empty - if len(addWebhookManager) != 0 { - fragments[machinery.NewMarkerFor(f.Path, addWebhookManagerMarker)] = addWebhookManager - } - if len(imports) != 0 { - fragments[machinery.NewMarkerFor(f.Path, importMarker)] = imports - } - if len(addScheme) != 0 { - fragments[machinery.NewMarkerFor(f.Path, addSchemeMarker)] = addScheme - } - - return fragments -} - -const webhookTestSuiteTemplate = `{{ .Boilerplate }} - -package {{ .Resource.Version }} - -import ( - "context" - "path/filepath" - "testing" - "fmt" - - . "github.com/onsi/ginkgo/v2" - . "github.com/onsi/gomega" - %s - "k8s.io/client-go/kubernetes/scheme" - "k8s.io/client-go/rest" - "k8s.io/apimachinery/pkg/runtime" - ctrl "sigs.k8s.io/controller-runtime" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/envtest" - logf "sigs.k8s.io/controller-runtime/pkg/log" - "sigs.k8s.io/controller-runtime/pkg/log/zap" -) - -// These tests use Ginkgo (BDD-style Go testing framework). Refer to -// http://onsi.github.io/ginkgo/ to learn more about Ginkgo. - -var cfg *rest.Config -var k8sClient client.Client -var testEnv *envtest.Environment -var ctx context.Context -var cancel context.CancelFunc - -func TestAPIs(t *testing.T) { - RegisterFailHandler(Fail) - - RunSpecs(t, "Webhook Suite") -} - -var _ = BeforeSuite(func() { - logf.SetLogger(zap.New(zap.WriteTo(GinkgoWriter), zap.UseDevMode(true))) - - ctx, cancel = context.WithCancel(context.TODO()) - - By("bootstrapping test environment") - testEnv = &envtest.Environment{ - CRDDirectoryPaths: []string{filepath.Join({{ .BaseDirectoryRelativePath }}, "config", "crd", "bases")}, - ErrorIfCRDPathMissing: {{ .WireResource }}, - WebhookInstallOptions: envtest.WebhookInstallOptions{ - Paths: []string{filepath.Join({{ .BaseDirectoryRelativePath }}, "config", "webhook")}, - }, - } - - var err error - // cfg is defined in this file globally. - cfg, err = testEnv.Start() - Expect(err).NotTo(HaveOccurred()) - Expect(cfg).NotTo(BeNil()) - - scheme := runtime.NewScheme() - err = AddToScheme(scheme) - Expect(err).NotTo(HaveOccurred()) - - err = %s.AddToScheme(scheme) - Expect(err).NotTo(HaveOccurred()) - - %s - - k8sClient, err = client.New(cfg, client.Options{Scheme: scheme}) - Expect(err).NotTo(HaveOccurred()) - Expect(k8sClient).NotTo(BeNil()) - - // start webhook server using Manager - webhookInstallOptions := &testEnv.WebhookInstallOptions - mgr, err := ctrl.NewManager(cfg, ctrl.Options{ - Scheme: scheme, - Host: webhookInstallOptions.LocalServingHost, - Port: webhookInstallOptions.LocalServingPort, - CertDir: webhookInstallOptions.LocalServingCertDir, - LeaderElection: false, - MetricsBindAddress: "0", - }) - Expect(err).NotTo(HaveOccurred()) - - %s - - go func() { - defer GinkgoRecover() - err = mgr.Start(ctx) - Expect(err).NotTo(HaveOccurred()) - }() - - // wait for the webhook server to get ready - dialer := &net.Dialer{Timeout: time.Second} - addrPort := fmt.Sprintf("%s:%s", webhookInstallOptions.LocalServingHost, webhookInstallOptions.LocalServingPort) - Eventually(func() error { - conn, err := tls.DialWithDialer(dialer, "tcp", addrPort, &tls.Config{InsecureSkipVerify: true}) - if err != nil { - return err - } - conn.Close() - return nil - }).Should(Succeed()) - -}) - -var _ = AfterSuite(func() { - cancel() - By("tearing down the test environment") - err := testEnv.Stop() - Expect(err).NotTo(HaveOccurred()) -}) -` diff --git a/pkg/plugins/golang/v3/scaffolds/internal/templates/controllers/controller_suitetest.go b/pkg/plugins/golang/v3/scaffolds/internal/templates/controllers/controller_suitetest.go deleted file mode 100644 index c199d774f1..0000000000 --- a/pkg/plugins/golang/v3/scaffolds/internal/templates/controllers/controller_suitetest.go +++ /dev/null @@ -1,187 +0,0 @@ -/* -Copyright 2020 The Kubernetes 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 controllers - -import ( - "fmt" - "path/filepath" - - "sigs.k8s.io/kubebuilder/v3/pkg/machinery" -) - -var _ machinery.Template = &SuiteTest{} -var _ machinery.Inserter = &SuiteTest{} - -// SuiteTest scaffolds the file that sets up the controller tests -// nolint:maligned -type SuiteTest struct { - machinery.TemplateMixin - machinery.MultiGroupMixin - machinery.BoilerplateMixin - machinery.ResourceMixin - - // CRDDirectoryRelativePath define the Path for the CRD - CRDDirectoryRelativePath string - - Force bool -} - -// SetTemplateDefaults implements file.Template -func (f *SuiteTest) SetTemplateDefaults() error { - if f.Path == "" { - if f.MultiGroup && f.Resource.Group != "" { - f.Path = filepath.Join("controllers", "%[group]", "suite_test.go") - } else { - f.Path = filepath.Join("controllers", "suite_test.go") - } - } - f.Path = f.Resource.Replacer().Replace(f.Path) - - f.TemplateBody = fmt.Sprintf(controllerSuiteTestTemplate, - machinery.NewMarkerFor(f.Path, importMarker), - machinery.NewMarkerFor(f.Path, addSchemeMarker), - ) - - // If is multigroup the path needs to be ../../ since it has - // the group dir. - f.CRDDirectoryRelativePath = `".."` - if f.MultiGroup && f.Resource.Group != "" { - f.CRDDirectoryRelativePath = `"..", ".."` - } - - if f.Force { - f.IfExistsAction = machinery.OverwriteFile - } - - return nil -} - -const ( - importMarker = "imports" - addSchemeMarker = "scheme" -) - -// GetMarkers implements file.Inserter -func (f *SuiteTest) GetMarkers() []machinery.Marker { - return []machinery.Marker{ - machinery.NewMarkerFor(f.Path, importMarker), - machinery.NewMarkerFor(f.Path, addSchemeMarker), - } -} - -const ( - apiImportCodeFragment = `%s "%s" -` - addschemeCodeFragment = `err = %s.AddToScheme(scheme.Scheme) -Expect(err).NotTo(HaveOccurred()) - -` -) - -// GetCodeFragments implements file.Inserter -func (f *SuiteTest) GetCodeFragments() machinery.CodeFragmentsMap { - fragments := make(machinery.CodeFragmentsMap, 2) - - // Generate import code fragments - imports := make([]string, 0) - if f.Resource.Path != "" { - imports = append(imports, fmt.Sprintf(apiImportCodeFragment, f.Resource.ImportAlias(), f.Resource.Path)) - } - - // Generate add scheme code fragments - addScheme := make([]string, 0) - if f.Resource.Path != "" { - addScheme = append(addScheme, fmt.Sprintf(addschemeCodeFragment, f.Resource.ImportAlias())) - } - - // Only store code fragments in the map if the slices are non-empty - if len(imports) != 0 { - fragments[machinery.NewMarkerFor(f.Path, importMarker)] = imports - } - if len(addScheme) != 0 { - fragments[machinery.NewMarkerFor(f.Path, addSchemeMarker)] = addScheme - } - - return fragments -} - -const controllerSuiteTestTemplate = `{{ .Boilerplate }} - -{{if and .MultiGroup .Resource.Group }} -package {{ .Resource.PackageName }} -{{else}} -package controllers -{{end}} - -import ( - "path/filepath" - "testing" - - . "github.com/onsi/ginkgo/v2" - . "github.com/onsi/gomega" - - "k8s.io/client-go/kubernetes/scheme" - "k8s.io/client-go/rest" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/envtest" - logf "sigs.k8s.io/controller-runtime/pkg/log" - "sigs.k8s.io/controller-runtime/pkg/log/zap" - %s -) - -// These tests use Ginkgo (BDD-style Go testing framework). Refer to -// http://onsi.github.io/ginkgo/ to learn more about Ginkgo. - -var cfg *rest.Config -var k8sClient client.Client -var testEnv *envtest.Environment - -func TestAPIs(t *testing.T) { - RegisterFailHandler(Fail) - - RunSpecs(t, "Controller Suite") -} - -var _ = BeforeSuite(func() { - logf.SetLogger(zap.New(zap.WriteTo(GinkgoWriter), zap.UseDevMode(true))) - - By("bootstrapping test environment") - testEnv = &envtest.Environment{ - CRDDirectoryPaths: []string{filepath.Join({{ .CRDDirectoryRelativePath }}, "config", "crd", "bases")}, - ErrorIfCRDPathMissing: {{ .Resource.HasAPI }}, - } - - var err error - // cfg is defined in this file globally. - cfg, err = testEnv.Start() - Expect(err).NotTo(HaveOccurred()) - Expect(cfg).NotTo(BeNil()) - - %s - - k8sClient, err = client.New(cfg, client.Options{Scheme: scheme.Scheme}) - Expect(err).NotTo(HaveOccurred()) - Expect(k8sClient).NotTo(BeNil()) - -}) - -var _ = AfterSuite(func() { - By("tearing down the test environment") - err := testEnv.Stop() - Expect(err).NotTo(HaveOccurred()) -}) -` diff --git a/pkg/plugins/golang/v3/scaffolds/internal/templates/main.go b/pkg/plugins/golang/v3/scaffolds/internal/templates/main.go deleted file mode 100644 index 8960a28050..0000000000 --- a/pkg/plugins/golang/v3/scaffolds/internal/templates/main.go +++ /dev/null @@ -1,296 +0,0 @@ -/* -Copyright 2020 The Kubernetes 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 templates - -import ( - "fmt" - "path/filepath" - - "sigs.k8s.io/kubebuilder/v3/pkg/machinery" -) - -const defaultMainPath = "main.go" - -var _ machinery.Template = &Main{} - -// Main scaffolds a file that defines the controller manager entry point -type Main struct { - machinery.TemplateMixin - machinery.BoilerplateMixin - machinery.DomainMixin - machinery.RepositoryMixin -} - -// SetTemplateDefaults implements file.Template -func (f *Main) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join(defaultMainPath) - } - - f.TemplateBody = fmt.Sprintf(mainTemplate, - machinery.NewMarkerFor(f.Path, importMarker), - machinery.NewMarkerFor(f.Path, addSchemeMarker), - machinery.NewMarkerFor(f.Path, setupMarker), - ) - - return nil -} - -var _ machinery.Inserter = &MainUpdater{} - -// MainUpdater updates main.go to run Controllers -type MainUpdater struct { //nolint:maligned - machinery.RepositoryMixin - machinery.MultiGroupMixin - machinery.ResourceMixin - - // Flags to indicate which parts need to be included when updating the file - WireResource, WireController, WireWebhook bool -} - -// GetPath implements file.Builder -func (*MainUpdater) GetPath() string { - return defaultMainPath -} - -// GetIfExistsAction implements file.Builder -func (*MainUpdater) GetIfExistsAction() machinery.IfExistsAction { - return machinery.OverwriteFile -} - -const ( - importMarker = "imports" - addSchemeMarker = "scheme" - setupMarker = "builder" -) - -// GetMarkers implements file.Inserter -func (f *MainUpdater) GetMarkers() []machinery.Marker { - return []machinery.Marker{ - machinery.NewMarkerFor(defaultMainPath, importMarker), - machinery.NewMarkerFor(defaultMainPath, addSchemeMarker), - machinery.NewMarkerFor(defaultMainPath, setupMarker), - } -} - -const ( - apiImportCodeFragment = `%s "%s" -` - controllerImportCodeFragment = `"%s/controllers" -` - multiGroupControllerImportCodeFragment = `%scontrollers "%s/controllers/%s" -` - addschemeCodeFragment = `utilruntime.Must(%s.AddToScheme(scheme)) -` - reconcilerSetupCodeFragment = `if err = (&controllers.%sReconciler{ - Client: mgr.GetClient(), - Scheme: mgr.GetScheme(), - }).SetupWithManager(mgr); err != nil { - setupLog.Error(err, "unable to create controller", "controller", "%s") - os.Exit(1) - } -` - multiGroupReconcilerSetupCodeFragment = `if err = (&%scontrollers.%sReconciler{ - Client: mgr.GetClient(), - Scheme: mgr.GetScheme(), - }).SetupWithManager(mgr); err != nil { - setupLog.Error(err, "unable to create controller", "controller", "%s") - os.Exit(1) - } -` - webhookSetupCodeFragment = `if err = (&%s.%s{}).SetupWebhookWithManager(mgr); err != nil { - setupLog.Error(err, "unable to create webhook", "webhook", "%s") - os.Exit(1) - } -` -) - -// GetCodeFragments implements file.Inserter -func (f *MainUpdater) GetCodeFragments() machinery.CodeFragmentsMap { - fragments := make(machinery.CodeFragmentsMap, 3) - - // If resource is not being provided we are creating the file, not updating it - if f.Resource == nil { - return fragments - } - - // Generate import code fragments - imports := make([]string, 0) - if f.WireResource { - imports = append(imports, fmt.Sprintf(apiImportCodeFragment, f.Resource.ImportAlias(), f.Resource.Path)) - } - - if f.WireController { - if !f.MultiGroup || f.Resource.Group == "" { - imports = append(imports, fmt.Sprintf(controllerImportCodeFragment, f.Repo)) - } else { - imports = append(imports, fmt.Sprintf(multiGroupControllerImportCodeFragment, - f.Resource.PackageName(), f.Repo, f.Resource.Group)) - } - } - - // Generate add scheme code fragments - addScheme := make([]string, 0) - if f.WireResource { - addScheme = append(addScheme, fmt.Sprintf(addschemeCodeFragment, f.Resource.ImportAlias())) - } - - // Generate setup code fragments - setup := make([]string, 0) - if f.WireController { - if !f.MultiGroup || f.Resource.Group == "" { - setup = append(setup, fmt.Sprintf(reconcilerSetupCodeFragment, - f.Resource.Kind, f.Resource.Kind)) - } else { - setup = append(setup, fmt.Sprintf(multiGroupReconcilerSetupCodeFragment, - f.Resource.PackageName(), f.Resource.Kind, f.Resource.Kind)) - } - } - if f.WireWebhook { - setup = append(setup, fmt.Sprintf(webhookSetupCodeFragment, - f.Resource.ImportAlias(), f.Resource.Kind, f.Resource.Kind)) - } - - // Only store code fragments in the map if the slices are non-empty - if len(imports) != 0 { - fragments[machinery.NewMarkerFor(defaultMainPath, importMarker)] = imports - } - if len(addScheme) != 0 { - fragments[machinery.NewMarkerFor(defaultMainPath, addSchemeMarker)] = addScheme - } - if len(setup) != 0 { - fragments[machinery.NewMarkerFor(defaultMainPath, setupMarker)] = setup - } - - return fragments -} - -var mainTemplate = `{{ .Boilerplate }} - -package main - -import ( - "crypto/tls" - "flag" - "os" - - // 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" - - "k8s.io/apimachinery/pkg/runtime" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" - clientgoscheme "k8s.io/client-go/kubernetes/scheme" - ctrl "sigs.k8s.io/controller-runtime" - "sigs.k8s.io/controller-runtime/pkg/log/zap" - "sigs.k8s.io/controller-runtime/pkg/healthz" - "sigs.k8s.io/controller-runtime/pkg/webhook" - %s -) - -var ( - scheme = runtime.NewScheme() - setupLog = ctrl.Log.WithName("setup") -) - -func init() { - utilruntime.Must(clientgoscheme.AddToScheme(scheme)) - - %s -} - -func main() { - var metricsAddr string - var enableLeaderElection bool - var probeAddr string - var enableHTTP2 bool - flag.StringVar(&metricsAddr, "metrics-bind-address", ":8080", "The address the metric endpoint binds to.") - flag.StringVar(&probeAddr, "health-probe-bind-address", ":8081", "The address the probe endpoint binds to.") - flag.BoolVar(&enableLeaderElection, "leader-elect", false, - "Enable leader election for controller manager. " + - "Enabling this will ensure there is only one active controller manager.") - flag.BoolVar(&enableHTTP2, "enable-http2", false, - "If set, HTTP/2 will be enabled for the metrics and webhook servers") - opts := zap.Options{ - Development: true, - } - opts.BindFlags(flag.CommandLine) - flag.Parse() - - ctrl.SetLogger(zap.New(zap.UseFlagOptions(&opts))) - - // 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 Cancellation and - // Rapid Reset CVEs. For more information see: - // - https://github.com/advisories/GHSA-qppj-fm5r-hxr3 - // - https://github.com/advisories/GHSA-4374-p667-p6c8 - disableHTTP2 := func(c *tls.Config) { - setupLog.Info("disabling http/2") - c.NextProtos = []string{"http/1.1"} - } - - tlsOpts := []func(*tls.Config){} - if !enableHTTP2 { - tlsOpts = append(tlsOpts, disableHTTP2) - } - - mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{ - Scheme: scheme, - MetricsBindAddress: metricsAddr, - WebhookServer: &webhook.Server{ - TLSOpts: tlsOpts, - }, - Port: 9443, - HealthProbeBindAddress: probeAddr, - LeaderElection: enableLeaderElection, - LeaderElectionID: "{{ hashFNV .Repo }}.{{ .Domain }}", - // LeaderElectionReleaseOnCancel defines if the leader should step down voluntarily - // when the Manager ends. This requires the binary to immediately end when the - // Manager is stopped, otherwise, this setting is unsafe. Setting this significantly - // speeds up voluntary leader transitions as the new leader don't have to wait - // LeaseDuration time first. - // - // In the default scaffold provided, the program ends immediately after - // the manager stops, so would be fine to enable this option. However, - // if you are doing or is intended to do any operation such as perform cleanups - // after the manager stops then its usage might be unsafe. - // LeaderElectionReleaseOnCancel: true, - }) - if err != nil { - setupLog.Error(err, "unable to start manager") - os.Exit(1) - } - - %s - - if err := mgr.AddHealthzCheck("healthz", healthz.Ping); err != nil { - setupLog.Error(err, "unable to set up health check") - os.Exit(1) - } - if err := mgr.AddReadyzCheck("readyz", healthz.Ping); err != nil { - setupLog.Error(err, "unable to set up ready check") - os.Exit(1) - } - - setupLog.Info("starting manager") - if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil { - setupLog.Error(err, "problem running manager") - os.Exit(1) - } -} -` diff --git a/pkg/plugins/golang/v3/scaffolds/internal/templates/makefile.go b/pkg/plugins/golang/v3/scaffolds/internal/templates/makefile.go deleted file mode 100644 index 114c3e2a30..0000000000 --- a/pkg/plugins/golang/v3/scaffolds/internal/templates/makefile.go +++ /dev/null @@ -1,217 +0,0 @@ -/* -Copyright 2020 The Kubernetes 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 templates - -import ( - "sigs.k8s.io/kubebuilder/v3/pkg/machinery" -) - -var _ machinery.Template = &Makefile{} - -// Makefile scaffolds a file that defines project management CLI commands -type Makefile struct { - machinery.TemplateMixin - machinery.ProjectNameMixin - - // Image is controller manager image name - Image string - // BoilerplatePath is the path to the boilerplate file - BoilerplatePath string - // Controller tools version to use in the project - ControllerToolsVersion string - // Kustomize version to use in the project - KustomizeVersion string - // ControllerRuntimeVersion version to be used to download the envtest setup script - ControllerRuntimeVersion string -} - -// SetTemplateDefaults implements file.Template -func (f *Makefile) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = "Makefile" - } - - f.TemplateBody = makefileTemplate - - f.IfExistsAction = machinery.Error - - if f.Image == "" { - f.Image = "controller:latest" - } - - return nil -} - -//nolint:lll -const makefileTemplate = ` -# Image URL to use all building/pushing image targets -IMG ?= {{ .Image }} -# ENVTEST_K8S_VERSION refers to the version of kubebuilder assets to be downloaded by envtest binary. -ENVTEST_K8S_VERSION = 1.26.1 - -# Get the currently used golang install path (in GOPATH/bin, unless GOBIN is set) -ifeq (,$(shell go env GOBIN)) -GOBIN=$(shell go env GOPATH)/bin -else -GOBIN=$(shell go env GOBIN) -endif - -# Setting SHELL to bash allows bash commands to be executed by recipes. -# Options are set to exit when a recipe line exits non-zero or a piped command fails. -SHELL = /usr/bin/env bash -o pipefail -.SHELLFLAGS = -ec - -.PHONY: all -all: build - -##@ General - -# The help target prints out all targets with their descriptions organized -# beneath their categories. The categories are represented by '##@' and the -# target descriptions by '##'. The awk command is responsible for reading the -# entire set of makefiles included in this invocation, looking for lines of the -# file as xyz: ## something, and then pretty-format the target and help. Then, -# if there's a line with ##@ something, that gets pretty-printed as a category. -# More info on the usage of ANSI control characters for terminal formatting: -# https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_parameters -# More info on the awk command: -# http://linuxcommand.org/lc3_adv_awk.php - -.PHONY: help -help: ## Display this help. - @awk 'BEGIN {FS = ":.*##"; printf "\nUsage:\n make \033[36m\033[0m\n"} /^[a-zA-Z_0-9-]+:.*?##/ { printf " \033[36m%-15s\033[0m %s\n", $$1, $$2 } /^##@/ { printf "\n\033[1m%s\033[0m\n", substr($$0, 5) } ' $(MAKEFILE_LIST) - -##@ Development - -.PHONY: manifests -manifests: controller-gen ## Generate WebhookConfiguration, ClusterRole and CustomResourceDefinition objects. - $(CONTROLLER_GEN) rbac:roleName=manager-role crd webhook paths="./..." output:crd:artifacts:config=config/crd/bases - -.PHONY: generate -generate: controller-gen ## Generate code containing DeepCopy, DeepCopyInto, and DeepCopyObject method implementations. - $(CONTROLLER_GEN) object:headerFile={{printf "%q" .BoilerplatePath}} paths="./..." - -.PHONY: fmt -fmt: ## Run go fmt against code. - go fmt ./... - -.PHONY: vet -vet: ## Run go vet against code. - go vet ./... - -.PHONY: test -test: manifests generate fmt vet envtest ## Run tests. - KUBEBUILDER_ASSETS="$(shell $(ENVTEST) use $(ENVTEST_K8S_VERSION) --bin-dir $(LOCALBIN) -p path)" go test ./... -coverprofile cover.out - -##@ Build - -.PHONY: build -build: manifests generate fmt vet ## Build manager binary. - go build -o bin/manager main.go - -.PHONY: run -run: manifests generate fmt vet ## Run a controller from your host. - go run ./main.go - -# If you wish to build the manager image targeting other platforms you can use the --platform flag. -# (i.e. docker build --platform linux/arm64). However, you must enable docker buildKit for it. -# More info: https://docs.docker.com/develop/develop-images/build_enhancements/ -.PHONY: docker-build -docker-build: test ## Build docker image with the manager. - docker build -t ${IMG} . - -.PHONY: docker-push -docker-push: ## Push docker image with the manager. - docker push ${IMG} - -# PLATFORMS defines the target platforms for the manager image be built to provide support to multiple -# architectures. (i.e. make docker-buildx IMG=myregistry/mypoperator:0.0.1). To use this option you need to: -# - be able to use docker buildx. More info: https://docs.docker.com/build/buildx/ -# - have enabled BuildKit. More info: https://docs.docker.com/develop/develop-images/build_enhancements/ -# - be able to push the image to your registry (i.e. if you do not set a valid value via IMG=> then the export will fail) -# To adequately provide solutions that are compatible with multiple platforms, you should consider using this option. -PLATFORMS ?= linux/arm64,linux/amd64,linux/s390x,linux/ppc64le -.PHONY: docker-buildx -docker-buildx: test ## Build and push docker image for the manager for cross-platform support - # copy existing Dockerfile and insert --platform=${BUILDPLATFORM} into Dockerfile.cross, and preserve the original Dockerfile - sed -e '1 s/\(^FROM\)/FROM --platform=\$$\{BUILDPLATFORM\}/; t' -e ' 1,// s//FROM --platform=\$$\{BUILDPLATFORM\}/' Dockerfile > Dockerfile.cross - - docker buildx create --name project-v3-builder - docker buildx use project-v3-builder - - docker buildx build --push --platform=$(PLATFORMS) --tag ${IMG} -f Dockerfile.cross . - - docker buildx rm project-v3-builder - rm Dockerfile.cross - -##@ Deployment - -ifndef ignore-not-found - ignore-not-found = false -endif - -.PHONY: install -install: manifests kustomize ## Install CRDs into the K8s cluster specified in ~/.kube/config. - $(KUSTOMIZE) build config/crd | kubectl apply -f - - -.PHONY: uninstall -uninstall: manifests kustomize ## Uninstall CRDs from the K8s cluster specified in ~/.kube/config. Call with ignore-not-found=true to ignore resource not found errors during deletion. - $(KUSTOMIZE) build config/crd | kubectl delete --ignore-not-found=$(ignore-not-found) -f - - -.PHONY: deploy -deploy: manifests kustomize ## Deploy controller to the K8s cluster specified in ~/.kube/config. - cd config/manager && $(KUSTOMIZE) edit set image controller=${IMG} - $(KUSTOMIZE) build config/default | kubectl apply -f - - -.PHONY: undeploy -undeploy: ## Undeploy controller from the K8s cluster specified in ~/.kube/config. Call with ignore-not-found=true to ignore resource not found errors during deletion. - $(KUSTOMIZE) build config/default | kubectl delete --ignore-not-found=$(ignore-not-found) -f - - -##@ Build Dependencies - -## Location to install dependencies to -LOCALBIN ?= $(shell pwd)/bin -$(LOCALBIN): - mkdir -p $(LOCALBIN) - -## Tool Binaries -KUSTOMIZE ?= $(LOCALBIN)/kustomize -CONTROLLER_GEN ?= $(LOCALBIN)/controller-gen -ENVTEST ?= $(LOCALBIN)/setup-envtest - -## Tool Versions -KUSTOMIZE_VERSION ?= {{ .KustomizeVersion }} -CONTROLLER_TOOLS_VERSION ?= {{ .ControllerToolsVersion }} - -KUSTOMIZE_INSTALL_SCRIPT ?= "https://raw.githubusercontent.com/kubernetes-sigs/kustomize/master/hack/install_kustomize.sh" -.PHONY: kustomize -kustomize: $(KUSTOMIZE) ## Download kustomize locally if necessary. If wrong version is installed, it will be removed before downloading. -$(KUSTOMIZE): $(LOCALBIN) - @if test -x $(LOCALBIN)/kustomize && ! $(LOCALBIN)/kustomize version | grep -q $(KUSTOMIZE_VERSION); then \ - echo "$(LOCALBIN)/kustomize version is not expected $(KUSTOMIZE_VERSION). Removing it before installing."; \ - rm -rf $(LOCALBIN)/kustomize; \ - fi - test -s $(LOCALBIN)/kustomize || { curl -Ss $(KUSTOMIZE_INSTALL_SCRIPT) --output install_kustomize.sh && bash install_kustomize.sh $(subst v,,$(KUSTOMIZE_VERSION)) $(LOCALBIN); rm install_kustomize.sh; } - -.PHONY: controller-gen -controller-gen: $(CONTROLLER_GEN) ## Download controller-gen locally if necessary. If wrong version is installed, it will be overwritten. -$(CONTROLLER_GEN): $(LOCALBIN) - test -s $(LOCALBIN)/controller-gen && $(LOCALBIN)/controller-gen --version | grep -q $(CONTROLLER_TOOLS_VERSION) || \ - GOBIN=$(LOCALBIN) go install sigs.k8s.io/controller-tools/cmd/controller-gen@$(CONTROLLER_TOOLS_VERSION) - -.PHONY: envtest -envtest: $(ENVTEST) ## Download envtest-setup locally if necessary. -$(ENVTEST): $(LOCALBIN) - test -s $(LOCALBIN)/setup-envtest || GOBIN=$(LOCALBIN) go install sigs.k8s.io/controller-runtime/tools/setup-envtest@latest -` diff --git a/pkg/plugins/golang/v4/scaffolds/init.go b/pkg/plugins/golang/v4/scaffolds/init.go index fbe83d328b..0ad28e2356 100644 --- a/pkg/plugins/golang/v4/scaffolds/init.go +++ b/pkg/plugins/golang/v4/scaffolds/init.go @@ -26,8 +26,7 @@ import ( "sigs.k8s.io/kubebuilder/v3/pkg/machinery" "sigs.k8s.io/kubebuilder/v3/pkg/plugin" "sigs.k8s.io/kubebuilder/v3/pkg/plugins" - kustomizecommonv1 "sigs.k8s.io/kubebuilder/v3/pkg/plugins/common/kustomize/v1" - kustomizecommonv2alpha "sigs.k8s.io/kubebuilder/v3/pkg/plugins/common/kustomize/v2" + kustomizecommonv2 "sigs.k8s.io/kubebuilder/v3/pkg/plugins/common/kustomize/v2" "sigs.k8s.io/kubebuilder/v3/pkg/plugins/golang/v4/scaffolds/internal/templates" "sigs.k8s.io/kubebuilder/v3/pkg/plugins/golang/v4/scaffolds/internal/templates/hack" "sigs.k8s.io/kubebuilder/v3/pkg/plugins/golang/v4/scaffolds/internal/templates/test/e2e" @@ -129,14 +128,13 @@ func (s *initScaffolder) Scaffold() error { // If the KustomizeV2 was used to do the scaffold then // we need to ensure that we use its supported Kustomize Version // in order to support it - kustomizeVersion = kustomizecommonv1.KustomizeVersion - kustomizev2 := kustomizecommonv2alpha.Plugin{} + kustomizev2 := kustomizecommonv2.Plugin{} gov4 := "go.kubebuilder.io/v4" pluginKeyForKustomizeV2 := plugin.KeyFor(kustomizev2) for _, pluginKey := range s.config.GetPluginChain() { if pluginKey == pluginKeyForKustomizeV2 || pluginKey == gov4 { - kustomizeVersion = kustomizecommonv2alpha.KustomizeVersion + kustomizeVersion = kustomizecommonv2.KustomizeVersion break } }