From 553cd4c89e3a3ca3989a4b0b965a2d52db2aac03 Mon Sep 17 00:00:00 2001 From: Camila Macedo <7708031+camilamacedo86@users.noreply.github.com> Date: Sat, 18 May 2024 08:59:20 +0100 Subject: [PATCH] =?UTF-8?q?=E2=9A=A0=EF=B8=8F=20remove=20declarative=20plu?= =?UTF-8?q?gin=20(#3922)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit remove declarative plugin --- cmd/main.go | 2 - docs/book/src/SUMMARY.md | 1 - docs/book/src/plugins/declarative-v1.md | 77 --------- docs/book/src/plugins/extending-cli.md | 6 +- .../src/plugins/to-add-optional-features.md | 1 - docs/book/src/plugins/to-be-extended.md | 1 - docs/book/src/reference/project-config.md | 44 +++-- pkg/cli/cli_test.go | 2 +- pkg/plugins/golang/declarative/v1/api.go | 136 --------------- pkg/plugins/golang/declarative/v1/init.go | 95 ----------- pkg/plugins/golang/declarative/v1/plugin.go | 81 --------- .../golang/declarative/v1/scaffolds/api.go | 85 ---------- .../scaffolds/internal/templates/channel.go | 53 ------ .../internal/templates/controller.go | 150 ----------------- .../scaffolds/internal/templates/manifest.go | 53 ------ .../v1/scaffolds/internal/templates/types.go | 157 ------------------ 16 files changed, 36 insertions(+), 908 deletions(-) delete mode 100644 docs/book/src/plugins/declarative-v1.md delete mode 100644 pkg/plugins/golang/declarative/v1/api.go delete mode 100644 pkg/plugins/golang/declarative/v1/init.go delete mode 100644 pkg/plugins/golang/declarative/v1/plugin.go delete mode 100644 pkg/plugins/golang/declarative/v1/scaffolds/api.go delete mode 100644 pkg/plugins/golang/declarative/v1/scaffolds/internal/templates/channel.go delete mode 100644 pkg/plugins/golang/declarative/v1/scaffolds/internal/templates/controller.go delete mode 100644 pkg/plugins/golang/declarative/v1/scaffolds/internal/templates/manifest.go delete mode 100644 pkg/plugins/golang/declarative/v1/scaffolds/internal/templates/types.go diff --git a/cmd/main.go b/cmd/main.go index 9955408588..3bca2992f8 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -27,7 +27,6 @@ import ( "sigs.k8s.io/kubebuilder/v3/pkg/plugins/golang" //nolint:staticcheck - declarativev1 "sigs.k8s.io/kubebuilder/v3/pkg/plugins/golang/declarative/v1" deployimagev1alpha1 "sigs.k8s.io/kubebuilder/v3/pkg/plugins/golang/deploy-image/v1alpha1" golangv4 "sigs.k8s.io/kubebuilder/v3/pkg/plugins/golang/v4" grafanav1alpha1 "sigs.k8s.io/kubebuilder/v3/pkg/plugins/optional/grafana/v1alpha" @@ -60,7 +59,6 @@ func main() { golangv4.Plugin{}, gov4Bundle, &kustomizecommonv2.Plugin{}, - &declarativev1.Plugin{}, &deployimagev1alpha1.Plugin{}, &grafanav1alpha1.Plugin{}, ), diff --git a/docs/book/src/SUMMARY.md b/docs/book/src/SUMMARY.md index 5bace7b406..7d9c7a52e4 100644 --- a/docs/book/src/SUMMARY.md +++ b/docs/book/src/SUMMARY.md @@ -116,7 +116,6 @@ - [To scaffold a project](./plugins/to-scaffold-project.md) - [go/v4 (Default init scaffold)](./plugins/go-v4-plugin.md) - [To add optional features](./plugins/to-add-optional-features.md) - - [declarative/v1 (Deprecated)](./plugins/declarative-v1.md) - [grafana/v1-alpha](./plugins/grafana-v1-alpha.md) - [deploy-image/v1-alpha](./plugins/deploy-image-plugin-v1-alpha.md) - [To be extended for others tools](./plugins/to-be-extended.md) diff --git a/docs/book/src/plugins/declarative-v1.md b/docs/book/src/plugins/declarative-v1.md deleted file mode 100644 index 4e8724f83b..0000000000 --- a/docs/book/src/plugins/declarative-v1.md +++ /dev/null @@ -1,77 +0,0 @@ -# [Deprecated] Declarative Plugin - - - -The declarative plugin allows you to create [controllers][controller-runtime] using the [kubebuilder-declarative-pattern][kubebuilder-declarative-pattern]. -By using the declarative plugin, you can make the required changes on top of what is scaffolded by default when you create a Go project with Kubebuilder and the Golang plugins (i.e. go/v2, go/v3). - - - -## When to use it ? - -- If you are looking to scaffold one or more [controllers][controller-runtime] following [the pattern][kubebuilder-declarative-pattern] ( See an e.g. of the reconcile method implemented [here][addon-v3-controller]) -- If you want to have manifests shipped inside your Manager container. The declarative plugin works with channels, which allow you to push manifests. [More info][addon-channels-info] - -## How to use it ? - -The declarative plugin requires to be used with one of the available Golang plugins -If you want that any API(s) and its respective controller(s) generate to reconcile them of your project adopt this partner then: - -```sh -kubebuilder init --plugins=go/v3,declarative/v1 --domain example.org --repo example.org/guestbook-operator -``` - -If you want to adopt this pattern for specific API(s) and its respective controller(s) (not for any API/controller scaffold using Kubebuilder CLI) then: - -```sh -kubebuilder create api --plugins=go/v3,declarative/v1 --version v1 --kind Guestbook -``` - -## Subcommands - -The declarative plugin implements the following subcommands: - -- init (`$ kubebuilder init [OPTIONS]`) -- create api (`$ kubebuilder create api [OPTIONS]`) - -## Affected files - -The following scaffolds will be created or updated by this plugin: - -- `controllers/*_controller.go` -- `api/*_types.go` -- `channels/packages///manifest.yaml` -- `channels/stable` -- `Dockerfile` - -## Further resources - -- Read more about the [declarative pattern][kubebuilder-declarative-pattern] -- Watch the KubeCon 2018 Video [Managing Addons with Operators][kubecon-video] -- Check the [plugin implementation][plugin-implementation] - -[addon-channels-info]: https://github.com/kubernetes-sigs/kubebuilder-declarative-pattern/blob/master/docs/addon/walkthrough/README.md#adding-a-manifest -[controller-runtime]: https://github.com/kubernetes-sigs/controller-runtime -[kubebuilder-declarative-pattern]: https://github.com/kubernetes-sigs/kubebuilder-declarative-pattern -[testdata]: https://github.com/kubernetes-sigs/kubebuilder/tree/master/testdata/ -[kubecon-video]: https://www.youtube.com/watch?v=LPejvfBR5_w -[plugin-implementation]: https://github.com/kubernetes-sigs/kubebuilder/tree/master/pkg/plugins/golang/declarative -[addon-v3-controller]: https://github.com/kubernetes-sigs/kubebuilder/tree/master/testdata/project-v3-declarative-v1 - diff --git a/docs/book/src/plugins/extending-cli.md b/docs/book/src/plugins/extending-cli.md index bf9da9363a..9589714920 100644 --- a/docs/book/src/plugins/extending-cli.md +++ b/docs/book/src/plugins/extending-cli.md @@ -23,8 +23,8 @@ import ( "sigs.k8s.io/kubebuilder/v3/pkg/plugin" kustomizecommonv2 "sigs.k8s.io/kubebuilder/v3/pkg/plugins/common/kustomize/v2" "sigs.k8s.io/kubebuilder/v3/pkg/plugins/golang" - declarativev1 "sigs.k8s.io/kubebuilder/v3/pkg/plugins/golang/declarative/v1" - golangv4 "sigs.k8s.io/kubebuilder/v3/pkg/plugins/golang/v4" + deployimage "sigs.k8s.io/kubebuilder/v3/pkg/plugins/golang/deploy-image/v1alpha1" + golangv4 "sigs.k8s.io/kubebuilder/v3/pkg/plugins/golang/v4" ) @@ -58,7 +58,7 @@ func GetPluginsCLI() (*cli.CLI) { // Register the plugins options which can be used to do the scaffolds via your CLI tool. See that we are using as example here the plugins which are implemented and provided by Kubebuilder cli.WithPlugins( gov3Bundle, - &declarativev1.Plugin{}, + &deployimage.Plugin{}, ), // Defines what will be the default plugin used by your binary. It means that will be the plugin used if no info be provided such as when the user runs `kubebuilder init` diff --git a/docs/book/src/plugins/to-add-optional-features.md b/docs/book/src/plugins/to-add-optional-features.md index f62da55d2a..048a23d873 100644 --- a/docs/book/src/plugins/to-add-optional-features.md +++ b/docs/book/src/plugins/to-add-optional-features.md @@ -4,6 +4,5 @@ The following plugins are useful to generate code and take advantage of optional | Plugin | Key | Description | |-------------------------------------------------------------------------| -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| [declarative.go.kubebuilder.io/v1 - (Deprecated) ](declarative-v1.md) | `declarative/v1` | Optional plugin used to scaffold APIs/controllers using the [kubebuilder-declarative-pattern][kubebuilder-declarative-pattern] project. | | [grafana.kubebuilder.io/v1-alpha](grafana-v1-alpha.md) | `grafana/v1-alpha` | Optional helper plugin which can be used to scaffold Grafana Manifests Dashboards for the default metrics which are exported by controller-runtime. | | [deploy-image.go.kubebuilder.io/v1-alpha](deploy-image-plugin-v1-alpha) | `deploy-image/v1-alpha` | Optional helper plugin which can be used to scaffold APIs and controller with code implementation to Deploy and Manage an Operand(image). | diff --git a/docs/book/src/plugins/to-be-extended.md b/docs/book/src/plugins/to-be-extended.md index e6137bdad2..49326e5fa9 100644 --- a/docs/book/src/plugins/to-be-extended.md +++ b/docs/book/src/plugins/to-be-extended.md @@ -21,7 +21,6 @@ helpers on top, such as [Operator-SDK][sdk] does to add their features to integr | `base.go.kubebuilder.io/v4` | `base/v4` | Responsible for scaffolding all files which specifically requires Golang. This plugin is used in the composition to create the plugin (`go/v4`) | [create-plugins]: creating-plugins.md -[kubebuilder-declarative-pattern]: https://github.com/kubernetes-sigs/kubebuilder-declarative-pattern [kustomize]: https://kustomize.io/ [sdk]: https://github.com/operator-framework/operator-sdk [olm]: https://olm.operatorframework.io/ diff --git a/docs/book/src/reference/project-config.md b/docs/book/src/reference/project-config.md index 3d3f7b352e..94c2841c1a 100644 --- a/docs/book/src/reference/project-config.md +++ b/docs/book/src/reference/project-config.md @@ -82,30 +82,50 @@ The `PROJECT` version `3` layout looks like: ```yaml domain: testproject.org layout: - - go.kubebuilder.io/v3 + - go.kubebuilder.io/v4 plugins: - declarative.go.kubebuilder.io/v1: + deploy-image.go.kubebuilder.io/v1-alpha: resources: - domain: testproject.org - group: crew - kind: FirstMate - version: v1 -projectName: example -repo: sigs.k8s.io/kubebuilder/example + group: example.com + kind: Memcached + options: + containerCommand: memcached,-m=64,-o,modern,-v + containerPort: "11211" + image: memcached:memcached:1.6.26-alpine3.19 + runAsUser: "1001" + version: v1alpha1 + - domain: testproject.org + group: example.com + kind: Busybox + options: + image: busybox:1.36.1 + version: v1alpha1 +projectName: project-v4-with-deploy-image +repo: sigs.k8s.io/kubebuilder/testdata/project-v4-with-deploy-image resources: - api: crdVersion: v1 namespaced: true controller: true domain: testproject.org - group: crew - kind: Captain - path: sigs.k8s.io/kubebuilder/example/api/v1 - version: v1 + group: example.com + kind: Memcached + path: sigs.k8s.io/kubebuilder/testdata/project-v4-with-deploy-image/api/v1alpha1 + version: v1alpha1 webhooks: - defaulting: true validation: true webhookVersion: v1 + - api: + crdVersion: v1 + namespaced: true + controller: true + domain: testproject.org + group: example.com + kind: Busybox + path: sigs.k8s.io/kubebuilder/testdata/project-v4-with-deploy-image/api/v1alpha1 + version: v1alpha1 +version: "3" ``` Now let's check its layout fields definition: diff --git a/pkg/cli/cli_test.go b/pkg/cli/cli_test.go index f92db2043d..ff886fa324 100644 --- a/pkg/cli/cli_test.go +++ b/pkg/cli/cli_test.go @@ -155,7 +155,7 @@ plugins: When("having multiple plugins in the layout field", func() { It("should succeed", func() { - pluginChain := []string{"go.kubebuilder.io/v2", "declarative.kubebuilder.io/v1"} + pluginChain := []string{"go.kubebuilder.io/v2", "deploy-image.go.kubebuilder.io/v1-alpha"} projectConfig := cfgv3.New() Expect(projectConfig.SetPluginChain(pluginChain)).To(Succeed()) diff --git a/pkg/plugins/golang/declarative/v1/api.go b/pkg/plugins/golang/declarative/v1/api.go deleted file mode 100644 index f74c0ac306..0000000000 --- a/pkg/plugins/golang/declarative/v1/api.go +++ /dev/null @@ -1,136 +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 v1 - -import ( - "errors" - "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/plugin" - "sigs.k8s.io/kubebuilder/v3/pkg/plugin/util" - "sigs.k8s.io/kubebuilder/v3/pkg/plugins/golang/declarative/v1/scaffolds" -) - -const ( - // kbDeclarativePattern is the sigs.k8s.io/kubebuilder-declarative-pattern version - kbDeclarativePatternForV4 = "9a410556b95de526e12acfe0d6f56fd35c0b0135" -) - -var _ plugin.CreateAPISubcommand = &createAPISubcommand{} - -type createAPISubcommand struct { - config config.Config - - resource *resource.Resource -} - -func (p *createAPISubcommand) UpdateMetadata(cliMeta plugin.CLIMetadata, subcmdMeta *plugin.SubcommandMetadata) { - subcmdMeta.Description = ` -Scaffold a Kubernetes API by writing a Resource definition and a Controller. - -After the scaffold is written, the dependencies will be updated and -make generate will be run. -` - subcmdMeta.Examples = fmt.Sprintf(` # Create a frigates API with Group: ship, Version: v1beta1 and Kind: Frigate - %[1]s create api --group ship --version v1beta1 --kind Frigate --resource --controller - - # Edit the API Scheme - nano api/v1beta1/frigate_types.go - - # Edit the Controller Test - nano controllers/frigate/frigate_controller_test.go - - # Generate the manifests - make manifests - - # Install CRDs into the Kubernetes cluster using kubectl apply - make install - - # Regenerate code and run against the Kubernetes cluster configured by ~/.kube/config - make run -`, cliMeta.CommandName) -} - -func (p *createAPISubcommand) InjectConfig(c config.Config) error { - p.config = c - - return nil -} - -func (p *createAPISubcommand) InjectResource(res *resource.Resource) error { - p.resource = res - - if !p.resource.HasAPI() || !p.resource.HasController() { - return plugin.ExitError{ - Plugin: pluginName, - Reason: "declarative pattern is only supported when API and controller are scaffolded", - } - } - - return nil -} - -func (p *createAPISubcommand) Scaffold(fs machinery.Filesystem) error { - log.Println("updating scaffold with declarative pattern...") - - scaffolder := scaffolds.NewAPIScaffolder(p.config, *p.resource) - scaffolder.InjectFS(fs) - err := scaffolder.Scaffold() - if err != nil { - return err - } - - // Update Dockerfile - // nolint:staticcheck - err = updateDockerfile(plugin.IsLegacyLayout(p.config)) - if err != nil { - return err - } - - // Track the resources following a declarative approach - cfg := pluginConfig{} - if err := p.config.DecodePluginConfig(pluginKey, &cfg); errors.As(err, &config.UnsupportedFieldError{}) { - // Config doesn't support per-plugin configuration, so we can't track them - } else { - // Fail unless they key wasn't found, which just means it is the first resource tracked - if err != nil && !errors.As(err, &config.PluginKeyNotFoundError{}) { - return err - } - - cfg.Resources = append(cfg.Resources, p.resource.GVK) - if err := p.config.EncodePluginConfig(pluginKey, cfg); err != nil { - return err - } - } - - // Ensure that we are pinning sigs.k8s.io/kubebuilder-declarative-pattern version - // Just pin an old value for go/v2. It shows fine for now. However, we should improve/change it - // if we see that more rules based on the plugins version are required. - kbDeclarativePattern := kbDeclarativePatternForV4 - err = util.RunCmd("Get declarative pattern", "go", "get", - "sigs.k8s.io/kubebuilder-declarative-pattern@"+kbDeclarativePattern) - if err != nil { - return err - } - - return nil -} diff --git a/pkg/plugins/golang/declarative/v1/init.go b/pkg/plugins/golang/declarative/v1/init.go deleted file mode 100644 index 0dd7e05f6c..0000000000 --- a/pkg/plugins/golang/declarative/v1/init.go +++ /dev/null @@ -1,95 +0,0 @@ -/* -Copyright 2021 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 v1 - -import ( - "fmt" - "os" - "path/filepath" - "strings" - - 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/plugin" - "sigs.k8s.io/kubebuilder/v3/pkg/plugin/util" -) - -var _ plugin.InitSubcommand = &initSubcommand{} - -type initSubcommand struct { - config config.Config -} - -func (p *initSubcommand) InjectConfig(c config.Config) error { - p.config = c - - return nil -} - -func (p *initSubcommand) Scaffold(_ machinery.Filesystem) error { - //nolint:staticcheck - err := updateDockerfile(plugin.IsLegacyLayout(p.config)) - if err != nil { - return err - } - return nil -} - -// updateDockerfile will add channels staging required for declarative plugin -func updateDockerfile(isLegacyLayout bool) error { - log.Println("updating Dockerfile to add channels/ directory in the image") - dockerfile := filepath.Join("Dockerfile") - - controllerPath := "internal/controller/" - if isLegacyLayout { - controllerPath = "controllers/" - } - // nolint:lll - err := insertCodeIfDoesNotExist(dockerfile, - fmt.Sprintf("COPY %s %s", controllerPath, controllerPath), - "\n# https://github.com/kubernetes-sigs/kubebuilder-declarative-pattern/blob/master/docs/addon/walkthrough/README.md#adding-a-manifest\n# Stage channels and make readable\nCOPY channels/ /channels/\nRUN chmod -R a+rx /channels/") - if err != nil { - return err - } - - err = insertCodeIfDoesNotExist(dockerfile, - "COPY --from=builder /workspace/manager .", - "\n# copy channels\nCOPY --from=builder /channels /channels\n") - if err != nil { - return err - } - return nil -} - -// insertCodeIfDoesNotExist insert code if it does not already exists -func insertCodeIfDoesNotExist(filename, target, code string) error { - // false positive - // nolint:gosec - contents, err := os.ReadFile(filename) - if err != nil { - return err - } - - idx := strings.Index(string(contents), code) - if idx != -1 { - return nil - } - - return util.InsertCode(filename, target, code) -} diff --git a/pkg/plugins/golang/declarative/v1/plugin.go b/pkg/plugins/golang/declarative/v1/plugin.go deleted file mode 100644 index 323ffae0cb..0000000000 --- a/pkg/plugins/golang/declarative/v1/plugin.go +++ /dev/null @@ -1,81 +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. -*/ - -// Deprecated: The declarative plugin has been deprecated. -// The Declarative plugin is an implementation derived from the kubebuilder-declarative-pattern project. -// As the project maintainers possess the most comprehensive knowledge about its changes and Kubebuilder -// allows the creation of custom plugins using its library, it has been decided that this plugin will be -// better maintained within the kubebuilder-declarative-pattern project -// itself, which falls under its domain of responsibility. This decision aims to improve the maintainability -// of both the plugin and Kubebuilder, ultimately providing an enhanced user experience. -// To follow up on this work, please refer to the Issue #293: -// https://github.com/kubernetes-sigs/kubebuilder-declarative-pattern/issues/293. -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/model/resource" - "sigs.k8s.io/kubebuilder/v3/pkg/plugin" - "sigs.k8s.io/kubebuilder/v3/pkg/plugins/golang" -) - -const pluginName = "declarative." + golang.DefaultNameQualifier - -var ( - pluginVersion = plugin.Version{Number: 1} - supportedProjectVersions = []config.Version{cfgv3.Version} - pluginKey = plugin.KeyFor(Plugin{}) -) - -var _ plugin.CreateAPI = Plugin{} - -// Plugin implements the plugin.Full interface -type Plugin struct { - initSubcommand - createAPISubcommand -} - -// 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 initializing and common scaffolding -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 } - -type pluginConfig struct { - Resources []resource.GVK `json:"resources,omitempty"` -} - -func (p Plugin) DeprecationWarning() string { - return "The declarative plugin has been deprecated. \n" + - "The Declarative plugin is an implementation derived from the kubebuilder-declarative-pattern project. " + - "As the project maintainers possess the most comprehensive knowledge about its changes and Kubebuilder " + - "allows the creation of custom plugins using its library, it has been decided that this plugin will be " + - "better maintained within the kubebuilder-declarative-pattern project " + - "itself, which falls under its domain of responsibility. This decision aims to improve the maintainability " + - "of both the plugin and Kubebuilder, ultimately providing an enhanced user experience." + - "To follow up on this work, please refer to the Issue #293: " + - "https://github.com/kubernetes-sigs/kubebuilder-declarative-pattern/issues/293." -} diff --git a/pkg/plugins/golang/declarative/v1/scaffolds/api.go b/pkg/plugins/golang/declarative/v1/scaffolds/api.go deleted file mode 100644 index 10273b1958..0000000000 --- a/pkg/plugins/golang/declarative/v1/scaffolds/api.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 ( - "fmt" - "path/filepath" - - "github.com/spf13/afero" - "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/plugin" - "sigs.k8s.io/kubebuilder/v3/pkg/plugins" - "sigs.k8s.io/kubebuilder/v3/pkg/plugins/golang/declarative/v1/scaffolds/internal/templates" -) - -const ( - exampleManifestVersion = "0.0.1" -) - -var _ plugins.Scaffolder = &apiScaffolder{} - -type apiScaffolder struct { - config config.Config - resource resource.Resource - - // fs is the filesystem that will be used by the scaffolder - fs machinery.Filesystem -} - -// NewAPIScaffolder returns a new Scaffolder for declarative -func NewAPIScaffolder(config config.Config, res resource.Resource) plugins.Scaffolder { - return &apiScaffolder{ - config: config, - resource: res, - } -} - -// InjectFS implements cmdutil.Scaffolder -func (s *apiScaffolder) InjectFS(fs machinery.Filesystem) { - s.fs = fs -} - -// Scaffold implements cmdutil.Scaffolder -func (s *apiScaffolder) Scaffold() error { - // Load the boilerplate - boilerplate, err := afero.ReadFile(s.fs.FS, filepath.Join("hack", "boilerplate.go.txt")) - if err != nil { - return fmt.Errorf("error updating scaffold: unable to load boilerplate: %w", err) - } - - // Initialize the machinery.Scaffold that will write the files to disk - scaffold := machinery.NewScaffold(s.fs, - machinery.WithConfig(s.config), - machinery.WithBoilerplate(string(boilerplate)), - machinery.WithResource(&s.resource), - ) - - //nolint:staticcheck - err = scaffold.Execute( - &templates.Types{IsLegacyLayout: plugin.IsLegacyLayout(s.config)}, - &templates.Controller{IsLegacyLayout: plugin.IsLegacyLayout(s.config)}, - &templates.Channel{ManifestVersion: exampleManifestVersion}, - &templates.Manifest{ManifestVersion: exampleManifestVersion}, - ) - if err != nil { - return fmt.Errorf("error updating scaffold: %w", err) - } - return nil -} diff --git a/pkg/plugins/golang/declarative/v1/scaffolds/internal/templates/channel.go b/pkg/plugins/golang/declarative/v1/scaffolds/internal/templates/channel.go deleted file mode 100644 index 4d5431d835..0000000000 --- a/pkg/plugins/golang/declarative/v1/scaffolds/internal/templates/channel.go +++ /dev/null @@ -1,53 +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 templates - -import ( - "path/filepath" - - log "github.com/sirupsen/logrus" - - "sigs.k8s.io/kubebuilder/v3/pkg/machinery" -) - -var _ machinery.Template = &Channel{} - -// Channel scaffolds the file for the channel -type Channel struct { - machinery.TemplateMixin - - ManifestVersion string -} - -// SetTemplateDefaults implements file.Template -func (f *Channel) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("channels", "stable") - } - log.Println(f.Path) - - f.TemplateBody = channelTemplate - - f.IfExistsAction = machinery.SkipFile - - return nil -} - -const channelTemplate = `# Versions for the stable channel -manifests: -- version: {{ .ManifestVersion }} -` diff --git a/pkg/plugins/golang/declarative/v1/scaffolds/internal/templates/controller.go b/pkg/plugins/golang/declarative/v1/scaffolds/internal/templates/controller.go deleted file mode 100644 index 12c60f4298..0000000000 --- a/pkg/plugins/golang/declarative/v1/scaffolds/internal/templates/controller.go +++ /dev/null @@ -1,150 +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 templates - -import ( - "path/filepath" - - log "github.com/sirupsen/logrus" - - "sigs.k8s.io/kubebuilder/v3/pkg/machinery" -) - -var _ machinery.Template = &Controller{} - -// Controller scaffolds the file that defines the controller for a CRD or a builtin resource -// nolint:maligned -type Controller struct { - machinery.TemplateMixin - machinery.MultiGroupMixin - machinery.BoilerplateMixin - machinery.ResourceMixin - - IsLegacyLayout bool - PackageName string -} - -// SetTemplateDefaults implements file.Template -func (f *Controller) SetTemplateDefaults() error { - if f.Path == "" { - if f.IsLegacyLayout { - if f.MultiGroup { - f.Path = filepath.Join("controllers", "%[group]", "%[kind]_controller.go") - } else { - f.Path = filepath.Join("controllers", "%[kind]_controller.go") - } - } else { - if f.MultiGroup { - f.Path = filepath.Join("internal", "controller", "%[group]", "%[kind]_controller.go") - } else { - f.Path = filepath.Join("internal", "controller", "%[kind]_controller.go") - } - } - - } - f.Path = f.Resource.Replacer().Replace(f.Path) - log.Println(f.Path) - - f.PackageName = "controller" - if f.IsLegacyLayout { - f.PackageName = "controllers" - } - - f.TemplateBody = controllerTemplate - - f.IfExistsAction = machinery.OverwriteFile - - return nil -} - -//nolint:lll -const controllerTemplate = `{{ .Boilerplate }} - -package {{ .PackageName }} - -import ( - "github.com/go-logr/logr" - "k8s.io/apimachinery/pkg/runtime" - ctrl "sigs.k8s.io/controller-runtime" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/controller" - "sigs.k8s.io/controller-runtime/pkg/handler" - "sigs.k8s.io/controller-runtime/pkg/reconcile" - "sigs.k8s.io/controller-runtime/pkg/source" - "sigs.k8s.io/kubebuilder-declarative-pattern/pkg/patterns/addon" - "sigs.k8s.io/kubebuilder-declarative-pattern/pkg/patterns/addon/pkg/status" - "sigs.k8s.io/kubebuilder-declarative-pattern/pkg/patterns/declarative" - - {{ .Resource.ImportAlias }} "{{ .Resource.Path }}" -) - -var _ reconcile.Reconciler = &{{ .Resource.Kind }}Reconciler{} - -// {{ .Resource.Kind }}Reconciler reconciles a {{ .Resource.Kind }} object -type {{ .Resource.Kind }}Reconciler struct { - client.Client - Log logr.Logger - Scheme *runtime.Scheme - - declarative.Reconciler -} - -//+kubebuilder:rbac:groups={{ .Resource.QualifiedGroup }},resources={{ .Resource.Plural }},verbs=get;list;watch;create;update;patch;delete -//+kubebuilder:rbac:groups={{ .Resource.QualifiedGroup }},resources={{ .Resource.Plural }}/status,verbs=get;update;patch - -// SetupWithManager sets up the controller with the Manager. -func (r *{{ .Resource.Kind }}Reconciler) SetupWithManager(mgr ctrl.Manager) error { - addon.Init() - - labels := map[string]string{ - "k8s-app": "{{ lower .Resource.Kind }}", - } - - watchLabels := declarative.SourceLabel(mgr.GetScheme()) - - if err := r.Reconciler.Init(mgr, &{{ .Resource.ImportAlias }}.{{ .Resource.Kind }}{}, - declarative.WithObjectTransform(declarative.AddLabels(labels)), - declarative.WithOwner(declarative.SourceAsOwner), - declarative.WithLabels(watchLabels), - declarative.WithStatus(status.NewBasic(mgr.GetClient())), - // TODO: add an application to your manifest: declarative.WithObjectTransform(addon.TransformApplicationFromStatus), - // TODO: add an application to your manifest: declarative.WithManagedApplication(watchLabels), - declarative.WithObjectTransform(addon.ApplyPatches), - ); err != nil { - return err - } - - c, err := controller.New("{{ lower .Resource.Kind }}-controller", mgr, controller.Options{Reconciler: r}) - if err != nil { - return err - } - - // Watch for changes to {{ .Resource.Kind }} - err = c.Watch(source.Kind(mgr.GetCache(), &{{ .Resource.ImportAlias }}.{{ .Resource.Kind }}{}), &handler.EnqueueRequestForObject{}) - if err != nil { - return err - } - - // Watch for changes to deployed objects - err = declarative.WatchAll(mgr.GetConfig(), c, r, watchLabels) - if err != nil { - return err - } - - return nil -} -` diff --git a/pkg/plugins/golang/declarative/v1/scaffolds/internal/templates/manifest.go b/pkg/plugins/golang/declarative/v1/scaffolds/internal/templates/manifest.go deleted file mode 100644 index d91f779aee..0000000000 --- a/pkg/plugins/golang/declarative/v1/scaffolds/internal/templates/manifest.go +++ /dev/null @@ -1,53 +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 templates - -import ( - "path/filepath" - - log "github.com/sirupsen/logrus" - - "sigs.k8s.io/kubebuilder/v3/pkg/machinery" -) - -var _ machinery.Template = &Manifest{} - -// Manifest scaffolds the file that acts as a placeholder for the manifest -type Manifest struct { - machinery.TemplateMixin - machinery.ResourceMixin - - ManifestVersion string -} - -// SetTemplateDefaults implements file.Template -func (f *Manifest) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("channels", "packages", "%[kind]", f.ManifestVersion, "manifest.yaml") - } - f.Path = f.Resource.Replacer().Replace(f.Path) - log.Println(f.Path) - - f.TemplateBody = manifestTemplate - - f.IfExistsAction = machinery.SkipFile - - return nil -} - -const manifestTemplate = `# Placeholder manifest - replace with the manifest for your addon -` diff --git a/pkg/plugins/golang/declarative/v1/scaffolds/internal/templates/types.go b/pkg/plugins/golang/declarative/v1/scaffolds/internal/templates/types.go deleted file mode 100644 index 9187c886c4..0000000000 --- a/pkg/plugins/golang/declarative/v1/scaffolds/internal/templates/types.go +++ /dev/null @@ -1,157 +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 templates - -import ( - "fmt" - "path/filepath" - "text/template" - - log "github.com/sirupsen/logrus" - - "sigs.k8s.io/kubebuilder/v3/pkg/machinery" -) - -var _ machinery.Template = &Types{} - -// Types scaffolds the file that defines the schema for a CRD -// nolint:maligned -type Types struct { - machinery.TemplateMixin - machinery.MultiGroupMixin - machinery.BoilerplateMixin - machinery.ResourceMixin - - IsLegacyLayout bool -} - -// SetTemplateDefaults implements file.Template -func (f *Types) SetTemplateDefaults() error { - if f.Path == "" { - if f.IsLegacyLayout { - if f.MultiGroup { - f.Path = filepath.Join("apis", "%[group]", "%[version]", "%[kind]_types.go") - } else { - f.Path = filepath.Join("api", "%[version]", "%[kind]_types.go") - } - } else { - if f.MultiGroup { - f.Path = filepath.Join("api", "%[group]", "%[version]", "%[kind]_types.go") - } else { - f.Path = filepath.Join("api", "%[version]", "%[kind]_types.go") - } - } - - } - f.Path = f.Resource.Replacer().Replace(f.Path) - log.Println(f.Path) - - f.TemplateBody = typesTemplate - - f.IfExistsAction = machinery.OverwriteFile - - return nil -} - -// GetFuncMap implements file.UseCustomFuncMap -func (f Types) GetFuncMap() template.FuncMap { - funcMap := machinery.DefaultFuncMap() - funcMap["JSONTag"] = func(tag string) string { - return fmt.Sprintf("`json:%q`", tag) - } - return funcMap -} - -const typesTemplate = `{{ .Boilerplate }} - -package {{ .Resource.Version }} - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - addonv1alpha1 "sigs.k8s.io/kubebuilder-declarative-pattern/pkg/patterns/addon/pkg/apis/v1alpha1" -) - -// EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN! -// NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized. - -// {{ .Resource.Kind }}Spec defines the desired state of {{ .Resource.Kind }} -type {{ .Resource.Kind }}Spec struct { - addonv1alpha1.CommonSpec {{ JSONTag ",inline" }} - addonv1alpha1.PatchSpec {{ JSONTag ",inline" }} - - // INSERT ADDITIONAL SPEC FIELDS - desired state of cluster - // Important: Run "make" to regenerate code after modifying this file -} - -// {{ .Resource.Kind }}Status defines the observed state of {{ .Resource.Kind }} -type {{ .Resource.Kind }}Status struct { - addonv1alpha1.CommonStatus {{ JSONTag ",inline" }} - - // INSERT ADDITIONAL STATUS FIELD - define observed state of cluster - // Important: Run "make" to regenerate code after modifying this file -} - -//+kubebuilder:object:root=true -//+kubebuilder:subresource:status -{{- if not .Resource.API.Namespaced }} -//+kubebuilder:resource:scope=Cluster -{{- end }} - -// {{ .Resource.Kind }} is the Schema for the {{ .Resource.Plural }} API -type {{ .Resource.Kind }} struct { - metav1.TypeMeta ` + "`" + `json:",inline"` + "`" + ` - metav1.ObjectMeta ` + "`" + `json:"metadata,omitempty"` + "`" + ` - - Spec {{ .Resource.Kind }}Spec ` + "`" + `json:"spec,omitempty"` + "`" + ` - Status {{ .Resource.Kind }}Status ` + "`" + `json:"status,omitempty"` + "`" + ` -} - -var _ addonv1alpha1.CommonObject = &{{ .Resource.Kind }}{} - -func (o *{{ .Resource.Kind }}) ComponentName() string { - return "{{ lower .Resource.Kind }}" -} - -func (o *{{ .Resource.Kind }}) CommonSpec() addonv1alpha1.CommonSpec { - return o.Spec.CommonSpec -} - -func (o *{{ .Resource.Kind }}) PatchSpec() addonv1alpha1.PatchSpec { - return o.Spec.PatchSpec -} - -func (o *{{ .Resource.Kind }}) GetCommonStatus() addonv1alpha1.CommonStatus { - return o.Status.CommonStatus -} - -func (o *{{ .Resource.Kind }}) SetCommonStatus(s addonv1alpha1.CommonStatus) { - o.Status.CommonStatus = s -} - -//+kubebuilder:object:root=true - -// {{ .Resource.Kind }}List contains a list of {{ .Resource.Kind }} -type {{ .Resource.Kind }}List struct { - metav1.TypeMeta ` + "`" + `json:",inline"` + "`" + ` - metav1.ListMeta ` + "`" + `json:"metadata,omitempty"` + "`" + ` - Items []{{ .Resource.Kind }} ` + "`" + `json:"items"` + "`" + ` -} - -func init() { - SchemeBuilder.Register(&{{ .Resource.Kind }}{}, &{{ .Resource.Kind }}List{}) -} -`