diff --git a/.travis.yml b/.travis.yml index 3c0972efacd..be6e9e2cd87 100644 --- a/.travis.yml +++ b/.travis.yml @@ -19,11 +19,6 @@ go_import_path: sigs.k8s.io/kubebuilder services: docker -# Install must be set to prevent default `go get` to run. -# The dependencies have already been vendored by `dep` so -# we don't need to fetch them. -install: skip - script: ./test.sh jobs: diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4158a9bbd1a..3a08dfb601d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -11,7 +11,6 @@ Please see https://git.k8s.io/community/CLA.md for more info. ## Prerequisites - [go](https://golang.org/dl/) version v1.13+. -- [dep](https://github.com/golang/dep) dep v0.5+ - [docker](https://docs.docker.com/install/) version 17.03+. - [kubectl](https://kubernetes.io/docs/tasks/tools/install-kubectl/) version v1.11.3+. - [kustomize](https://sigs.k8s.io/kustomize/docs/INSTALL.md) v3.1.0+ diff --git a/Makefile b/Makefile index 0fbb7c38055..445ecc1f845 100644 --- a/Makefile +++ b/Makefile @@ -61,11 +61,6 @@ generate: ## Update/generate all mock data. You should run this commands to upda .PHONY: generate-testdata generate-testdata: ## Update/generate the testdata in $GOPATH/src/sigs.k8s.io/kubebuilder GO111MODULE=on ./generate_testdata.sh - -.PHONY: generate-vendor -generate-vendor: ## (Deprecated) Update/generate the vendor by using the path $GOPATH/src/sigs.k8s.io/kubebuilder-test - GO111MODULE=off ./generate_vendor.sh - .PHONY: lint lint: ## Run code lint checks ./scripts/verify.sh diff --git a/check_testdata.sh b/check_testdata.sh index eae986b55ee..6c75035fbd9 100755 --- a/check_testdata.sh +++ b/check_testdata.sh @@ -23,7 +23,6 @@ export TRACE=1 export GO111MODULE=on fetch_tools -install_go_dep build_kb setup_envs diff --git a/cmd/edit.go b/cmd/edit.go index 30939fde426..bb89a3e85b6 100644 --- a/cmd/edit.go +++ b/cmd/edit.go @@ -76,12 +76,6 @@ func (o *editOptions) bindFlags(cmd *cobra.Command) { } func (o *editOptions) Validate() error { - if !o.config.IsV2() && !o.config.IsV3() { - if o.config.MultiGroup { - return fmt.Errorf("multiple group support can't be enabled for version %s", o.config.Version) - } - } - return nil } diff --git a/cmd/main.go b/cmd/main.go index 9de836ec384..b22d517ac9d 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -21,18 +21,15 @@ import ( "sigs.k8s.io/kubebuilder/cmd/version" "sigs.k8s.io/kubebuilder/pkg/cli" - pluginv1 "sigs.k8s.io/kubebuilder/pkg/plugin/v1" pluginv2 "sigs.k8s.io/kubebuilder/pkg/plugin/v2" ) func main() { c, err := cli.New( cli.WithPlugins( - &pluginv1.Plugin{}, &pluginv2.Plugin{}, ), cli.WithDefaultPlugins( - &pluginv1.Plugin{}, &pluginv2.Plugin{}, ), cli.WithExtraCommands( diff --git a/common.sh b/common.sh index d187bb48092..fa87ade09a7 100644 --- a/common.sh +++ b/common.sh @@ -155,33 +155,6 @@ function build_kb { GO111MODULE=on go build $opts -o $tmp_root/kubebuilder/bin/kubebuilder ./cmd } -# Required to install the go dep in the https://prow.k8s.io/. -function install_dep_by_git { - header_text "Checking for dep" - export PATH=$(go env GOPATH)/src/github.com/golang/dep/bin:$PATH - if ! is_installed dep ; then - header_text "Installing dep" - DEP_DIR=$(go env GOPATH)/src/github.com/golang/dep - mkdir -p $DEP_DIR - pushd $DEP_DIR - git clone https://github.com/golang/dep.git . - DEP_LATEST=$(git describe --abbrev=0 --tags) - git checkout $DEP_LATEST - mkdir bin - GO111MODULE=off go build -ldflags="-X main.version=$DEP_LATEST" -o bin/dep ./cmd/dep - popd - fi -} - -function install_go_dep { - header_text "Checking for dep" - export PATH=$(go env GOPATH)/src/github.com/golang/dep/bin:$PATH - if ! is_installed dep ; then - header_text "Installing dep" - curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh - fi -} - function install_kind { header_text "Checking for kind" if ! is_installed kind ; then @@ -218,27 +191,6 @@ function setup_envs { export TEST_DEP=$tmp_root/kubebuilder/init_project } -# download_vendor_archive downloads vendor tarball for v1 projects. It skips the -# download if tarball exists. -function download_vendor_archive { - archive_name="vendor.v1.tgz" - archive_download_url="https://storage.googleapis.com/kubebuilder-vendor/$archive_name" - archive_path="$tmp_root/$archive_name" - header_text "checking the path $archive_path to download the $archive_name" - if [ -f $archive_path ]; then - header_text "removing file which exists" - rm $archive_path - fi - header_text "downloading vendor archive from $archive_download_url" - curl -sL ${archive_download_url} -o "$archive_path" -} - -function restore_go_deps { - header_text "restoring Go dependencies" - download_vendor_archive - tar -zxf $tmp_root/vendor.v1.tgz -} - function cache_project { header_text "caching initialized projects" if [ -d "$TEST_DEP" ]; then @@ -252,6 +204,5 @@ function dump_project { header_text "restoring cached project" if [ -d "$TEST_DEP" ]; then cp -r $TEST_DEP/* . - restore_go_deps fi } diff --git a/generate_testdata.sh b/generate_testdata.sh index 8252b42f952..b8a08b9fb6e 100755 --- a/generate_testdata.sh +++ b/generate_testdata.sh @@ -37,25 +37,7 @@ scaffold_test_project() { cd testdata/$project kb=$testdata_dir/../bin/kubebuilder oldgopath=$GOPATH - if [ $version == "1" ]; then - export GO111MODULE=off - export GOPATH=$(pwd)/../.. # go ignores vendor under testdata, so fake out a gopath - # untar Gopkg.lock and vendor directory for appropriate project version - download_vendor_archive - tar -zxf $tmp_root/vendor.v$version.tgz - - $kb init --project-version $version --domain testproject.org --license apache2 --owner "The Kubernetes authors" --dep=false - $kb create api --group crew --version v1 --kind FirstMate --controller=true --resource=true --make=false - $kb alpha webhook --group crew --version v1 --kind FirstMate --type=mutating --operations=create,update --make=false - $kb alpha webhook --group crew --version v1 --kind FirstMate --type=mutating --operations=delete --make=false - $kb create api --group ship --version v1beta1 --kind Frigate --example=false --controller=true --resource=true --make=false - $kb alpha webhook --group ship --version v1beta1 --kind Frigate --type=validating --operations=update --make=false - $kb create api --group creatures --version v2alpha1 --kind Kraken --namespaced=false --example=false --controller=true --resource=true --make=false - $kb alpha webhook --group creatures --version v2alpha1 --kind Kraken --type=validating --operations=create --make=false - $kb create api --group core --version v1 --kind Namespace --example=false --controller=true --resource=false --namespaced=false --make=false - $kb alpha webhook --group core --version v1 --kind Namespace --type=mutating --operations=update --make=false - $kb create api --group policy --version v1beta1 --kind HealthCheckPolicy --example=false --controller=true --resource=true --namespaced=false --make=false - elif [ $version == "2" ] || [ $version == "3-alpha" ]; then + if [ $version == "2" ] || [ $version == "3-alpha" ]; then header_text "Starting to generate projects with version $version" header_text "Generating $project" @@ -96,10 +78,8 @@ scaffold_test_project() { $kb create api --group crew --version v1 --kind Admiral --controller=true --resource=true --namespaced=false --make=false --pattern=addon fi fi - make all test # v2 doesn't test by default - rm -f Gopkg.lock + make all test rm -f go.sum - rm -rf ./vendor rm -rf ./bin export GOPATH=$oldgopath popd @@ -108,7 +88,6 @@ scaffold_test_project() { set -e build_kb -scaffold_test_project gopath/src/project 1 scaffold_test_project project-v2 2 scaffold_test_project project-v2-multigroup 2 scaffold_test_project project-v2-addon 2 diff --git a/generate_vendor.sh b/generate_vendor.sh deleted file mode 100755 index 2b1d125a152..00000000000 --- a/generate_vendor.sh +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/env bash - -# Copyright 2019 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. - -# -# Script to generate vendor archive that contains vendor and Gopkg.toml for a -# given project version -# -set -e - -go_workspace='' -for p in ${GOPATH//:/ }; do - if [[ $PWD/ = $p/* ]]; then - go_workspace=$p - fi -done - -if [ -z $go_workspace ]; then - echo 'Current directory is not in $GOPATH' >&2 - exit 1 -fi - -build_kb() { - rm -f /tmp/kb && \ - GO111MODULE=on go build -o /tmp/kb sigs.k8s.io/kubebuilder/cmd -} - - -# -# generate_vendor takes project version as input and creates vendor archive -# containing Go dependencies for a Kubebuilder project along with the Gopkg.lock -# file. -# -generate_vendor() { - version=$1 - project_dir=${go_workspace}/src/sigs.k8s.io/kubebuilder-test - mkdir -p ${project_dir} - rm -rf ${project_dir}/* - pushd . - cd ${project_dir} - /tmp/kb init --project-version $version --domain testproject.org --license apache2 --owner "The Kubernetes authors" --dep=true - make - tar -zcvf vendor.v$version.tgz vendor Gopkg.lock && \ - echo "vendor archieve vendor.v$version.tgz is ready." - popd -} - -build_kb && \ -generate_vendor 1 diff --git a/pkg/cli/cli.go b/pkg/cli/cli.go index 6a602cf87a0..1d9dacfd567 100644 --- a/pkg/cli/cli.go +++ b/pkg/cli/cli.go @@ -194,6 +194,11 @@ func (c *cli) initialize() error { } else if err == nil { c.configured = true c.projectVersion = projectConfig.Version + + if projectConfig.IsV1() { + return fmt.Errorf(noticeColor, "The v1 projects are no longer supported.\n"+ + "See how to upgrade your project to v2: https://book.kubebuilder.io/migration/guide.html\n") + } } else { return fmt.Errorf("failed to read config: %v", err) } @@ -359,16 +364,12 @@ func validatePlugins(plugins ...plugin.Base) error { // buildRootCmd returns a root command with a subcommand tree reflecting the // current project's state. func (c cli) buildRootCmd() *cobra.Command { - configuredAndV1 := c.configured && c.projectVersion == config.Version1 - rootCmd := c.defaultCommand() // kubebuilder alpha alphaCmd := c.newAlphaCmd() - // kubebuilder alpha webhook (v1 only) - if configuredAndV1 { - alphaCmd.AddCommand(c.newCreateWebhookCmd()) - } + + // Only add alpha group if it has subcommands if alphaCmd.HasSubCommands() { rootCmd.AddCommand(alphaCmd) } @@ -377,10 +378,7 @@ func (c cli) buildRootCmd() *cobra.Command { createCmd := c.newCreateCmd() // kubebuilder create api createCmd.AddCommand(c.newCreateAPICmd()) - // kubebuilder create webhook (!v1) - if !configuredAndV1 { - createCmd.AddCommand(c.newCreateWebhookCmd()) - } + createCmd.AddCommand(c.newCreateWebhookCmd()) if createCmd.HasSubCommands() { rootCmd.AddCommand(createCmd) } diff --git a/pkg/model/resource/options.go b/pkg/model/resource/options.go index 337ed1fba1b..d6ce892b794 100644 --- a/pkg/model/resource/options.go +++ b/pkg/model/resource/options.go @@ -18,9 +18,7 @@ package resource import ( "fmt" - "os" "path" - "path/filepath" "regexp" "strings" @@ -85,10 +83,6 @@ type Options struct { // Namespaced is true if the resource is namespaced. Namespaced bool - - // CreateExampleReconcileBody will create a Deployment in the Reconcile example. - // v1 only - CreateExampleReconcileBody bool } // Validate verifies that all the fields have valid values @@ -165,45 +159,6 @@ func (opts *Options) safeImport(unsafe string) string { return safe } -// NewV1Resource creates a new resource from the options specific to v1 -func (opts *Options) NewV1Resource(c *config.Config, doResource bool) *Resource { - res := opts.newResource() - - replacer := res.Replacer() - - // NOTE: while directories can have "-" and ".", v1 needs that directory to be a Go package - // and that is the reason why we remove them for the directory - pkg := replacer.Replace(path.Join(c.Repo, "pkg", "apis", "%[group-package-name]", "%[version]")) - domain := c.Domain - - // pkg and domain may need to be changed in case we are referring to a builtin core resource: - // - Check if we are scaffolding the resource now => project resource - // - Check if we already scaffolded the resource => project resource - // - Check if the resource group is a well-known core group => builtin core resource - // - In any other case, default to => project resource - // TODO: need to support '--resource-pkg-path' flag for specifying resourcePath - if !doResource { - file := replacer.Replace(filepath.Join( - "pkg", "apis", "%[group-package-name]", "%[version]", "%[kind]_types.go")) - if _, err := os.Stat(file); os.IsNotExist(err) { - if coreDomain, found := coreGroups[opts.Group]; found { - pkg = replacer.Replace(path.Join("k8s.io", "api", "%[group]", "%[version]")) - domain = coreDomain - } - } - } - - res.Package = pkg - res.Domain = opts.Group - if domain != "" { - res.Domain += "." + domain - } - - res.CreateExampleReconcileBody = opts.CreateExampleReconcileBody - - return res -} - // NewResource creates a new resource from the options func (opts *Options) NewResource(c *config.Config, doResource bool) *Resource { res := opts.newResource() diff --git a/pkg/model/resource/resource.go b/pkg/model/resource/resource.go index dee7e5ee1c0..b6a58313c07 100644 --- a/pkg/model/resource/resource.go +++ b/pkg/model/resource/resource.go @@ -51,10 +51,6 @@ type Resource struct { // Namespaced is true if the resource is namespaced. Namespaced bool `json:"namespaced,omitempty"` - - // CreateExampleReconcileBody will create a Deployment in the Reconcile example. - // v1 only - CreateExampleReconcileBody bool `json:"-"` } // GVK returns the group-version-kind information to check against tracked resources in the configuration file diff --git a/pkg/model/resource/resource_test.go b/pkg/model/resource/resource_test.go index 4b74f2953b1..73b6ac69f46 100644 --- a/pkg/model/resource/resource_test.go +++ b/pkg/model/resource/resource_test.go @@ -49,7 +49,6 @@ var _ = Describe("Resource", func() { Expect(resource.ImportAlias).To(Equal("crewv1")) Expect(resource.Package).To(Equal(path.Join("test", "api", "v1"))) Expect(resource.Domain).To(Equal("crew.test.io")) - Expect(resource.CreateExampleReconcileBody).To(Equal(false)) resource = options.NewResource( &config.Config{ @@ -69,26 +68,6 @@ var _ = Describe("Resource", func() { Expect(resource.ImportAlias).To(Equal("crewv1")) Expect(resource.Package).To(Equal(path.Join("test", "apis", "crew", "v1"))) Expect(resource.Domain).To(Equal("crew.test.io")) - Expect(resource.CreateExampleReconcileBody).To(Equal(false)) - - resource = options.NewV1Resource( - &config.Config{ - Version: config.Version1, - Domain: "test.io", - Repo: "test", - }, - true, - ) - Expect(resource.Namespaced).To(Equal(options.Namespaced)) - Expect(resource.Group).To(Equal(options.Group)) - Expect(resource.GroupPackageName).To(Equal("crew")) - Expect(resource.Version).To(Equal(options.Version)) - Expect(resource.Kind).To(Equal(options.Kind)) - Expect(resource.Plural).To(Equal("firstmates")) - Expect(resource.ImportAlias).To(Equal("crewv1")) - Expect(resource.Package).To(Equal(path.Join("test", "pkg", "apis", "crew", "v1"))) - Expect(resource.Domain).To(Equal("crew.test.io")) - Expect(resource.CreateExampleReconcileBody).To(Equal(options.CreateExampleReconcileBody)) }) It("should default the Plural by pluralizing the Kind", func() { @@ -99,9 +78,6 @@ var _ = Describe("Resource", func() { Version: config.Version2, MultiGroup: true, } - v1Config := &config.Config{ - Version: config.Version1, - } options := &Options{Group: "crew", Version: "v1", Kind: "FirstMate"} Expect(options.Validate()).To(Succeed()) @@ -112,9 +88,6 @@ var _ = Describe("Resource", func() { resource = options.NewResource(multiGroupConfig, true) Expect(resource.Plural).To(Equal("firstmates")) - resource = options.NewV1Resource(v1Config, true) - Expect(resource.Plural).To(Equal("firstmates")) - options = &Options{Group: "crew", Version: "v1", Kind: "Fish"} Expect(options.Validate()).To(Succeed()) @@ -124,9 +97,6 @@ var _ = Describe("Resource", func() { resource = options.NewResource(multiGroupConfig, true) Expect(resource.Plural).To(Equal("fish")) - resource = options.NewV1Resource(v1Config, true) - Expect(resource.Plural).To(Equal("fish")) - options = &Options{Group: "crew", Version: "v1", Kind: "Helmswoman"} Expect(options.Validate()).To(Succeed()) @@ -135,9 +105,6 @@ var _ = Describe("Resource", func() { resource = options.NewResource(multiGroupConfig, true) Expect(resource.Plural).To(Equal("helmswomen")) - - resource = options.NewV1Resource(v1Config, true) - Expect(resource.Plural).To(Equal("helmswomen")) }) It("should keep the Plural if specified", func() { @@ -160,14 +127,6 @@ var _ = Describe("Resource", func() { true, ) Expect(resource.Plural).To(Equal("mates")) - - resource = options.NewV1Resource( - &config.Config{ - Version: config.Version1, - }, - true, - ) - Expect(resource.Plural).To(Equal("mates")) }) It("should allow hyphens and dots in group names", func() { @@ -182,11 +141,6 @@ var _ = Describe("Resource", func() { Repo: "test", MultiGroup: true, } - v1Config := &config.Config{ - Version: config.Version1, - Domain: "test.io", - Repo: "test", - } options := &Options{Group: "my-project", Version: "v1", Kind: "FirstMate"} Expect(options.Validate()).To(Succeed()) @@ -205,13 +159,6 @@ var _ = Describe("Resource", func() { Expect(resource.Package).To(Equal(path.Join("test", "apis", "my-project", "v1"))) Expect(resource.Domain).To(Equal("my-project.test.io")) - resource = options.NewV1Resource(v1Config, true) - Expect(resource.Group).To(Equal(options.Group)) - Expect(resource.GroupPackageName).To(Equal("myproject")) - Expect(resource.ImportAlias).To(Equal("myprojectv1")) - Expect(resource.Package).To(Equal(path.Join("test", "pkg", "apis", "myproject", "v1"))) - Expect(resource.Domain).To(Equal("my-project.test.io")) - options = &Options{Group: "my.project", Version: "v1", Kind: "FirstMate"} Expect(options.Validate()).To(Succeed()) @@ -228,13 +175,6 @@ var _ = Describe("Resource", func() { Expect(resource.ImportAlias).To(Equal("myprojectv1")) Expect(resource.Package).To(Equal(path.Join("test", "apis", "my.project", "v1"))) Expect(resource.Domain).To(Equal("my.project.test.io")) - - resource = options.NewV1Resource(v1Config, true) - Expect(resource.Group).To(Equal(options.Group)) - Expect(resource.GroupPackageName).To(Equal("myproject")) - Expect(resource.ImportAlias).To(Equal("myprojectv1")) - Expect(resource.Package).To(Equal(path.Join("test", "pkg", "apis", "myproject", "v1"))) - Expect(resource.Domain).To(Equal("my.project.test.io")) }) It("should not append '.' if provided an empty domain", func() { @@ -257,14 +197,6 @@ var _ = Describe("Resource", func() { true, ) Expect(resource.Domain).To(Equal("crew")) - - resource = options.NewV1Resource( - &config.Config{ - Version: config.Version1, - }, - true, - ) - Expect(resource.Domain).To(Equal("crew")) }) It("should use core apis", func() { @@ -279,11 +211,6 @@ var _ = Describe("Resource", func() { Repo: "test", MultiGroup: true, } - v1Config := &config.Config{ - Version: config.Version1, - Domain: "test.io", - Repo: "test", - } options := &Options{Group: "apps", Version: "v1", Kind: "FirstMate"} Expect(options.Validate()).To(Succeed()) @@ -296,10 +223,6 @@ var _ = Describe("Resource", func() { Expect(resource.Package).To(Equal(path.Join("k8s.io", "api", options.Group, options.Version))) Expect(resource.Domain).To(Equal("apps")) - resource = options.NewV1Resource(v1Config, false) - Expect(resource.Package).To(Equal(path.Join("k8s.io", "api", options.Group, options.Version))) - Expect(resource.Domain).To(Equal("apps")) - options = &Options{Group: "authentication", Version: "v1", Kind: "FirstMate"} Expect(options.Validate()).To(Succeed()) @@ -310,40 +233,6 @@ var _ = Describe("Resource", func() { resource = options.NewResource(multiGroupConfig, false) Expect(resource.Package).To(Equal(path.Join("k8s.io", "api", options.Group, options.Version))) Expect(resource.Domain).To(Equal("authentication.k8s.io")) - - resource = options.NewV1Resource(v1Config, false) - Expect(resource.Package).To(Equal(path.Join("k8s.io", "api", options.Group, options.Version))) - Expect(resource.Domain).To(Equal("authentication.k8s.io")) - }) - - It("should create an example reconcile body if requested (v1 only)", func() { - options := &Options{Group: "crew", Version: "v1", Kind: "FirstMate", CreateExampleReconcileBody: true} - Expect(options.Validate()).To(Succeed()) - - resource := options.NewResource( - &config.Config{ - Version: config.Version2, - }, - true, - ) - Expect(resource.CreateExampleReconcileBody).To(Equal(false)) - - resource = options.NewResource( - &config.Config{ - Version: config.Version2, - MultiGroup: true, - }, - true, - ) - Expect(resource.CreateExampleReconcileBody).To(Equal(false)) - - resource = options.NewV1Resource( - &config.Config{ - Version: config.Version1, - }, - true, - ) - Expect(resource.CreateExampleReconcileBody).To(Equal(options.CreateExampleReconcileBody)) }) }) }) diff --git a/pkg/plugin/v1/api.go b/pkg/plugin/v1/api.go deleted file mode 100644 index 637e74333f5..00000000000 --- a/pkg/plugin/v1/api.go +++ /dev/null @@ -1,170 +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 v1 - -import ( - "bufio" - "fmt" - "io/ioutil" - "os" - "path/filepath" - "strings" - - "github.com/spf13/pflag" - - "sigs.k8s.io/kubebuilder/internal/cmdutil" - "sigs.k8s.io/kubebuilder/pkg/model" - "sigs.k8s.io/kubebuilder/pkg/model/config" - "sigs.k8s.io/kubebuilder/pkg/model/resource" - "sigs.k8s.io/kubebuilder/pkg/plugin" - "sigs.k8s.io/kubebuilder/pkg/plugin/internal" - "sigs.k8s.io/kubebuilder/pkg/scaffold" - "sigs.k8s.io/kubebuilder/plugins/addon" -) - -type createAPIPlugin struct { - config *config.Config - - // pattern indicates that we should use a plugin to build according to a pattern - pattern string - - resource *resource.Options - - // Check if we have to scaffold resource and/or controller - resourceFlag *pflag.Flag - controllerFlag *pflag.Flag - doResource bool - doController bool - - // runMake indicates whether to run make or not after scaffolding APIs - runMake bool -} - -var ( - _ plugin.CreateAPI = &createAPIPlugin{} - _ cmdutil.RunOptions = &createAPIPlugin{} -) - -func (p createAPIPlugin) UpdateContext(ctx *plugin.Context) { - ctx.Description = `Scaffold a Kubernetes API by creating a Resource definition and / or a Controller. - -create resource will prompt the user for if it should scaffold the Resource and / or Controller. To only -scaffold a Controller for an existing Resource, select "n" for Resource. To only define -the schema for a Resource without writing a Controller, select "n" for Controller. - -After the scaffold is written, api will run make on the project. -` - ctx.Examples = fmt.Sprintf(` # Create a frigates API with Group: ship, Version: v1beta1 and Kind: Frigate - %s create api --group ship --version v1beta1 --kind Frigate - - # Edit the API Scheme - nano api/v1beta1/frigate_types.go - - # Edit the Controller - nano controllers/frigate/frigate_controller.go - - # Edit the Controller Test - nano controllers/frigate/frigate_controller_test.go - - # 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 - `, - ctx.CommandName) -} - -func (p *createAPIPlugin) BindFlags(fs *pflag.FlagSet) { - fs.BoolVar(&p.runMake, "make", true, "if true, run make after generating files") - - fs.BoolVar(&p.doResource, "resource", true, - "if set, generate the resource without prompting the user") - p.resourceFlag = fs.Lookup("resource") - fs.BoolVar(&p.doController, "controller", true, - "if set, generate the controller without prompting the user") - p.controllerFlag = fs.Lookup("controller") - - if os.Getenv("KUBEBUILDER_ENABLE_PLUGINS") != "" { - fs.StringVar(&p.pattern, "pattern", "", - "generates an API following an extension pattern (addon)") - } - - p.resource = &resource.Options{} - fs.StringVar(&p.resource.Kind, "kind", "", "resource Kind") - fs.StringVar(&p.resource.Group, "group", "", "resource Group") - fs.StringVar(&p.resource.Version, "version", "", "resource Version") - fs.BoolVar(&p.resource.Namespaced, "namespaced", true, "resource is namespaced") - fs.BoolVar(&p.resource.CreateExampleReconcileBody, "example", true, - "if true an example reconcile body should be written while scaffolding a resource.") -} - -func (p *createAPIPlugin) InjectConfig(c *config.Config) { - p.config = c -} - -func (p *createAPIPlugin) Run() error { - return cmdutil.Run(p) -} - -func (p *createAPIPlugin) Validate() error { - if err := p.resource.Validate(); err != nil { - return err - } - - reader := bufio.NewReader(os.Stdin) - if !p.resourceFlag.Changed { - fmt.Println("Create Resource [y/n]") - p.doResource = internal.YesNo(reader) - } - if !p.controllerFlag.Changed { - fmt.Println("Create Controller [y/n]") - p.doController = internal.YesNo(reader) - } - - return nil -} - -func (p *createAPIPlugin) GetScaffolder() (scaffold.Scaffolder, error) { - // Load the boilerplate - bp, err := ioutil.ReadFile(filepath.Join("hack", "boilerplate.go.txt")) //nolint:gosec - if err != nil { - return nil, fmt.Errorf("unable to load boilerplate: %v", err) - } - - // Load the requested plugins - plugins := make([]model.Plugin, 0) - switch strings.ToLower(p.pattern) { - case "": - // Default pattern - case "addon": - plugins = append(plugins, &addon.Plugin{}) - default: - return nil, fmt.Errorf("unknown pattern %q", p.pattern) - } - - // Create the actual resource from the resource options - res := p.resource.NewV1Resource(p.config, p.doResource) - return scaffold.NewAPIScaffolder(p.config, string(bp), res, p.doResource, p.doController, plugins), nil -} - -func (p *createAPIPlugin) PostScaffold() error { - if p.runMake { - return internal.RunCmd("Running make", "make") - } - return nil -} diff --git a/pkg/plugin/v1/init.go b/pkg/plugin/v1/init.go deleted file mode 100644 index a4dbccb1abf..00000000000 --- a/pkg/plugin/v1/init.go +++ /dev/null @@ -1,186 +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 v1 - -import ( - "bufio" - "fmt" - "log" - "os" - "os/exec" - "path/filepath" - "strings" - - "github.com/spf13/pflag" - - "sigs.k8s.io/kubebuilder/internal/cmdutil" - "sigs.k8s.io/kubebuilder/pkg/internal/validation" - "sigs.k8s.io/kubebuilder/pkg/model/config" - "sigs.k8s.io/kubebuilder/pkg/plugin" - "sigs.k8s.io/kubebuilder/pkg/plugin/internal" - "sigs.k8s.io/kubebuilder/pkg/scaffold" -) - -type initPlugin struct { - config *config.Config - // For help text. - commandName string - - // boilerplate options - license string - owner string - - // deprecated flags - depFlag *pflag.Flag - depArgs []string - dep bool - - // flags - fetchDeps bool - skipGoVersionCheck bool -} - -var ( - _ plugin.Init = &initPlugin{} - _ cmdutil.RunOptions = &initPlugin{} -) - -func (p *initPlugin) UpdateContext(ctx *plugin.Context) { - ctx.Description = `Initialize a new project including vendor/ directory and Go package directories. - -Writes the following files: -- a boilerplate license file -- a PROJECT file with the domain and repo -- a Makefile to build the project -- a go.mod with project dependencies -- a Kustomization.yaml for customizating manifests -- a Patch file for customizing image for manager manifests -- a Patch file for enabling prometheus metrics -- a cmd/manager/main.go to run - -project will prompt the user to run 'dep ensure' after writing the project files. -` - ctx.Examples = fmt.Sprintf(` # Scaffold a project using the apache2 license with "The Kubernetes authors" as owners - %s init --project-version=1 --domain example.org --license apache2 --owner "The Kubernetes authors" -`, - ctx.CommandName) - - p.commandName = ctx.CommandName -} - -func (p *initPlugin) BindFlags(fs *pflag.FlagSet) { - fs.BoolVar(&p.skipGoVersionCheck, "skip-go-version-check", - false, "if specified, skip checking the Go version") - - // dependency args - fs.BoolVar(&p.fetchDeps, "fetch-deps", true, "ensure dependencies are downloaded") - - // deprecated dependency args - fs.BoolVar(&p.dep, "dep", true, "if specified, determines whether dep will be used.") - p.depFlag = fs.Lookup("dep") - fs.StringArrayVar(&p.depArgs, "depArgs", nil, "additional arguments for dep") - - if err := fs.MarkDeprecated("dep", "use the fetch-deps flag instead"); err != nil { - log.Printf("error to mark dep flag as deprecated: %v", err) - } - if err := fs.MarkDeprecated("depArgs", "will be removed with version 1 scaffolding"); err != nil { - log.Printf("error to mark dep flag as deprecated: %v", err) - } - - // boilerplate args - fs.StringVar(&p.license, "license", "apache2", - "license to use to boilerplate, may be one of 'apache2', 'none'") - fs.StringVar(&p.owner, "owner", "", "owner to add to the copyright") - - // project args - fs.StringVar(&p.config.Repo, "repo", "", "name to use for go module (e.g., github.com/user/repo), "+ - "defaults to the go package of the current working directory.") - fs.StringVar(&p.config.Domain, "domain", "my.domain", "domain for groups") -} - -func (p *initPlugin) InjectConfig(c *config.Config) { - p.config = c -} - -func (p *initPlugin) Run() error { - return cmdutil.Run(p) -} - -func (p *initPlugin) Validate() error { - // Requires go1.11+ - if !p.skipGoVersionCheck { - if err := internal.ValidateGoVersion(); err != nil { - return err - } - } - - // Check if the project name is a valid namespace according to k8s - dir, err := os.Getwd() - if err != nil { - return fmt.Errorf("error to get the current path: %v", err) - } - projectName := filepath.Base(dir) - if err := validation.IsDNS1123Label(strings.ToLower(projectName)); err != nil { - return fmt.Errorf("project name (%s) is invalid: %v", projectName, err) - } - - // Try to guess repository if flag is not set - if p.config.Repo == "" { - repoPath, err := internal.FindCurrentRepo() - if err != nil { - return fmt.Errorf("error finding current repository: %v", err) - } - p.config.Repo = repoPath - } - - // Verify dep is installed - if _, err := exec.LookPath("dep"); err != nil { - return fmt.Errorf("dep is not installed: %v\n"+ - "Follow steps at: https://golang.github.io/dep/docs/installation.html", err) - } - - return nil -} - -func (p *initPlugin) GetScaffolder() (scaffold.Scaffolder, error) { - return scaffold.NewInitScaffolder(p.config, p.license, p.owner), nil -} - -func (p *initPlugin) PostScaffold() error { - if !p.depFlag.Changed { - reader := bufio.NewReader(os.Stdin) - fmt.Println("Run `dep ensure` to fetch dependencies (Recommended) [y/n]?") - p.dep = internal.YesNo(reader) - } - if !p.dep { - fmt.Println("Skipping fetching dependencies.") - return nil - } - - err := internal.RunCmd("Fetching dependencies", "dep", append([]string{"ensure"}, p.depArgs...)...) - if err != nil { - return err - } - - err = internal.RunCmd("Running make", "make") - if err != nil { - return err - } - - fmt.Printf("Next: define a resource with:\n$ %s create api\n", p.commandName) - return nil -} diff --git a/pkg/plugin/v1/plugin.go b/pkg/plugin/v1/plugin.go deleted file mode 100644 index 08c20197ce5..00000000000 --- a/pkg/plugin/v1/plugin.go +++ /dev/null @@ -1,54 +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 v1 - -import ( - "sigs.k8s.io/kubebuilder/pkg/model/config" - "sigs.k8s.io/kubebuilder/pkg/plugin" -) - -const ( - pluginName = "go" + plugin.DefaultNameQualifier - pluginVersion = "v1.0.0" - - deprecationWarning = `The v1 projects are deprecated and will not be supported beyond Feb 1, 2020. -See how to upgrade your project to v2: https://book.kubebuilder.io/migration/guide.html` -) - -var supportedProjectVersions = []string{config.Version1} - -var ( - _ plugin.Base = Plugin{} - _ plugin.InitPluginGetter = Plugin{} - _ plugin.CreateAPIPluginGetter = Plugin{} - _ plugin.CreateWebhookPluginGetter = Plugin{} - _ plugin.Deprecated = Plugin{} -) - -type Plugin struct { - initPlugin - createAPIPlugin - createWebhookPlugin -} - -func (Plugin) Name() string { return pluginName } -func (Plugin) Version() string { return pluginVersion } -func (Plugin) SupportedProjectVersions() []string { return supportedProjectVersions } -func (p Plugin) GetInitPlugin() plugin.Init { return &p.initPlugin } -func (p Plugin) GetCreateAPIPlugin() plugin.CreateAPI { return &p.createAPIPlugin } -func (p Plugin) GetCreateWebhookPlugin() plugin.CreateWebhook { return &p.createWebhookPlugin } -func (Plugin) DeprecationWarning() string { return deprecationWarning } diff --git a/pkg/plugin/v1/webhook.go b/pkg/plugin/v1/webhook.go deleted file mode 100644 index b843463c550..00000000000 --- a/pkg/plugin/v1/webhook.go +++ /dev/null @@ -1,111 +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 v1 - -import ( - "fmt" - "io/ioutil" - "path/filepath" - - "github.com/spf13/pflag" - - "sigs.k8s.io/kubebuilder/internal/cmdutil" - "sigs.k8s.io/kubebuilder/pkg/model/config" - "sigs.k8s.io/kubebuilder/pkg/model/resource" - "sigs.k8s.io/kubebuilder/pkg/plugin" - "sigs.k8s.io/kubebuilder/pkg/plugin/internal" - "sigs.k8s.io/kubebuilder/pkg/scaffold" -) - -type createWebhookPlugin struct { - config *config.Config - - resource *resource.Options - server string - webhookType string - operations []string - doMake bool -} - -var ( - _ plugin.CreateWebhook = &createWebhookPlugin{} - _ cmdutil.RunOptions = &createAPIPlugin{} -) - -func (p createWebhookPlugin) UpdateContext(ctx *plugin.Context) { - ctx.Description = `Scaffold a webhook server if there is no existing server. -Scaffolds webhook handlers based on group, version, kind and other user inputs. -This command is only available for v1 scaffolding project. -` - ctx.Examples = fmt.Sprintf(` # Create webhook for CRD of group crew, version v1 and kind FirstMate. - # Set type to be mutating and operations to be create and update. - %s alpha webhook --group crew --version v1 --kind FirstMate --type=mutating --operations=create,update -`, - ctx.CommandName) -} - -func (p *createWebhookPlugin) BindFlags(fs *pflag.FlagSet) { - fs.StringVar(&p.server, "server", "default", "name of the server") - fs.StringVar(&p.webhookType, "type", "", "webhook type, e.g. mutating or validating") - fs.StringSliceVar(&p.operations, "operations", []string{"create"}, - "the operations that the webhook will intercept, e.g. create, update, delete and connect") - - fs.BoolVar(&p.doMake, "make", true, "if true, run make after generating files") - - p.resource = &resource.Options{} - fs.StringVar(&p.resource.Group, "group", "", "resource Group") - fs.StringVar(&p.resource.Version, "version", "", "resource Version") - fs.StringVar(&p.resource.Kind, "kind", "", "resource Kind") - fs.StringVar(&p.resource.Plural, "resource", "", "resource Resource") -} - -func (p *createWebhookPlugin) InjectConfig(c *config.Config) { - p.config = c -} - -func (p *createWebhookPlugin) Run() error { - return cmdutil.Run(p) -} - -func (p *createWebhookPlugin) Validate() error { - if err := p.resource.Validate(); err != nil { - return err - } - return nil -} - -func (p *createWebhookPlugin) GetScaffolder() (scaffold.Scaffolder, error) { - // Load the boilerplate - bp, err := ioutil.ReadFile(filepath.Join("hack", "boilerplate.go.txt")) //nolint:gosec - if err != nil { - return nil, fmt.Errorf("unable to load boilerplate: %v", err) - } - - // Create the actual resource from the resource options - res := p.resource.NewV1Resource(p.config, false) - return scaffold.NewV1WebhookScaffolder(p.config, string(bp), res, p.server, p.webhookType, p.operations), nil -} - -func (p *createWebhookPlugin) PostScaffold() error { - if p.doMake { - err := internal.RunCmd("Running make", "make") - if err != nil { - return err - } - } - return nil -} diff --git a/pkg/plugin/v2/webhook.go b/pkg/plugin/v2/webhook.go index 739bd30191f..80ab43aebb1 100644 --- a/pkg/plugin/v2/webhook.go +++ b/pkg/plugin/v2/webhook.go @@ -107,7 +107,7 @@ func (p *createWebhookPlugin) GetScaffolder() (scaffold.Scaffolder, error) { // Create the actual resource from the resource options res := p.resource.NewResource(p.config, false) - return scaffold.NewV2WebhookScaffolder(p.config, string(bp), res, p.defaulting, p.validation, p.conversion), nil + return scaffold.NewWebhookScaffolder(p.config, string(bp), res, p.defaulting, p.validation, p.conversion), nil } func (p *createWebhookPlugin) PostScaffold() error { diff --git a/pkg/scaffold/api.go b/pkg/scaffold/api.go index 02c296345c2..e29367cc888 100644 --- a/pkg/scaffold/api.go +++ b/pkg/scaffold/api.go @@ -23,11 +23,9 @@ import ( "sigs.k8s.io/kubebuilder/pkg/model/config" "sigs.k8s.io/kubebuilder/pkg/model/resource" "sigs.k8s.io/kubebuilder/pkg/scaffold/internal/machinery" - controllerv1 "sigs.k8s.io/kubebuilder/pkg/scaffold/internal/templates/v1/controller" - crdv1 "sigs.k8s.io/kubebuilder/pkg/scaffold/internal/templates/v1/crd" - templatesv2 "sigs.k8s.io/kubebuilder/pkg/scaffold/internal/templates/v2" - controllerv2 "sigs.k8s.io/kubebuilder/pkg/scaffold/internal/templates/v2/controller" - crdv2 "sigs.k8s.io/kubebuilder/pkg/scaffold/internal/templates/v2/crd" + "sigs.k8s.io/kubebuilder/pkg/scaffold/internal/templates" + "sigs.k8s.io/kubebuilder/pkg/scaffold/internal/templates/controller" + "sigs.k8s.io/kubebuilder/pkg/scaffold/internal/templates/crd" ) var _ Scaffolder = &apiScaffolder{} @@ -69,10 +67,8 @@ func (s *apiScaffolder) Scaffold() error { fmt.Println("Writing scaffold for you to edit...") switch { - case s.config.IsV1(): - return s.scaffoldV1() case s.config.IsV2(), s.config.IsV3(): - return s.scaffoldV2() + return s.scaffold() default: return fmt.Errorf("unknown project version %v", s.config.Version) } @@ -86,82 +82,38 @@ func (s *apiScaffolder) newUniverse() *model.Universe { ) } -func (s *apiScaffolder) scaffoldV1() error { - if s.doResource { - if err := machinery.NewScaffold().Execute( - s.newUniverse(), - &crdv1.Register{}, - &crdv1.Types{}, - &crdv1.VersionSuiteTest{}, - &crdv1.TypesTest{}, - &crdv1.Doc{}, - &crdv1.Group{}, - &crdv1.AddToScheme{}, - &crdv1.CRDSample{}, - ); err != nil { - return fmt.Errorf("error scaffolding APIs: %v", err) - } - } else { - // disable generation of example reconcile body if not scaffolding resource - // because this could result in a fork-bomb of k8s resources where watching a - // deployment, replicaset etc. results in generating deployment which - // end up generating replicaset, pod etc recursively. - s.resource.CreateExampleReconcileBody = false - } - - if s.doController { - if err := machinery.NewScaffold().Execute( - s.newUniverse(), - &controllerv1.Controller{}, - &controllerv1.AddController{}, - &controllerv1.Test{}, - &controllerv1.SuiteTest{}, - ); err != nil { - return fmt.Errorf("error scaffolding controller: %v", err) - } - } - - return nil -} - -func (s *apiScaffolder) scaffoldV2() error { +func (s *apiScaffolder) scaffold() error { if s.doResource { s.config.AddResource(s.resource.GVK()) if err := machinery.NewScaffold(s.plugins...).Execute( s.newUniverse(), - &templatesv2.Types{}, - &templatesv2.Group{}, - &templatesv2.CRDSample{}, - &templatesv2.CRDEditorRole{}, - &templatesv2.CRDViewerRole{}, - &crdv2.EnableWebhookPatch{}, - &crdv2.EnableCAInjectionPatch{}, + &templates.Types{}, + &templates.Group{}, + &templates.CRDSample{}, + &templates.CRDEditorRole{}, + &templates.CRDViewerRole{}, + &crd.EnableWebhookPatch{}, + &crd.EnableCAInjectionPatch{}, ); err != nil { return fmt.Errorf("error scaffolding APIs: %v", err) } if err := machinery.NewScaffold().Execute( s.newUniverse(), - &crdv2.Kustomization{}, - &crdv2.KustomizeConfig{}, + &crd.Kustomization{}, + &crd.KustomizeConfig{}, ); err != nil { return fmt.Errorf("error scaffolding kustomization: %v", err) } - } else { - // disable generation of example reconcile body if not scaffolding resource - // because this could result in a fork-bomb of k8s resources where watching a - // deployment, replicaset etc. results in generating deployment which - // end up generating replicaset, pod etc recursively. - s.resource.CreateExampleReconcileBody = false } if s.doController { if err := machinery.NewScaffold(s.plugins...).Execute( s.newUniverse(), - &controllerv2.SuiteTest{}, - &controllerv2.Controller{}, + &controller.SuiteTest{}, + &controller.Controller{}, ); err != nil { return fmt.Errorf("error scaffolding controller: %v", err) } @@ -169,7 +121,7 @@ func (s *apiScaffolder) scaffoldV2() error { if err := machinery.NewScaffold(s.plugins...).Execute( s.newUniverse(), - &templatesv2.MainUpdater{WireResource: s.doResource, WireController: s.doController}, + &templates.MainUpdater{WireResource: s.doResource, WireController: s.doController}, ); err != nil { return fmt.Errorf("error updating main.go: %v", err) } diff --git a/pkg/scaffold/init.go b/pkg/scaffold/init.go index 0945f9aad8b..5ba89138fa2 100644 --- a/pkg/scaffold/init.go +++ b/pkg/scaffold/init.go @@ -24,15 +24,12 @@ import ( "sigs.k8s.io/kubebuilder/pkg/model" "sigs.k8s.io/kubebuilder/pkg/model/config" "sigs.k8s.io/kubebuilder/pkg/scaffold/internal/machinery" - templatesv1 "sigs.k8s.io/kubebuilder/pkg/scaffold/internal/templates/v1" - managerv1 "sigs.k8s.io/kubebuilder/pkg/scaffold/internal/templates/v1/manager" - metricsauthv1 "sigs.k8s.io/kubebuilder/pkg/scaffold/internal/templates/v1/metricsauth" - templatesv2 "sigs.k8s.io/kubebuilder/pkg/scaffold/internal/templates/v2" - certmanagerv2 "sigs.k8s.io/kubebuilder/pkg/scaffold/internal/templates/v2/certmanager" - managerv2 "sigs.k8s.io/kubebuilder/pkg/scaffold/internal/templates/v2/manager" - metricsauthv2 "sigs.k8s.io/kubebuilder/pkg/scaffold/internal/templates/v2/metricsauth" - prometheusv2 "sigs.k8s.io/kubebuilder/pkg/scaffold/internal/templates/v2/prometheus" - webhookv2 "sigs.k8s.io/kubebuilder/pkg/scaffold/internal/templates/v2/webhook" + "sigs.k8s.io/kubebuilder/pkg/scaffold/internal/templates" + "sigs.k8s.io/kubebuilder/pkg/scaffold/internal/templates/certmanager" + "sigs.k8s.io/kubebuilder/pkg/scaffold/internal/templates/manager" + "sigs.k8s.io/kubebuilder/pkg/scaffold/internal/templates/metricsauth" + "sigs.k8s.io/kubebuilder/pkg/scaffold/internal/templates/prometheus" + "sigs.k8s.io/kubebuilder/pkg/scaffold/internal/templates/webhook" ) const ( @@ -77,17 +74,15 @@ func (s *initScaffolder) Scaffold() error { fmt.Println("Writing scaffold for you to edit...") switch { - case s.config.IsV1(): - return s.scaffoldV1() case s.config.IsV2(), s.config.IsV3(): - return s.scaffoldV2() + return s.scaffold() default: return fmt.Errorf("unknown project version %v", s.config.Version) } } -func (s *initScaffolder) scaffoldV1() error { - bpFile := &templatesv1.Boilerplate{} +func (s *initScaffolder) scaffold() error { + bpFile := &templates.Boilerplate{} bpFile.Path = s.boilerplatePath bpFile.License = s.license bpFile.Owner = s.owner @@ -105,77 +100,37 @@ func (s *initScaffolder) scaffoldV1() error { return machinery.NewScaffold().Execute( s.newUniverse(string(boilerplate)), - &templatesv1.GitIgnore{}, - &templatesv1.AuthProxyRole{}, - &templatesv1.AuthProxyRoleBinding{}, - &templatesv1.KustomizeRBAC{}, - &templatesv1.KustomizeImagePatch{}, - &metricsauthv1.KustomizePrometheusMetricsPatch{}, - &metricsauthv1.KustomizeAuthProxyPatch{}, - &templatesv1.AuthProxyService{}, - &managerv1.Config{Image: imageName}, - &templatesv1.Makefile{Image: imageName}, - &templatesv1.GopkgToml{}, - &managerv1.Dockerfile{}, - &templatesv1.Kustomize{}, - &templatesv1.KustomizeManager{}, - &managerv1.APIs{BoilerplatePath: s.boilerplatePath}, - &managerv1.Controller{}, - &managerv1.Webhook{}, - &managerv1.Cmd{}, - ) -} - -func (s *initScaffolder) scaffoldV2() error { - bpFile := &templatesv2.Boilerplate{} - bpFile.Path = s.boilerplatePath - bpFile.License = s.license - bpFile.Owner = s.owner - if err := machinery.NewScaffold().Execute( - s.newUniverse(""), - bpFile, - ); err != nil { - return err - } - - boilerplate, err := ioutil.ReadFile(s.boilerplatePath) //nolint:gosec - if err != nil { - return err - } - - return machinery.NewScaffold().Execute( - s.newUniverse(string(boilerplate)), - &templatesv2.GitIgnore{}, - &templatesv2.AuthProxyRole{}, - &templatesv2.AuthProxyRoleBinding{}, - &metricsauthv2.AuthProxyPatch{}, - &metricsauthv2.AuthProxyService{}, - &metricsauthv2.ClientClusterRole{}, - &managerv2.Config{Image: imageName}, - &templatesv2.Main{}, - &templatesv2.GoMod{ControllerRuntimeVersion: ControllerRuntimeVersion}, - &templatesv2.Makefile{ + &templates.GitIgnore{}, + &templates.AuthProxyRole{}, + &templates.AuthProxyRoleBinding{}, + &metricsauth.AuthProxyPatch{}, + &metricsauth.AuthProxyService{}, + &metricsauth.ClientClusterRole{}, + &manager.Config{Image: imageName}, + &templates.Main{}, + &templates.GoMod{ControllerRuntimeVersion: ControllerRuntimeVersion}, + &templates.Makefile{ Image: imageName, BoilerplatePath: s.boilerplatePath, ControllerToolsVersion: ControllerToolsVersion, KustomizeVersion: KustomizeVersion, }, - &templatesv2.Dockerfile{}, - &templatesv2.Kustomize{}, - &templatesv2.ManagerWebhookPatch{}, - &templatesv2.ManagerRoleBinding{}, - &templatesv2.LeaderElectionRole{}, - &templatesv2.LeaderElectionRoleBinding{}, - &templatesv2.KustomizeRBAC{}, - &managerv2.Kustomization{}, - &webhookv2.Kustomization{}, - &webhookv2.KustomizeConfigWebhook{}, - &webhookv2.Service{}, - &webhookv2.InjectCAPatch{}, - &prometheusv2.Kustomization{}, - &prometheusv2.ServiceMonitor{}, - &certmanagerv2.CertManager{}, - &certmanagerv2.Kustomization{}, - &certmanagerv2.KustomizeConfig{}, + &templates.Dockerfile{}, + &templates.Kustomize{}, + &templates.ManagerWebhookPatch{}, + &templates.ManagerRoleBinding{}, + &templates.LeaderElectionRole{}, + &templates.LeaderElectionRoleBinding{}, + &templates.KustomizeRBAC{}, + &manager.Kustomization{}, + &webhook.Kustomization{}, + &webhook.KustomizeConfigWebhook{}, + &webhook.Service{}, + &webhook.InjectCAPatch{}, + &prometheus.Kustomization{}, + &prometheus.ServiceMonitor{}, + &certmanager.CertManager{}, + &certmanager.Kustomization{}, + &certmanager.KustomizeConfig{}, ) } diff --git a/pkg/scaffold/internal/templates/v2/authproxyrole.go b/pkg/scaffold/internal/templates/authproxyrole.go similarity index 98% rename from pkg/scaffold/internal/templates/v2/authproxyrole.go rename to pkg/scaffold/internal/templates/authproxyrole.go index 8ee1dfc3559..e168b11813c 100644 --- a/pkg/scaffold/internal/templates/v2/authproxyrole.go +++ b/pkg/scaffold/internal/templates/authproxyrole.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v2 +package templates import ( "path/filepath" diff --git a/pkg/scaffold/internal/templates/v1/authproxyrolebinding.go b/pkg/scaffold/internal/templates/authproxyrolebinding.go similarity index 98% rename from pkg/scaffold/internal/templates/v1/authproxyrolebinding.go rename to pkg/scaffold/internal/templates/authproxyrolebinding.go index cefdda8eac4..59de387e42a 100644 --- a/pkg/scaffold/internal/templates/v1/authproxyrolebinding.go +++ b/pkg/scaffold/internal/templates/authproxyrolebinding.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1 +package templates import ( "path/filepath" diff --git a/pkg/scaffold/internal/templates/v2/boilerplate.go b/pkg/scaffold/internal/templates/boilerplate.go similarity index 99% rename from pkg/scaffold/internal/templates/v2/boilerplate.go rename to pkg/scaffold/internal/templates/boilerplate.go index b07fa524c54..fc53e1a3156 100644 --- a/pkg/scaffold/internal/templates/v2/boilerplate.go +++ b/pkg/scaffold/internal/templates/boilerplate.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v2 +package templates import ( "fmt" diff --git a/pkg/scaffold/internal/templates/v2/certmanager/certificate.go b/pkg/scaffold/internal/templates/certmanager/certificate.go similarity index 100% rename from pkg/scaffold/internal/templates/v2/certmanager/certificate.go rename to pkg/scaffold/internal/templates/certmanager/certificate.go diff --git a/pkg/scaffold/internal/templates/v2/certmanager/kustomize.go b/pkg/scaffold/internal/templates/certmanager/kustomize.go similarity index 100% rename from pkg/scaffold/internal/templates/v2/certmanager/kustomize.go rename to pkg/scaffold/internal/templates/certmanager/kustomize.go diff --git a/pkg/scaffold/internal/templates/v2/certmanager/kustomizeconfig.go b/pkg/scaffold/internal/templates/certmanager/kustomizeconfig.go similarity index 100% rename from pkg/scaffold/internal/templates/v2/certmanager/kustomizeconfig.go rename to pkg/scaffold/internal/templates/certmanager/kustomizeconfig.go diff --git a/pkg/scaffold/internal/templates/v2/controller/controller.go b/pkg/scaffold/internal/templates/controller/controller.go similarity index 100% rename from pkg/scaffold/internal/templates/v2/controller/controller.go rename to pkg/scaffold/internal/templates/controller/controller.go diff --git a/pkg/scaffold/internal/templates/v2/controller/controller_suitetest.go b/pkg/scaffold/internal/templates/controller/controller_suitetest.go similarity index 100% rename from pkg/scaffold/internal/templates/v2/controller/controller_suitetest.go rename to pkg/scaffold/internal/templates/controller/controller_suitetest.go diff --git a/pkg/scaffold/internal/templates/v2/crd/enablecainjection_patch.go b/pkg/scaffold/internal/templates/crd/enablecainjection_patch.go similarity index 100% rename from pkg/scaffold/internal/templates/v2/crd/enablecainjection_patch.go rename to pkg/scaffold/internal/templates/crd/enablecainjection_patch.go diff --git a/pkg/scaffold/internal/templates/v2/crd/enablewebhook_patch.go b/pkg/scaffold/internal/templates/crd/enablewebhook_patch.go similarity index 100% rename from pkg/scaffold/internal/templates/v2/crd/enablewebhook_patch.go rename to pkg/scaffold/internal/templates/crd/enablewebhook_patch.go diff --git a/pkg/scaffold/internal/templates/v2/crd/kustomization.go b/pkg/scaffold/internal/templates/crd/kustomization.go similarity index 100% rename from pkg/scaffold/internal/templates/v2/crd/kustomization.go rename to pkg/scaffold/internal/templates/crd/kustomization.go diff --git a/pkg/scaffold/internal/templates/v2/crd/kustomizeconfig.go b/pkg/scaffold/internal/templates/crd/kustomizeconfig.go similarity index 100% rename from pkg/scaffold/internal/templates/v2/crd/kustomizeconfig.go rename to pkg/scaffold/internal/templates/crd/kustomizeconfig.go diff --git a/pkg/scaffold/internal/templates/v2/crd_editor_rbac.go b/pkg/scaffold/internal/templates/crd_editor_rbac.go similarity index 98% rename from pkg/scaffold/internal/templates/v2/crd_editor_rbac.go rename to pkg/scaffold/internal/templates/crd_editor_rbac.go index 87131e23e76..aa6019f5dc4 100644 --- a/pkg/scaffold/internal/templates/v2/crd_editor_rbac.go +++ b/pkg/scaffold/internal/templates/crd_editor_rbac.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v2 +package templates import ( "path/filepath" diff --git a/pkg/scaffold/internal/templates/v2/crd_sample.go b/pkg/scaffold/internal/templates/crd_sample.go similarity index 98% rename from pkg/scaffold/internal/templates/v2/crd_sample.go rename to pkg/scaffold/internal/templates/crd_sample.go index b83e14d2f6d..9f0f8ac729f 100644 --- a/pkg/scaffold/internal/templates/v2/crd_sample.go +++ b/pkg/scaffold/internal/templates/crd_sample.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v2 +package templates import ( "path/filepath" diff --git a/pkg/scaffold/internal/templates/v2/crd_viewer_rbac.go b/pkg/scaffold/internal/templates/crd_viewer_rbac.go similarity index 98% rename from pkg/scaffold/internal/templates/v2/crd_viewer_rbac.go rename to pkg/scaffold/internal/templates/crd_viewer_rbac.go index fd82cdd205d..67c38ae68f7 100644 --- a/pkg/scaffold/internal/templates/v2/crd_viewer_rbac.go +++ b/pkg/scaffold/internal/templates/crd_viewer_rbac.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v2 +package templates import ( "path/filepath" diff --git a/pkg/scaffold/internal/templates/v2/dockerfile.go b/pkg/scaffold/internal/templates/dockerfile.go similarity index 99% rename from pkg/scaffold/internal/templates/v2/dockerfile.go rename to pkg/scaffold/internal/templates/dockerfile.go index 1e12ec9fa93..fbf5100394a 100644 --- a/pkg/scaffold/internal/templates/v2/dockerfile.go +++ b/pkg/scaffold/internal/templates/dockerfile.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v2 +package templates import ( "sigs.k8s.io/kubebuilder/pkg/model/file" diff --git a/pkg/scaffold/internal/templates/v1/gitignore.go b/pkg/scaffold/internal/templates/gitignore.go similarity index 98% rename from pkg/scaffold/internal/templates/v1/gitignore.go rename to pkg/scaffold/internal/templates/gitignore.go index a5119a5530f..7a91371f982 100644 --- a/pkg/scaffold/internal/templates/v1/gitignore.go +++ b/pkg/scaffold/internal/templates/gitignore.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1 +package templates import ( "sigs.k8s.io/kubebuilder/pkg/model/file" diff --git a/pkg/scaffold/internal/templates/v2/gomod.go b/pkg/scaffold/internal/templates/gomod.go similarity index 98% rename from pkg/scaffold/internal/templates/v2/gomod.go rename to pkg/scaffold/internal/templates/gomod.go index 2e172927f64..75a7b79650d 100644 --- a/pkg/scaffold/internal/templates/v2/gomod.go +++ b/pkg/scaffold/internal/templates/gomod.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v2 +package templates import ( "sigs.k8s.io/kubebuilder/pkg/model/file" diff --git a/pkg/scaffold/internal/templates/v1/gopkg.go b/pkg/scaffold/internal/templates/gopkg.go similarity index 99% rename from pkg/scaffold/internal/templates/v1/gopkg.go rename to pkg/scaffold/internal/templates/gopkg.go index ad19ad5d930..fca45012c5b 100644 --- a/pkg/scaffold/internal/templates/v1/gopkg.go +++ b/pkg/scaffold/internal/templates/gopkg.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1 +package templates import ( "bufio" diff --git a/pkg/scaffold/internal/templates/v2/group.go b/pkg/scaffold/internal/templates/group.go similarity index 99% rename from pkg/scaffold/internal/templates/v2/group.go rename to pkg/scaffold/internal/templates/group.go index 4bc41e428cb..a3b09def6cc 100644 --- a/pkg/scaffold/internal/templates/v2/group.go +++ b/pkg/scaffold/internal/templates/group.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v2 +package templates import ( "path/filepath" diff --git a/pkg/scaffold/internal/templates/v2/kustomize.go b/pkg/scaffold/internal/templates/kustomize.go similarity index 99% rename from pkg/scaffold/internal/templates/v2/kustomize.go rename to pkg/scaffold/internal/templates/kustomize.go index fa2170e2b7c..2f27a379357 100644 --- a/pkg/scaffold/internal/templates/v2/kustomize.go +++ b/pkg/scaffold/internal/templates/kustomize.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v2 +package templates import ( "os" diff --git a/pkg/scaffold/internal/templates/v2/leaderelectionrole.go b/pkg/scaffold/internal/templates/leaderelectionrole.go similarity index 98% rename from pkg/scaffold/internal/templates/v2/leaderelectionrole.go rename to pkg/scaffold/internal/templates/leaderelectionrole.go index 9ac3a71ec86..081187540ae 100644 --- a/pkg/scaffold/internal/templates/v2/leaderelectionrole.go +++ b/pkg/scaffold/internal/templates/leaderelectionrole.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v2 +package templates import ( "path/filepath" diff --git a/pkg/scaffold/internal/templates/v2/leaderelectionrolebinding.go b/pkg/scaffold/internal/templates/leaderelectionrolebinding.go similarity index 98% rename from pkg/scaffold/internal/templates/v2/leaderelectionrolebinding.go rename to pkg/scaffold/internal/templates/leaderelectionrolebinding.go index a8684a43981..1d6b9b13728 100644 --- a/pkg/scaffold/internal/templates/v2/leaderelectionrolebinding.go +++ b/pkg/scaffold/internal/templates/leaderelectionrolebinding.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v2 +package templates import ( "path/filepath" diff --git a/pkg/scaffold/internal/templates/v2/main.go b/pkg/scaffold/internal/templates/main.go similarity index 99% rename from pkg/scaffold/internal/templates/v2/main.go rename to pkg/scaffold/internal/templates/main.go index 525f0b7e016..6443e5d4630 100644 --- a/pkg/scaffold/internal/templates/v2/main.go +++ b/pkg/scaffold/internal/templates/main.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v2 +package templates import ( "fmt" diff --git a/pkg/scaffold/internal/templates/v2/makefile.go b/pkg/scaffold/internal/templates/makefile.go similarity index 99% rename from pkg/scaffold/internal/templates/v2/makefile.go rename to pkg/scaffold/internal/templates/makefile.go index 039bbd53682..a8f19127aa1 100644 --- a/pkg/scaffold/internal/templates/v2/makefile.go +++ b/pkg/scaffold/internal/templates/makefile.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v2 +package templates import ( "sigs.k8s.io/kubebuilder/pkg/model/file" diff --git a/pkg/scaffold/internal/templates/v2/manager/config.go b/pkg/scaffold/internal/templates/manager/config.go similarity index 100% rename from pkg/scaffold/internal/templates/v2/manager/config.go rename to pkg/scaffold/internal/templates/manager/config.go diff --git a/pkg/scaffold/internal/templates/v2/manager/kustomization.go b/pkg/scaffold/internal/templates/manager/kustomization.go similarity index 100% rename from pkg/scaffold/internal/templates/v2/manager/kustomization.go rename to pkg/scaffold/internal/templates/manager/kustomization.go diff --git a/pkg/scaffold/internal/templates/v2/metricsauth/auth_proxy_patch.go b/pkg/scaffold/internal/templates/metricsauth/auth_proxy_patch.go similarity index 100% rename from pkg/scaffold/internal/templates/v2/metricsauth/auth_proxy_patch.go rename to pkg/scaffold/internal/templates/metricsauth/auth_proxy_patch.go diff --git a/pkg/scaffold/internal/templates/v2/metricsauth/authproxyservice.go b/pkg/scaffold/internal/templates/metricsauth/authproxyservice.go similarity index 100% rename from pkg/scaffold/internal/templates/v2/metricsauth/authproxyservice.go rename to pkg/scaffold/internal/templates/metricsauth/authproxyservice.go diff --git a/pkg/scaffold/internal/templates/v2/metricsauth/clientclusterrole.go b/pkg/scaffold/internal/templates/metricsauth/clientclusterrole.go similarity index 100% rename from pkg/scaffold/internal/templates/v2/metricsauth/clientclusterrole.go rename to pkg/scaffold/internal/templates/metricsauth/clientclusterrole.go diff --git a/pkg/scaffold/internal/templates/v2/mgrrolebinding.go b/pkg/scaffold/internal/templates/mgrrolebinding.go similarity index 98% rename from pkg/scaffold/internal/templates/v2/mgrrolebinding.go rename to pkg/scaffold/internal/templates/mgrrolebinding.go index 96cd0e1d322..07af8c57edf 100644 --- a/pkg/scaffold/internal/templates/v2/mgrrolebinding.go +++ b/pkg/scaffold/internal/templates/mgrrolebinding.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v2 +package templates import ( "path/filepath" diff --git a/pkg/scaffold/internal/templates/v2/prometheus/kustomize.go b/pkg/scaffold/internal/templates/prometheus/kustomize.go similarity index 100% rename from pkg/scaffold/internal/templates/v2/prometheus/kustomize.go rename to pkg/scaffold/internal/templates/prometheus/kustomize.go diff --git a/pkg/scaffold/internal/templates/v2/prometheus/monitor.go b/pkg/scaffold/internal/templates/prometheus/monitor.go similarity index 100% rename from pkg/scaffold/internal/templates/v2/prometheus/monitor.go rename to pkg/scaffold/internal/templates/prometheus/monitor.go diff --git a/pkg/scaffold/internal/templates/v2/rbac.go b/pkg/scaffold/internal/templates/rbac.go similarity index 98% rename from pkg/scaffold/internal/templates/v2/rbac.go rename to pkg/scaffold/internal/templates/rbac.go index d925fff7272..39b146e9c2d 100644 --- a/pkg/scaffold/internal/templates/v2/rbac.go +++ b/pkg/scaffold/internal/templates/rbac.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v2 +package templates import ( "path/filepath" diff --git a/pkg/scaffold/internal/templates/v2/types.go b/pkg/scaffold/internal/templates/types.go similarity index 99% rename from pkg/scaffold/internal/templates/v2/types.go rename to pkg/scaffold/internal/templates/types.go index a28ab80230c..97cc0ca29cc 100644 --- a/pkg/scaffold/internal/templates/v2/types.go +++ b/pkg/scaffold/internal/templates/types.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v2 +package templates import ( "fmt" diff --git a/pkg/scaffold/internal/templates/v1/authproxyrole.go b/pkg/scaffold/internal/templates/v1/authproxyrole.go deleted file mode 100644 index ddcb19db5e0..00000000000 --- a/pkg/scaffold/internal/templates/v1/authproxyrole.go +++ /dev/null @@ -1,56 +0,0 @@ -/* -Copyright 2018 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 ( - "path/filepath" - - "sigs.k8s.io/kubebuilder/pkg/model/file" -) - -var _ file.Template = &AuthProxyRole{} - -// AuthProxyRole scaffolds the config/rbac/auth_proxy_role.yaml file -type AuthProxyRole struct { - file.TemplateMixin -} - -// SetTemplateDefaults implements input.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: - name: proxy-role -rules: -- apiGroups: ["authentication.k8s.io"] - resources: - - tokenreviews - verbs: ["create"] -- apiGroups: ["authorization.k8s.io"] - resources: - - subjectaccessreviews - verbs: ["create"] -` diff --git a/pkg/scaffold/internal/templates/v1/authproxyservice.go b/pkg/scaffold/internal/templates/v1/authproxyservice.go deleted file mode 100644 index 3a9b914d899..00000000000 --- a/pkg/scaffold/internal/templates/v1/authproxyservice.go +++ /dev/null @@ -1,63 +0,0 @@ -/* -Copyright 2018 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 ( - "path/filepath" - - "sigs.k8s.io/kubebuilder/pkg/model/file" -) - -var _ file.Template = &AuthProxyService{} - -// AuthProxyService scaffolds the config/rbac/auth_proxy_service.yaml file -type AuthProxyService struct { - file.TemplateMixin -} - -// SetTemplateDefaults implements input.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: - annotations: - prometheus.io/port: "8443" - prometheus.io/scheme: https - prometheus.io/scrape: "true" - labels: - control-plane: controller-manager - controller-tools.k8s.io: "1.0" - name: controller-manager-metrics-service - namespace: system -spec: - ports: - - name: https - port: 8443 - targetPort: https - selector: - control-plane: controller-manager - controller-tools.k8s.io: "1.0" -` diff --git a/pkg/scaffold/internal/templates/v1/boilerplate.go b/pkg/scaffold/internal/templates/v1/boilerplate.go deleted file mode 100644 index d693227f790..00000000000 --- a/pkg/scaffold/internal/templates/v1/boilerplate.go +++ /dev/null @@ -1,93 +0,0 @@ -/* -Copyright 2018 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" - "path/filepath" - "time" - - "sigs.k8s.io/kubebuilder/pkg/model/file" -) - -var _ file.Template = &Boilerplate{} - -// Boilerplate scaffolds a boilerplate header file. -type Boilerplate struct { - file.TemplateMixin - file.BoilerplateMixin - - // License is the License type to write - License string - - // Owner is the copyright owner - e.g. "The Kubernetes Authors" - Owner string - - // Year is the copyright year - Year string -} - -// SetTemplateDefaults implements input.Template -func (f *Boilerplate) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("hack", "boilerplate.go.txt") - } - - if f.Year == "" { - f.Year = fmt.Sprintf("%v", time.Now().Year()) - } - - // Boilerplate given - if len(f.Boilerplate) > 0 { - f.TemplateBody = f.Boilerplate - return nil - } - - // Pick a template boilerplate option - switch f.License { - case "", "apache2": - f.TemplateBody = apache - case "none": - f.TemplateBody = none - } - - return nil -} - -const apache = `/* -{{ if .Owner -}} -Copyright {{ .Year }} {{ .Owner }}. -{{- end }} - -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. -*/` - -const none = `/* -{{ if .Owner -}} -Copyright {{ .Year }} {{ .Owner }}. -{{- end }} -*/` diff --git a/pkg/scaffold/internal/templates/v1/controller/add.go b/pkg/scaffold/internal/templates/v1/controller/add.go deleted file mode 100644 index 93371edf22a..00000000000 --- a/pkg/scaffold/internal/templates/v1/controller/add.go +++ /dev/null @@ -1,59 +0,0 @@ -/* -Copyright 2018 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 controller - -import ( - "path/filepath" - - "sigs.k8s.io/kubebuilder/pkg/model/file" -) - -var _ file.Template = &AddController{} - -// AddController scaffolds adds a new Controller. -type AddController struct { - file.TemplateMixin - file.RepositoryMixin - file.BoilerplateMixin - file.ResourceMixin -} - -// SetTemplateDefaults implements input.Template -func (f *AddController) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("pkg", "controller", "add_%[kind].go") - } - f.Path = f.Resource.Replacer().Replace(f.Path) - - f.TemplateBody = addControllerTemplate - - return nil -} - -const addControllerTemplate = `{{ .Boilerplate }} - -package controller - -import ( - "{{ .Repo }}/pkg/controller/{{ lower .Resource.Kind }}" -) - -func init() { - // AddToManagerFuncs is a list of functions to create controllers and add them to a manager. - AddToManagerFuncs = append(AddToManagerFuncs, {{ lower .Resource.Kind }}.Add) -} -` diff --git a/pkg/scaffold/internal/templates/v1/controller/controller.go b/pkg/scaffold/internal/templates/v1/controller/controller.go deleted file mode 100644 index ad251c4bb9d..00000000000 --- a/pkg/scaffold/internal/templates/v1/controller/controller.go +++ /dev/null @@ -1,221 +0,0 @@ -/* -Copyright 2018 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 controller - -import ( - "fmt" - "path/filepath" - - "sigs.k8s.io/kubebuilder/pkg/model/file" -) - -var _ file.Template = &Controller{} - -// Controller scaffolds a Controller for a Resource -type Controller struct { - file.TemplateMixin - file.BoilerplateMixin - file.ResourceMixin -} - -// SetTemplateDefaults implements input.Template -func (f *Controller) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("pkg", "controller", "%[kind]", "%[kind]_controller.go") - } - f.Path = f.Resource.Replacer().Replace(f.Path) - fmt.Println(f.Path) - - f.TemplateBody = controllerTemplate - - f.IfExistsAction = file.Error - - return nil -} - -//nolint:lll -const controllerTemplate = `{{ .Boilerplate }} - -package {{ lower .Resource.Kind }} - -import ( -{{ if .Resource.CreateExampleReconcileBody }} "context" - "reflect" - appsv1 "k8s.io/api/apps/v1" - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/types" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/controller" - "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" - "sigs.k8s.io/controller-runtime/pkg/handler" - "sigs.k8s.io/controller-runtime/pkg/manager" - "sigs.k8s.io/controller-runtime/pkg/reconcile" - logf "sigs.k8s.io/controller-runtime/pkg/runtime/log" - "sigs.k8s.io/controller-runtime/pkg/source" - {{ .Resource.ImportAlias }} "{{ .Resource.Package }}" -) - -var log = logf.Log.WithName("{{ lower .Resource.Kind }}-controller") -{{ else }} "context" - appsv1 "k8s.io/api/apps/v1" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/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/manager" - "sigs.k8s.io/controller-runtime/pkg/reconcile" - "sigs.k8s.io/controller-runtime/pkg/source" - {{ .Resource.ImportAlias }} "{{ .Resource.Package }}" -) -{{ end -}} - -/** -* USER ACTION REQUIRED: This is a scaffold file intended for the user to modify with their own Controller -* business logic. Delete these comments after modifying this file.* - */ - -// Add creates a new {{ .Resource.Kind }} Controller and adds it to the Manager with default RBAC. -// The Manager will set fields on the Controller and Start it when the Manager is Started. -func Add(mgr manager.Manager) error { - return add(mgr, newReconciler(mgr)) -} - -// newReconciler returns a new reconcile.Reconciler -func newReconciler(mgr manager.Manager) reconcile.Reconciler { - return &Reconcile{{ .Resource.Kind }}{Client: mgr.GetClient(), scheme: mgr.GetScheme()} -} - -// add adds a new Controller to mgr with r as the reconcile.Reconciler -func add(mgr manager.Manager, r reconcile.Reconciler) error { - // Create a new controller - 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{Type: &{{ .Resource.ImportAlias }}.{{ .Resource.Kind }}{}}, &handler.EnqueueRequestForObject{}) - if err != nil { - return err - } - - // TODO(user): Modify this to be the types you create - // Uncomment watch a Deployment created by {{ .Resource.Kind }} - change this for objects you create - err = c.Watch(&source.Kind{Type: &appsv1.Deployment{}}, &handler.EnqueueRequestForOwner{ - IsController: true, - OwnerType: &{{ .Resource.ImportAlias }}.{{ .Resource.Kind }}{}, - }) - if err != nil { - return err - } - - return nil -} - -var _ reconcile.Reconciler = &Reconcile{{ .Resource.Kind }}{} - -// Reconcile{{ .Resource.Kind }} reconciles a {{ .Resource.Kind }} object -type Reconcile{{ .Resource.Kind }} struct { - client.Client - scheme *runtime.Scheme -} - -// Reconcile reads that state of the cluster for a {{ .Resource.Kind }} object and makes changes based on the state read -// and what is in the {{ .Resource.Kind }}.Spec -// TODO(user): Modify this Reconcile function to implement your Controller logic. The scaffolding writes -// a Deployment as an example -{{ if .Resource.CreateExampleReconcileBody -}} -// Automatically generate RBAC rules to allow the Controller to read and write Deployments -// +kubebuilder:rbac:groups=apps,resources=deployments,verbs=get;list;watch;create;update;patch;delete -// +kubebuilder:rbac:groups=apps,resources=deployments/status,verbs=get;update;patch -{{ end -}} -// +kubebuilder:rbac:groups={{ .Resource.Domain }},resources={{ .Resource.Plural }},verbs=get;list;watch;create;update;patch;delete -// +kubebuilder:rbac:groups={{ .Resource.Domain }},resources={{ .Resource.Plural }}/status,verbs=get;update;patch -func (r *Reconcile{{ .Resource.Kind }}) Reconcile(request reconcile.Request) (reconcile.Result, error) { - // Fetch the {{ .Resource.Kind }} instance - instance := &{{ .Resource.ImportAlias }}.{{ .Resource.Kind }}{} - err := r.Get(context.TODO(), request.NamespacedName, instance) - if err != nil { - if errors.IsNotFound(err) { - // Object not found, return. Created objects are automatically garbage collected. - // For additional cleanup logic use finalizers. - return reconcile.Result{}, nil - } - // Error reading the object - requeue the request. - return reconcile.Result{}, err - } - - {{ if .Resource.CreateExampleReconcileBody -}} - // TODO(user): Change this to be the object type created by your controller - // Define the desired Deployment object - deploy := &appsv1.Deployment{ - ObjectMeta: metav1.ObjectMeta{ - Name: instance.Name + "-deployment", - Namespace: {{ if .Resource.Namespaced}}instance.Namespace{{ else }}"default"{{ end }}, - }, - Spec: appsv1.DeploymentSpec{ - Selector: &metav1.LabelSelector{ - MatchLabels: map[string]string{"deployment": instance.Name + "-deployment"}, - }, - Template: corev1.PodTemplateSpec{ - ObjectMeta: metav1.ObjectMeta{Labels: map[string]string{"deployment": instance.Name + "-deployment"}}, - Spec: corev1.PodSpec{ - Containers: []corev1.Container{ - { - Name: "nginx", - Image: "nginx", - }, - }, - }, - }, - }, - } - if err := controllerutil.SetControllerReference(instance, deploy, r.scheme); err != nil { - return reconcile.Result{}, err - } - - // TODO(user): Change this for the object type created by your controller - // Check if the Deployment already exists - found := &appsv1.Deployment{} - err = r.Get(context.TODO(), types.NamespacedName{Name: deploy.Name, Namespace: deploy.Namespace}, found) - if err != nil && errors.IsNotFound(err) { - log.Info("Creating Deployment", "namespace", deploy.Namespace, "name", deploy.Name) - err = r.Create(context.TODO(), deploy) - return reconcile.Result{}, err - } else if err != nil { - return reconcile.Result{}, err - } - - // TODO(user): Change this for the object type created by your controller - // Update the found object and write the result back if there are any changes - if !reflect.DeepEqual(deploy.Spec, found.Spec) { - found.Spec = deploy.Spec - log.Info("Updating Deployment", "namespace", deploy.Namespace, "name", deploy.Name) - err = r.Update(context.TODO(), found) - if err != nil { - return reconcile.Result{}, err - } - } - {{ end -}} - - return reconcile.Result{}, nil -} -` diff --git a/pkg/scaffold/internal/templates/v1/controller/controllersuitetest.go b/pkg/scaffold/internal/templates/v1/controller/controllersuitetest.go deleted file mode 100644 index df3a290909d..00000000000 --- a/pkg/scaffold/internal/templates/v1/controller/controllersuitetest.go +++ /dev/null @@ -1,107 +0,0 @@ -/* -Copyright 2018 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 controller - -import ( - "path/filepath" - - "sigs.k8s.io/kubebuilder/pkg/model/file" -) - -var _ file.Template = &SuiteTest{} - -// SuiteTest scaffolds a SuiteTest -type SuiteTest struct { - file.TemplateMixin - file.RepositoryMixin - file.BoilerplateMixin - file.ResourceMixin -} - -// SetTemplateDefaults implements input.Template -func (f *SuiteTest) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("pkg", "controller", "%[kind]", "%[kind]_controller_suite_test.go") - } - f.Path = f.Resource.Replacer().Replace(f.Path) - - f.TemplateBody = controllerSuiteTestTemplate - - return nil -} - -const controllerSuiteTestTemplate = `{{ .Boilerplate }} - -package {{ lower .Resource.Kind }} - -import ( - stdlog "log" - "os" - "path/filepath" - "sync" - "testing" - "github.com/onsi/gomega" - "k8s.io/client-go/kubernetes/scheme" - "k8s.io/client-go/rest" - "sigs.k8s.io/controller-runtime/pkg/envtest" - "sigs.k8s.io/controller-runtime/pkg/manager" - "sigs.k8s.io/controller-runtime/pkg/reconcile" - "{{ .Repo }}/pkg/apis" -) - -var cfg *rest.Config - -func TestMain(m *testing.M) { - t := &envtest.Environment{ - CRDDirectoryPaths: []string{filepath.Join("..", "..", "..", "config", "crds")}, - } - apis.AddToScheme(scheme.Scheme) - - var err error - if cfg, err = t.Start(); err != nil { - stdlog.Fatal(err) - } - - code := m.Run() - t.Stop() - os.Exit(code) -} - -// SetupTestReconcile returns a reconcile.Reconcile implementation that delegates to inner and -// writes the request to requests after Reconcile is finished. -func SetupTestReconcile(inner reconcile.Reconciler) (reconcile.Reconciler, chan reconcile.Request) { - requests := make(chan reconcile.Request) - fn := reconcile.Func(func(req reconcile.Request) (reconcile.Result, error) { - result, err := inner.Reconcile(req) - requests <- req - return result, err - }) - return fn, requests -} - -// StartTestManager adds recFn -func StartTestManager(mgr manager.Manager, g *gomega.GomegaWithT) (chan struct{}, *sync.WaitGroup) { - stop := make(chan struct{}) - wg := &sync.WaitGroup{} - wg.Add(1) - go func() { - defer wg.Done() - g.Expect(mgr.Start(stop)).NotTo(gomega.HaveOccurred()) - }() - return stop, wg -} -` diff --git a/pkg/scaffold/internal/templates/v1/controller/controllertest.go b/pkg/scaffold/internal/templates/v1/controller/controllertest.go deleted file mode 100644 index aa0b87a138d..00000000000 --- a/pkg/scaffold/internal/templates/v1/controller/controllertest.go +++ /dev/null @@ -1,126 +0,0 @@ -/* -Copyright 2018 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 controller - -import ( - "fmt" - "path/filepath" - - "sigs.k8s.io/kubebuilder/pkg/model/file" -) - -var _ file.Template = &Test{} - -// Test scaffolds a Controller Test -type Test struct { - file.TemplateMixin - file.BoilerplateMixin - file.ResourceMixin -} - -// SetTemplateDefaults implements input.Template -func (f *Test) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("pkg", "controller", "%[kind]", "%[kind]_controller_test.go") - } - f.Path = f.Resource.Replacer().Replace(f.Path) - fmt.Println(f.Path) - - f.TemplateBody = controllerTestTemplate - - f.IfExistsAction = file.Error - - return nil -} - -//nolint:lll -const controllerTestTemplate = `{{ .Boilerplate }} - -package {{ lower .Resource.Kind }} - -import ( - "testing" - "time" - "github.com/onsi/gomega" - "golang.org/x/net/context" - {{ if .Resource.CreateExampleReconcileBody -}} - appsv1 "k8s.io/api/apps/v1" - {{ end -}} - apierrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/manager" - "sigs.k8s.io/controller-runtime/pkg/reconcile" - {{ .Resource.ImportAlias }} "{{ .Resource.Package }}" -) - -var c client.Client - -var expectedRequest = reconcile.Request{NamespacedName: types.NamespacedName{Name: "foo"{{ if .Resource.Namespaced }}, Namespace: "default"{{end}}}} -{{ if .Resource.CreateExampleReconcileBody }}var depKey = types.NamespacedName{Name: "foo-deployment", Namespace: "default"} -{{ end }} -const timeout = time.Second * 5 - -func TestReconcile(t *testing.T) { - g := gomega.NewGomegaWithT(t) - instance := &{{ .Resource.ImportAlias }}.{{ .Resource.Kind }}{ObjectMeta: metav1.ObjectMeta{Name: "foo"{{ if .Resource.Namespaced }}, Namespace: "default"{{end}}}} - - // Setup the Manager and Controller. Wrap the Controller Reconcile function so it writes each request to a - // channel when it is finished. - mgr, err := manager.New(cfg, manager.Options{}) - g.Expect(err).NotTo(gomega.HaveOccurred()) - c = mgr.GetClient() - - recFn, requests := SetupTestReconcile(newReconciler(mgr)) - g.Expect(add(mgr, recFn)).To(gomega.Succeed()) - - stopMgr, mgrStopped := StartTestManager(mgr, g) - - defer func() { - close(stopMgr) - mgrStopped.Wait() - }() - - // Create the {{ .Resource.Kind }} object and expect the Reconcile{{ if .Resource.CreateExampleReconcileBody }} and Deployment to be created{{ end }} - err = c.Create(context.TODO(), instance) - // The instance object may not be a valid object because it might be missing some required fields. - // Please modify the instance object by adding required fields and then remove the following if statement. - if apierrors.IsInvalid(err) { - t.Logf("failed to create object, got an invalid object error: %v", err) - return - } - g.Expect(err).NotTo(gomega.HaveOccurred()) - defer c.Delete(context.TODO(), instance) - g.Eventually(requests, timeout).Should(gomega.Receive(gomega.Equal(expectedRequest))) -{{ if .Resource.CreateExampleReconcileBody }} - deploy := &appsv1.Deployment{} - g.Eventually(func() error { return c.Get(context.TODO(), depKey, deploy) }, timeout). - Should(gomega.Succeed()) - - // Delete the Deployment and expect Reconcile to be called for Deployment deletion - g.Expect(c.Delete(context.TODO(), deploy)).To(gomega.Succeed()) - g.Eventually(requests, timeout).Should(gomega.Receive(gomega.Equal(expectedRequest))) - g.Eventually(func() error { return c.Get(context.TODO(), depKey, deploy) }, timeout). - Should(gomega.Succeed()) - - // Manually delete Deployment since GC isn't enabled in the test control plane - g.Eventually(func() error { return c.Delete(context.TODO(), deploy) }, timeout). - Should(gomega.MatchError("deployments.apps \"foo-deployment\" not found")) -{{ end }} -} -` diff --git a/pkg/scaffold/internal/templates/v1/crd/addtoscheme.go b/pkg/scaffold/internal/templates/v1/crd/addtoscheme.go deleted file mode 100644 index 382447cc9b9..00000000000 --- a/pkg/scaffold/internal/templates/v1/crd/addtoscheme.go +++ /dev/null @@ -1,61 +0,0 @@ -/* -Copyright 2018 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/pkg/model/file" -) - -var _ file.Template = &AddToScheme{} - -// AddToScheme scaffolds the code to add the resource to a SchemeBuilder. -type AddToScheme struct { - file.TemplateMixin - file.BoilerplateMixin - file.ResourceMixin -} - -// SetTemplateDefaults implements input.Template -func (f *AddToScheme) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("pkg", "apis", "addtoscheme_%[group-package-name]_%[version].go") - } - f.Path = f.Resource.Replacer().Replace(f.Path) - - f.TemplateBody = addResourceTemplate - - return nil -} - -// NB(directxman12): we need that package alias on the API import otherwise imports.Process -// gets wicked (or hella, if you're feeling west-coasty) confused. - -const addResourceTemplate = `{{ .Boilerplate }} - -package apis - -import ( - {{ .Resource.ImportAlias }} "{{ .Resource.Package }}" -) - -func init() { - // Register the types with the Scheme so the components can map objects to GroupVersionKinds and back - AddToSchemes = append(AddToSchemes, {{ .Resource.ImportAlias }}.SchemeBuilder.AddToScheme) -} -` diff --git a/pkg/scaffold/internal/templates/v1/crd/crd_sample.go b/pkg/scaffold/internal/templates/v1/crd/crd_sample.go deleted file mode 100644 index b1a201de3c0..00000000000 --- a/pkg/scaffold/internal/templates/v1/crd/crd_sample.go +++ /dev/null @@ -1,57 +0,0 @@ -/* -Copyright 2018 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/pkg/model/file" -) - -var _ file.Template = &CRDSample{} - -// CRDSample scaffolds a manifest for CRD sample. -//nolint:golint -type CRDSample struct { - file.TemplateMixin - file.ResourceMixin -} - -// SetTemplateDefaults implements input.Template -func (f *CRDSample) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("config", "samples", "%[group-package-name]_%[version]_%[kind].yaml") - } - f.Path = f.Resource.Replacer().Replace(f.Path) - - f.TemplateBody = crdSampleTemplate - - f.IfExistsAction = file.Error - - return nil -} - -const crdSampleTemplate = `apiVersion: {{ .Resource.Domain }}/{{ .Resource.Version }} -kind: {{ .Resource.Kind }} -metadata: - labels: - controller-tools.k8s.io: "1.0" - name: {{ lower .Resource.Kind }}-sample -spec: - # Add fields here - foo: bar -` diff --git a/pkg/scaffold/internal/templates/v1/crd/doc.go b/pkg/scaffold/internal/templates/v1/crd/doc.go deleted file mode 100644 index 13d57ed43d1..00000000000 --- a/pkg/scaffold/internal/templates/v1/crd/doc.go +++ /dev/null @@ -1,57 +0,0 @@ -/* -Copyright 2018 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/pkg/model/file" -) - -var _ file.Template = &Doc{} - -// Doc scaffolds the pkg/apis/group/version/doc.go directory -type Doc struct { - file.TemplateMixin - file.RepositoryMixin - file.BoilerplateMixin - file.ResourceMixin -} - -// SetTemplateDefaults implements input.Template -func (f *Doc) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("pkg", "apis", "%[group-package-name]", "%[version]", "doc.go") - } - f.Path = f.Resource.Replacer().Replace(f.Path) - - f.TemplateBody = docGoTemplate - - return nil -} - -//nolint:lll -const docGoTemplate = `{{ .Boilerplate }} - -// Package {{ .Resource.Version }} contains API Schema definitions for the {{ .Resource.Group }} {{ .Resource.Version }} API group -// +k8s:openapi-gen=true -// +k8s:deepcopy-gen=package,register -// +k8s:conversion-gen={{ .Repo }}/pkg/apis/{{ .Resource.GroupPackageName }} -// +k8s:defaulter-gen=TypeMeta -// +groupName={{ .Resource.Domain }} -package {{ .Resource.Version }} -` diff --git a/pkg/scaffold/internal/templates/v1/crd/group.go b/pkg/scaffold/internal/templates/v1/crd/group.go deleted file mode 100644 index 85aef6a98ad..00000000000 --- a/pkg/scaffold/internal/templates/v1/crd/group.go +++ /dev/null @@ -1,50 +0,0 @@ -/* -Copyright 2018 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/pkg/model/file" -) - -var _ file.Template = &Group{} - -// Group scaffolds the pkg/apis/group/group.go -type Group struct { - file.TemplateMixin - file.BoilerplateMixin - file.ResourceMixin -} - -// SetTemplateDefaults implements input.Template -func (f *Group) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("pkg", "apis", "%[group-package-name]", "group.go") - } - f.Path = f.Resource.Replacer().Replace(f.Path) - - f.TemplateBody = groupTemplate - - return nil -} - -const groupTemplate = `{{ .Boilerplate }} - -// Package {{ .Resource.GroupPackageName }} contains {{ .Resource.Group }} API versions -package {{ .Resource.GroupPackageName }} -` diff --git a/pkg/scaffold/internal/templates/v1/crd/register.go b/pkg/scaffold/internal/templates/v1/crd/register.go deleted file mode 100644 index 08306688c76..00000000000 --- a/pkg/scaffold/internal/templates/v1/crd/register.go +++ /dev/null @@ -1,80 +0,0 @@ -/* -Copyright 2018 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/pkg/model/file" -) - -var _ file.Template = &Register{} - -// Register scaffolds the pkg/apis/group/version/register.go file -type Register struct { - file.TemplateMixin - file.RepositoryMixin - file.BoilerplateMixin - file.ResourceMixin -} - -// SetTemplateDefaults implements input.Template -func (f *Register) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("pkg", "apis", "%[group-package-name]", "%[version]", "register.go") - } - f.Path = f.Resource.Replacer().Replace(f.Path) - - f.TemplateBody = registerTemplate - - return nil -} - -//nolint:lll -const registerTemplate = `{{ .Boilerplate }} - -// NOTE: Boilerplate only. Ignore this file. - -// Package {{ .Resource.Version }} contains API Schema definitions for the {{ .Resource.Group }} {{ .Resource.Version }} API group -// +k8s:openapi-gen=true -// +k8s:deepcopy-gen=package,register -// +k8s:conversion-gen={{ .Repo }}/pkg/apis/{{ .Resource.GroupPackageName }} -// +k8s:defaulter-gen=TypeMeta -// +groupName={{ .Resource.Domain }} -package {{ .Resource.Version }} - -import ( - "k8s.io/apimachinery/pkg/runtime/schema" - "sigs.k8s.io/controller-runtime/pkg/runtime/scheme" -) - -var ( - // SchemeGroupVersion is group version used to register these objects - SchemeGroupVersion = schema.GroupVersion{Group: "{{ .Resource.Domain }}", Version: "{{ .Resource.Version }}"} - - // SchemeBuilder is used to add go types to the GroupVersionKind scheme - SchemeBuilder = &scheme.Builder{GroupVersion: SchemeGroupVersion} - - // AddToScheme is required by pkg/client/... - AddToScheme = SchemeBuilder.AddToScheme -) - -// Resource is required by pkg/client/listers/... -func Resource(resource string) schema.GroupResource { - return SchemeGroupVersion.WithResource(resource).GroupResource() -} -` diff --git a/pkg/scaffold/internal/templates/v1/crd/types.go b/pkg/scaffold/internal/templates/v1/crd/types.go deleted file mode 100644 index b4a22da4610..00000000000 --- a/pkg/scaffold/internal/templates/v1/crd/types.go +++ /dev/null @@ -1,104 +0,0 @@ -/* -Copyright 2018 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/pkg/model/file" -) - -var _ file.Template = &Types{} - -// Types scaffolds the pkg/apis/group/version/kind_types.go file to define the schema for an API -type Types struct { - file.TemplateMixin - file.BoilerplateMixin - file.ResourceMixin -} - -// SetTemplateDefaults implements input.Template -func (f *Types) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("pkg", "apis", "%[group-package-name]", "%[version]", "%[kind]_types.go") - } - f.Path = f.Resource.Replacer().Replace(f.Path) - fmt.Println(f.Path) - - f.TemplateBody = typesTemplate - - f.IfExistsAction = file.Error - - return nil -} - -const typesTemplate = `{{ .Boilerplate }} - -package {{ .Resource.Version }} - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -// 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 { - // 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 { - // INSERT ADDITIONAL STATUS FIELD - define observed state of cluster - // Important: Run "make" to regenerate code after modifying this file -} - -// +genclient -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -{{- if not .Resource.Namespaced }} -// +genclient:nonNamespaced -{{- end }} - -// {{ .Resource.Kind }} is the Schema for the {{ .Resource.Plural }} API -// +k8s:openapi-gen=true -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"` + "`" + ` -} - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -{{- if not .Resource.Namespaced }} -// +genclient:nonNamespaced -{{- end }} - -// {{ .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{}) -} -` diff --git a/pkg/scaffold/internal/templates/v1/crd/typestest.go b/pkg/scaffold/internal/templates/v1/crd/typestest.go deleted file mode 100644 index 197d0b8b23f..00000000000 --- a/pkg/scaffold/internal/templates/v1/crd/typestest.go +++ /dev/null @@ -1,97 +0,0 @@ -/* -Copyright 2018 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/pkg/model/file" -) - -var _ file.Template = &TypesTest{} - -// TypesTest scaffolds the pkg/apis/group/version/kind_types_test.go file to test the API schema -type TypesTest struct { - file.TemplateMixin - file.BoilerplateMixin - file.ResourceMixin -} - -// SetTemplateDefaults implements input.Template -func (f *TypesTest) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("pkg", "apis", "%[group-package-name]", "%[version]", "%[kind]_types_test.go") - } - f.Path = f.Resource.Replacer().Replace(f.Path) - fmt.Println(f.Path) - - f.TemplateBody = typesTestTemplate - - f.IfExistsAction = file.Error - - return nil -} - -const typesTestTemplate = `{{ .Boilerplate }} - -package {{ .Resource.Version }} - -import ( - "testing" - "github.com/onsi/gomega" - "golang.org/x/net/context" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" -) - -func TestStorage{{ .Resource.Kind }}(t *testing.T) { - key := types.NamespacedName{ - Name: "foo", - {{ if .Resource.Namespaced -}} - Namespace: "default", - {{ end -}} - } - created := &{{ .Resource.Kind }}{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - {{ if .Resource.Namespaced -}} - Namespace: "default", - {{ end -}} - }} - g := gomega.NewGomegaWithT(t) - - // Test Create - fetched := &{{ .Resource.Kind }}{} - g.Expect(c.Create(context.TODO(), created)).To(gomega.Succeed()) - - g.Expect(c.Get(context.TODO(), key, fetched)).To(gomega.Succeed()) - g.Expect(fetched).To(gomega.Equal(created)) - - // Test Updating the Labels - updated := fetched.DeepCopy() - updated.Labels = map[string]string{"hello": "world"} - g.Expect(c.Update(context.TODO(), updated)).To(gomega.Succeed()) - - g.Expect(c.Get(context.TODO(), key, fetched)).To(gomega.Succeed()) - g.Expect(fetched).To(gomega.Equal(updated)) - - // Test Delete - g.Expect(c.Delete(context.TODO(), fetched)).To(gomega.Succeed()) - g.Expect(c.Get(context.TODO(), key, fetched)).ToNot(gomega.Succeed()) -} -` diff --git a/pkg/scaffold/internal/templates/v1/crd/version_suitetest.go b/pkg/scaffold/internal/templates/v1/crd/version_suitetest.go deleted file mode 100644 index 7a0198efee1..00000000000 --- a/pkg/scaffold/internal/templates/v1/crd/version_suitetest.go +++ /dev/null @@ -1,86 +0,0 @@ -/* -Copyright 2018 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/pkg/model/file" -) - -var _ file.Template = &TypesTest{} - -// VersionSuiteTest scaffolds the version_suite_test.go file to setup the versions test -type VersionSuiteTest struct { - file.TemplateMixin - file.BoilerplateMixin - file.ResourceMixin -} - -// SetTemplateDefaults implements input.Template -func (f *VersionSuiteTest) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("pkg", "apis", "%[group-package-name]", "%[version]", "%[version]_suite_test.go") - } - f.Path = f.Resource.Replacer().Replace(f.Path) - - f.TemplateBody = versionSuiteTestTemplate - - return nil -} - -const versionSuiteTestTemplate = `{{ .Boilerplate }} - -package {{ .Resource.Version }} - -import ( - "log" - "os" - "path/filepath" - "testing" - "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" -) - -var cfg *rest.Config -var c client.Client - -func TestMain(m *testing.M) { - t := &envtest.Environment{ - CRDDirectoryPaths: []string{filepath.Join("..", "..", "..", "..", "config", "crds")}, - } - - err := SchemeBuilder.AddToScheme(scheme.Scheme) - if err != nil { - log.Fatal(err) - } - - if cfg, err = t.Start(); err != nil { - log.Fatal(err) - } - - if c, err = client.New(cfg, client.Options{Scheme: scheme.Scheme}); err != nil { - log.Fatal(err) - } - - code := m.Run() - t.Stop() - os.Exit(code) -} -` diff --git a/pkg/scaffold/internal/templates/v1/kustomize.go b/pkg/scaffold/internal/templates/v1/kustomize.go deleted file mode 100644 index 5f66ddb4920..00000000000 --- a/pkg/scaffold/internal/templates/v1/kustomize.go +++ /dev/null @@ -1,96 +0,0 @@ -/* -Copyright 2018 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 ( - "os" - "path/filepath" - "strings" - - "sigs.k8s.io/kubebuilder/pkg/model/file" -) - -var _ file.Template = &Kustomize{} - -// Kustomize scaffolds the Kustomization file. -type Kustomize struct { - file.TemplateMixin - - // Prefix to use for name prefix customization - Prefix string -} - -// SetTemplateDefaults implements input.Template -func (f *Kustomize) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("config", "default", "kustomization.yaml") - } - - f.TemplateBody = kustomizeTemplate - - f.IfExistsAction = file.Error - - if f.Prefix == "" { - // use directory name as prefix - dir, err := os.Getwd() - if err != nil { - return err - } - f.Prefix = strings.ToLower(filepath.Base(dir)) - } - - return nil -} - -const kustomizeTemplate = `# Adds namespace to all resources. -namespace: {{ .Prefix }}-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: {{ .Prefix }}- - -# Labels to add to all resources and selectors. -#commonLabels: -# someName: someValue - -bases: -- ../rbac -- ../manager - -patchesStrategicMerge: -- manager_image_patch.yaml - # Protect the /metrics endpoint by putting it behind auth. - # Only one of manager_auth_proxy_patch.yaml and - # manager_prometheus_metrics_patch.yaml should be enabled. -- manager_auth_proxy_patch.yaml - # If you want your controller-manager to expose the /metrics - # endpoint w/o any authn/z, uncomment the following line and - # comment manager_auth_proxy_patch.yaml. - # Only one of manager_auth_proxy_patch.yaml and - # manager_prometheus_metrics_patch.yaml should be enabled. -#- manager_prometheus_metrics_patch.yaml - -vars: -- name: WEBHOOK_SECRET_NAME - objref: - kind: Secret - name: webhook-server-secret - apiVersion: v1 -` diff --git a/pkg/scaffold/internal/templates/v1/kustomize_image_patch.go b/pkg/scaffold/internal/templates/v1/kustomize_image_patch.go deleted file mode 100644 index 464c883820d..00000000000 --- a/pkg/scaffold/internal/templates/v1/kustomize_image_patch.go +++ /dev/null @@ -1,65 +0,0 @@ -/* -Copyright 2018 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 ( - "path/filepath" - - "sigs.k8s.io/kubebuilder/pkg/model/file" -) - -var _ file.Template = &KustomizeImagePatch{} - -// KustomizeImagePatch scaffolds the patch file for customizing image URL -// manifest file for manager resource. -type KustomizeImagePatch struct { - file.TemplateMixin - - // ImageURL to use for controller image in manager's manifest. - ImageURL string -} - -// SetTemplateDefaults implements input.Template -func (f *KustomizeImagePatch) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("config", "default", "manager_image_patch.yaml") - } - - f.TemplateBody = kustomizeImagePatchTemplate - - f.IfExistsAction = file.Error - - if f.ImageURL == "" { - f.ImageURL = "IMAGE_URL" - } - - return nil -} - -const kustomizeImagePatchTemplate = `apiVersion: apps/v1 -kind: StatefulSet -metadata: - name: controller-manager - namespace: system -spec: - template: - spec: - containers: - # Change the value of image field below to your controller image URL - - image: {{ .ImageURL }} - name: manager -` diff --git a/pkg/scaffold/internal/templates/v1/kustomize_manager_base.go b/pkg/scaffold/internal/templates/v1/kustomize_manager_base.go deleted file mode 100644 index 1659c53e266..00000000000 --- a/pkg/scaffold/internal/templates/v1/kustomize_manager_base.go +++ /dev/null @@ -1,47 +0,0 @@ -/* -Copyright 2019 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 ( - "path/filepath" - - "sigs.k8s.io/kubebuilder/pkg/model/file" -) - -var _ file.Template = &KustomizeManager{} - -// KustomizeManager scaffolds the Kustomization file in manager folder. -type KustomizeManager struct { - file.TemplateMixin -} - -// SetTemplateDefaults implements input.Template -func (f *KustomizeManager) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("config", "manager", "kustomization.yaml") - } - - f.TemplateBody = kustomizeManagerTemplate - - f.IfExistsAction = file.Error - - return nil -} - -const kustomizeManagerTemplate = `resources: -- manager.yaml -` diff --git a/pkg/scaffold/internal/templates/v1/kustomize_rbac_base.go b/pkg/scaffold/internal/templates/v1/kustomize_rbac_base.go deleted file mode 100644 index 7115db70033..00000000000 --- a/pkg/scaffold/internal/templates/v1/kustomize_rbac_base.go +++ /dev/null @@ -1,54 +0,0 @@ -/* -Copyright 2019 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 ( - "path/filepath" - - "sigs.k8s.io/kubebuilder/pkg/model/file" -) - -var _ file.Template = &KustomizeRBAC{} - -// KustomizeRBAC scaffolds the Kustomization file in rbac folder. -type KustomizeRBAC struct { - file.TemplateMixin -} - -// SetTemplateDefaults implements input.Template -func (f *KustomizeRBAC) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("config", "rbac", "kustomization.yaml") - } - - f.TemplateBody = kustomizeRBACTemplate - - f.IfExistsAction = file.Error - - return nil -} - -const kustomizeRBACTemplate = `resources: -- rbac_role.yaml -- rbac_role_binding.yaml - # Comment the following 3 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 -` diff --git a/pkg/scaffold/internal/templates/v1/makefile.go b/pkg/scaffold/internal/templates/v1/makefile.go deleted file mode 100644 index 746c2074066..00000000000 --- a/pkg/scaffold/internal/templates/v1/makefile.go +++ /dev/null @@ -1,113 +0,0 @@ -/* -Copyright 2018 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 ( - "sigs.k8s.io/kubebuilder/pkg/model/file" -) - -var _ file.Template = &Makefile{} - -// Makefile scaffolds the Makefile -type Makefile struct { - file.TemplateMixin - file.RepositoryMixin - - // Image is controller manager image name - Image string - - // path for controller-tools pkg - ControllerToolsPath string -} - -// SetTemplateDefaults implements input.Template -func (f *Makefile) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = "Makefile" - } - - f.TemplateBody = makefileTemplate - - f.IfExistsAction = file.Error - - if f.Image == "" { - f.Image = "controller:latest" - } - - if f.ControllerToolsPath == "" { - f.ControllerToolsPath = "vendor/sigs.k8s.io/controller-tools" - } - - return nil -} - -const makefileTemplate = ` -# Image URL to use all building/pushing image targets -IMG ?= {{ .Image }} - -all: test manager - -# Run tests -test: generate fmt vet manifests - go test ./pkg/... ./cmd/... -coverprofile cover.out - -# Build manager binary -manager: generate fmt vet - go build -o bin/manager {{ .Repo }}/cmd/manager - -# Run against the configured Kubernetes cluster in ~/.kube/config -run: generate fmt vet - go run ./cmd/manager/main.go - -# Install CRDs into a cluster -install: manifests - kubectl apply -f config/crds - -# Deploy controller in the configured Kubernetes cluster in ~/.kube/config -deploy: manifests - kubectl apply -f config/crds - kustomize build config/default | kubectl apply -f - - -# Generate manifests e.g. CRD, RBAC etc. -manifests: - go run {{ .ControllerToolsPath }}/cmd/controller-gen/main.go all - -# Run go fmt against code -fmt: - go fmt ./pkg/... ./cmd/... - -# Run go vet against code -vet: - go vet ./pkg/... ./cmd/... - -# Generate code -generate: -ifndef GOPATH - $(error GOPATH not defined, please define GOPATH. Run "go help gopath" to learn more about GOPATH) -endif - go generate ./pkg/... ./cmd/... - -# Build the docker image -docker-build: test - docker build . -t ${IMG} - @echo "updating kustomize image patch file for manager resource" - sed -i'' -e 's@image: .*@image: '"${IMG}"'@' ./config/default/manager_image_patch.yaml - -# Push the docker image -docker-push: - docker push ${IMG} -` diff --git a/pkg/scaffold/internal/templates/v1/manager/apis.go b/pkg/scaffold/internal/templates/v1/manager/apis.go deleted file mode 100644 index 9e7c7936181..00000000000 --- a/pkg/scaffold/internal/templates/v1/manager/apis.go +++ /dev/null @@ -1,86 +0,0 @@ -/* -Copyright 2018 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 ( - "fmt" - "path/filepath" - "strings" - - "sigs.k8s.io/kubebuilder/pkg/model/file" -) - -var _ file.Template = &APIs{} - -// APIs scaffolds a apis.go to register types with a Scheme -type APIs struct { - file.TemplateMixin - file.BoilerplateMixin - - // BoilerplatePath is the path to the boilerplate file - BoilerplatePath string - // Comments is a list of comments to add to the apis.go - Comments []string -} - -var deepCopy = strings.Join([]string{ - "//go:generate go run", - "../../vendor/k8s.io/code-generator/cmd/deepcopy-gen/main.go", - "-O zz_generated.deepcopy", - "-i ./..."}, " ") - -// SetTemplateDefaults implements input.Template -func (f *APIs) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("pkg", "apis", "apis.go") - } - - f.TemplateBody = apisTemplate - - relPath, err := filepath.Rel(filepath.Dir(f.Path), f.BoilerplatePath) - if err != nil { - return err - } - - if len(f.Comments) == 0 { - f.Comments = append(f.Comments, - "// Generate deepcopy for apis", fmt.Sprintf("%s -h %s", deepCopy, filepath.ToSlash(relPath))) - } - - return nil -} - -const apisTemplate = `{{ .Boilerplate }} - -{{ range $line := .Comments -}} -{{ $line }} -{{ end }} -// Package apis contains Kubernetes API groups. -package apis - -import ( - "k8s.io/apimachinery/pkg/runtime" -) - -// AddToSchemes may be used to add all resources defined in the project to a Scheme -var AddToSchemes runtime.SchemeBuilder - -// AddToScheme adds all Resources to the Scheme -func AddToScheme(s *runtime.Scheme) error { - return AddToSchemes.AddToScheme(s) -} -` diff --git a/pkg/scaffold/internal/templates/v1/manager/cmd.go b/pkg/scaffold/internal/templates/v1/manager/cmd.go deleted file mode 100644 index e048ea7282c..00000000000 --- a/pkg/scaffold/internal/templates/v1/manager/cmd.go +++ /dev/null @@ -1,114 +0,0 @@ -/* -Copyright 2018 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/pkg/model/file" -) - -var _ file.Template = &Cmd{} - -// Cmd scaffolds a manager.go to run Controllers -type Cmd struct { - file.TemplateMixin - file.RepositoryMixin - file.BoilerplateMixin -} - -// SetTemplateDefaults implements input.Template -func (f *Cmd) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("cmd", "manager", "main.go") - } - - f.TemplateBody = cmdTemplate - - return nil -} - -const cmdTemplate = `{{ .Boilerplate }} - -package main - -import ( - "flag" - "os" - _ "k8s.io/client-go/plugin/pkg/client/auth/gcp" - "sigs.k8s.io/controller-runtime/pkg/client/config" - "sigs.k8s.io/controller-runtime/pkg/manager" - logf "sigs.k8s.io/controller-runtime/pkg/runtime/log" - "sigs.k8s.io/controller-runtime/pkg/runtime/signals" - "{{ .Repo }}/pkg/apis" - "{{ .Repo }}/pkg/controller" - "{{ .Repo }}/pkg/webhook" -) - -func main() { - var metricsAddr string - flag.StringVar(&metricsAddr, "metrics-addr", ":8080", "The address the metric endpoint binds to.") - flag.Parse() - logf.SetLogger(logf.ZapLogger(false)) - log := logf.Log.WithName("entrypoint") - - // Get a config to talk to the apiserver - log.Info("setting up client for manager") - cfg, err := config.GetConfig() - if err != nil { - log.Error(err, "unable to set up client config") - os.Exit(1) - } - - // Create a new Cmd to provide shared dependencies and start components - log.Info("setting up manager") - mgr, err := manager.New(cfg, manager.Options{MetricsBindAddress: metricsAddr}) - if err != nil { - log.Error(err, "unable to set up overall controller manager") - os.Exit(1) - } - - log.Info("Registering Components.") - - // Setup Scheme for all resources - log.Info("setting up scheme") - if err := apis.AddToScheme(mgr.GetScheme()); err != nil { - log.Error(err, "unable add APIs to scheme") - os.Exit(1) - } - - // Setup all Controllers - log.Info("Setting up controller") - if err := controller.AddToManager(mgr); err != nil { - log.Error(err, "unable to register controllers to the manager") - os.Exit(1) - } - - log.Info("setting up webhooks") - if err := webhook.AddToManager(mgr); err != nil { - log.Error(err, "unable to register webhooks to the manager") - os.Exit(1) - } - - // Start the Cmd - log.Info("Starting the Cmd.") - if err := mgr.Start(signals.SetupSignalHandler()); err != nil { - log.Error(err, "unable to run the manager") - os.Exit(1) - } -} -` diff --git a/pkg/scaffold/internal/templates/v1/manager/config.go b/pkg/scaffold/internal/templates/v1/manager/config.go deleted file mode 100644 index bee783ced28..00000000000 --- a/pkg/scaffold/internal/templates/v1/manager/config.go +++ /dev/null @@ -1,130 +0,0 @@ -/* -Copyright 2018 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/pkg/model/file" -) - -var _ file.Template = &Config{} - -// Config scaffolds yaml config for the manager. -type Config struct { - file.TemplateMixin - - // Image is controller manager image name - Image string -} - -// SetTemplateDefaults implements input.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 - controller-tools.k8s.io: "1.0" - name: system ---- -apiVersion: v1 -kind: Service -metadata: - name: controller-manager-service - namespace: system - labels: - control-plane: controller-manager - controller-tools.k8s.io: "1.0" -spec: - selector: - control-plane: controller-manager - controller-tools.k8s.io: "1.0" - ports: - - port: 443 ---- -apiVersion: apps/v1 -kind: StatefulSet -metadata: - name: controller-manager - namespace: system - labels: - control-plane: controller-manager - controller-tools.k8s.io: "1.0" -spec: - selector: - matchLabels: - control-plane: controller-manager - controller-tools.k8s.io: "1.0" - serviceName: controller-manager-service - replicas: 1 - podManagementPolicy: Parallel - template: - metadata: - labels: - control-plane: controller-manager - controller-tools.k8s.io: "1.0" - spec: - containers: - - command: - - /manager - image: {{ .Image }} - name: manager - env: - - name: POD_NAMESPACE - valueFrom: - fieldRef: - fieldPath: metadata.namespace - - name: SECRET_NAME - value: $(WEBHOOK_SECRET_NAME) - resources: - limits: - cpu: 100m - memory: 30Mi - requests: - cpu: 100m - memory: 20Mi - ports: - - containerPort: 9876 - name: webhook-server - protocol: TCP - volumeMounts: - - mountPath: /tmp/cert - name: cert - readOnly: true - terminationGracePeriodSeconds: 10 - volumes: - - name: cert - secret: - defaultMode: 420 - secretName: webhook-server-secret ---- -apiVersion: v1 -kind: Secret -metadata: - name: webhook-server-secret - namespace: system -` diff --git a/pkg/scaffold/internal/templates/v1/manager/controller.go b/pkg/scaffold/internal/templates/v1/manager/controller.go deleted file mode 100644 index b4ec536e0ce..00000000000 --- a/pkg/scaffold/internal/templates/v1/manager/controller.go +++ /dev/null @@ -1,64 +0,0 @@ -/* -Copyright 2018 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/pkg/model/file" -) - -var _ file.Template = &Controller{} - -// Controller scaffolds a controller.go to add Controllers to a manager.Cmd -type Controller struct { - file.TemplateMixin - file.BoilerplateMixin -} - -// SetTemplateDefaults implements input.Template -func (f *Controller) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("pkg", "controller", "controller.go") - } - - f.TemplateBody = controllerTemplate - - return nil -} - -const controllerTemplate = `{{ .Boilerplate }} - -package controller - -import ( - "sigs.k8s.io/controller-runtime/pkg/manager" -) - -// AddToManagerFuncs is a list of functions to add all Controllers to the Manager -var AddToManagerFuncs []func(manager.Manager) error - -// AddToManager adds all Controllers to the Manager -func AddToManager(m manager.Manager) error { - for _, f := range AddToManagerFuncs { - if err := f(m); err != nil { - return err - } - } - return nil -} -` diff --git a/pkg/scaffold/internal/templates/v1/manager/dockerfile.go b/pkg/scaffold/internal/templates/v1/manager/dockerfile.go deleted file mode 100644 index 91b673d0b53..00000000000 --- a/pkg/scaffold/internal/templates/v1/manager/dockerfile.go +++ /dev/null @@ -1,59 +0,0 @@ -/* -Copyright 2018 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 ( - "sigs.k8s.io/kubebuilder/pkg/model/file" -) - -var _ file.Template = &Dockerfile{} - -// Dockerfile scaffolds a Dockerfile for building a main -type Dockerfile struct { - file.TemplateMixin - file.RepositoryMixin -} - -// SetTemplateDefaults implements input.Template -func (f *Dockerfile) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = "Dockerfile" - } - - f.TemplateBody = dockerfileTemplate - - return nil -} - -const dockerfileTemplate = `# Build the manager binary -FROM golang:1.10.3 as builder - -# Copy in the go src -WORKDIR /go/src/{{ .Repo }} -COPY cmd/ cmd/ -COPY vendor/ vendor/ -COPY pkg/ pkg/ - -# Build -RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -a -o manager {{ .Repo }}/cmd/manager - -# Copy the controller-manager into a thin image -FROM ubuntu:latest -WORKDIR / -COPY --from=builder /go/src/{{ .Repo }}/manager . -ENTRYPOINT ["/manager"] -` diff --git a/pkg/scaffold/internal/templates/v1/manager/webhook.go b/pkg/scaffold/internal/templates/v1/manager/webhook.go deleted file mode 100644 index bef81f89536..00000000000 --- a/pkg/scaffold/internal/templates/v1/manager/webhook.go +++ /dev/null @@ -1,68 +0,0 @@ -/* -Copyright 2018 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/pkg/model/file" -) - -var _ file.Template = &Webhook{} - -// Webhook scaffolds a webhook.go to add webhook server(s) to a manager.Cmd -type Webhook struct { - file.TemplateMixin - file.BoilerplateMixin -} - -// SetTemplateDefaults implements input.Template -func (f *Webhook) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("pkg", "webhook", "webhook.go") - } - - f.TemplateBody = webhookTemplate - - return nil -} - -//nolint:lll -const webhookTemplate = `{{ .Boilerplate }} - -package webhook - -import ( - "sigs.k8s.io/controller-runtime/pkg/manager" -) - -// AddToManagerFuncs is a list of functions to add all Controllers to the Manager -var AddToManagerFuncs []func(manager.Manager) error - -// AddToManager adds all Controllers to the Manager -// +kubebuilder:rbac:groups=admissionregistration.k8s.io,resources=mutatingwebhookconfigurations;validatingwebhookconfigurations,verbs=get;list;watch;create;update;patch;delete -// +kubebuilder:rbac:groups="",resources=secrets,verbs=get;list;watch;create;update;patch;delete -// +kubebuilder:rbac:groups="",resources=services,verbs=get;list;watch;create;update;patch;delete -func AddToManager(m manager.Manager) error { - for _, f := range AddToManagerFuncs { - if err := f(m); err != nil { - return err - } - } - return nil -} -` diff --git a/pkg/scaffold/internal/templates/v1/metricsauth/kustomize_auth_proxy_patch.go b/pkg/scaffold/internal/templates/v1/metricsauth/kustomize_auth_proxy_patch.go deleted file mode 100644 index 7f8f15c3c6e..00000000000 --- a/pkg/scaffold/internal/templates/v1/metricsauth/kustomize_auth_proxy_patch.go +++ /dev/null @@ -1,70 +0,0 @@ -/* -Copyright 2018 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 metricsauth - -import ( - "path/filepath" - - "sigs.k8s.io/kubebuilder/pkg/model/file" -) - -var _ file.Template = &KustomizeAuthProxyPatch{} - -// KustomizeAuthProxyPatch scaffolds the patch file for enabling -// prometheus metrics for manager Pod. -type KustomizeAuthProxyPatch struct { - file.TemplateMixin -} - -// SetTemplateDefaults implements input.Template -func (f *KustomizeAuthProxyPatch) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("config", "default", "manager_auth_proxy_patch.yaml") - } - - f.TemplateBody = kustomizeAuthProxyPatchTemplate - - f.IfExistsAction = file.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: StatefulSet -metadata: - name: controller-manager - namespace: system -spec: - template: - spec: - containers: - - name: kube-rbac-proxy - image: gcr.io/kubebuilder/kube-rbac-proxy:v0.5.0 - args: - - "--secure-listen-address=0.0.0.0:8443" - - "--upstream=http://127.0.0.1:8080/" - - "--logtostderr=true" - - "--v=10" - ports: - - containerPort: 8443 - name: https - - name: manager - args: - - "--metrics-addr=127.0.0.1:8080" -` diff --git a/pkg/scaffold/internal/templates/v1/metricsauth/kustomize_metrics_patch.go b/pkg/scaffold/internal/templates/v1/metricsauth/kustomize_metrics_patch.go deleted file mode 100644 index 81d4fc50e40..00000000000 --- a/pkg/scaffold/internal/templates/v1/metricsauth/kustomize_metrics_patch.go +++ /dev/null @@ -1,65 +0,0 @@ -/* -Copyright 2018 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 metricsauth - -import ( - "path/filepath" - - "sigs.k8s.io/kubebuilder/pkg/model/file" -) - -var _ file.Template = &KustomizePrometheusMetricsPatch{} - -// KustomizePrometheusMetricsPatch scaffolds the patch file for enabling -// prometheus metrics for manager Pod. -type KustomizePrometheusMetricsPatch struct { - file.TemplateMixin -} - -// SetTemplateDefaults implements input.Template -func (f *KustomizePrometheusMetricsPatch) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("config", "default", "manager_prometheus_metrics_patch.yaml") - } - - f.TemplateBody = kustomizePrometheusMetricsPatchTemplate - - f.IfExistsAction = file.Error - - return nil -} - -const kustomizePrometheusMetricsPatchTemplate = `# This patch enables Prometheus scraping for the manager pod. -apiVersion: apps/v1 -kind: StatefulSet -metadata: - name: controller-manager - namespace: system -spec: - template: - metadata: - annotations: - prometheus.io/scrape: 'true' - spec: - containers: - # Expose the prometheus metrics on default port - - name: manager - ports: - - containerPort: 8080 - name: metrics - protocol: TCP -` diff --git a/pkg/scaffold/internal/templates/v1/webhook/add_admissionbuilder_handler.go b/pkg/scaffold/internal/templates/v1/webhook/add_admissionbuilder_handler.go deleted file mode 100644 index 50778ae44f7..00000000000 --- a/pkg/scaffold/internal/templates/v1/webhook/add_admissionbuilder_handler.go +++ /dev/null @@ -1,85 +0,0 @@ -/* -Copyright 2018 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" - "strings" - - "sigs.k8s.io/kubebuilder/pkg/model/file" -) - -var _ file.Template = &AddAdmissionWebhookBuilderHandler{} - -// AddAdmissionWebhookBuilderHandler scaffolds adds a new admission webhook builder. -type AddAdmissionWebhookBuilderHandler struct { - file.TemplateMixin - file.RepositoryMixin - file.BoilerplateMixin - file.ResourceMixin - - Config -} - -// SetTemplateDefaults implements input.Template -func (f *AddAdmissionWebhookBuilderHandler) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("pkg", "webhook", f.Server+"_server", "add_"+f.Type+"_%[kind].go") - } - f.Path = f.Resource.Replacer().Replace(f.Path) - - f.TemplateBody = addAdmissionWebhookBuilderHandlerTemplate - - f.Server = strings.ToLower(f.Server) - - return nil -} - -const addAdmissionWebhookBuilderHandlerTemplate = `{{ .Boilerplate }} - -package {{ .Server }}server - -import ( - "fmt" - "{{ .Repo }}/pkg/webhook/{{ .Server }}_server/{{ lower .Resource.Kind }}/{{ .Type }}" -) - -func init() { - for k, v := range {{ .Type }}.Builders { - _, found := builderMap[k] - if found { - log.V(1).Info(fmt.Sprintf( - "conflicting webhook builder names in builder map: %v", k)) - } - builderMap[k] = v - } - for k, v := range {{ .Type }}.HandlerMap { - _, found := HandlerMap[k] - if found { - log.V(1).Info(fmt.Sprintf( - "conflicting webhook builder names in handler map: %v", k)) - } - _, found = builderMap[k] - if !found { - log.V(1).Info(fmt.Sprintf( - "can't find webhook builder name %q in builder map", k)) - continue - } - HandlerMap[k] = v - } -} -` diff --git a/pkg/scaffold/internal/templates/v1/webhook/add_server.go b/pkg/scaffold/internal/templates/v1/webhook/add_server.go deleted file mode 100644 index bef83fd313a..00000000000 --- a/pkg/scaffold/internal/templates/v1/webhook/add_server.go +++ /dev/null @@ -1,59 +0,0 @@ -/* -Copyright 2018 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/pkg/model/file" -) - -var _ file.Template = &AddServer{} - -// AddServer scaffolds adds a new webhook server. -type AddServer struct { - file.TemplateMixin - file.RepositoryMixin - file.BoilerplateMixin - - Config -} - -// SetTemplateDefaults implements input.Template -func (f *AddServer) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("pkg", "webhook", "add_"+f.Server+"_server.go") - } - - f.TemplateBody = addServerTemplate - - return nil -} - -const addServerTemplate = `{{ .Boilerplate }} - -package webhook - -import ( - server "{{ .Repo }}/pkg/webhook/{{ .Server }}_server" -) - -func init() { - // AddToManagerFuncs is a list of functions to create webhook servers and add them to a manager. - AddToManagerFuncs = append(AddToManagerFuncs, server.Add) -} -` diff --git a/pkg/scaffold/internal/templates/v1/webhook/admissionbuilder.go b/pkg/scaffold/internal/templates/v1/webhook/admissionbuilder.go deleted file mode 100644 index 57aea0b3363..00000000000 --- a/pkg/scaffold/internal/templates/v1/webhook/admissionbuilder.go +++ /dev/null @@ -1,94 +0,0 @@ -/* -Copyright 2018 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" - "strings" - - "sigs.k8s.io/kubebuilder/pkg/model/file" -) - -var _ file.Template = &AdmissionWebhookBuilder{} - -// AdmissionWebhookBuilder scaffolds adds a new webhook server. -type AdmissionWebhookBuilder struct { - file.TemplateMixin - file.DomainMixin - file.BoilerplateMixin - file.ResourceMixin - - Config - - BuilderName string - - OperationsParameterString string - - Mutating bool -} - -// SetTemplateDefaults implements input.Template -func (f *AdmissionWebhookBuilder) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("pkg", "webhook", f.Server+"_server", "%[kind]", f.Type, - strings.Join(f.Operations, "_")+"_webhook.go") - } - f.Path = f.Resource.Replacer().Replace(f.Path) - - f.TemplateBody = admissionWebhookBuilderTemplate - - f.Type = strings.ToLower(f.Type) - - if f.Type == "mutating" { - f.Mutating = true - } - - f.BuilderName = builderName(f.Config, strings.ToLower(f.Resource.Kind)) - - ops := make([]string, len(f.Operations)) - for i, op := range f.Operations { - ops[i] = "admissionregistrationv1beta1." + strings.Title(op) - } - f.OperationsParameterString = strings.Join(ops, ", ") - - return nil -} - -const admissionWebhookBuilderTemplate = `{{ .Boilerplate }} - -package {{ .Type }} - -import ( - admissionregistrationv1beta1 "k8s.io/api/admissionregistration/v1beta1" - "sigs.k8s.io/controller-runtime/pkg/webhook/admission/builder" - {{ .Resource.ImportAlias }} "{{ .Resource.Package }}" -) - -func init() { - builderName := "{{ .BuilderName }}" - Builders[builderName] = builder. - NewWebhookBuilder(). - Name(builderName + ".{{ .Domain }}"). - Path("/" + builderName). -{{ if .Mutating }} Mutating(). -{{ else }} Validating(). -{{ end }} - Operations({{ .OperationsParameterString }}). - FailurePolicy(admissionregistrationv1beta1.Fail). - ForType(&{{ .Resource.ImportAlias }}.{{ .Resource.Kind }}{}) -} -` diff --git a/pkg/scaffold/internal/templates/v1/webhook/admissionhandler.go b/pkg/scaffold/internal/templates/v1/webhook/admissionhandler.go deleted file mode 100644 index 45053665993..00000000000 --- a/pkg/scaffold/internal/templates/v1/webhook/admissionhandler.go +++ /dev/null @@ -1,165 +0,0 @@ -/* -Copyright 2018 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" - "strings" - - "sigs.k8s.io/kubebuilder/pkg/model/file" -) - -var _ file.Template = &AddAdmissionWebhookBuilderHandler{} - -// AdmissionHandler scaffolds an admission handler -type AdmissionHandler struct { - file.TemplateMixin - file.BoilerplateMixin - file.ResourceMixin - - Config - - BuilderName string - - OperationsString string - - Mutate bool -} - -// SetTemplateDefaults implements input.Template -func (f *AdmissionHandler) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("pkg", "webhook", f.Server+"_server", "%[kind]", f.Type, - "%[kind]_"+strings.Join(f.Operations, "_")+"_handler.go") - } - f.Path = f.Resource.Replacer().Replace(f.Path) - - f.TemplateBody = addAdmissionHandlerTemplate - - f.Type = strings.ToLower(f.Type) - - if f.Type == "mutating" { - f.Mutate = true - } - - f.BuilderName = builderName(f.Config, strings.ToLower(f.Resource.Kind)) - - ops := make([]string, len(f.Operations)) - for i, op := range f.Operations { - ops[i] = strings.Title(op) - } - f.OperationsString = strings.Join(ops, "") - - return nil -} - -//nolint:lll -const addAdmissionHandlerTemplate = `{{ .Boilerplate }} - -package {{ .Type }} - -import ( - "context" - "net/http" - - "sigs.k8s.io/controller-runtime/pkg/runtime/inject" - "sigs.k8s.io/controller-runtime/pkg/webhook/admission" - "sigs.k8s.io/controller-runtime/pkg/webhook/admission/types" - {{ .Resource.ImportAlias }} "{{ .Resource.Package }}" -) - -func init() { - webhookName := "{{ .BuilderName }}" - if HandlerMap[webhookName] == nil { - HandlerMap[webhookName] = []admission.Handler{} - } - HandlerMap[webhookName] = append(HandlerMap[webhookName], &{{ .Resource.Kind }}{{ .OperationsString }}Handler{}) -} - -// {{ .Resource.Kind }}{{ .OperationsString }}Handler handles {{ .Resource.Kind }} -type {{ .Resource.Kind }}{{ .OperationsString }}Handler struct { - // To use the client, you need to do the following: - // - uncomment it - // - import sigs.k8s.io/controller-runtime/pkg/client - // - uncomment the InjectClient method at the bottom of this file. - // Client client.Client - - // Decoder decodes objects - Decoder types.Decoder -} -{{ if .Mutate }} -func (h *{{ .Resource.Kind }}{{ .OperationsString }}Handler) {{ .Type }}{{ .Resource.Kind }}Fn(ctx context.Context, obj *{{ .Resource.ImportAlias }}.{{ .Resource.Kind }}) error { - // TODO(user): implement your admission logic - return nil -} -{{ else }} -func (h *{{ .Resource.Kind }}{{ .OperationsString }}Handler) {{ .Type }}{{ .Resource.Kind }}Fn(ctx context.Context, obj *{{ .Resource.ImportAlias }}.{{ .Resource.Kind }}) (bool, string, error) { - // TODO(user): implement your admission logic - return true, "allowed to be admitted", nil -} -{{ end }} -var _ admission.Handler = &{{ .Resource.Kind }}{{ .OperationsString }}Handler{} -{{ if .Mutate }} -// Handle handles admission requests. -func (h *{{ .Resource.Kind }}{{ .OperationsString }}Handler) Handle(ctx context.Context, req types.Request) types.Response { - obj := &{{ .Resource.ImportAlias }}.{{ .Resource.Kind }}{} - - err := h.Decoder.Decode(req, obj) - if err != nil { - return admission.ErrorResponse(http.StatusBadRequest, err) - } - copy := obj.DeepCopy() - - err = h.{{ .Type }}{{ .Resource.Kind }}Fn(ctx, copy) - if err != nil { - return admission.ErrorResponse(http.StatusInternalServerError, err) - } - return admission.PatchResponse(obj, copy) -} -{{ else }} -// Handle handles admission requests. -func (h *{{ .Resource.Kind }}{{ .OperationsString }}Handler) Handle(ctx context.Context, req types.Request) types.Response { - obj := &{{ .Resource.ImportAlias }}.{{ .Resource.Kind }}{} - - err := h.Decoder.Decode(req, obj) - if err != nil { - return admission.ErrorResponse(http.StatusBadRequest, err) - } - - allowed, reason, err := h.{{ .Type }}{{ .Resource.Kind }}Fn(ctx, obj) - if err != nil { - return admission.ErrorResponse(http.StatusInternalServerError, err) - } - return admission.ValidationResponse(allowed, reason) -} -{{ end }} -//var _ inject.Client = &{{ .Resource.Kind }}{{ .OperationsString }}Handler{} -// -//// InjectClient injects the client into the {{ .Resource.Kind }}{{ .OperationsString }}Handler -//func (h *{{ .Resource.Kind }}{{ .OperationsString }}Handler) InjectClient(c client.Client) error { -// h.Client = c -// return nil -//} - -var _ inject.Decoder = &{{ .Resource.Kind }}{{ .OperationsString }}Handler{} - -// InjectDecoder injects the decoder into the {{ .Resource.Kind }}{{ .OperationsString }}Handler -func (h *{{ .Resource.Kind }}{{ .OperationsString }}Handler) InjectDecoder(d types.Decoder) error { - h.Decoder = d - return nil -} -` diff --git a/pkg/scaffold/internal/templates/v1/webhook/admissionwebhooks.go b/pkg/scaffold/internal/templates/v1/webhook/admissionwebhooks.go deleted file mode 100644 index 1cc85e90a04..00000000000 --- a/pkg/scaffold/internal/templates/v1/webhook/admissionwebhooks.go +++ /dev/null @@ -1,68 +0,0 @@ -/* -Copyright 2018 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" - "strings" - - "sigs.k8s.io/kubebuilder/pkg/model/file" -) - -var _ file.Template = &AdmissionWebhooks{} - -// AdmissionWebhooks scaffolds how to construct a webhook server and register webhooks. -type AdmissionWebhooks struct { - file.TemplateMixin - file.BoilerplateMixin - file.ResourceMixin - - Config -} - -// SetTemplateDefaults implements input.Template -func (f *AdmissionWebhooks) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("pkg", "webhook", f.Server+"_server", "%[kind]", f.Type, "webhooks.go") - } - f.Path = f.Resource.Replacer().Replace(f.Path) - - f.TemplateBody = webhooksTemplate - - f.Server = strings.ToLower(f.Server) - - f.Type = strings.ToLower(f.Type) - - return nil -} - -const webhooksTemplate = `{{ .Boilerplate }} - -package {{ .Type }} - -import ( - "sigs.k8s.io/controller-runtime/pkg/webhook/admission" - "sigs.k8s.io/controller-runtime/pkg/webhook/admission/builder" -) - -var ( - // Builders contain admission webhook builders - Builders = map[string]*builder.WebhookBuilder{} - // HandlerMap contains admission webhook handlers - HandlerMap = map[string][]admission.Handler{} -) -` diff --git a/pkg/scaffold/internal/templates/v1/webhook/config.go b/pkg/scaffold/internal/templates/v1/webhook/config.go deleted file mode 100644 index dd48bf5682b..00000000000 --- a/pkg/scaffold/internal/templates/v1/webhook/config.go +++ /dev/null @@ -1,27 +0,0 @@ -/* -Copyright 2018 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 - -// Config contains the information required to scaffold files for a webhook. -type Config struct { - // Server is the name of the server. - Server string - // Type is the type of the webhook. - Type string - // Operations that the webhook will intercept, e.g. create, update, delete, connect - Operations []string -} diff --git a/pkg/scaffold/internal/templates/v1/webhook/server.go b/pkg/scaffold/internal/templates/v1/webhook/server.go deleted file mode 100644 index 884486a5a8a..00000000000 --- a/pkg/scaffold/internal/templates/v1/webhook/server.go +++ /dev/null @@ -1,122 +0,0 @@ -/* -Copyright 2018 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/pkg/model/file" -) - -var _ file.Template = &Server{} - -// Server scaffolds how to construct a webhook server and register webhooks. -type Server struct { - file.TemplateMixin - file.BoilerplateMixin - - Config -} - -// SetTemplateDefaults implements input.Template -func (f *Server) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = filepath.Join("pkg", "webhook", f.Server+"_server", "server.go") - } - - f.TemplateBody = serverTemplate - - return nil -} - -const serverTemplate = `{{ .Boilerplate }} - -package {{ .Server }}server - -import ( - "fmt" - "os" - "k8s.io/apimachinery/pkg/types" - "sigs.k8s.io/controller-runtime/pkg/manager" - logf "sigs.k8s.io/controller-runtime/pkg/runtime/log" - "sigs.k8s.io/controller-runtime/pkg/webhook" - "sigs.k8s.io/controller-runtime/pkg/webhook/admission" - "sigs.k8s.io/controller-runtime/pkg/webhook/admission/builder" -) - -var ( - log = logf.Log.WithName("{{ .Server }}_server") - builderMap = map[string]*builder.WebhookBuilder{} - // HandlerMap contains all admission webhook handlers. - HandlerMap = map[string][]admission.Handler{} -) - -// Add adds itself to the manager -func Add(mgr manager.Manager) error { - ns := os.Getenv("POD_NAMESPACE") - if len(ns) == 0 { - ns = "default" - } - secretName := os.Getenv("SECRET_NAME") - if len(secretName) == 0 { - secretName = "webhook-server-secret" - } - - svr, err := webhook.NewServer("foo-admission-server", mgr, webhook.ServerOptions{ - // TODO(user): change the configuration of ServerOptions based on your need. - Port: 9876, - CertDir: "/tmp/cert", - BootstrapOptions: &webhook.BootstrapOptions{ - Secret: &types.NamespacedName{ - Namespace: ns, - Name: secretName, - }, - - Service: &webhook.Service{ - Namespace: ns, - Name: "webhook-server-service", - // Selectors should select the pods that runs this webhook server. - Selectors: map[string]string{ - "control-plane": "controller-manager", - }, - }, - }, - }) - if err != nil { - return err - } - - var webhooks []webhook.Webhook - for k, builder := range builderMap { - handlers, ok := HandlerMap[k] - if !ok { - log.V(1).Info(fmt.Sprintf("can't find handlers for builder: %v", k)) - handlers = []admission.Handler{} - } - wh, err := builder. - Handlers(handlers...). - WithManager(mgr). - Build() - if err != nil { - return err - } - webhooks = append(webhooks, wh) - } - - return svr.Register(webhooks...) -} -` diff --git a/pkg/scaffold/internal/templates/v1/webhook/util.go b/pkg/scaffold/internal/templates/v1/webhook/util.go deleted file mode 100644 index e13b3e45362..00000000000 --- a/pkg/scaffold/internal/templates/v1/webhook/util.go +++ /dev/null @@ -1,26 +0,0 @@ -/* -Copyright 2018 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 ( - "fmt" - "strings" -) - -func builderName(config Config, resource string) string { - return fmt.Sprintf("%s-%s-%s", config.Type, strings.Join(config.Operations, "-"), resource) -} diff --git a/pkg/scaffold/internal/templates/v2/authproxyrolebinding.go b/pkg/scaffold/internal/templates/v2/authproxyrolebinding.go deleted file mode 100644 index 163e4c386b2..00000000000 --- a/pkg/scaffold/internal/templates/v2/authproxyrolebinding.go +++ /dev/null @@ -1,55 +0,0 @@ -/* -Copyright 2018 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 v2 - -import ( - "path/filepath" - - "sigs.k8s.io/kubebuilder/pkg/model/file" -) - -var _ file.Template = &AuthProxyRoleBinding{} - -// AuthProxyRoleBinding scaffolds the config/rbac/auth_proxy_role_binding_rbac.yaml file -type AuthProxyRoleBinding struct { - file.TemplateMixin -} - -// SetTemplateDefaults implements input.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: - name: proxy-rolebinding -roleRef: - apiGroup: rbac.authorization.k8s.io - kind: ClusterRole - name: proxy-role -subjects: -- kind: ServiceAccount - name: default - namespace: system -` diff --git a/pkg/scaffold/internal/templates/v2/gitignore.go b/pkg/scaffold/internal/templates/v2/gitignore.go deleted file mode 100644 index d8da014db02..00000000000 --- a/pkg/scaffold/internal/templates/v2/gitignore.go +++ /dev/null @@ -1,65 +0,0 @@ -/* -Copyright 2018 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 v2 - -import ( - "sigs.k8s.io/kubebuilder/pkg/model/file" -) - -var _ file.Template = &GitIgnore{} - -// GitIgnore scaffolds the .gitignore file -type GitIgnore struct { - file.TemplateMixin -} - -// SetTemplateDefaults implements input.Template -func (f *GitIgnore) SetTemplateDefaults() error { - if f.Path == "" { - f.Path = ".gitignore" - } - - f.TemplateBody = gitignoreTemplate - - return nil -} - -const gitignoreTemplate = ` -# Binaries for programs and plugins -*.exe -*.exe~ -*.dll -*.so -*.dylib -bin - -# Test binary, build with ` + "`go test -c`" + ` -*.test - -# Output of the go coverage tool, specifically when used with LiteIDE -*.out - -# Kubernetes Generated files - skip generated files, except for vendored files - -!vendor/**/zz_generated.* - -# editor and IDE paraphernalia -.idea -*.swp -*.swo -*~ -` diff --git a/pkg/scaffold/internal/templates/v2/webhook/enablecainection_patch.go b/pkg/scaffold/internal/templates/webhook/enablecainection_patch.go similarity index 100% rename from pkg/scaffold/internal/templates/v2/webhook/enablecainection_patch.go rename to pkg/scaffold/internal/templates/webhook/enablecainection_patch.go diff --git a/pkg/scaffold/internal/templates/v2/webhook/kustomization.go b/pkg/scaffold/internal/templates/webhook/kustomization.go similarity index 100% rename from pkg/scaffold/internal/templates/v2/webhook/kustomization.go rename to pkg/scaffold/internal/templates/webhook/kustomization.go diff --git a/pkg/scaffold/internal/templates/v2/webhook/kustomizeconfig.go b/pkg/scaffold/internal/templates/webhook/kustomizeconfig.go similarity index 100% rename from pkg/scaffold/internal/templates/v2/webhook/kustomizeconfig.go rename to pkg/scaffold/internal/templates/webhook/kustomizeconfig.go diff --git a/pkg/scaffold/internal/templates/v2/webhook/service.go b/pkg/scaffold/internal/templates/webhook/service.go similarity index 100% rename from pkg/scaffold/internal/templates/v2/webhook/service.go rename to pkg/scaffold/internal/templates/webhook/service.go diff --git a/pkg/scaffold/internal/templates/v2/webhook/webhook.go b/pkg/scaffold/internal/templates/webhook/webhook.go similarity index 100% rename from pkg/scaffold/internal/templates/v2/webhook/webhook.go rename to pkg/scaffold/internal/templates/webhook/webhook.go diff --git a/pkg/scaffold/internal/templates/v2/webhook_manager_patch.go b/pkg/scaffold/internal/templates/webhook_manager_patch.go similarity index 98% rename from pkg/scaffold/internal/templates/v2/webhook_manager_patch.go rename to pkg/scaffold/internal/templates/webhook_manager_patch.go index 49930f567a1..ba6734ce940 100644 --- a/pkg/scaffold/internal/templates/v2/webhook_manager_patch.go +++ b/pkg/scaffold/internal/templates/webhook_manager_patch.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v2 +package templates import ( "path/filepath" diff --git a/pkg/scaffold/update.go b/pkg/scaffold/update.go index 309858d544b..db275d11cc0 100644 --- a/pkg/scaffold/update.go +++ b/pkg/scaffold/update.go @@ -20,7 +20,7 @@ import ( "sigs.k8s.io/kubebuilder/pkg/model" "sigs.k8s.io/kubebuilder/pkg/model/config" "sigs.k8s.io/kubebuilder/pkg/scaffold/internal/machinery" - templatesv1 "sigs.k8s.io/kubebuilder/pkg/scaffold/internal/templates/v1" + "sigs.k8s.io/kubebuilder/pkg/scaffold/internal/templates" ) var _ Scaffolder = &updateScaffolder{} @@ -43,6 +43,6 @@ func (s *updateScaffolder) Scaffold() error { model.WithConfig(s.config), model.WithoutBoilerplate, ), - &templatesv1.GopkgToml{}, + &templates.GopkgToml{}, ) } diff --git a/pkg/scaffold/webhook.go b/pkg/scaffold/webhook.go index e928755c94a..b37167f7197 100644 --- a/pkg/scaffold/webhook.go +++ b/pkg/scaffold/webhook.go @@ -23,10 +23,8 @@ import ( "sigs.k8s.io/kubebuilder/pkg/model/config" "sigs.k8s.io/kubebuilder/pkg/model/resource" "sigs.k8s.io/kubebuilder/pkg/scaffold/internal/machinery" - managerv1 "sigs.k8s.io/kubebuilder/pkg/scaffold/internal/templates/v1/manager" - webhookv1 "sigs.k8s.io/kubebuilder/pkg/scaffold/internal/templates/v1/webhook" - templatesv2 "sigs.k8s.io/kubebuilder/pkg/scaffold/internal/templates/v2" - webhookv2 "sigs.k8s.io/kubebuilder/pkg/scaffold/internal/templates/v2/webhook" + "sigs.k8s.io/kubebuilder/pkg/scaffold/internal/templates" + "sigs.k8s.io/kubebuilder/pkg/scaffold/internal/templates/webhook" ) var _ Scaffolder = &webhookScaffolder{} @@ -35,35 +33,13 @@ type webhookScaffolder struct { config *config.Config boilerplate string resource *resource.Resource - // v1 - server string - webhookType string - operations []string + // v2 defaulting, validation, conversion bool } -// NewV1WebhookScaffolder returns a new Scaffolder for v1 webhook creation operations -func NewV1WebhookScaffolder( - config *config.Config, - boilerplate string, - resource *resource.Resource, - server string, - webhookType string, - operations []string, -) Scaffolder { - return &webhookScaffolder{ - config: config, - boilerplate: boilerplate, - resource: resource, - server: server, - webhookType: webhookType, - operations: operations, - } -} - -// NewV2WebhookScaffolder returns a new Scaffolder for v2 webhook creation operations -func NewV2WebhookScaffolder( +// NewWebhookScaffolder returns a new Scaffolder for v2 webhook creation operations +func NewWebhookScaffolder( config *config.Config, boilerplate string, resource *resource.Resource, @@ -86,10 +62,8 @@ func (s *webhookScaffolder) Scaffold() error { fmt.Println("Writing scaffold for you to edit...") switch { - case s.config.IsV1(): - return s.scaffoldV1() case s.config.IsV2(), s.config.IsV3(): - return s.scaffoldV2() + return s.scaffold() default: return fmt.Errorf("unknown project version %v", s.config.Version) } @@ -103,22 +77,7 @@ func (s *webhookScaffolder) newUniverse() *model.Universe { ) } -func (s *webhookScaffolder) scaffoldV1() error { - webhookConfig := webhookv1.Config{Server: s.server, Type: s.webhookType, Operations: s.operations} - - return machinery.NewScaffold().Execute( - s.newUniverse(), - &managerv1.Webhook{}, - &webhookv1.AdmissionHandler{Config: webhookConfig}, - &webhookv1.AdmissionWebhookBuilder{Config: webhookConfig}, - &webhookv1.AdmissionWebhooks{Config: webhookConfig}, - &webhookv1.AddAdmissionWebhookBuilderHandler{Config: webhookConfig}, - &webhookv1.Server{Config: webhookConfig}, - &webhookv1.AddServer{Config: webhookConfig}, - ) -} - -func (s *webhookScaffolder) scaffoldV2() error { +func (s *webhookScaffolder) scaffold() error { if s.conversion { fmt.Println(`Webhook server has been set up for you. You need to implement the conversion.Hub and conversion.Convertible interfaces for your CRD types.`) @@ -126,8 +85,8 @@ You need to implement the conversion.Hub and conversion.Convertible interfaces f if err := machinery.NewScaffold().Execute( s.newUniverse(), - &webhookv2.Webhook{Defaulting: s.defaulting, Validating: s.validation}, - &templatesv2.MainUpdater{WireWebhook: true}, + &webhook.Webhook{Defaulting: s.defaulting, Validating: s.validation}, + &templates.MainUpdater{WireWebhook: true}, ); err != nil { return err } diff --git a/scripts/generate_dep_manifest.sh b/scripts/generate_dep_manifest.sh deleted file mode 100755 index 46c47a68d43..00000000000 --- a/scripts/generate_dep_manifest.sh +++ /dev/null @@ -1,61 +0,0 @@ -#!/bin/bash - -# 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. - -# -# Script to generate Gopkg.toml file with override stanzas -# Script assumes you have run 'dep ensure' on the project and it is -# in compilable state. -# -# Notes about generating override stanza: -# Create a project using Kubebuilder -# Remove all the override stanzas except the k8s one. -# Run 'dep ensure' to update the dependencies and then -# run this script. -# Save the output of the script and copy its content to replace the value -# depManifestOverride variable in cmd/kubebuilder/initproject/dep_manifest.go -# - -######################################################################################################## -# NOTE: It is deprecated since is valid just for version 1 # -######################################################################################################## - -tmp_file="/tmp/dep.txt" -dep status -json|jq '.[]|.ProjectRoot,.Revision, .Version' > $tmp_file -while read name ; do - read revision; read version; - # strip quotes - myver=$(echo "$version" | tr -d '"') - myname=$(echo "$name"|tr -d '"') - if [ "$myname" = "sigs.k8s.io/kubebuilder" ]; then - continue - fi - if [ "$myver" = "branch master" ] || [ -z "$myver" ]; then - printf "\n[[override]]\nname=$name\nrevision=$revision\n" ; - else - printf "\n[[override]]\nname=$name\nversion=$version\n" ; - fi -done < $tmp_file - -cat << EOF - -[[override]] -name = "sigs.k8s.io/kubebuilder" -{{ if eq .Version "unknown" -}} -branch = "master" -{{ else -}} -version = "{{.Version}}" -{{ end }} -EOF diff --git a/test.sh b/test.sh index bdfa464504e..aa4a0f9997c 100755 --- a/test.sh +++ b/test.sh @@ -22,12 +22,9 @@ source common.sh export TRACE=1 export GO111MODULE=on -# This test is used by prow and if the dep not be installed by git then it will face the GOBIN issue. -install_dep_by_git - function test_init_project { header_text "performing init project" - kubebuilder init --project-version 1 --domain example.com <<< "n" + kubebuilder init --domain example.com <<< "n" } function test_make_project { @@ -96,19 +93,9 @@ function test_project { project_dir=$1 version=$2 header_text "performing tests in dir $project_dir for project version v$version" - vendor_tarball=$tmp_root/vendor.v$version.tgz - old_gopath=$GOPATH - if [[ $version == "1" ]]; then - export GOPATH=$(pwd)/testdata/gopath - download_vendor_archive - fi cd testdata/$project_dir - # v2 uses modules, and thus doesn't have a vendor directory - [[ -e ${vendor_tarball} ]] && tar -zxf $vendor_tarball - make all test # v2 doesn't test on all by default - [[ -e ${vendor_tarball} ]] && rm -rf ./vendor && rm -f Gopkg.lock + make all test cd - - export GOPATH=$old_gopath } prepare_staging_dir @@ -117,7 +104,6 @@ build_kb setup_envs -export GO111MODULE=off prepare_testdir_under_gopath test_init_project cache_project @@ -156,11 +142,6 @@ cd ${go_workspace}/src/sigs.k8s.io/kubebuilder export GO111MODULE=on go test ./cmd/... ./pkg/... -# test project v1 -# auto is roughly equivalent to off in our case, -# since we'll be in a gopath (basically, reset to default) -GO111MODULE=off test_project gopath/src/project 1 - # test project v2 GO111MODULE=on test_project project-v2 2 GO111MODULE=on test_project project-v2-multigroup 2 diff --git a/test/e2e/v1/e2e_suite.go b/test/e2e/v1/e2e_suite.go deleted file mode 100644 index 27a62b30584..00000000000 --- a/test/e2e/v1/e2e_suite.go +++ /dev/null @@ -1,166 +0,0 @@ -/* -Copyright 2019 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/exec" - "path/filepath" - "strings" - "time" - - . "github.com/onsi/ginkgo" //nolint:golint - . "github.com/onsi/gomega" //nolint:golint - - "sigs.k8s.io/kubebuilder/test/e2e/utils" -) - -var _ = Describe("kubebuilder", func() { - Context("with v1 scaffolding", func() { - var kbc *utils.KBTestContext - BeforeEach(func() { - var err error - kbc, err = utils.TestContext("GO111MODULE=off") - Expect(err).NotTo(HaveOccurred()) - Expect(kbc.Prepare()).To(Succeed()) - }) - - AfterEach(func() { - By("clean up created API objects during test process") - kbc.CleanupManifests(filepath.Join("config", "default")) - if _, err := kbc.Kubectl.Command( - "delete", "--recursive", - "-f", filepath.Join("config", "crds"), - ); err != nil { - fmt.Fprintf(GinkgoWriter, "error when running kubectl delete during cleaning up crd: %v\n", err) - } - - By("remove container image and work dir") - kbc.Destroy() - }) - - It("should generate a runnable project", func() { - // prepare v1 vendor - By("downloading the vendor tarball") - cmd := exec.Command("wget", - "https://storage.googleapis.com/kubebuilder-vendor/vendor.v1.tgz", - "-O", "/tmp/vendor.v1.tgz") - _, err := kbc.Run(cmd) - Expect(err).Should(Succeed()) - - By("untar the vendor tarball") - cmd = exec.Command("tar", "-zxf", "/tmp/vendor.v1.tgz") - _, err = kbc.Run(cmd) - Expect(err).Should(Succeed()) - - var controllerPodName string - - By("init v1 project") - err = kbc.Init( - "--project-version", "1", - "--domain", kbc.Domain, - "--dep=false") - Expect(err).Should(Succeed()) - - By("creating api definition") - err = kbc.CreateAPI( - "--group", kbc.Group, - "--version", kbc.Version, - "--kind", kbc.Kind, - "--namespaced", - "--resource", - "--controller", - "--make=false") - Expect(err).Should(Succeed()) - - By("creating core-type resource controller") - err = kbc.CreateAPI( - "--group", "apps", - "--version", "v1", - "--kind", "Deployment", - "--namespaced", - "--resource=false", - "--controller", - "--make=false") - Expect(err).Should(Succeed()) - - By("building image") - err = kbc.Make("docker-build", "IMG="+kbc.ImageName) - Expect(err).Should(Succeed()) - - By("loading docker image into kind cluster") - err = kbc.LoadImageToKindCluster() - Expect(err).Should(Succeed()) - - // NOTE: If you want to run the test against a GKE cluster, you will need to grant yourself permission. - // Otherwise, you may see "... is forbidden: attempt to grant extra privileges" - // $ kubectl create clusterrolebinding myname-cluster-admin-binding \ - // --clusterrole=cluster-admin --user=myname@mycompany.com - // https://cloud.google.com/kubernetes-engine/docs/how-to/role-based-access-control - By("deploying controller manager") - err = kbc.Make("deploy") - Expect(err).Should(Succeed()) - - By("validate the controller-manager pod running as expected") - verifyControllerUp := func() error { - // Get pod name - podOutput, err := kbc.Kubectl.Get( - true, - "pods", "-l", "control-plane=controller-manager", - "-o", "go-template={{ range .items }}{{ if not .metadata.deletionTimestamp }}{{ .metadata.name }}"+ - "{{ \"\\n\" }}{{ end }}{{ end }}", - ) - Expect(err).NotTo(HaveOccurred()) - podNames := utils.GetNonEmptyLines(podOutput) - if len(podNames) != 1 { - return fmt.Errorf("expect 1 controller pods running, but got %d", len(podNames)) - } - controllerPodName = podNames[0] - Expect(controllerPodName).Should(ContainSubstring("controller-manager")) - - // Validate pod status - status, err := kbc.Kubectl.Get( - true, - "pods", controllerPodName, "-o", "jsonpath={.status.phase}", - ) - Expect(err).NotTo(HaveOccurred()) - if status != "Running" { - return fmt.Errorf("controller pod in %s status", status) - } - - return nil - } - Eventually(verifyControllerUp, 2*time.Minute, time.Second).Should(Succeed()) - - By("creating an instance of CR") - inputFile := filepath.Join("config", "samples", - fmt.Sprintf("%s_%s_%s.yaml", kbc.Group, kbc.Version, strings.ToLower(kbc.Kind))) - _, err = kbc.Kubectl.Apply(false, "-f", inputFile) - Expect(err).NotTo(HaveOccurred()) - - By("validate the created resource object gets reconciled in controller") - controllerContainerLogs := func() string { - // Check container log to validate that the created resource object gets reconciled in controller - logOutput, err := kbc.Kubectl.Logs(controllerPodName, "-c", "manager") - Expect(err).NotTo(HaveOccurred()) - - return logOutput - } - Eventually(controllerContainerLogs, 2*time.Minute, time.Second).Should(ContainSubstring("Updating")) - }) - }) -}) diff --git a/test/e2e/v1/e2e_test.go b/test/e2e/v1/e2e_test.go deleted file mode 100644 index 646335063f1..00000000000 --- a/test/e2e/v1/e2e_test.go +++ /dev/null @@ -1,32 +0,0 @@ -/* -Copyright 2018 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" - "testing" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -// Run e2e tests using the Ginkgo runner. -func TestE2E(t *testing.T) { - RegisterFailHandler(Fail) - fmt.Fprintf(GinkgoWriter, "Starting kubebuilder suite\n") - RunSpecs(t, "Kubebuilder e2e suite") -} diff --git a/test/e2e/v3/e2e_suite.go b/test/e2e/v3/e2e_suite.go index 3505849812e..edd2836b27f 100644 --- a/test/e2e/v3/e2e_suite.go +++ b/test/e2e/v3/e2e_suite.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v2 +package v3 import ( "encoding/base64" diff --git a/test/e2e/v3/e2e_test.go b/test/e2e/v3/e2e_test.go index d82f46b8540..93e56624a95 100644 --- a/test/e2e/v3/e2e_test.go +++ b/test/e2e/v3/e2e_test.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v2 +package v3 import ( "fmt" diff --git a/test_e2e.sh b/test_e2e.sh index 2ec6004493f..f7fe1804a2c 100755 --- a/test_e2e.sh +++ b/test_e2e.sh @@ -23,8 +23,6 @@ export TRACE=1 export GO111MODULE=on fetch_tools -# This test is used by prow and if the dep not be installed by git then it will face the GOBIN issue. -install_dep_by_git install_kind build_kb @@ -40,8 +38,5 @@ function cleanup() { } trap cleanup EXIT - -# The v1 is deprecated -go test ./test/e2e/v1 go test ./test/e2e/v2 go test ./test/e2e/v3 diff --git a/testdata/gopath/src/project/.gitignore b/testdata/gopath/src/project/.gitignore deleted file mode 100644 index d97ffc5159b..00000000000 --- a/testdata/gopath/src/project/.gitignore +++ /dev/null @@ -1,24 +0,0 @@ - -# Binaries for programs and plugins -*.exe -*.exe~ -*.dll -*.so -*.dylib -bin - -# Test binary, build with `go test -c` -*.test - -# Output of the go coverage tool, specifically when used with LiteIDE -*.out - -# Kubernetes Generated files - skip generated files, except for vendored files - -!vendor/**/zz_generated.* - -# editor and IDE paraphernalia -.idea -*.swp -*.swo -*~ diff --git a/testdata/gopath/src/project/Dockerfile b/testdata/gopath/src/project/Dockerfile deleted file mode 100644 index 62d28876d1d..00000000000 --- a/testdata/gopath/src/project/Dockerfile +++ /dev/null @@ -1,17 +0,0 @@ -# Build the manager binary -FROM golang:1.10.3 as builder - -# Copy in the go src -WORKDIR /go/src/project -COPY cmd/ cmd/ -COPY vendor/ vendor/ -COPY pkg/ pkg/ - -# Build -RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -a -o manager project/cmd/manager - -# Copy the controller-manager into a thin image -FROM ubuntu:latest -WORKDIR / -COPY --from=builder /go/src/project/manager . -ENTRYPOINT ["/manager"] diff --git a/testdata/gopath/src/project/Gopkg.toml b/testdata/gopath/src/project/Gopkg.toml deleted file mode 100644 index 8ee09333625..00000000000 --- a/testdata/gopath/src/project/Gopkg.toml +++ /dev/null @@ -1,37 +0,0 @@ -required = [ - "github.com/emicklei/go-restful", - "github.com/onsi/ginkgo", # for test framework - "github.com/onsi/gomega", # for test matchers - "k8s.io/client-go/plugin/pkg/client/auth/gcp", # for development against gcp - "k8s.io/code-generator/cmd/client-gen", # for go generate - "k8s.io/code-generator/cmd/deepcopy-gen", # for go generate - "sigs.k8s.io/controller-tools/cmd/controller-gen", # for crd/rbac generation - "sigs.k8s.io/controller-runtime/pkg/client/config", - "sigs.k8s.io/controller-runtime/pkg/controller", - "sigs.k8s.io/controller-runtime/pkg/handler", - "sigs.k8s.io/controller-runtime/pkg/manager", - "sigs.k8s.io/controller-runtime/pkg/runtime/signals", - "sigs.k8s.io/controller-runtime/pkg/source", - "sigs.k8s.io/testing_frameworks/integration", # for integration testing - "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1", - ] - -[prune] - go-tests = true - - -# STANZAS BELOW ARE GENERATED AND MAY BE WRITTEN - DO NOT MODIFY BELOW THIS LINE. - -[[constraint]] - name="sigs.k8s.io/controller-runtime" - version="v0.1.8" - -[[constraint]] - name="sigs.k8s.io/controller-tools" - version="v0.1.1" - -# For dependency below: Refer to issue https://github.com/golang/dep/issues/1799 -[[override]] -name = "gopkg.in/fsnotify.v1" -source = "https://github.com/fsnotify/fsnotify.git" -version="v1.4.7" diff --git a/testdata/gopath/src/project/Makefile b/testdata/gopath/src/project/Makefile deleted file mode 100644 index d81a7b1cf7c..00000000000 --- a/testdata/gopath/src/project/Makefile +++ /dev/null @@ -1,55 +0,0 @@ - -# Image URL to use all building/pushing image targets -IMG ?= controller:latest - -all: test manager - -# Run tests -test: generate fmt vet manifests - go test ./pkg/... ./cmd/... -coverprofile cover.out - -# Build manager binary -manager: generate fmt vet - go build -o bin/manager project/cmd/manager - -# Run against the configured Kubernetes cluster in ~/.kube/config -run: generate fmt vet - go run ./cmd/manager/main.go - -# Install CRDs into a cluster -install: manifests - kubectl apply -f config/crds - -# Deploy controller in the configured Kubernetes cluster in ~/.kube/config -deploy: manifests - kubectl apply -f config/crds - kustomize build config/default | kubectl apply -f - - -# Generate manifests e.g. CRD, RBAC etc. -manifests: - go run vendor/sigs.k8s.io/controller-tools/cmd/controller-gen/main.go all - -# Run go fmt against code -fmt: - go fmt ./pkg/... ./cmd/... - -# Run go vet against code -vet: - go vet ./pkg/... ./cmd/... - -# Generate code -generate: -ifndef GOPATH - $(error GOPATH not defined, please define GOPATH. Run "go help gopath" to learn more about GOPATH) -endif - go generate ./pkg/... ./cmd/... - -# Build the docker image -docker-build: test - docker build . -t ${IMG} - @echo "updating kustomize image patch file for manager resource" - sed -i'' -e 's@image: .*@image: '"${IMG}"'@' ./config/default/manager_image_patch.yaml - -# Push the docker image -docker-push: - docker push ${IMG} diff --git a/testdata/gopath/src/project/PROJECT b/testdata/gopath/src/project/PROJECT deleted file mode 100644 index 9ee326caba7..00000000000 --- a/testdata/gopath/src/project/PROJECT +++ /dev/null @@ -1,3 +0,0 @@ -domain: testproject.org -repo: project -version: "1" diff --git a/testdata/gopath/src/project/cmd/manager/main.go b/testdata/gopath/src/project/cmd/manager/main.go deleted file mode 100644 index a7a610b25db..00000000000 --- a/testdata/gopath/src/project/cmd/manager/main.go +++ /dev/null @@ -1,85 +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 main - -import ( - "flag" - "os" - - _ "k8s.io/client-go/plugin/pkg/client/auth/gcp" - "sigs.k8s.io/controller-runtime/pkg/client/config" - "sigs.k8s.io/controller-runtime/pkg/manager" - logf "sigs.k8s.io/controller-runtime/pkg/runtime/log" - "sigs.k8s.io/controller-runtime/pkg/runtime/signals" - - "project/pkg/apis" - "project/pkg/controller" - "project/pkg/webhook" -) - -func main() { - var metricsAddr string - flag.StringVar(&metricsAddr, "metrics-addr", ":8080", "The address the metric endpoint binds to.") - flag.Parse() - logf.SetLogger(logf.ZapLogger(false)) - log := logf.Log.WithName("entrypoint") - - // Get a config to talk to the apiserver - log.Info("setting up client for manager") - cfg, err := config.GetConfig() - if err != nil { - log.Error(err, "unable to set up client config") - os.Exit(1) - } - - // Create a new Cmd to provide shared dependencies and start components - log.Info("setting up manager") - mgr, err := manager.New(cfg, manager.Options{MetricsBindAddress: metricsAddr}) - if err != nil { - log.Error(err, "unable to set up overall controller manager") - os.Exit(1) - } - - log.Info("Registering Components.") - - // Setup Scheme for all resources - log.Info("setting up scheme") - if err := apis.AddToScheme(mgr.GetScheme()); err != nil { - log.Error(err, "unable add APIs to scheme") - os.Exit(1) - } - - // Setup all Controllers - log.Info("Setting up controller") - if err := controller.AddToManager(mgr); err != nil { - log.Error(err, "unable to register controllers to the manager") - os.Exit(1) - } - - log.Info("setting up webhooks") - if err := webhook.AddToManager(mgr); err != nil { - log.Error(err, "unable to register webhooks to the manager") - os.Exit(1) - } - - // Start the Cmd - log.Info("Starting the Cmd.") - if err := mgr.Start(signals.SetupSignalHandler()); err != nil { - log.Error(err, "unable to run the manager") - os.Exit(1) - } -} diff --git a/testdata/gopath/src/project/config/crds/creatures_v2alpha1_kraken.yaml b/testdata/gopath/src/project/config/crds/creatures_v2alpha1_kraken.yaml deleted file mode 100644 index ad84aabbcec..00000000000 --- a/testdata/gopath/src/project/config/crds/creatures_v2alpha1_kraken.yaml +++ /dev/null @@ -1,39 +0,0 @@ -apiVersion: apiextensions.k8s.io/v1beta1 -kind: CustomResourceDefinition -metadata: - creationTimestamp: null - labels: - controller-tools.k8s.io: "1.0" - name: krakens.creatures.testproject.org -spec: - group: creatures.testproject.org - names: - kind: Kraken - plural: krakens - scope: Cluster - validation: - openAPIV3Schema: - properties: - apiVersion: - description: 'APIVersion defines the versioned schema of this representation - of an object. Servers should convert recognized schemas to the latest - internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources' - type: string - kind: - description: 'Kind is a string value representing the REST resource this - object represents. Servers may infer this from the endpoint the client - submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds' - type: string - metadata: - type: object - spec: - type: object - status: - type: object - version: v2alpha1 -status: - acceptedNames: - kind: "" - plural: "" - conditions: [] - storedVersions: [] diff --git a/testdata/gopath/src/project/config/crds/crew_v1_firstmate.yaml b/testdata/gopath/src/project/config/crds/crew_v1_firstmate.yaml deleted file mode 100644 index 69ed750c41c..00000000000 --- a/testdata/gopath/src/project/config/crds/crew_v1_firstmate.yaml +++ /dev/null @@ -1,39 +0,0 @@ -apiVersion: apiextensions.k8s.io/v1beta1 -kind: CustomResourceDefinition -metadata: - creationTimestamp: null - labels: - controller-tools.k8s.io: "1.0" - name: firstmates.crew.testproject.org -spec: - group: crew.testproject.org - names: - kind: FirstMate - plural: firstmates - scope: Namespaced - validation: - openAPIV3Schema: - properties: - apiVersion: - description: 'APIVersion defines the versioned schema of this representation - of an object. Servers should convert recognized schemas to the latest - internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources' - type: string - kind: - description: 'Kind is a string value representing the REST resource this - object represents. Servers may infer this from the endpoint the client - submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds' - type: string - metadata: - type: object - spec: - type: object - status: - type: object - version: v1 -status: - acceptedNames: - kind: "" - plural: "" - conditions: [] - storedVersions: [] diff --git a/testdata/gopath/src/project/config/crds/policy_v1beta1_healthcheckpolicy.yaml b/testdata/gopath/src/project/config/crds/policy_v1beta1_healthcheckpolicy.yaml deleted file mode 100644 index 7a89740f599..00000000000 --- a/testdata/gopath/src/project/config/crds/policy_v1beta1_healthcheckpolicy.yaml +++ /dev/null @@ -1,39 +0,0 @@ -apiVersion: apiextensions.k8s.io/v1beta1 -kind: CustomResourceDefinition -metadata: - creationTimestamp: null - labels: - controller-tools.k8s.io: "1.0" - name: healthcheckpolicies.policy.testproject.org -spec: - group: policy.testproject.org - names: - kind: HealthCheckPolicy - plural: healthcheckpolicies - scope: Cluster - validation: - openAPIV3Schema: - properties: - apiVersion: - description: 'APIVersion defines the versioned schema of this representation - of an object. Servers should convert recognized schemas to the latest - internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources' - type: string - kind: - description: 'Kind is a string value representing the REST resource this - object represents. Servers may infer this from the endpoint the client - submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds' - type: string - metadata: - type: object - spec: - type: object - status: - type: object - version: v1beta1 -status: - acceptedNames: - kind: "" - plural: "" - conditions: [] - storedVersions: [] diff --git a/testdata/gopath/src/project/config/crds/ship_v1beta1_frigate.yaml b/testdata/gopath/src/project/config/crds/ship_v1beta1_frigate.yaml deleted file mode 100644 index 6f3e1c24f19..00000000000 --- a/testdata/gopath/src/project/config/crds/ship_v1beta1_frigate.yaml +++ /dev/null @@ -1,39 +0,0 @@ -apiVersion: apiextensions.k8s.io/v1beta1 -kind: CustomResourceDefinition -metadata: - creationTimestamp: null - labels: - controller-tools.k8s.io: "1.0" - name: frigates.ship.testproject.org -spec: - group: ship.testproject.org - names: - kind: Frigate - plural: frigates - scope: Namespaced - validation: - openAPIV3Schema: - properties: - apiVersion: - description: 'APIVersion defines the versioned schema of this representation - of an object. Servers should convert recognized schemas to the latest - internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources' - type: string - kind: - description: 'Kind is a string value representing the REST resource this - object represents. Servers may infer this from the endpoint the client - submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds' - type: string - metadata: - type: object - spec: - type: object - status: - type: object - version: v1beta1 -status: - acceptedNames: - kind: "" - plural: "" - conditions: [] - storedVersions: [] diff --git a/testdata/gopath/src/project/config/default/kustomization.yaml b/testdata/gopath/src/project/config/default/kustomization.yaml deleted file mode 100644 index 4e7fa75e2f1..00000000000 --- a/testdata/gopath/src/project/config/default/kustomization.yaml +++ /dev/null @@ -1,37 +0,0 @@ -# Adds namespace to all resources. -namespace: project-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: project- - -# Labels to add to all resources and selectors. -#commonLabels: -# someName: someValue - -bases: -- ../rbac -- ../manager - -patchesStrategicMerge: -- manager_image_patch.yaml - # Protect the /metrics endpoint by putting it behind auth. - # Only one of manager_auth_proxy_patch.yaml and - # manager_prometheus_metrics_patch.yaml should be enabled. -- manager_auth_proxy_patch.yaml - # If you want your controller-manager to expose the /metrics - # endpoint w/o any authn/z, uncomment the following line and - # comment manager_auth_proxy_patch.yaml. - # Only one of manager_auth_proxy_patch.yaml and - # manager_prometheus_metrics_patch.yaml should be enabled. -#- manager_prometheus_metrics_patch.yaml - -vars: -- name: WEBHOOK_SECRET_NAME - objref: - kind: Secret - name: webhook-server-secret - apiVersion: v1 diff --git a/testdata/gopath/src/project/config/default/manager_auth_proxy_patch.yaml b/testdata/gopath/src/project/config/default/manager_auth_proxy_patch.yaml deleted file mode 100644 index ca0a7896584..00000000000 --- a/testdata/gopath/src/project/config/default/manager_auth_proxy_patch.yaml +++ /dev/null @@ -1,24 +0,0 @@ -# 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: StatefulSet -metadata: - name: controller-manager - namespace: system -spec: - template: - spec: - containers: - - name: kube-rbac-proxy - image: gcr.io/kubebuilder/kube-rbac-proxy:v0.5.0 - args: - - "--secure-listen-address=0.0.0.0:8443" - - "--upstream=http://127.0.0.1:8080/" - - "--logtostderr=true" - - "--v=10" - ports: - - containerPort: 8443 - name: https - - name: manager - args: - - "--metrics-addr=127.0.0.1:8080" diff --git a/testdata/gopath/src/project/config/default/manager_image_patch.yaml b/testdata/gopath/src/project/config/default/manager_image_patch.yaml deleted file mode 100644 index fcbf39dc6a5..00000000000 --- a/testdata/gopath/src/project/config/default/manager_image_patch.yaml +++ /dev/null @@ -1,12 +0,0 @@ -apiVersion: apps/v1 -kind: StatefulSet -metadata: - name: controller-manager - namespace: system -spec: - template: - spec: - containers: - # Change the value of image field below to your controller image URL - - image: IMAGE_URL - name: manager diff --git a/testdata/gopath/src/project/config/default/manager_prometheus_metrics_patch.yaml b/testdata/gopath/src/project/config/default/manager_prometheus_metrics_patch.yaml deleted file mode 100644 index 96fdcdac9d9..00000000000 --- a/testdata/gopath/src/project/config/default/manager_prometheus_metrics_patch.yaml +++ /dev/null @@ -1,19 +0,0 @@ -# This patch enables Prometheus scraping for the manager pod. -apiVersion: apps/v1 -kind: StatefulSet -metadata: - name: controller-manager - namespace: system -spec: - template: - metadata: - annotations: - prometheus.io/scrape: 'true' - spec: - containers: - # Expose the prometheus metrics on default port - - name: manager - ports: - - containerPort: 8080 - name: metrics - protocol: TCP diff --git a/testdata/gopath/src/project/config/manager/kustomization.yaml b/testdata/gopath/src/project/config/manager/kustomization.yaml deleted file mode 100644 index 5c5f0b84cba..00000000000 --- a/testdata/gopath/src/project/config/manager/kustomization.yaml +++ /dev/null @@ -1,2 +0,0 @@ -resources: -- manager.yaml diff --git a/testdata/gopath/src/project/config/manager/manager.yaml b/testdata/gopath/src/project/config/manager/manager.yaml deleted file mode 100644 index 2e57718d1dc..00000000000 --- a/testdata/gopath/src/project/config/manager/manager.yaml +++ /dev/null @@ -1,84 +0,0 @@ -apiVersion: v1 -kind: Namespace -metadata: - labels: - control-plane: controller-manager - controller-tools.k8s.io: "1.0" - name: system ---- -apiVersion: v1 -kind: Service -metadata: - name: controller-manager-service - namespace: system - labels: - control-plane: controller-manager - controller-tools.k8s.io: "1.0" -spec: - selector: - control-plane: controller-manager - controller-tools.k8s.io: "1.0" - ports: - - port: 443 ---- -apiVersion: apps/v1 -kind: StatefulSet -metadata: - name: controller-manager - namespace: system - labels: - control-plane: controller-manager - controller-tools.k8s.io: "1.0" -spec: - selector: - matchLabels: - control-plane: controller-manager - controller-tools.k8s.io: "1.0" - serviceName: controller-manager-service - replicas: 1 - podManagementPolicy: Parallel - template: - metadata: - labels: - control-plane: controller-manager - controller-tools.k8s.io: "1.0" - spec: - containers: - - command: - - /manager - image: controller:latest - name: manager - env: - - name: POD_NAMESPACE - valueFrom: - fieldRef: - fieldPath: metadata.namespace - - name: SECRET_NAME - value: $(WEBHOOK_SECRET_NAME) - resources: - limits: - cpu: 100m - memory: 30Mi - requests: - cpu: 100m - memory: 20Mi - ports: - - containerPort: 9876 - name: webhook-server - protocol: TCP - volumeMounts: - - mountPath: /tmp/cert - name: cert - readOnly: true - terminationGracePeriodSeconds: 10 - volumes: - - name: cert - secret: - defaultMode: 420 - secretName: webhook-server-secret ---- -apiVersion: v1 -kind: Secret -metadata: - name: webhook-server-secret - namespace: system diff --git a/testdata/gopath/src/project/config/rbac/auth_proxy_role.yaml b/testdata/gopath/src/project/config/rbac/auth_proxy_role.yaml deleted file mode 100644 index 618f5e4177c..00000000000 --- a/testdata/gopath/src/project/config/rbac/auth_proxy_role.yaml +++ /dev/null @@ -1,13 +0,0 @@ -apiVersion: rbac.authorization.k8s.io/v1 -kind: ClusterRole -metadata: - name: proxy-role -rules: -- apiGroups: ["authentication.k8s.io"] - resources: - - tokenreviews - verbs: ["create"] -- apiGroups: ["authorization.k8s.io"] - resources: - - subjectaccessreviews - verbs: ["create"] diff --git a/testdata/gopath/src/project/config/rbac/auth_proxy_role_binding.yaml b/testdata/gopath/src/project/config/rbac/auth_proxy_role_binding.yaml deleted file mode 100644 index 48ed1e4b85c..00000000000 --- a/testdata/gopath/src/project/config/rbac/auth_proxy_role_binding.yaml +++ /dev/null @@ -1,12 +0,0 @@ -apiVersion: rbac.authorization.k8s.io/v1 -kind: ClusterRoleBinding -metadata: - name: proxy-rolebinding -roleRef: - apiGroup: rbac.authorization.k8s.io - kind: ClusterRole - name: proxy-role -subjects: -- kind: ServiceAccount - name: default - namespace: system diff --git a/testdata/gopath/src/project/config/rbac/auth_proxy_service.yaml b/testdata/gopath/src/project/config/rbac/auth_proxy_service.yaml deleted file mode 100644 index 027073f9528..00000000000 --- a/testdata/gopath/src/project/config/rbac/auth_proxy_service.yaml +++ /dev/null @@ -1,20 +0,0 @@ -apiVersion: v1 -kind: Service -metadata: - annotations: - prometheus.io/port: "8443" - prometheus.io/scheme: https - prometheus.io/scrape: "true" - labels: - control-plane: controller-manager - controller-tools.k8s.io: "1.0" - name: controller-manager-metrics-service - namespace: system -spec: - ports: - - name: https - port: 8443 - targetPort: https - selector: - control-plane: controller-manager - controller-tools.k8s.io: "1.0" diff --git a/testdata/gopath/src/project/config/rbac/kustomization.yaml b/testdata/gopath/src/project/config/rbac/kustomization.yaml deleted file mode 100644 index 8c6d6a5b93c..00000000000 --- a/testdata/gopath/src/project/config/rbac/kustomization.yaml +++ /dev/null @@ -1,9 +0,0 @@ -resources: -- rbac_role.yaml -- rbac_role_binding.yaml - # Comment the following 3 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 diff --git a/testdata/gopath/src/project/config/rbac/rbac_role.yaml b/testdata/gopath/src/project/config/rbac/rbac_role.yaml deleted file mode 100644 index b56f2f6bd1c..00000000000 --- a/testdata/gopath/src/project/config/rbac/rbac_role.yaml +++ /dev/null @@ -1,163 +0,0 @@ -apiVersion: rbac.authorization.k8s.io/v1 -kind: ClusterRole -metadata: - creationTimestamp: null - name: manager-role -rules: -- apiGroups: - - apps - resources: - - deployments - verbs: - - get - - list - - watch - - create - - update - - patch - - delete -- apiGroups: - - apps - resources: - - deployments/status - verbs: - - get - - update - - patch -- apiGroups: - - crew.testproject.org - resources: - - firstmates - verbs: - - get - - list - - watch - - create - - update - - patch - - delete -- apiGroups: - - crew.testproject.org - resources: - - firstmates/status - verbs: - - get - - update - - patch -- apiGroups: - - ship.testproject.org - resources: - - frigates - verbs: - - get - - list - - watch - - create - - update - - patch - - delete -- apiGroups: - - ship.testproject.org - resources: - - frigates/status - verbs: - - get - - update - - patch -- apiGroups: - - policy.testproject.org - resources: - - healthcheckpolicies - verbs: - - get - - list - - watch - - create - - update - - patch - - delete -- apiGroups: - - policy.testproject.org - resources: - - healthcheckpolicies/status - verbs: - - get - - update - - patch -- apiGroups: - - creatures.testproject.org - resources: - - krakens - verbs: - - get - - list - - watch - - create - - update - - patch - - delete -- apiGroups: - - creatures.testproject.org - resources: - - krakens/status - verbs: - - get - - update - - patch -- apiGroups: - - "" - resources: - - namespaces - verbs: - - get - - list - - watch - - create - - update - - patch - - delete -- apiGroups: - - "" - resources: - - namespaces/status - verbs: - - get - - update - - patch -- apiGroups: - - admissionregistration.k8s.io - resources: - - mutatingwebhookconfigurations - - validatingwebhookconfigurations - verbs: - - get - - list - - watch - - create - - update - - patch - - delete -- apiGroups: - - "" - resources: - - secrets - verbs: - - get - - list - - watch - - create - - update - - patch - - delete -- apiGroups: - - "" - resources: - - services - verbs: - - get - - list - - watch - - create - - update - - patch - - delete diff --git a/testdata/gopath/src/project/config/rbac/rbac_role_binding.yaml b/testdata/gopath/src/project/config/rbac/rbac_role_binding.yaml deleted file mode 100644 index c1033e23fb9..00000000000 --- a/testdata/gopath/src/project/config/rbac/rbac_role_binding.yaml +++ /dev/null @@ -1,13 +0,0 @@ -apiVersion: rbac.authorization.k8s.io/v1 -kind: ClusterRoleBinding -metadata: - creationTimestamp: null - name: manager-rolebinding -roleRef: - apiGroup: rbac.authorization.k8s.io - kind: ClusterRole - name: manager-role -subjects: -- kind: ServiceAccount - name: default - namespace: system diff --git a/testdata/gopath/src/project/config/samples/creatures_v2alpha1_kraken.yaml b/testdata/gopath/src/project/config/samples/creatures_v2alpha1_kraken.yaml deleted file mode 100644 index 68712b3319b..00000000000 --- a/testdata/gopath/src/project/config/samples/creatures_v2alpha1_kraken.yaml +++ /dev/null @@ -1,9 +0,0 @@ -apiVersion: creatures.testproject.org/v2alpha1 -kind: Kraken -metadata: - labels: - controller-tools.k8s.io: "1.0" - name: kraken-sample -spec: - # Add fields here - foo: bar diff --git a/testdata/gopath/src/project/config/samples/crew_v1_firstmate.yaml b/testdata/gopath/src/project/config/samples/crew_v1_firstmate.yaml deleted file mode 100644 index 45ebf31f208..00000000000 --- a/testdata/gopath/src/project/config/samples/crew_v1_firstmate.yaml +++ /dev/null @@ -1,9 +0,0 @@ -apiVersion: crew.testproject.org/v1 -kind: FirstMate -metadata: - labels: - controller-tools.k8s.io: "1.0" - name: firstmate-sample -spec: - # Add fields here - foo: bar diff --git a/testdata/gopath/src/project/config/samples/policy_v1beta1_healthcheckpolicy.yaml b/testdata/gopath/src/project/config/samples/policy_v1beta1_healthcheckpolicy.yaml deleted file mode 100644 index 880a99ed369..00000000000 --- a/testdata/gopath/src/project/config/samples/policy_v1beta1_healthcheckpolicy.yaml +++ /dev/null @@ -1,9 +0,0 @@ -apiVersion: policy.testproject.org/v1beta1 -kind: HealthCheckPolicy -metadata: - labels: - controller-tools.k8s.io: "1.0" - name: healthcheckpolicy-sample -spec: - # Add fields here - foo: bar diff --git a/testdata/gopath/src/project/config/samples/ship_v1beta1_frigate.yaml b/testdata/gopath/src/project/config/samples/ship_v1beta1_frigate.yaml deleted file mode 100644 index 796f468e814..00000000000 --- a/testdata/gopath/src/project/config/samples/ship_v1beta1_frigate.yaml +++ /dev/null @@ -1,9 +0,0 @@ -apiVersion: ship.testproject.org/v1beta1 -kind: Frigate -metadata: - labels: - controller-tools.k8s.io: "1.0" - name: frigate-sample -spec: - # Add fields here - foo: bar diff --git a/testdata/gopath/src/project/hack/boilerplate.go.txt b/testdata/gopath/src/project/hack/boilerplate.go.txt deleted file mode 100644 index b75c7954b88..00000000000 --- a/testdata/gopath/src/project/hack/boilerplate.go.txt +++ /dev/null @@ -1,15 +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. -*/ \ No newline at end of file diff --git a/testdata/gopath/src/project/pkg/apis/addtoscheme_creatures_v2alpha1.go b/testdata/gopath/src/project/pkg/apis/addtoscheme_creatures_v2alpha1.go deleted file mode 100644 index 0c01bcdf9e4..00000000000 --- a/testdata/gopath/src/project/pkg/apis/addtoscheme_creatures_v2alpha1.go +++ /dev/null @@ -1,26 +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 apis - -import ( - creaturesv2alpha1 "project/pkg/apis/creatures/v2alpha1" -) - -func init() { - // Register the types with the Scheme so the components can map objects to GroupVersionKinds and back - AddToSchemes = append(AddToSchemes, creaturesv2alpha1.SchemeBuilder.AddToScheme) -} diff --git a/testdata/gopath/src/project/pkg/apis/addtoscheme_crew_v1.go b/testdata/gopath/src/project/pkg/apis/addtoscheme_crew_v1.go deleted file mode 100644 index b83c0cd11f6..00000000000 --- a/testdata/gopath/src/project/pkg/apis/addtoscheme_crew_v1.go +++ /dev/null @@ -1,26 +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 apis - -import ( - crewv1 "project/pkg/apis/crew/v1" -) - -func init() { - // Register the types with the Scheme so the components can map objects to GroupVersionKinds and back - AddToSchemes = append(AddToSchemes, crewv1.SchemeBuilder.AddToScheme) -} diff --git a/testdata/gopath/src/project/pkg/apis/addtoscheme_policy_v1beta1.go b/testdata/gopath/src/project/pkg/apis/addtoscheme_policy_v1beta1.go deleted file mode 100644 index a7d2b230ed2..00000000000 --- a/testdata/gopath/src/project/pkg/apis/addtoscheme_policy_v1beta1.go +++ /dev/null @@ -1,26 +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 apis - -import ( - policyv1beta1 "project/pkg/apis/policy/v1beta1" -) - -func init() { - // Register the types with the Scheme so the components can map objects to GroupVersionKinds and back - AddToSchemes = append(AddToSchemes, policyv1beta1.SchemeBuilder.AddToScheme) -} diff --git a/testdata/gopath/src/project/pkg/apis/addtoscheme_ship_v1beta1.go b/testdata/gopath/src/project/pkg/apis/addtoscheme_ship_v1beta1.go deleted file mode 100644 index dcd014d0c77..00000000000 --- a/testdata/gopath/src/project/pkg/apis/addtoscheme_ship_v1beta1.go +++ /dev/null @@ -1,26 +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 apis - -import ( - shipv1beta1 "project/pkg/apis/ship/v1beta1" -) - -func init() { - // Register the types with the Scheme so the components can map objects to GroupVersionKinds and back - AddToSchemes = append(AddToSchemes, shipv1beta1.SchemeBuilder.AddToScheme) -} diff --git a/testdata/gopath/src/project/pkg/apis/apis.go b/testdata/gopath/src/project/pkg/apis/apis.go deleted file mode 100644 index 8bb3fd6643b..00000000000 --- a/testdata/gopath/src/project/pkg/apis/apis.go +++ /dev/null @@ -1,33 +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. -*/ - -// Generate deepcopy for apis -//go:generate go run ../../vendor/k8s.io/code-generator/cmd/deepcopy-gen/main.go -O zz_generated.deepcopy -i ./... -h ../../hack/boilerplate.go.txt - -// Package apis contains Kubernetes API groups. -package apis - -import ( - "k8s.io/apimachinery/pkg/runtime" -) - -// AddToSchemes may be used to add all resources defined in the project to a Scheme -var AddToSchemes runtime.SchemeBuilder - -// AddToScheme adds all Resources to the Scheme -func AddToScheme(s *runtime.Scheme) error { - return AddToSchemes.AddToScheme(s) -} diff --git a/testdata/gopath/src/project/pkg/apis/creatures/group.go b/testdata/gopath/src/project/pkg/apis/creatures/group.go deleted file mode 100644 index b4339573585..00000000000 --- a/testdata/gopath/src/project/pkg/apis/creatures/group.go +++ /dev/null @@ -1,18 +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 creatures contains creatures API versions -package creatures diff --git a/testdata/gopath/src/project/pkg/apis/creatures/v2alpha1/doc.go b/testdata/gopath/src/project/pkg/apis/creatures/v2alpha1/doc.go deleted file mode 100644 index 4800ffa9025..00000000000 --- a/testdata/gopath/src/project/pkg/apis/creatures/v2alpha1/doc.go +++ /dev/null @@ -1,23 +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 v2alpha1 contains API Schema definitions for the creatures v2alpha1 API group -// +k8s:openapi-gen=true -// +k8s:deepcopy-gen=package,register -// +k8s:conversion-gen=project/pkg/apis/creatures -// +k8s:defaulter-gen=TypeMeta -// +groupName=creatures.testproject.org -package v2alpha1 diff --git a/testdata/gopath/src/project/pkg/apis/creatures/v2alpha1/kraken_types.go b/testdata/gopath/src/project/pkg/apis/creatures/v2alpha1/kraken_types.go deleted file mode 100644 index 0dd4d0720b0..00000000000 --- a/testdata/gopath/src/project/pkg/apis/creatures/v2alpha1/kraken_types.go +++ /dev/null @@ -1,64 +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 v2alpha1 - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -// 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. - -// KrakenSpec defines the desired state of Kraken -type KrakenSpec struct { - // INSERT ADDITIONAL SPEC FIELDS - desired state of cluster - // Important: Run "make" to regenerate code after modifying this file -} - -// KrakenStatus defines the observed state of Kraken -type KrakenStatus struct { - // INSERT ADDITIONAL STATUS FIELD - define observed state of cluster - // Important: Run "make" to regenerate code after modifying this file -} - -// +genclient -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -// +genclient:nonNamespaced - -// Kraken is the Schema for the krakens API -// +k8s:openapi-gen=true -type Kraken struct { - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata,omitempty"` - - Spec KrakenSpec `json:"spec,omitempty"` - Status KrakenStatus `json:"status,omitempty"` -} - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -// +genclient:nonNamespaced - -// KrakenList contains a list of Kraken -type KrakenList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata,omitempty"` - Items []Kraken `json:"items"` -} - -func init() { - SchemeBuilder.Register(&Kraken{}, &KrakenList{}) -} diff --git a/testdata/gopath/src/project/pkg/apis/creatures/v2alpha1/kraken_types_test.go b/testdata/gopath/src/project/pkg/apis/creatures/v2alpha1/kraken_types_test.go deleted file mode 100644 index 9accf54f238..00000000000 --- a/testdata/gopath/src/project/pkg/apis/creatures/v2alpha1/kraken_types_test.go +++ /dev/null @@ -1,56 +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 v2alpha1 - -import ( - "testing" - - "github.com/onsi/gomega" - "golang.org/x/net/context" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" -) - -func TestStorageKraken(t *testing.T) { - key := types.NamespacedName{ - Name: "foo", - } - created := &Kraken{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - }} - g := gomega.NewGomegaWithT(t) - - // Test Create - fetched := &Kraken{} - g.Expect(c.Create(context.TODO(), created)).To(gomega.Succeed()) - - g.Expect(c.Get(context.TODO(), key, fetched)).To(gomega.Succeed()) - g.Expect(fetched).To(gomega.Equal(created)) - - // Test Updating the Labels - updated := fetched.DeepCopy() - updated.Labels = map[string]string{"hello": "world"} - g.Expect(c.Update(context.TODO(), updated)).To(gomega.Succeed()) - - g.Expect(c.Get(context.TODO(), key, fetched)).To(gomega.Succeed()) - g.Expect(fetched).To(gomega.Equal(updated)) - - // Test Delete - g.Expect(c.Delete(context.TODO(), fetched)).To(gomega.Succeed()) - g.Expect(c.Get(context.TODO(), key, fetched)).ToNot(gomega.Succeed()) -} diff --git a/testdata/gopath/src/project/pkg/apis/creatures/v2alpha1/register.go b/testdata/gopath/src/project/pkg/apis/creatures/v2alpha1/register.go deleted file mode 100644 index 15bdef7e056..00000000000 --- a/testdata/gopath/src/project/pkg/apis/creatures/v2alpha1/register.go +++ /dev/null @@ -1,46 +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. -*/ - -// NOTE: Boilerplate only. Ignore this file. - -// Package v2alpha1 contains API Schema definitions for the creatures v2alpha1 API group -// +k8s:openapi-gen=true -// +k8s:deepcopy-gen=package,register -// +k8s:conversion-gen=project/pkg/apis/creatures -// +k8s:defaulter-gen=TypeMeta -// +groupName=creatures.testproject.org -package v2alpha1 - -import ( - "k8s.io/apimachinery/pkg/runtime/schema" - "sigs.k8s.io/controller-runtime/pkg/runtime/scheme" -) - -var ( - // SchemeGroupVersion is group version used to register these objects - SchemeGroupVersion = schema.GroupVersion{Group: "creatures.testproject.org", Version: "v2alpha1"} - - // SchemeBuilder is used to add go types to the GroupVersionKind scheme - SchemeBuilder = &scheme.Builder{GroupVersion: SchemeGroupVersion} - - // AddToScheme is required by pkg/client/... - AddToScheme = SchemeBuilder.AddToScheme -) - -// Resource is required by pkg/client/listers/... -func Resource(resource string) schema.GroupResource { - return SchemeGroupVersion.WithResource(resource).GroupResource() -} diff --git a/testdata/gopath/src/project/pkg/apis/creatures/v2alpha1/v2alpha1_suite_test.go b/testdata/gopath/src/project/pkg/apis/creatures/v2alpha1/v2alpha1_suite_test.go deleted file mode 100644 index ded62b47924..00000000000 --- a/testdata/gopath/src/project/pkg/apis/creatures/v2alpha1/v2alpha1_suite_test.go +++ /dev/null @@ -1,55 +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 v2alpha1 - -import ( - "log" - "os" - "path/filepath" - "testing" - - "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" -) - -var cfg *rest.Config -var c client.Client - -func TestMain(m *testing.M) { - t := &envtest.Environment{ - CRDDirectoryPaths: []string{filepath.Join("..", "..", "..", "..", "config", "crds")}, - } - - err := SchemeBuilder.AddToScheme(scheme.Scheme) - if err != nil { - log.Fatal(err) - } - - if cfg, err = t.Start(); err != nil { - log.Fatal(err) - } - - if c, err = client.New(cfg, client.Options{Scheme: scheme.Scheme}); err != nil { - log.Fatal(err) - } - - code := m.Run() - t.Stop() - os.Exit(code) -} diff --git a/testdata/gopath/src/project/pkg/apis/creatures/v2alpha1/zz_generated.deepcopy.go b/testdata/gopath/src/project/pkg/apis/creatures/v2alpha1/zz_generated.deepcopy.go deleted file mode 100644 index edb428209de..00000000000 --- a/testdata/gopath/src/project/pkg/apis/creatures/v2alpha1/zz_generated.deepcopy.go +++ /dev/null @@ -1,117 +0,0 @@ -// +build !ignore_autogenerated - -/* -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. -*/ -// Code generated by main. DO NOT EDIT. - -package v2alpha1 - -import ( - runtime "k8s.io/apimachinery/pkg/runtime" -) - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Kraken) DeepCopyInto(out *Kraken) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - out.Spec = in.Spec - out.Status = in.Status - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Kraken. -func (in *Kraken) DeepCopy() *Kraken { - if in == nil { - return nil - } - out := new(Kraken) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *Kraken) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *KrakenList) DeepCopyInto(out *KrakenList) { - *out = *in - out.TypeMeta = in.TypeMeta - out.ListMeta = in.ListMeta - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]Kraken, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new KrakenList. -func (in *KrakenList) DeepCopy() *KrakenList { - if in == nil { - return nil - } - out := new(KrakenList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *KrakenList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *KrakenSpec) DeepCopyInto(out *KrakenSpec) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new KrakenSpec. -func (in *KrakenSpec) DeepCopy() *KrakenSpec { - if in == nil { - return nil - } - out := new(KrakenSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *KrakenStatus) DeepCopyInto(out *KrakenStatus) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new KrakenStatus. -func (in *KrakenStatus) DeepCopy() *KrakenStatus { - if in == nil { - return nil - } - out := new(KrakenStatus) - in.DeepCopyInto(out) - return out -} diff --git a/testdata/gopath/src/project/pkg/apis/crew/group.go b/testdata/gopath/src/project/pkg/apis/crew/group.go deleted file mode 100644 index 22e79fd0bc2..00000000000 --- a/testdata/gopath/src/project/pkg/apis/crew/group.go +++ /dev/null @@ -1,18 +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 crew contains crew API versions -package crew diff --git a/testdata/gopath/src/project/pkg/apis/crew/v1/doc.go b/testdata/gopath/src/project/pkg/apis/crew/v1/doc.go deleted file mode 100644 index 602e9b64b36..00000000000 --- a/testdata/gopath/src/project/pkg/apis/crew/v1/doc.go +++ /dev/null @@ -1,23 +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 v1 contains API Schema definitions for the crew v1 API group -// +k8s:openapi-gen=true -// +k8s:deepcopy-gen=package,register -// +k8s:conversion-gen=project/pkg/apis/crew -// +k8s:defaulter-gen=TypeMeta -// +groupName=crew.testproject.org -package v1 diff --git a/testdata/gopath/src/project/pkg/apis/crew/v1/firstmate_types.go b/testdata/gopath/src/project/pkg/apis/crew/v1/firstmate_types.go deleted file mode 100644 index d8dd6005ad4..00000000000 --- a/testdata/gopath/src/project/pkg/apis/crew/v1/firstmate_types.go +++ /dev/null @@ -1,62 +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 v1 - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -// 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. - -// FirstMateSpec defines the desired state of FirstMate -type FirstMateSpec struct { - // INSERT ADDITIONAL SPEC FIELDS - desired state of cluster - // Important: Run "make" to regenerate code after modifying this file -} - -// FirstMateStatus defines the observed state of FirstMate -type FirstMateStatus struct { - // INSERT ADDITIONAL STATUS FIELD - define observed state of cluster - // Important: Run "make" to regenerate code after modifying this file -} - -// +genclient -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// FirstMate is the Schema for the firstmates API -// +k8s:openapi-gen=true -type FirstMate struct { - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata,omitempty"` - - Spec FirstMateSpec `json:"spec,omitempty"` - Status FirstMateStatus `json:"status,omitempty"` -} - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// FirstMateList contains a list of FirstMate -type FirstMateList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata,omitempty"` - Items []FirstMate `json:"items"` -} - -func init() { - SchemeBuilder.Register(&FirstMate{}, &FirstMateList{}) -} diff --git a/testdata/gopath/src/project/pkg/apis/crew/v1/firstmate_types_test.go b/testdata/gopath/src/project/pkg/apis/crew/v1/firstmate_types_test.go deleted file mode 100644 index 03812d3c92c..00000000000 --- a/testdata/gopath/src/project/pkg/apis/crew/v1/firstmate_types_test.go +++ /dev/null @@ -1,58 +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 v1 - -import ( - "testing" - - "github.com/onsi/gomega" - "golang.org/x/net/context" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" -) - -func TestStorageFirstMate(t *testing.T) { - key := types.NamespacedName{ - Name: "foo", - Namespace: "default", - } - created := &FirstMate{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "default", - }} - g := gomega.NewGomegaWithT(t) - - // Test Create - fetched := &FirstMate{} - g.Expect(c.Create(context.TODO(), created)).To(gomega.Succeed()) - - g.Expect(c.Get(context.TODO(), key, fetched)).To(gomega.Succeed()) - g.Expect(fetched).To(gomega.Equal(created)) - - // Test Updating the Labels - updated := fetched.DeepCopy() - updated.Labels = map[string]string{"hello": "world"} - g.Expect(c.Update(context.TODO(), updated)).To(gomega.Succeed()) - - g.Expect(c.Get(context.TODO(), key, fetched)).To(gomega.Succeed()) - g.Expect(fetched).To(gomega.Equal(updated)) - - // Test Delete - g.Expect(c.Delete(context.TODO(), fetched)).To(gomega.Succeed()) - g.Expect(c.Get(context.TODO(), key, fetched)).ToNot(gomega.Succeed()) -} diff --git a/testdata/gopath/src/project/pkg/apis/crew/v1/register.go b/testdata/gopath/src/project/pkg/apis/crew/v1/register.go deleted file mode 100644 index 352c06dd363..00000000000 --- a/testdata/gopath/src/project/pkg/apis/crew/v1/register.go +++ /dev/null @@ -1,46 +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. -*/ - -// NOTE: Boilerplate only. Ignore this file. - -// Package v1 contains API Schema definitions for the crew v1 API group -// +k8s:openapi-gen=true -// +k8s:deepcopy-gen=package,register -// +k8s:conversion-gen=project/pkg/apis/crew -// +k8s:defaulter-gen=TypeMeta -// +groupName=crew.testproject.org -package v1 - -import ( - "k8s.io/apimachinery/pkg/runtime/schema" - "sigs.k8s.io/controller-runtime/pkg/runtime/scheme" -) - -var ( - // SchemeGroupVersion is group version used to register these objects - SchemeGroupVersion = schema.GroupVersion{Group: "crew.testproject.org", Version: "v1"} - - // SchemeBuilder is used to add go types to the GroupVersionKind scheme - SchemeBuilder = &scheme.Builder{GroupVersion: SchemeGroupVersion} - - // AddToScheme is required by pkg/client/... - AddToScheme = SchemeBuilder.AddToScheme -) - -// Resource is required by pkg/client/listers/... -func Resource(resource string) schema.GroupResource { - return SchemeGroupVersion.WithResource(resource).GroupResource() -} diff --git a/testdata/gopath/src/project/pkg/apis/crew/v1/v1_suite_test.go b/testdata/gopath/src/project/pkg/apis/crew/v1/v1_suite_test.go deleted file mode 100644 index 719dc7c2119..00000000000 --- a/testdata/gopath/src/project/pkg/apis/crew/v1/v1_suite_test.go +++ /dev/null @@ -1,55 +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 v1 - -import ( - "log" - "os" - "path/filepath" - "testing" - - "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" -) - -var cfg *rest.Config -var c client.Client - -func TestMain(m *testing.M) { - t := &envtest.Environment{ - CRDDirectoryPaths: []string{filepath.Join("..", "..", "..", "..", "config", "crds")}, - } - - err := SchemeBuilder.AddToScheme(scheme.Scheme) - if err != nil { - log.Fatal(err) - } - - if cfg, err = t.Start(); err != nil { - log.Fatal(err) - } - - if c, err = client.New(cfg, client.Options{Scheme: scheme.Scheme}); err != nil { - log.Fatal(err) - } - - code := m.Run() - t.Stop() - os.Exit(code) -} diff --git a/testdata/gopath/src/project/pkg/apis/crew/v1/zz_generated.deepcopy.go b/testdata/gopath/src/project/pkg/apis/crew/v1/zz_generated.deepcopy.go deleted file mode 100644 index 2e734a09fa2..00000000000 --- a/testdata/gopath/src/project/pkg/apis/crew/v1/zz_generated.deepcopy.go +++ /dev/null @@ -1,117 +0,0 @@ -// +build !ignore_autogenerated - -/* -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. -*/ -// Code generated by main. DO NOT EDIT. - -package v1 - -import ( - runtime "k8s.io/apimachinery/pkg/runtime" -) - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *FirstMate) DeepCopyInto(out *FirstMate) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - out.Spec = in.Spec - out.Status = in.Status - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new FirstMate. -func (in *FirstMate) DeepCopy() *FirstMate { - if in == nil { - return nil - } - out := new(FirstMate) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *FirstMate) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *FirstMateList) DeepCopyInto(out *FirstMateList) { - *out = *in - out.TypeMeta = in.TypeMeta - out.ListMeta = in.ListMeta - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]FirstMate, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new FirstMateList. -func (in *FirstMateList) DeepCopy() *FirstMateList { - if in == nil { - return nil - } - out := new(FirstMateList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *FirstMateList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *FirstMateSpec) DeepCopyInto(out *FirstMateSpec) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new FirstMateSpec. -func (in *FirstMateSpec) DeepCopy() *FirstMateSpec { - if in == nil { - return nil - } - out := new(FirstMateSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *FirstMateStatus) DeepCopyInto(out *FirstMateStatus) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new FirstMateStatus. -func (in *FirstMateStatus) DeepCopy() *FirstMateStatus { - if in == nil { - return nil - } - out := new(FirstMateStatus) - in.DeepCopyInto(out) - return out -} diff --git a/testdata/gopath/src/project/pkg/apis/policy/group.go b/testdata/gopath/src/project/pkg/apis/policy/group.go deleted file mode 100644 index de777a89f10..00000000000 --- a/testdata/gopath/src/project/pkg/apis/policy/group.go +++ /dev/null @@ -1,18 +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 policy contains policy API versions -package policy diff --git a/testdata/gopath/src/project/pkg/apis/policy/v1beta1/doc.go b/testdata/gopath/src/project/pkg/apis/policy/v1beta1/doc.go deleted file mode 100644 index d4866313037..00000000000 --- a/testdata/gopath/src/project/pkg/apis/policy/v1beta1/doc.go +++ /dev/null @@ -1,23 +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 v1beta1 contains API Schema definitions for the policy v1beta1 API group -// +k8s:openapi-gen=true -// +k8s:deepcopy-gen=package,register -// +k8s:conversion-gen=project/pkg/apis/policy -// +k8s:defaulter-gen=TypeMeta -// +groupName=policy.testproject.org -package v1beta1 diff --git a/testdata/gopath/src/project/pkg/apis/policy/v1beta1/healthcheckpolicy_types.go b/testdata/gopath/src/project/pkg/apis/policy/v1beta1/healthcheckpolicy_types.go deleted file mode 100644 index 1c47b1974c3..00000000000 --- a/testdata/gopath/src/project/pkg/apis/policy/v1beta1/healthcheckpolicy_types.go +++ /dev/null @@ -1,64 +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 v1beta1 - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -// 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. - -// HealthCheckPolicySpec defines the desired state of HealthCheckPolicy -type HealthCheckPolicySpec struct { - // INSERT ADDITIONAL SPEC FIELDS - desired state of cluster - // Important: Run "make" to regenerate code after modifying this file -} - -// HealthCheckPolicyStatus defines the observed state of HealthCheckPolicy -type HealthCheckPolicyStatus struct { - // INSERT ADDITIONAL STATUS FIELD - define observed state of cluster - // Important: Run "make" to regenerate code after modifying this file -} - -// +genclient -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -// +genclient:nonNamespaced - -// HealthCheckPolicy is the Schema for the healthcheckpolicies API -// +k8s:openapi-gen=true -type HealthCheckPolicy struct { - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata,omitempty"` - - Spec HealthCheckPolicySpec `json:"spec,omitempty"` - Status HealthCheckPolicyStatus `json:"status,omitempty"` -} - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -// +genclient:nonNamespaced - -// HealthCheckPolicyList contains a list of HealthCheckPolicy -type HealthCheckPolicyList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata,omitempty"` - Items []HealthCheckPolicy `json:"items"` -} - -func init() { - SchemeBuilder.Register(&HealthCheckPolicy{}, &HealthCheckPolicyList{}) -} diff --git a/testdata/gopath/src/project/pkg/apis/policy/v1beta1/healthcheckpolicy_types_test.go b/testdata/gopath/src/project/pkg/apis/policy/v1beta1/healthcheckpolicy_types_test.go deleted file mode 100644 index 9fb78b19f16..00000000000 --- a/testdata/gopath/src/project/pkg/apis/policy/v1beta1/healthcheckpolicy_types_test.go +++ /dev/null @@ -1,56 +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 v1beta1 - -import ( - "testing" - - "github.com/onsi/gomega" - "golang.org/x/net/context" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" -) - -func TestStorageHealthCheckPolicy(t *testing.T) { - key := types.NamespacedName{ - Name: "foo", - } - created := &HealthCheckPolicy{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - }} - g := gomega.NewGomegaWithT(t) - - // Test Create - fetched := &HealthCheckPolicy{} - g.Expect(c.Create(context.TODO(), created)).To(gomega.Succeed()) - - g.Expect(c.Get(context.TODO(), key, fetched)).To(gomega.Succeed()) - g.Expect(fetched).To(gomega.Equal(created)) - - // Test Updating the Labels - updated := fetched.DeepCopy() - updated.Labels = map[string]string{"hello": "world"} - g.Expect(c.Update(context.TODO(), updated)).To(gomega.Succeed()) - - g.Expect(c.Get(context.TODO(), key, fetched)).To(gomega.Succeed()) - g.Expect(fetched).To(gomega.Equal(updated)) - - // Test Delete - g.Expect(c.Delete(context.TODO(), fetched)).To(gomega.Succeed()) - g.Expect(c.Get(context.TODO(), key, fetched)).ToNot(gomega.Succeed()) -} diff --git a/testdata/gopath/src/project/pkg/apis/policy/v1beta1/register.go b/testdata/gopath/src/project/pkg/apis/policy/v1beta1/register.go deleted file mode 100644 index 109d9628097..00000000000 --- a/testdata/gopath/src/project/pkg/apis/policy/v1beta1/register.go +++ /dev/null @@ -1,46 +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. -*/ - -// NOTE: Boilerplate only. Ignore this file. - -// Package v1beta1 contains API Schema definitions for the policy v1beta1 API group -// +k8s:openapi-gen=true -// +k8s:deepcopy-gen=package,register -// +k8s:conversion-gen=project/pkg/apis/policy -// +k8s:defaulter-gen=TypeMeta -// +groupName=policy.testproject.org -package v1beta1 - -import ( - "k8s.io/apimachinery/pkg/runtime/schema" - "sigs.k8s.io/controller-runtime/pkg/runtime/scheme" -) - -var ( - // SchemeGroupVersion is group version used to register these objects - SchemeGroupVersion = schema.GroupVersion{Group: "policy.testproject.org", Version: "v1beta1"} - - // SchemeBuilder is used to add go types to the GroupVersionKind scheme - SchemeBuilder = &scheme.Builder{GroupVersion: SchemeGroupVersion} - - // AddToScheme is required by pkg/client/... - AddToScheme = SchemeBuilder.AddToScheme -) - -// Resource is required by pkg/client/listers/... -func Resource(resource string) schema.GroupResource { - return SchemeGroupVersion.WithResource(resource).GroupResource() -} diff --git a/testdata/gopath/src/project/pkg/apis/policy/v1beta1/v1beta1_suite_test.go b/testdata/gopath/src/project/pkg/apis/policy/v1beta1/v1beta1_suite_test.go deleted file mode 100644 index 192b395f666..00000000000 --- a/testdata/gopath/src/project/pkg/apis/policy/v1beta1/v1beta1_suite_test.go +++ /dev/null @@ -1,55 +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 v1beta1 - -import ( - "log" - "os" - "path/filepath" - "testing" - - "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" -) - -var cfg *rest.Config -var c client.Client - -func TestMain(m *testing.M) { - t := &envtest.Environment{ - CRDDirectoryPaths: []string{filepath.Join("..", "..", "..", "..", "config", "crds")}, - } - - err := SchemeBuilder.AddToScheme(scheme.Scheme) - if err != nil { - log.Fatal(err) - } - - if cfg, err = t.Start(); err != nil { - log.Fatal(err) - } - - if c, err = client.New(cfg, client.Options{Scheme: scheme.Scheme}); err != nil { - log.Fatal(err) - } - - code := m.Run() - t.Stop() - os.Exit(code) -} diff --git a/testdata/gopath/src/project/pkg/apis/policy/v1beta1/zz_generated.deepcopy.go b/testdata/gopath/src/project/pkg/apis/policy/v1beta1/zz_generated.deepcopy.go deleted file mode 100644 index fece4b6af82..00000000000 --- a/testdata/gopath/src/project/pkg/apis/policy/v1beta1/zz_generated.deepcopy.go +++ /dev/null @@ -1,117 +0,0 @@ -// +build !ignore_autogenerated - -/* -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. -*/ -// Code generated by main. DO NOT EDIT. - -package v1beta1 - -import ( - runtime "k8s.io/apimachinery/pkg/runtime" -) - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *HealthCheckPolicy) DeepCopyInto(out *HealthCheckPolicy) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - out.Spec = in.Spec - out.Status = in.Status - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HealthCheckPolicy. -func (in *HealthCheckPolicy) DeepCopy() *HealthCheckPolicy { - if in == nil { - return nil - } - out := new(HealthCheckPolicy) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *HealthCheckPolicy) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *HealthCheckPolicyList) DeepCopyInto(out *HealthCheckPolicyList) { - *out = *in - out.TypeMeta = in.TypeMeta - out.ListMeta = in.ListMeta - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]HealthCheckPolicy, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HealthCheckPolicyList. -func (in *HealthCheckPolicyList) DeepCopy() *HealthCheckPolicyList { - if in == nil { - return nil - } - out := new(HealthCheckPolicyList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *HealthCheckPolicyList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *HealthCheckPolicySpec) DeepCopyInto(out *HealthCheckPolicySpec) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HealthCheckPolicySpec. -func (in *HealthCheckPolicySpec) DeepCopy() *HealthCheckPolicySpec { - if in == nil { - return nil - } - out := new(HealthCheckPolicySpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *HealthCheckPolicyStatus) DeepCopyInto(out *HealthCheckPolicyStatus) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HealthCheckPolicyStatus. -func (in *HealthCheckPolicyStatus) DeepCopy() *HealthCheckPolicyStatus { - if in == nil { - return nil - } - out := new(HealthCheckPolicyStatus) - in.DeepCopyInto(out) - return out -} diff --git a/testdata/gopath/src/project/pkg/apis/ship/group.go b/testdata/gopath/src/project/pkg/apis/ship/group.go deleted file mode 100644 index 236da88a1da..00000000000 --- a/testdata/gopath/src/project/pkg/apis/ship/group.go +++ /dev/null @@ -1,18 +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 ship contains ship API versions -package ship diff --git a/testdata/gopath/src/project/pkg/apis/ship/v1beta1/doc.go b/testdata/gopath/src/project/pkg/apis/ship/v1beta1/doc.go deleted file mode 100644 index 4749c7ea562..00000000000 --- a/testdata/gopath/src/project/pkg/apis/ship/v1beta1/doc.go +++ /dev/null @@ -1,23 +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 v1beta1 contains API Schema definitions for the ship v1beta1 API group -// +k8s:openapi-gen=true -// +k8s:deepcopy-gen=package,register -// +k8s:conversion-gen=project/pkg/apis/ship -// +k8s:defaulter-gen=TypeMeta -// +groupName=ship.testproject.org -package v1beta1 diff --git a/testdata/gopath/src/project/pkg/apis/ship/v1beta1/frigate_types.go b/testdata/gopath/src/project/pkg/apis/ship/v1beta1/frigate_types.go deleted file mode 100644 index 3fe41e2c70a..00000000000 --- a/testdata/gopath/src/project/pkg/apis/ship/v1beta1/frigate_types.go +++ /dev/null @@ -1,62 +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 v1beta1 - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -// 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. - -// FrigateSpec defines the desired state of Frigate -type FrigateSpec struct { - // INSERT ADDITIONAL SPEC FIELDS - desired state of cluster - // Important: Run "make" to regenerate code after modifying this file -} - -// FrigateStatus defines the observed state of Frigate -type FrigateStatus struct { - // INSERT ADDITIONAL STATUS FIELD - define observed state of cluster - // Important: Run "make" to regenerate code after modifying this file -} - -// +genclient -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// Frigate is the Schema for the frigates API -// +k8s:openapi-gen=true -type Frigate struct { - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata,omitempty"` - - Spec FrigateSpec `json:"spec,omitempty"` - Status FrigateStatus `json:"status,omitempty"` -} - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// FrigateList contains a list of Frigate -type FrigateList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata,omitempty"` - Items []Frigate `json:"items"` -} - -func init() { - SchemeBuilder.Register(&Frigate{}, &FrigateList{}) -} diff --git a/testdata/gopath/src/project/pkg/apis/ship/v1beta1/frigate_types_test.go b/testdata/gopath/src/project/pkg/apis/ship/v1beta1/frigate_types_test.go deleted file mode 100644 index fe285a59e60..00000000000 --- a/testdata/gopath/src/project/pkg/apis/ship/v1beta1/frigate_types_test.go +++ /dev/null @@ -1,58 +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 v1beta1 - -import ( - "testing" - - "github.com/onsi/gomega" - "golang.org/x/net/context" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" -) - -func TestStorageFrigate(t *testing.T) { - key := types.NamespacedName{ - Name: "foo", - Namespace: "default", - } - created := &Frigate{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "default", - }} - g := gomega.NewGomegaWithT(t) - - // Test Create - fetched := &Frigate{} - g.Expect(c.Create(context.TODO(), created)).To(gomega.Succeed()) - - g.Expect(c.Get(context.TODO(), key, fetched)).To(gomega.Succeed()) - g.Expect(fetched).To(gomega.Equal(created)) - - // Test Updating the Labels - updated := fetched.DeepCopy() - updated.Labels = map[string]string{"hello": "world"} - g.Expect(c.Update(context.TODO(), updated)).To(gomega.Succeed()) - - g.Expect(c.Get(context.TODO(), key, fetched)).To(gomega.Succeed()) - g.Expect(fetched).To(gomega.Equal(updated)) - - // Test Delete - g.Expect(c.Delete(context.TODO(), fetched)).To(gomega.Succeed()) - g.Expect(c.Get(context.TODO(), key, fetched)).ToNot(gomega.Succeed()) -} diff --git a/testdata/gopath/src/project/pkg/apis/ship/v1beta1/register.go b/testdata/gopath/src/project/pkg/apis/ship/v1beta1/register.go deleted file mode 100644 index 3ad8ae993a8..00000000000 --- a/testdata/gopath/src/project/pkg/apis/ship/v1beta1/register.go +++ /dev/null @@ -1,46 +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. -*/ - -// NOTE: Boilerplate only. Ignore this file. - -// Package v1beta1 contains API Schema definitions for the ship v1beta1 API group -// +k8s:openapi-gen=true -// +k8s:deepcopy-gen=package,register -// +k8s:conversion-gen=project/pkg/apis/ship -// +k8s:defaulter-gen=TypeMeta -// +groupName=ship.testproject.org -package v1beta1 - -import ( - "k8s.io/apimachinery/pkg/runtime/schema" - "sigs.k8s.io/controller-runtime/pkg/runtime/scheme" -) - -var ( - // SchemeGroupVersion is group version used to register these objects - SchemeGroupVersion = schema.GroupVersion{Group: "ship.testproject.org", Version: "v1beta1"} - - // SchemeBuilder is used to add go types to the GroupVersionKind scheme - SchemeBuilder = &scheme.Builder{GroupVersion: SchemeGroupVersion} - - // AddToScheme is required by pkg/client/... - AddToScheme = SchemeBuilder.AddToScheme -) - -// Resource is required by pkg/client/listers/... -func Resource(resource string) schema.GroupResource { - return SchemeGroupVersion.WithResource(resource).GroupResource() -} diff --git a/testdata/gopath/src/project/pkg/apis/ship/v1beta1/v1beta1_suite_test.go b/testdata/gopath/src/project/pkg/apis/ship/v1beta1/v1beta1_suite_test.go deleted file mode 100644 index 192b395f666..00000000000 --- a/testdata/gopath/src/project/pkg/apis/ship/v1beta1/v1beta1_suite_test.go +++ /dev/null @@ -1,55 +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 v1beta1 - -import ( - "log" - "os" - "path/filepath" - "testing" - - "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" -) - -var cfg *rest.Config -var c client.Client - -func TestMain(m *testing.M) { - t := &envtest.Environment{ - CRDDirectoryPaths: []string{filepath.Join("..", "..", "..", "..", "config", "crds")}, - } - - err := SchemeBuilder.AddToScheme(scheme.Scheme) - if err != nil { - log.Fatal(err) - } - - if cfg, err = t.Start(); err != nil { - log.Fatal(err) - } - - if c, err = client.New(cfg, client.Options{Scheme: scheme.Scheme}); err != nil { - log.Fatal(err) - } - - code := m.Run() - t.Stop() - os.Exit(code) -} diff --git a/testdata/gopath/src/project/pkg/apis/ship/v1beta1/zz_generated.deepcopy.go b/testdata/gopath/src/project/pkg/apis/ship/v1beta1/zz_generated.deepcopy.go deleted file mode 100644 index d5fc144cf3e..00000000000 --- a/testdata/gopath/src/project/pkg/apis/ship/v1beta1/zz_generated.deepcopy.go +++ /dev/null @@ -1,117 +0,0 @@ -// +build !ignore_autogenerated - -/* -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. -*/ -// Code generated by main. DO NOT EDIT. - -package v1beta1 - -import ( - runtime "k8s.io/apimachinery/pkg/runtime" -) - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Frigate) DeepCopyInto(out *Frigate) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - out.Spec = in.Spec - out.Status = in.Status - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Frigate. -func (in *Frigate) DeepCopy() *Frigate { - if in == nil { - return nil - } - out := new(Frigate) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *Frigate) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *FrigateList) DeepCopyInto(out *FrigateList) { - *out = *in - out.TypeMeta = in.TypeMeta - out.ListMeta = in.ListMeta - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]Frigate, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new FrigateList. -func (in *FrigateList) DeepCopy() *FrigateList { - if in == nil { - return nil - } - out := new(FrigateList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *FrigateList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *FrigateSpec) DeepCopyInto(out *FrigateSpec) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new FrigateSpec. -func (in *FrigateSpec) DeepCopy() *FrigateSpec { - if in == nil { - return nil - } - out := new(FrigateSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *FrigateStatus) DeepCopyInto(out *FrigateStatus) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new FrigateStatus. -func (in *FrigateStatus) DeepCopy() *FrigateStatus { - if in == nil { - return nil - } - out := new(FrigateStatus) - in.DeepCopyInto(out) - return out -} diff --git a/testdata/gopath/src/project/pkg/controller/add_firstmate.go b/testdata/gopath/src/project/pkg/controller/add_firstmate.go deleted file mode 100644 index 49c5c1cbdaa..00000000000 --- a/testdata/gopath/src/project/pkg/controller/add_firstmate.go +++ /dev/null @@ -1,26 +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 controller - -import ( - "project/pkg/controller/firstmate" -) - -func init() { - // AddToManagerFuncs is a list of functions to create controllers and add them to a manager. - AddToManagerFuncs = append(AddToManagerFuncs, firstmate.Add) -} diff --git a/testdata/gopath/src/project/pkg/controller/add_frigate.go b/testdata/gopath/src/project/pkg/controller/add_frigate.go deleted file mode 100644 index d311549d15f..00000000000 --- a/testdata/gopath/src/project/pkg/controller/add_frigate.go +++ /dev/null @@ -1,26 +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 controller - -import ( - "project/pkg/controller/frigate" -) - -func init() { - // AddToManagerFuncs is a list of functions to create controllers and add them to a manager. - AddToManagerFuncs = append(AddToManagerFuncs, frigate.Add) -} diff --git a/testdata/gopath/src/project/pkg/controller/add_healthcheckpolicy.go b/testdata/gopath/src/project/pkg/controller/add_healthcheckpolicy.go deleted file mode 100644 index a716b47c785..00000000000 --- a/testdata/gopath/src/project/pkg/controller/add_healthcheckpolicy.go +++ /dev/null @@ -1,26 +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 controller - -import ( - "project/pkg/controller/healthcheckpolicy" -) - -func init() { - // AddToManagerFuncs is a list of functions to create controllers and add them to a manager. - AddToManagerFuncs = append(AddToManagerFuncs, healthcheckpolicy.Add) -} diff --git a/testdata/gopath/src/project/pkg/controller/add_kraken.go b/testdata/gopath/src/project/pkg/controller/add_kraken.go deleted file mode 100644 index 0d7f880e6a7..00000000000 --- a/testdata/gopath/src/project/pkg/controller/add_kraken.go +++ /dev/null @@ -1,26 +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 controller - -import ( - "project/pkg/controller/kraken" -) - -func init() { - // AddToManagerFuncs is a list of functions to create controllers and add them to a manager. - AddToManagerFuncs = append(AddToManagerFuncs, kraken.Add) -} diff --git a/testdata/gopath/src/project/pkg/controller/add_namespace.go b/testdata/gopath/src/project/pkg/controller/add_namespace.go deleted file mode 100644 index 5a78fef4aae..00000000000 --- a/testdata/gopath/src/project/pkg/controller/add_namespace.go +++ /dev/null @@ -1,26 +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 controller - -import ( - "project/pkg/controller/namespace" -) - -func init() { - // AddToManagerFuncs is a list of functions to create controllers and add them to a manager. - AddToManagerFuncs = append(AddToManagerFuncs, namespace.Add) -} diff --git a/testdata/gopath/src/project/pkg/controller/controller.go b/testdata/gopath/src/project/pkg/controller/controller.go deleted file mode 100644 index 4fc3d84211a..00000000000 --- a/testdata/gopath/src/project/pkg/controller/controller.go +++ /dev/null @@ -1,34 +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 controller - -import ( - "sigs.k8s.io/controller-runtime/pkg/manager" -) - -// AddToManagerFuncs is a list of functions to add all Controllers to the Manager -var AddToManagerFuncs []func(manager.Manager) error - -// AddToManager adds all Controllers to the Manager -func AddToManager(m manager.Manager) error { - for _, f := range AddToManagerFuncs { - if err := f(m); err != nil { - return err - } - } - return nil -} diff --git a/testdata/gopath/src/project/pkg/controller/firstmate/firstmate_controller.go b/testdata/gopath/src/project/pkg/controller/firstmate/firstmate_controller.go deleted file mode 100644 index 951dcf23888..00000000000 --- a/testdata/gopath/src/project/pkg/controller/firstmate/firstmate_controller.go +++ /dev/null @@ -1,168 +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 firstmate - -import ( - "context" - "reflect" - - appsv1 "k8s.io/api/apps/v1" - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/types" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/controller" - "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" - "sigs.k8s.io/controller-runtime/pkg/handler" - "sigs.k8s.io/controller-runtime/pkg/manager" - "sigs.k8s.io/controller-runtime/pkg/reconcile" - logf "sigs.k8s.io/controller-runtime/pkg/runtime/log" - "sigs.k8s.io/controller-runtime/pkg/source" - - crewv1 "project/pkg/apis/crew/v1" -) - -var log = logf.Log.WithName("firstmate-controller") - -/** -* USER ACTION REQUIRED: This is a scaffold file intended for the user to modify with their own Controller -* business logic. Delete these comments after modifying this file.* - */ - -// Add creates a new FirstMate Controller and adds it to the Manager with default RBAC. -// The Manager will set fields on the Controller and Start it when the Manager is Started. -func Add(mgr manager.Manager) error { - return add(mgr, newReconciler(mgr)) -} - -// newReconciler returns a new reconcile.Reconciler -func newReconciler(mgr manager.Manager) reconcile.Reconciler { - return &ReconcileFirstMate{Client: mgr.GetClient(), scheme: mgr.GetScheme()} -} - -// add adds a new Controller to mgr with r as the reconcile.Reconciler -func add(mgr manager.Manager, r reconcile.Reconciler) error { - // Create a new controller - c, err := controller.New("firstmate-controller", mgr, controller.Options{Reconciler: r}) - if err != nil { - return err - } - - // Watch for changes to FirstMate - err = c.Watch(&source.Kind{Type: &crewv1.FirstMate{}}, &handler.EnqueueRequestForObject{}) - if err != nil { - return err - } - - // TODO(user): Modify this to be the types you create - // Uncomment watch a Deployment created by FirstMate - change this for objects you create - err = c.Watch(&source.Kind{Type: &appsv1.Deployment{}}, &handler.EnqueueRequestForOwner{ - IsController: true, - OwnerType: &crewv1.FirstMate{}, - }) - if err != nil { - return err - } - - return nil -} - -var _ reconcile.Reconciler = &ReconcileFirstMate{} - -// ReconcileFirstMate reconciles a FirstMate object -type ReconcileFirstMate struct { - client.Client - scheme *runtime.Scheme -} - -// Reconcile reads that state of the cluster for a FirstMate object and makes changes based on the state read -// and what is in the FirstMate.Spec -// TODO(user): Modify this Reconcile function to implement your Controller logic. The scaffolding writes -// a Deployment as an example -// Automatically generate RBAC rules to allow the Controller to read and write Deployments -// +kubebuilder:rbac:groups=apps,resources=deployments,verbs=get;list;watch;create;update;patch;delete -// +kubebuilder:rbac:groups=apps,resources=deployments/status,verbs=get;update;patch -// +kubebuilder:rbac:groups=crew.testproject.org,resources=firstmates,verbs=get;list;watch;create;update;patch;delete -// +kubebuilder:rbac:groups=crew.testproject.org,resources=firstmates/status,verbs=get;update;patch -func (r *ReconcileFirstMate) Reconcile(request reconcile.Request) (reconcile.Result, error) { - // Fetch the FirstMate instance - instance := &crewv1.FirstMate{} - err := r.Get(context.TODO(), request.NamespacedName, instance) - if err != nil { - if errors.IsNotFound(err) { - // Object not found, return. Created objects are automatically garbage collected. - // For additional cleanup logic use finalizers. - return reconcile.Result{}, nil - } - // Error reading the object - requeue the request. - return reconcile.Result{}, err - } - - // TODO(user): Change this to be the object type created by your controller - // Define the desired Deployment object - deploy := &appsv1.Deployment{ - ObjectMeta: metav1.ObjectMeta{ - Name: instance.Name + "-deployment", - Namespace: instance.Namespace, - }, - Spec: appsv1.DeploymentSpec{ - Selector: &metav1.LabelSelector{ - MatchLabels: map[string]string{"deployment": instance.Name + "-deployment"}, - }, - Template: corev1.PodTemplateSpec{ - ObjectMeta: metav1.ObjectMeta{Labels: map[string]string{"deployment": instance.Name + "-deployment"}}, - Spec: corev1.PodSpec{ - Containers: []corev1.Container{ - { - Name: "nginx", - Image: "nginx", - }, - }, - }, - }, - }, - } - if err := controllerutil.SetControllerReference(instance, deploy, r.scheme); err != nil { - return reconcile.Result{}, err - } - - // TODO(user): Change this for the object type created by your controller - // Check if the Deployment already exists - found := &appsv1.Deployment{} - err = r.Get(context.TODO(), types.NamespacedName{Name: deploy.Name, Namespace: deploy.Namespace}, found) - if err != nil && errors.IsNotFound(err) { - log.Info("Creating Deployment", "namespace", deploy.Namespace, "name", deploy.Name) - err = r.Create(context.TODO(), deploy) - return reconcile.Result{}, err - } else if err != nil { - return reconcile.Result{}, err - } - - // TODO(user): Change this for the object type created by your controller - // Update the found object and write the result back if there are any changes - if !reflect.DeepEqual(deploy.Spec, found.Spec) { - found.Spec = deploy.Spec - log.Info("Updating Deployment", "namespace", deploy.Namespace, "name", deploy.Name) - err = r.Update(context.TODO(), found) - if err != nil { - return reconcile.Result{}, err - } - } - return reconcile.Result{}, nil -} diff --git a/testdata/gopath/src/project/pkg/controller/firstmate/firstmate_controller_suite_test.go b/testdata/gopath/src/project/pkg/controller/firstmate/firstmate_controller_suite_test.go deleted file mode 100644 index 6b5f661a5e9..00000000000 --- a/testdata/gopath/src/project/pkg/controller/firstmate/firstmate_controller_suite_test.go +++ /dev/null @@ -1,76 +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 firstmate - -import ( - stdlog "log" - "os" - "path/filepath" - "sync" - "testing" - - "github.com/onsi/gomega" - "k8s.io/client-go/kubernetes/scheme" - "k8s.io/client-go/rest" - "sigs.k8s.io/controller-runtime/pkg/envtest" - "sigs.k8s.io/controller-runtime/pkg/manager" - "sigs.k8s.io/controller-runtime/pkg/reconcile" - - "project/pkg/apis" -) - -var cfg *rest.Config - -func TestMain(m *testing.M) { - t := &envtest.Environment{ - CRDDirectoryPaths: []string{filepath.Join("..", "..", "..", "config", "crds")}, - } - apis.AddToScheme(scheme.Scheme) - - var err error - if cfg, err = t.Start(); err != nil { - stdlog.Fatal(err) - } - - code := m.Run() - t.Stop() - os.Exit(code) -} - -// SetupTestReconcile returns a reconcile.Reconcile implementation that delegates to inner and -// writes the request to requests after Reconcile is finished. -func SetupTestReconcile(inner reconcile.Reconciler) (reconcile.Reconciler, chan reconcile.Request) { - requests := make(chan reconcile.Request) - fn := reconcile.Func(func(req reconcile.Request) (reconcile.Result, error) { - result, err := inner.Reconcile(req) - requests <- req - return result, err - }) - return fn, requests -} - -// StartTestManager adds recFn -func StartTestManager(mgr manager.Manager, g *gomega.GomegaWithT) (chan struct{}, *sync.WaitGroup) { - stop := make(chan struct{}) - wg := &sync.WaitGroup{} - wg.Add(1) - go func() { - defer wg.Done() - g.Expect(mgr.Start(stop)).NotTo(gomega.HaveOccurred()) - }() - return stop, wg -} diff --git a/testdata/gopath/src/project/pkg/controller/firstmate/firstmate_controller_test.go b/testdata/gopath/src/project/pkg/controller/firstmate/firstmate_controller_test.go deleted file mode 100644 index 6e7d191ce3a..00000000000 --- a/testdata/gopath/src/project/pkg/controller/firstmate/firstmate_controller_test.go +++ /dev/null @@ -1,89 +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 firstmate - -import ( - "testing" - "time" - - "github.com/onsi/gomega" - "golang.org/x/net/context" - appsv1 "k8s.io/api/apps/v1" - apierrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/manager" - "sigs.k8s.io/controller-runtime/pkg/reconcile" - - crewv1 "project/pkg/apis/crew/v1" -) - -var c client.Client - -var expectedRequest = reconcile.Request{NamespacedName: types.NamespacedName{Name: "foo", Namespace: "default"}} -var depKey = types.NamespacedName{Name: "foo-deployment", Namespace: "default"} - -const timeout = time.Second * 5 - -func TestReconcile(t *testing.T) { - g := gomega.NewGomegaWithT(t) - instance := &crewv1.FirstMate{ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "default"}} - - // Setup the Manager and Controller. Wrap the Controller Reconcile function so it writes each request to a - // channel when it is finished. - mgr, err := manager.New(cfg, manager.Options{}) - g.Expect(err).NotTo(gomega.HaveOccurred()) - c = mgr.GetClient() - - recFn, requests := SetupTestReconcile(newReconciler(mgr)) - g.Expect(add(mgr, recFn)).To(gomega.Succeed()) - - stopMgr, mgrStopped := StartTestManager(mgr, g) - - defer func() { - close(stopMgr) - mgrStopped.Wait() - }() - - // Create the FirstMate object and expect the Reconcile and Deployment to be created - err = c.Create(context.TODO(), instance) - // The instance object may not be a valid object because it might be missing some required fields. - // Please modify the instance object by adding required fields and then remove the following if statement. - if apierrors.IsInvalid(err) { - t.Logf("failed to create object, got an invalid object error: %v", err) - return - } - g.Expect(err).NotTo(gomega.HaveOccurred()) - defer c.Delete(context.TODO(), instance) - g.Eventually(requests, timeout).Should(gomega.Receive(gomega.Equal(expectedRequest))) - - deploy := &appsv1.Deployment{} - g.Eventually(func() error { return c.Get(context.TODO(), depKey, deploy) }, timeout). - Should(gomega.Succeed()) - - // Delete the Deployment and expect Reconcile to be called for Deployment deletion - g.Expect(c.Delete(context.TODO(), deploy)).To(gomega.Succeed()) - g.Eventually(requests, timeout).Should(gomega.Receive(gomega.Equal(expectedRequest))) - g.Eventually(func() error { return c.Get(context.TODO(), depKey, deploy) }, timeout). - Should(gomega.Succeed()) - - // Manually delete Deployment since GC isn't enabled in the test control plane - g.Eventually(func() error { return c.Delete(context.TODO(), deploy) }, timeout). - Should(gomega.MatchError("deployments.apps \"foo-deployment\" not found")) - -} diff --git a/testdata/gopath/src/project/pkg/controller/frigate/frigate_controller.go b/testdata/gopath/src/project/pkg/controller/frigate/frigate_controller.go deleted file mode 100644 index 87b8a867df1..00000000000 --- a/testdata/gopath/src/project/pkg/controller/frigate/frigate_controller.go +++ /dev/null @@ -1,107 +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 frigate - -import ( - "context" - - appsv1 "k8s.io/api/apps/v1" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/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/manager" - "sigs.k8s.io/controller-runtime/pkg/reconcile" - "sigs.k8s.io/controller-runtime/pkg/source" - - shipv1beta1 "project/pkg/apis/ship/v1beta1" -) - -/** -* USER ACTION REQUIRED: This is a scaffold file intended for the user to modify with their own Controller -* business logic. Delete these comments after modifying this file.* - */ - -// Add creates a new Frigate Controller and adds it to the Manager with default RBAC. -// The Manager will set fields on the Controller and Start it when the Manager is Started. -func Add(mgr manager.Manager) error { - return add(mgr, newReconciler(mgr)) -} - -// newReconciler returns a new reconcile.Reconciler -func newReconciler(mgr manager.Manager) reconcile.Reconciler { - return &ReconcileFrigate{Client: mgr.GetClient(), scheme: mgr.GetScheme()} -} - -// add adds a new Controller to mgr with r as the reconcile.Reconciler -func add(mgr manager.Manager, r reconcile.Reconciler) error { - // Create a new controller - c, err := controller.New("frigate-controller", mgr, controller.Options{Reconciler: r}) - if err != nil { - return err - } - - // Watch for changes to Frigate - err = c.Watch(&source.Kind{Type: &shipv1beta1.Frigate{}}, &handler.EnqueueRequestForObject{}) - if err != nil { - return err - } - - // TODO(user): Modify this to be the types you create - // Uncomment watch a Deployment created by Frigate - change this for objects you create - err = c.Watch(&source.Kind{Type: &appsv1.Deployment{}}, &handler.EnqueueRequestForOwner{ - IsController: true, - OwnerType: &shipv1beta1.Frigate{}, - }) - if err != nil { - return err - } - - return nil -} - -var _ reconcile.Reconciler = &ReconcileFrigate{} - -// ReconcileFrigate reconciles a Frigate object -type ReconcileFrigate struct { - client.Client - scheme *runtime.Scheme -} - -// Reconcile reads that state of the cluster for a Frigate object and makes changes based on the state read -// and what is in the Frigate.Spec -// TODO(user): Modify this Reconcile function to implement your Controller logic. The scaffolding writes -// a Deployment as an example -// +kubebuilder:rbac:groups=ship.testproject.org,resources=frigates,verbs=get;list;watch;create;update;patch;delete -// +kubebuilder:rbac:groups=ship.testproject.org,resources=frigates/status,verbs=get;update;patch -func (r *ReconcileFrigate) Reconcile(request reconcile.Request) (reconcile.Result, error) { - // Fetch the Frigate instance - instance := &shipv1beta1.Frigate{} - err := r.Get(context.TODO(), request.NamespacedName, instance) - if err != nil { - if errors.IsNotFound(err) { - // Object not found, return. Created objects are automatically garbage collected. - // For additional cleanup logic use finalizers. - return reconcile.Result{}, nil - } - // Error reading the object - requeue the request. - return reconcile.Result{}, err - } - - return reconcile.Result{}, nil -} diff --git a/testdata/gopath/src/project/pkg/controller/frigate/frigate_controller_suite_test.go b/testdata/gopath/src/project/pkg/controller/frigate/frigate_controller_suite_test.go deleted file mode 100644 index 3598e5b2fd1..00000000000 --- a/testdata/gopath/src/project/pkg/controller/frigate/frigate_controller_suite_test.go +++ /dev/null @@ -1,76 +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 frigate - -import ( - stdlog "log" - "os" - "path/filepath" - "sync" - "testing" - - "github.com/onsi/gomega" - "k8s.io/client-go/kubernetes/scheme" - "k8s.io/client-go/rest" - "sigs.k8s.io/controller-runtime/pkg/envtest" - "sigs.k8s.io/controller-runtime/pkg/manager" - "sigs.k8s.io/controller-runtime/pkg/reconcile" - - "project/pkg/apis" -) - -var cfg *rest.Config - -func TestMain(m *testing.M) { - t := &envtest.Environment{ - CRDDirectoryPaths: []string{filepath.Join("..", "..", "..", "config", "crds")}, - } - apis.AddToScheme(scheme.Scheme) - - var err error - if cfg, err = t.Start(); err != nil { - stdlog.Fatal(err) - } - - code := m.Run() - t.Stop() - os.Exit(code) -} - -// SetupTestReconcile returns a reconcile.Reconcile implementation that delegates to inner and -// writes the request to requests after Reconcile is finished. -func SetupTestReconcile(inner reconcile.Reconciler) (reconcile.Reconciler, chan reconcile.Request) { - requests := make(chan reconcile.Request) - fn := reconcile.Func(func(req reconcile.Request) (reconcile.Result, error) { - result, err := inner.Reconcile(req) - requests <- req - return result, err - }) - return fn, requests -} - -// StartTestManager adds recFn -func StartTestManager(mgr manager.Manager, g *gomega.GomegaWithT) (chan struct{}, *sync.WaitGroup) { - stop := make(chan struct{}) - wg := &sync.WaitGroup{} - wg.Add(1) - go func() { - defer wg.Done() - g.Expect(mgr.Start(stop)).NotTo(gomega.HaveOccurred()) - }() - return stop, wg -} diff --git a/testdata/gopath/src/project/pkg/controller/frigate/frigate_controller_test.go b/testdata/gopath/src/project/pkg/controller/frigate/frigate_controller_test.go deleted file mode 100644 index 5beae0fc4a1..00000000000 --- a/testdata/gopath/src/project/pkg/controller/frigate/frigate_controller_test.go +++ /dev/null @@ -1,73 +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 frigate - -import ( - "testing" - "time" - - "github.com/onsi/gomega" - "golang.org/x/net/context" - apierrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/manager" - "sigs.k8s.io/controller-runtime/pkg/reconcile" - - shipv1beta1 "project/pkg/apis/ship/v1beta1" -) - -var c client.Client - -var expectedRequest = reconcile.Request{NamespacedName: types.NamespacedName{Name: "foo", Namespace: "default"}} - -const timeout = time.Second * 5 - -func TestReconcile(t *testing.T) { - g := gomega.NewGomegaWithT(t) - instance := &shipv1beta1.Frigate{ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "default"}} - - // Setup the Manager and Controller. Wrap the Controller Reconcile function so it writes each request to a - // channel when it is finished. - mgr, err := manager.New(cfg, manager.Options{}) - g.Expect(err).NotTo(gomega.HaveOccurred()) - c = mgr.GetClient() - - recFn, requests := SetupTestReconcile(newReconciler(mgr)) - g.Expect(add(mgr, recFn)).To(gomega.Succeed()) - - stopMgr, mgrStopped := StartTestManager(mgr, g) - - defer func() { - close(stopMgr) - mgrStopped.Wait() - }() - - // Create the Frigate object and expect the Reconcile - err = c.Create(context.TODO(), instance) - // The instance object may not be a valid object because it might be missing some required fields. - // Please modify the instance object by adding required fields and then remove the following if statement. - if apierrors.IsInvalid(err) { - t.Logf("failed to create object, got an invalid object error: %v", err) - return - } - g.Expect(err).NotTo(gomega.HaveOccurred()) - defer c.Delete(context.TODO(), instance) - g.Eventually(requests, timeout).Should(gomega.Receive(gomega.Equal(expectedRequest))) - -} diff --git a/testdata/gopath/src/project/pkg/controller/healthcheckpolicy/healthcheckpolicy_controller.go b/testdata/gopath/src/project/pkg/controller/healthcheckpolicy/healthcheckpolicy_controller.go deleted file mode 100644 index 78fb4b0d389..00000000000 --- a/testdata/gopath/src/project/pkg/controller/healthcheckpolicy/healthcheckpolicy_controller.go +++ /dev/null @@ -1,107 +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 healthcheckpolicy - -import ( - "context" - - appsv1 "k8s.io/api/apps/v1" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/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/manager" - "sigs.k8s.io/controller-runtime/pkg/reconcile" - "sigs.k8s.io/controller-runtime/pkg/source" - - policyv1beta1 "project/pkg/apis/policy/v1beta1" -) - -/** -* USER ACTION REQUIRED: This is a scaffold file intended for the user to modify with their own Controller -* business logic. Delete these comments after modifying this file.* - */ - -// Add creates a new HealthCheckPolicy Controller and adds it to the Manager with default RBAC. -// The Manager will set fields on the Controller and Start it when the Manager is Started. -func Add(mgr manager.Manager) error { - return add(mgr, newReconciler(mgr)) -} - -// newReconciler returns a new reconcile.Reconciler -func newReconciler(mgr manager.Manager) reconcile.Reconciler { - return &ReconcileHealthCheckPolicy{Client: mgr.GetClient(), scheme: mgr.GetScheme()} -} - -// add adds a new Controller to mgr with r as the reconcile.Reconciler -func add(mgr manager.Manager, r reconcile.Reconciler) error { - // Create a new controller - c, err := controller.New("healthcheckpolicy-controller", mgr, controller.Options{Reconciler: r}) - if err != nil { - return err - } - - // Watch for changes to HealthCheckPolicy - err = c.Watch(&source.Kind{Type: &policyv1beta1.HealthCheckPolicy{}}, &handler.EnqueueRequestForObject{}) - if err != nil { - return err - } - - // TODO(user): Modify this to be the types you create - // Uncomment watch a Deployment created by HealthCheckPolicy - change this for objects you create - err = c.Watch(&source.Kind{Type: &appsv1.Deployment{}}, &handler.EnqueueRequestForOwner{ - IsController: true, - OwnerType: &policyv1beta1.HealthCheckPolicy{}, - }) - if err != nil { - return err - } - - return nil -} - -var _ reconcile.Reconciler = &ReconcileHealthCheckPolicy{} - -// ReconcileHealthCheckPolicy reconciles a HealthCheckPolicy object -type ReconcileHealthCheckPolicy struct { - client.Client - scheme *runtime.Scheme -} - -// Reconcile reads that state of the cluster for a HealthCheckPolicy object and makes changes based on the state read -// and what is in the HealthCheckPolicy.Spec -// TODO(user): Modify this Reconcile function to implement your Controller logic. The scaffolding writes -// a Deployment as an example -// +kubebuilder:rbac:groups=policy.testproject.org,resources=healthcheckpolicies,verbs=get;list;watch;create;update;patch;delete -// +kubebuilder:rbac:groups=policy.testproject.org,resources=healthcheckpolicies/status,verbs=get;update;patch -func (r *ReconcileHealthCheckPolicy) Reconcile(request reconcile.Request) (reconcile.Result, error) { - // Fetch the HealthCheckPolicy instance - instance := &policyv1beta1.HealthCheckPolicy{} - err := r.Get(context.TODO(), request.NamespacedName, instance) - if err != nil { - if errors.IsNotFound(err) { - // Object not found, return. Created objects are automatically garbage collected. - // For additional cleanup logic use finalizers. - return reconcile.Result{}, nil - } - // Error reading the object - requeue the request. - return reconcile.Result{}, err - } - - return reconcile.Result{}, nil -} diff --git a/testdata/gopath/src/project/pkg/controller/healthcheckpolicy/healthcheckpolicy_controller_suite_test.go b/testdata/gopath/src/project/pkg/controller/healthcheckpolicy/healthcheckpolicy_controller_suite_test.go deleted file mode 100644 index 70e428c06e7..00000000000 --- a/testdata/gopath/src/project/pkg/controller/healthcheckpolicy/healthcheckpolicy_controller_suite_test.go +++ /dev/null @@ -1,76 +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 healthcheckpolicy - -import ( - stdlog "log" - "os" - "path/filepath" - "sync" - "testing" - - "github.com/onsi/gomega" - "k8s.io/client-go/kubernetes/scheme" - "k8s.io/client-go/rest" - "sigs.k8s.io/controller-runtime/pkg/envtest" - "sigs.k8s.io/controller-runtime/pkg/manager" - "sigs.k8s.io/controller-runtime/pkg/reconcile" - - "project/pkg/apis" -) - -var cfg *rest.Config - -func TestMain(m *testing.M) { - t := &envtest.Environment{ - CRDDirectoryPaths: []string{filepath.Join("..", "..", "..", "config", "crds")}, - } - apis.AddToScheme(scheme.Scheme) - - var err error - if cfg, err = t.Start(); err != nil { - stdlog.Fatal(err) - } - - code := m.Run() - t.Stop() - os.Exit(code) -} - -// SetupTestReconcile returns a reconcile.Reconcile implementation that delegates to inner and -// writes the request to requests after Reconcile is finished. -func SetupTestReconcile(inner reconcile.Reconciler) (reconcile.Reconciler, chan reconcile.Request) { - requests := make(chan reconcile.Request) - fn := reconcile.Func(func(req reconcile.Request) (reconcile.Result, error) { - result, err := inner.Reconcile(req) - requests <- req - return result, err - }) - return fn, requests -} - -// StartTestManager adds recFn -func StartTestManager(mgr manager.Manager, g *gomega.GomegaWithT) (chan struct{}, *sync.WaitGroup) { - stop := make(chan struct{}) - wg := &sync.WaitGroup{} - wg.Add(1) - go func() { - defer wg.Done() - g.Expect(mgr.Start(stop)).NotTo(gomega.HaveOccurred()) - }() - return stop, wg -} diff --git a/testdata/gopath/src/project/pkg/controller/healthcheckpolicy/healthcheckpolicy_controller_test.go b/testdata/gopath/src/project/pkg/controller/healthcheckpolicy/healthcheckpolicy_controller_test.go deleted file mode 100644 index c475be2ea04..00000000000 --- a/testdata/gopath/src/project/pkg/controller/healthcheckpolicy/healthcheckpolicy_controller_test.go +++ /dev/null @@ -1,73 +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 healthcheckpolicy - -import ( - "testing" - "time" - - "github.com/onsi/gomega" - "golang.org/x/net/context" - apierrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/manager" - "sigs.k8s.io/controller-runtime/pkg/reconcile" - - policyv1beta1 "project/pkg/apis/policy/v1beta1" -) - -var c client.Client - -var expectedRequest = reconcile.Request{NamespacedName: types.NamespacedName{Name: "foo"}} - -const timeout = time.Second * 5 - -func TestReconcile(t *testing.T) { - g := gomega.NewGomegaWithT(t) - instance := &policyv1beta1.HealthCheckPolicy{ObjectMeta: metav1.ObjectMeta{Name: "foo"}} - - // Setup the Manager and Controller. Wrap the Controller Reconcile function so it writes each request to a - // channel when it is finished. - mgr, err := manager.New(cfg, manager.Options{}) - g.Expect(err).NotTo(gomega.HaveOccurred()) - c = mgr.GetClient() - - recFn, requests := SetupTestReconcile(newReconciler(mgr)) - g.Expect(add(mgr, recFn)).To(gomega.Succeed()) - - stopMgr, mgrStopped := StartTestManager(mgr, g) - - defer func() { - close(stopMgr) - mgrStopped.Wait() - }() - - // Create the HealthCheckPolicy object and expect the Reconcile - err = c.Create(context.TODO(), instance) - // The instance object may not be a valid object because it might be missing some required fields. - // Please modify the instance object by adding required fields and then remove the following if statement. - if apierrors.IsInvalid(err) { - t.Logf("failed to create object, got an invalid object error: %v", err) - return - } - g.Expect(err).NotTo(gomega.HaveOccurred()) - defer c.Delete(context.TODO(), instance) - g.Eventually(requests, timeout).Should(gomega.Receive(gomega.Equal(expectedRequest))) - -} diff --git a/testdata/gopath/src/project/pkg/controller/kraken/kraken_controller.go b/testdata/gopath/src/project/pkg/controller/kraken/kraken_controller.go deleted file mode 100644 index dd69a13d84d..00000000000 --- a/testdata/gopath/src/project/pkg/controller/kraken/kraken_controller.go +++ /dev/null @@ -1,107 +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 kraken - -import ( - "context" - - appsv1 "k8s.io/api/apps/v1" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/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/manager" - "sigs.k8s.io/controller-runtime/pkg/reconcile" - "sigs.k8s.io/controller-runtime/pkg/source" - - creaturesv2alpha1 "project/pkg/apis/creatures/v2alpha1" -) - -/** -* USER ACTION REQUIRED: This is a scaffold file intended for the user to modify with their own Controller -* business logic. Delete these comments after modifying this file.* - */ - -// Add creates a new Kraken Controller and adds it to the Manager with default RBAC. -// The Manager will set fields on the Controller and Start it when the Manager is Started. -func Add(mgr manager.Manager) error { - return add(mgr, newReconciler(mgr)) -} - -// newReconciler returns a new reconcile.Reconciler -func newReconciler(mgr manager.Manager) reconcile.Reconciler { - return &ReconcileKraken{Client: mgr.GetClient(), scheme: mgr.GetScheme()} -} - -// add adds a new Controller to mgr with r as the reconcile.Reconciler -func add(mgr manager.Manager, r reconcile.Reconciler) error { - // Create a new controller - c, err := controller.New("kraken-controller", mgr, controller.Options{Reconciler: r}) - if err != nil { - return err - } - - // Watch for changes to Kraken - err = c.Watch(&source.Kind{Type: &creaturesv2alpha1.Kraken{}}, &handler.EnqueueRequestForObject{}) - if err != nil { - return err - } - - // TODO(user): Modify this to be the types you create - // Uncomment watch a Deployment created by Kraken - change this for objects you create - err = c.Watch(&source.Kind{Type: &appsv1.Deployment{}}, &handler.EnqueueRequestForOwner{ - IsController: true, - OwnerType: &creaturesv2alpha1.Kraken{}, - }) - if err != nil { - return err - } - - return nil -} - -var _ reconcile.Reconciler = &ReconcileKraken{} - -// ReconcileKraken reconciles a Kraken object -type ReconcileKraken struct { - client.Client - scheme *runtime.Scheme -} - -// Reconcile reads that state of the cluster for a Kraken object and makes changes based on the state read -// and what is in the Kraken.Spec -// TODO(user): Modify this Reconcile function to implement your Controller logic. The scaffolding writes -// a Deployment as an example -// +kubebuilder:rbac:groups=creatures.testproject.org,resources=krakens,verbs=get;list;watch;create;update;patch;delete -// +kubebuilder:rbac:groups=creatures.testproject.org,resources=krakens/status,verbs=get;update;patch -func (r *ReconcileKraken) Reconcile(request reconcile.Request) (reconcile.Result, error) { - // Fetch the Kraken instance - instance := &creaturesv2alpha1.Kraken{} - err := r.Get(context.TODO(), request.NamespacedName, instance) - if err != nil { - if errors.IsNotFound(err) { - // Object not found, return. Created objects are automatically garbage collected. - // For additional cleanup logic use finalizers. - return reconcile.Result{}, nil - } - // Error reading the object - requeue the request. - return reconcile.Result{}, err - } - - return reconcile.Result{}, nil -} diff --git a/testdata/gopath/src/project/pkg/controller/kraken/kraken_controller_suite_test.go b/testdata/gopath/src/project/pkg/controller/kraken/kraken_controller_suite_test.go deleted file mode 100644 index 3061742bba5..00000000000 --- a/testdata/gopath/src/project/pkg/controller/kraken/kraken_controller_suite_test.go +++ /dev/null @@ -1,76 +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 kraken - -import ( - stdlog "log" - "os" - "path/filepath" - "sync" - "testing" - - "github.com/onsi/gomega" - "k8s.io/client-go/kubernetes/scheme" - "k8s.io/client-go/rest" - "sigs.k8s.io/controller-runtime/pkg/envtest" - "sigs.k8s.io/controller-runtime/pkg/manager" - "sigs.k8s.io/controller-runtime/pkg/reconcile" - - "project/pkg/apis" -) - -var cfg *rest.Config - -func TestMain(m *testing.M) { - t := &envtest.Environment{ - CRDDirectoryPaths: []string{filepath.Join("..", "..", "..", "config", "crds")}, - } - apis.AddToScheme(scheme.Scheme) - - var err error - if cfg, err = t.Start(); err != nil { - stdlog.Fatal(err) - } - - code := m.Run() - t.Stop() - os.Exit(code) -} - -// SetupTestReconcile returns a reconcile.Reconcile implementation that delegates to inner and -// writes the request to requests after Reconcile is finished. -func SetupTestReconcile(inner reconcile.Reconciler) (reconcile.Reconciler, chan reconcile.Request) { - requests := make(chan reconcile.Request) - fn := reconcile.Func(func(req reconcile.Request) (reconcile.Result, error) { - result, err := inner.Reconcile(req) - requests <- req - return result, err - }) - return fn, requests -} - -// StartTestManager adds recFn -func StartTestManager(mgr manager.Manager, g *gomega.GomegaWithT) (chan struct{}, *sync.WaitGroup) { - stop := make(chan struct{}) - wg := &sync.WaitGroup{} - wg.Add(1) - go func() { - defer wg.Done() - g.Expect(mgr.Start(stop)).NotTo(gomega.HaveOccurred()) - }() - return stop, wg -} diff --git a/testdata/gopath/src/project/pkg/controller/kraken/kraken_controller_test.go b/testdata/gopath/src/project/pkg/controller/kraken/kraken_controller_test.go deleted file mode 100644 index 5453238f3ea..00000000000 --- a/testdata/gopath/src/project/pkg/controller/kraken/kraken_controller_test.go +++ /dev/null @@ -1,73 +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 kraken - -import ( - "testing" - "time" - - "github.com/onsi/gomega" - "golang.org/x/net/context" - apierrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/manager" - "sigs.k8s.io/controller-runtime/pkg/reconcile" - - creaturesv2alpha1 "project/pkg/apis/creatures/v2alpha1" -) - -var c client.Client - -var expectedRequest = reconcile.Request{NamespacedName: types.NamespacedName{Name: "foo"}} - -const timeout = time.Second * 5 - -func TestReconcile(t *testing.T) { - g := gomega.NewGomegaWithT(t) - instance := &creaturesv2alpha1.Kraken{ObjectMeta: metav1.ObjectMeta{Name: "foo"}} - - // Setup the Manager and Controller. Wrap the Controller Reconcile function so it writes each request to a - // channel when it is finished. - mgr, err := manager.New(cfg, manager.Options{}) - g.Expect(err).NotTo(gomega.HaveOccurred()) - c = mgr.GetClient() - - recFn, requests := SetupTestReconcile(newReconciler(mgr)) - g.Expect(add(mgr, recFn)).To(gomega.Succeed()) - - stopMgr, mgrStopped := StartTestManager(mgr, g) - - defer func() { - close(stopMgr) - mgrStopped.Wait() - }() - - // Create the Kraken object and expect the Reconcile - err = c.Create(context.TODO(), instance) - // The instance object may not be a valid object because it might be missing some required fields. - // Please modify the instance object by adding required fields and then remove the following if statement. - if apierrors.IsInvalid(err) { - t.Logf("failed to create object, got an invalid object error: %v", err) - return - } - g.Expect(err).NotTo(gomega.HaveOccurred()) - defer c.Delete(context.TODO(), instance) - g.Eventually(requests, timeout).Should(gomega.Receive(gomega.Equal(expectedRequest))) - -} diff --git a/testdata/gopath/src/project/pkg/controller/namespace/namespace_controller.go b/testdata/gopath/src/project/pkg/controller/namespace/namespace_controller.go deleted file mode 100644 index 91be9177255..00000000000 --- a/testdata/gopath/src/project/pkg/controller/namespace/namespace_controller.go +++ /dev/null @@ -1,106 +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 namespace - -import ( - "context" - - appsv1 "k8s.io/api/apps/v1" - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/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/manager" - "sigs.k8s.io/controller-runtime/pkg/reconcile" - "sigs.k8s.io/controller-runtime/pkg/source" -) - -/** -* USER ACTION REQUIRED: This is a scaffold file intended for the user to modify with their own Controller -* business logic. Delete these comments after modifying this file.* - */ - -// Add creates a new Namespace Controller and adds it to the Manager with default RBAC. -// The Manager will set fields on the Controller and Start it when the Manager is Started. -func Add(mgr manager.Manager) error { - return add(mgr, newReconciler(mgr)) -} - -// newReconciler returns a new reconcile.Reconciler -func newReconciler(mgr manager.Manager) reconcile.Reconciler { - return &ReconcileNamespace{Client: mgr.GetClient(), scheme: mgr.GetScheme()} -} - -// add adds a new Controller to mgr with r as the reconcile.Reconciler -func add(mgr manager.Manager, r reconcile.Reconciler) error { - // Create a new controller - c, err := controller.New("namespace-controller", mgr, controller.Options{Reconciler: r}) - if err != nil { - return err - } - - // Watch for changes to Namespace - err = c.Watch(&source.Kind{Type: &corev1.Namespace{}}, &handler.EnqueueRequestForObject{}) - if err != nil { - return err - } - - // TODO(user): Modify this to be the types you create - // Uncomment watch a Deployment created by Namespace - change this for objects you create - err = c.Watch(&source.Kind{Type: &appsv1.Deployment{}}, &handler.EnqueueRequestForOwner{ - IsController: true, - OwnerType: &corev1.Namespace{}, - }) - if err != nil { - return err - } - - return nil -} - -var _ reconcile.Reconciler = &ReconcileNamespace{} - -// ReconcileNamespace reconciles a Namespace object -type ReconcileNamespace struct { - client.Client - scheme *runtime.Scheme -} - -// Reconcile reads that state of the cluster for a Namespace object and makes changes based on the state read -// and what is in the Namespace.Spec -// TODO(user): Modify this Reconcile function to implement your Controller logic. The scaffolding writes -// a Deployment as an example -// +kubebuilder:rbac:groups=core,resources=namespaces,verbs=get;list;watch;create;update;patch;delete -// +kubebuilder:rbac:groups=core,resources=namespaces/status,verbs=get;update;patch -func (r *ReconcileNamespace) Reconcile(request reconcile.Request) (reconcile.Result, error) { - // Fetch the Namespace instance - instance := &corev1.Namespace{} - err := r.Get(context.TODO(), request.NamespacedName, instance) - if err != nil { - if errors.IsNotFound(err) { - // Object not found, return. Created objects are automatically garbage collected. - // For additional cleanup logic use finalizers. - return reconcile.Result{}, nil - } - // Error reading the object - requeue the request. - return reconcile.Result{}, err - } - - return reconcile.Result{}, nil -} diff --git a/testdata/gopath/src/project/pkg/controller/namespace/namespace_controller_suite_test.go b/testdata/gopath/src/project/pkg/controller/namespace/namespace_controller_suite_test.go deleted file mode 100644 index e4443287f49..00000000000 --- a/testdata/gopath/src/project/pkg/controller/namespace/namespace_controller_suite_test.go +++ /dev/null @@ -1,76 +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 namespace - -import ( - stdlog "log" - "os" - "path/filepath" - "sync" - "testing" - - "github.com/onsi/gomega" - "k8s.io/client-go/kubernetes/scheme" - "k8s.io/client-go/rest" - "sigs.k8s.io/controller-runtime/pkg/envtest" - "sigs.k8s.io/controller-runtime/pkg/manager" - "sigs.k8s.io/controller-runtime/pkg/reconcile" - - "project/pkg/apis" -) - -var cfg *rest.Config - -func TestMain(m *testing.M) { - t := &envtest.Environment{ - CRDDirectoryPaths: []string{filepath.Join("..", "..", "..", "config", "crds")}, - } - apis.AddToScheme(scheme.Scheme) - - var err error - if cfg, err = t.Start(); err != nil { - stdlog.Fatal(err) - } - - code := m.Run() - t.Stop() - os.Exit(code) -} - -// SetupTestReconcile returns a reconcile.Reconcile implementation that delegates to inner and -// writes the request to requests after Reconcile is finished. -func SetupTestReconcile(inner reconcile.Reconciler) (reconcile.Reconciler, chan reconcile.Request) { - requests := make(chan reconcile.Request) - fn := reconcile.Func(func(req reconcile.Request) (reconcile.Result, error) { - result, err := inner.Reconcile(req) - requests <- req - return result, err - }) - return fn, requests -} - -// StartTestManager adds recFn -func StartTestManager(mgr manager.Manager, g *gomega.GomegaWithT) (chan struct{}, *sync.WaitGroup) { - stop := make(chan struct{}) - wg := &sync.WaitGroup{} - wg.Add(1) - go func() { - defer wg.Done() - g.Expect(mgr.Start(stop)).NotTo(gomega.HaveOccurred()) - }() - return stop, wg -} diff --git a/testdata/gopath/src/project/pkg/controller/namespace/namespace_controller_test.go b/testdata/gopath/src/project/pkg/controller/namespace/namespace_controller_test.go deleted file mode 100644 index 6badd00fe0a..00000000000 --- a/testdata/gopath/src/project/pkg/controller/namespace/namespace_controller_test.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 namespace - -import ( - "testing" - "time" - - "github.com/onsi/gomega" - "golang.org/x/net/context" - corev1 "k8s.io/api/core/v1" - apierrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/manager" - "sigs.k8s.io/controller-runtime/pkg/reconcile" -) - -var c client.Client - -var expectedRequest = reconcile.Request{NamespacedName: types.NamespacedName{Name: "foo"}} - -const timeout = time.Second * 5 - -func TestReconcile(t *testing.T) { - g := gomega.NewGomegaWithT(t) - instance := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "foo"}} - - // Setup the Manager and Controller. Wrap the Controller Reconcile function so it writes each request to a - // channel when it is finished. - mgr, err := manager.New(cfg, manager.Options{}) - g.Expect(err).NotTo(gomega.HaveOccurred()) - c = mgr.GetClient() - - recFn, requests := SetupTestReconcile(newReconciler(mgr)) - g.Expect(add(mgr, recFn)).To(gomega.Succeed()) - - stopMgr, mgrStopped := StartTestManager(mgr, g) - - defer func() { - close(stopMgr) - mgrStopped.Wait() - }() - - // Create the Namespace object and expect the Reconcile - err = c.Create(context.TODO(), instance) - // The instance object may not be a valid object because it might be missing some required fields. - // Please modify the instance object by adding required fields and then remove the following if statement. - if apierrors.IsInvalid(err) { - t.Logf("failed to create object, got an invalid object error: %v", err) - return - } - g.Expect(err).NotTo(gomega.HaveOccurred()) - defer c.Delete(context.TODO(), instance) - g.Eventually(requests, timeout).Should(gomega.Receive(gomega.Equal(expectedRequest))) - -} diff --git a/testdata/gopath/src/project/pkg/webhook/add_default_server.go b/testdata/gopath/src/project/pkg/webhook/add_default_server.go deleted file mode 100644 index 6d5e2193423..00000000000 --- a/testdata/gopath/src/project/pkg/webhook/add_default_server.go +++ /dev/null @@ -1,26 +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 ( - server "project/pkg/webhook/default_server" -) - -func init() { - // AddToManagerFuncs is a list of functions to create webhook servers and add them to a manager. - AddToManagerFuncs = append(AddToManagerFuncs, server.Add) -} diff --git a/testdata/gopath/src/project/pkg/webhook/default_server/add_mutating_firstmate.go b/testdata/gopath/src/project/pkg/webhook/default_server/add_mutating_firstmate.go deleted file mode 100644 index d5b92d06a66..00000000000 --- a/testdata/gopath/src/project/pkg/webhook/default_server/add_mutating_firstmate.go +++ /dev/null @@ -1,48 +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 defaultserver - -import ( - "fmt" - - "project/pkg/webhook/default_server/firstmate/mutating" -) - -func init() { - for k, v := range mutating.Builders { - _, found := builderMap[k] - if found { - log.V(1).Info(fmt.Sprintf( - "conflicting webhook builder names in builder map: %v", k)) - } - builderMap[k] = v - } - for k, v := range mutating.HandlerMap { - _, found := HandlerMap[k] - if found { - log.V(1).Info(fmt.Sprintf( - "conflicting webhook builder names in handler map: %v", k)) - } - _, found = builderMap[k] - if !found { - log.V(1).Info(fmt.Sprintf( - "can't find webhook builder name %q in builder map", k)) - continue - } - HandlerMap[k] = v - } -} diff --git a/testdata/gopath/src/project/pkg/webhook/default_server/add_mutating_namespace.go b/testdata/gopath/src/project/pkg/webhook/default_server/add_mutating_namespace.go deleted file mode 100644 index 763a137be21..00000000000 --- a/testdata/gopath/src/project/pkg/webhook/default_server/add_mutating_namespace.go +++ /dev/null @@ -1,48 +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 defaultserver - -import ( - "fmt" - - "project/pkg/webhook/default_server/namespace/mutating" -) - -func init() { - for k, v := range mutating.Builders { - _, found := builderMap[k] - if found { - log.V(1).Info(fmt.Sprintf( - "conflicting webhook builder names in builder map: %v", k)) - } - builderMap[k] = v - } - for k, v := range mutating.HandlerMap { - _, found := HandlerMap[k] - if found { - log.V(1).Info(fmt.Sprintf( - "conflicting webhook builder names in handler map: %v", k)) - } - _, found = builderMap[k] - if !found { - log.V(1).Info(fmt.Sprintf( - "can't find webhook builder name %q in builder map", k)) - continue - } - HandlerMap[k] = v - } -} diff --git a/testdata/gopath/src/project/pkg/webhook/default_server/add_validating_frigate.go b/testdata/gopath/src/project/pkg/webhook/default_server/add_validating_frigate.go deleted file mode 100644 index 0b8073a3c10..00000000000 --- a/testdata/gopath/src/project/pkg/webhook/default_server/add_validating_frigate.go +++ /dev/null @@ -1,48 +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 defaultserver - -import ( - "fmt" - - "project/pkg/webhook/default_server/frigate/validating" -) - -func init() { - for k, v := range validating.Builders { - _, found := builderMap[k] - if found { - log.V(1).Info(fmt.Sprintf( - "conflicting webhook builder names in builder map: %v", k)) - } - builderMap[k] = v - } - for k, v := range validating.HandlerMap { - _, found := HandlerMap[k] - if found { - log.V(1).Info(fmt.Sprintf( - "conflicting webhook builder names in handler map: %v", k)) - } - _, found = builderMap[k] - if !found { - log.V(1).Info(fmt.Sprintf( - "can't find webhook builder name %q in builder map", k)) - continue - } - HandlerMap[k] = v - } -} diff --git a/testdata/gopath/src/project/pkg/webhook/default_server/add_validating_kraken.go b/testdata/gopath/src/project/pkg/webhook/default_server/add_validating_kraken.go deleted file mode 100644 index 65bd75d1423..00000000000 --- a/testdata/gopath/src/project/pkg/webhook/default_server/add_validating_kraken.go +++ /dev/null @@ -1,48 +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 defaultserver - -import ( - "fmt" - - "project/pkg/webhook/default_server/kraken/validating" -) - -func init() { - for k, v := range validating.Builders { - _, found := builderMap[k] - if found { - log.V(1).Info(fmt.Sprintf( - "conflicting webhook builder names in builder map: %v", k)) - } - builderMap[k] = v - } - for k, v := range validating.HandlerMap { - _, found := HandlerMap[k] - if found { - log.V(1).Info(fmt.Sprintf( - "conflicting webhook builder names in handler map: %v", k)) - } - _, found = builderMap[k] - if !found { - log.V(1).Info(fmt.Sprintf( - "can't find webhook builder name %q in builder map", k)) - continue - } - HandlerMap[k] = v - } -} diff --git a/testdata/gopath/src/project/pkg/webhook/default_server/firstmate/mutating/create_update_webhook.go b/testdata/gopath/src/project/pkg/webhook/default_server/firstmate/mutating/create_update_webhook.go deleted file mode 100644 index b226ca78e3f..00000000000 --- a/testdata/gopath/src/project/pkg/webhook/default_server/firstmate/mutating/create_update_webhook.go +++ /dev/null @@ -1,36 +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 mutating - -import ( - admissionregistrationv1beta1 "k8s.io/api/admissionregistration/v1beta1" - "sigs.k8s.io/controller-runtime/pkg/webhook/admission/builder" - - crewv1 "project/pkg/apis/crew/v1" -) - -func init() { - builderName := "mutating-create-update-firstmate" - Builders[builderName] = builder. - NewWebhookBuilder(). - Name(builderName+".testproject.org"). - Path("/"+builderName). - Mutating(). - Operations(admissionregistrationv1beta1.Create, admissionregistrationv1beta1.Update). - FailurePolicy(admissionregistrationv1beta1.Fail). - ForType(&crewv1.FirstMate{}) -} diff --git a/testdata/gopath/src/project/pkg/webhook/default_server/firstmate/mutating/delete_webhook.go b/testdata/gopath/src/project/pkg/webhook/default_server/firstmate/mutating/delete_webhook.go deleted file mode 100644 index e6b4bb3bb2f..00000000000 --- a/testdata/gopath/src/project/pkg/webhook/default_server/firstmate/mutating/delete_webhook.go +++ /dev/null @@ -1,36 +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 mutating - -import ( - admissionregistrationv1beta1 "k8s.io/api/admissionregistration/v1beta1" - "sigs.k8s.io/controller-runtime/pkg/webhook/admission/builder" - - crewv1 "project/pkg/apis/crew/v1" -) - -func init() { - builderName := "mutating-delete-firstmate" - Builders[builderName] = builder. - NewWebhookBuilder(). - Name(builderName + ".testproject.org"). - Path("/" + builderName). - Mutating(). - Operations(admissionregistrationv1beta1.Delete). - FailurePolicy(admissionregistrationv1beta1.Fail). - ForType(&crewv1.FirstMate{}) -} diff --git a/testdata/gopath/src/project/pkg/webhook/default_server/firstmate/mutating/firstmate_create_update_handler.go b/testdata/gopath/src/project/pkg/webhook/default_server/firstmate/mutating/firstmate_create_update_handler.go deleted file mode 100644 index bb9275df4e3..00000000000 --- a/testdata/gopath/src/project/pkg/webhook/default_server/firstmate/mutating/firstmate_create_update_handler.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 mutating - -import ( - "context" - "net/http" - - "sigs.k8s.io/controller-runtime/pkg/runtime/inject" - "sigs.k8s.io/controller-runtime/pkg/webhook/admission" - "sigs.k8s.io/controller-runtime/pkg/webhook/admission/types" - - crewv1 "project/pkg/apis/crew/v1" -) - -func init() { - webhookName := "mutating-create-update-firstmate" - if HandlerMap[webhookName] == nil { - HandlerMap[webhookName] = []admission.Handler{} - } - HandlerMap[webhookName] = append(HandlerMap[webhookName], &FirstMateCreateUpdateHandler{}) -} - -// FirstMateCreateUpdateHandler handles FirstMate -type FirstMateCreateUpdateHandler struct { - // To use the client, you need to do the following: - // - uncomment it - // - import sigs.k8s.io/controller-runtime/pkg/client - // - uncomment the InjectClient method at the bottom of this file. - // Client client.Client - - // Decoder decodes objects - Decoder types.Decoder -} - -func (h *FirstMateCreateUpdateHandler) mutatingFirstMateFn(ctx context.Context, obj *crewv1.FirstMate) error { - // TODO(user): implement your admission logic - return nil -} - -var _ admission.Handler = &FirstMateCreateUpdateHandler{} - -// Handle handles admission requests. -func (h *FirstMateCreateUpdateHandler) Handle(ctx context.Context, req types.Request) types.Response { - obj := &crewv1.FirstMate{} - - err := h.Decoder.Decode(req, obj) - if err != nil { - return admission.ErrorResponse(http.StatusBadRequest, err) - } - copy := obj.DeepCopy() - - err = h.mutatingFirstMateFn(ctx, copy) - if err != nil { - return admission.ErrorResponse(http.StatusInternalServerError, err) - } - return admission.PatchResponse(obj, copy) -} - -//var _ inject.Client = &FirstMateCreateUpdateHandler{} -// -//// InjectClient injects the client into the FirstMateCreateUpdateHandler -//func (h *FirstMateCreateUpdateHandler) InjectClient(c client.Client) error { -// h.Client = c -// return nil -//} - -var _ inject.Decoder = &FirstMateCreateUpdateHandler{} - -// InjectDecoder injects the decoder into the FirstMateCreateUpdateHandler -func (h *FirstMateCreateUpdateHandler) InjectDecoder(d types.Decoder) error { - h.Decoder = d - return nil -} diff --git a/testdata/gopath/src/project/pkg/webhook/default_server/firstmate/mutating/firstmate_delete_handler.go b/testdata/gopath/src/project/pkg/webhook/default_server/firstmate/mutating/firstmate_delete_handler.go deleted file mode 100644 index 7147f369e59..00000000000 --- a/testdata/gopath/src/project/pkg/webhook/default_server/firstmate/mutating/firstmate_delete_handler.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 mutating - -import ( - "context" - "net/http" - - "sigs.k8s.io/controller-runtime/pkg/runtime/inject" - "sigs.k8s.io/controller-runtime/pkg/webhook/admission" - "sigs.k8s.io/controller-runtime/pkg/webhook/admission/types" - - crewv1 "project/pkg/apis/crew/v1" -) - -func init() { - webhookName := "mutating-delete-firstmate" - if HandlerMap[webhookName] == nil { - HandlerMap[webhookName] = []admission.Handler{} - } - HandlerMap[webhookName] = append(HandlerMap[webhookName], &FirstMateDeleteHandler{}) -} - -// FirstMateDeleteHandler handles FirstMate -type FirstMateDeleteHandler struct { - // To use the client, you need to do the following: - // - uncomment it - // - import sigs.k8s.io/controller-runtime/pkg/client - // - uncomment the InjectClient method at the bottom of this file. - // Client client.Client - - // Decoder decodes objects - Decoder types.Decoder -} - -func (h *FirstMateDeleteHandler) mutatingFirstMateFn(ctx context.Context, obj *crewv1.FirstMate) error { - // TODO(user): implement your admission logic - return nil -} - -var _ admission.Handler = &FirstMateDeleteHandler{} - -// Handle handles admission requests. -func (h *FirstMateDeleteHandler) Handle(ctx context.Context, req types.Request) types.Response { - obj := &crewv1.FirstMate{} - - err := h.Decoder.Decode(req, obj) - if err != nil { - return admission.ErrorResponse(http.StatusBadRequest, err) - } - copy := obj.DeepCopy() - - err = h.mutatingFirstMateFn(ctx, copy) - if err != nil { - return admission.ErrorResponse(http.StatusInternalServerError, err) - } - return admission.PatchResponse(obj, copy) -} - -//var _ inject.Client = &FirstMateDeleteHandler{} -// -//// InjectClient injects the client into the FirstMateDeleteHandler -//func (h *FirstMateDeleteHandler) InjectClient(c client.Client) error { -// h.Client = c -// return nil -//} - -var _ inject.Decoder = &FirstMateDeleteHandler{} - -// InjectDecoder injects the decoder into the FirstMateDeleteHandler -func (h *FirstMateDeleteHandler) InjectDecoder(d types.Decoder) error { - h.Decoder = d - return nil -} diff --git a/testdata/gopath/src/project/pkg/webhook/default_server/firstmate/mutating/webhooks.go b/testdata/gopath/src/project/pkg/webhook/default_server/firstmate/mutating/webhooks.go deleted file mode 100644 index bf37f7ab4f2..00000000000 --- a/testdata/gopath/src/project/pkg/webhook/default_server/firstmate/mutating/webhooks.go +++ /dev/null @@ -1,29 +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 mutating - -import ( - "sigs.k8s.io/controller-runtime/pkg/webhook/admission" - "sigs.k8s.io/controller-runtime/pkg/webhook/admission/builder" -) - -var ( - // Builders contain admission webhook builders - Builders = map[string]*builder.WebhookBuilder{} - // HandlerMap contains admission webhook handlers - HandlerMap = map[string][]admission.Handler{} -) diff --git a/testdata/gopath/src/project/pkg/webhook/default_server/frigate/validating/frigate_update_handler.go b/testdata/gopath/src/project/pkg/webhook/default_server/frigate/validating/frigate_update_handler.go deleted file mode 100644 index 62352ac15b3..00000000000 --- a/testdata/gopath/src/project/pkg/webhook/default_server/frigate/validating/frigate_update_handler.go +++ /dev/null @@ -1,87 +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 validating - -import ( - "context" - "net/http" - - "sigs.k8s.io/controller-runtime/pkg/runtime/inject" - "sigs.k8s.io/controller-runtime/pkg/webhook/admission" - "sigs.k8s.io/controller-runtime/pkg/webhook/admission/types" - - shipv1beta1 "project/pkg/apis/ship/v1beta1" -) - -func init() { - webhookName := "validating-update-frigate" - if HandlerMap[webhookName] == nil { - HandlerMap[webhookName] = []admission.Handler{} - } - HandlerMap[webhookName] = append(HandlerMap[webhookName], &FrigateUpdateHandler{}) -} - -// FrigateUpdateHandler handles Frigate -type FrigateUpdateHandler struct { - // To use the client, you need to do the following: - // - uncomment it - // - import sigs.k8s.io/controller-runtime/pkg/client - // - uncomment the InjectClient method at the bottom of this file. - // Client client.Client - - // Decoder decodes objects - Decoder types.Decoder -} - -func (h *FrigateUpdateHandler) validatingFrigateFn(ctx context.Context, obj *shipv1beta1.Frigate) (bool, string, error) { - // TODO(user): implement your admission logic - return true, "allowed to be admitted", nil -} - -var _ admission.Handler = &FrigateUpdateHandler{} - -// Handle handles admission requests. -func (h *FrigateUpdateHandler) Handle(ctx context.Context, req types.Request) types.Response { - obj := &shipv1beta1.Frigate{} - - err := h.Decoder.Decode(req, obj) - if err != nil { - return admission.ErrorResponse(http.StatusBadRequest, err) - } - - allowed, reason, err := h.validatingFrigateFn(ctx, obj) - if err != nil { - return admission.ErrorResponse(http.StatusInternalServerError, err) - } - return admission.ValidationResponse(allowed, reason) -} - -//var _ inject.Client = &FrigateUpdateHandler{} -// -//// InjectClient injects the client into the FrigateUpdateHandler -//func (h *FrigateUpdateHandler) InjectClient(c client.Client) error { -// h.Client = c -// return nil -//} - -var _ inject.Decoder = &FrigateUpdateHandler{} - -// InjectDecoder injects the decoder into the FrigateUpdateHandler -func (h *FrigateUpdateHandler) InjectDecoder(d types.Decoder) error { - h.Decoder = d - return nil -} diff --git a/testdata/gopath/src/project/pkg/webhook/default_server/frigate/validating/update_webhook.go b/testdata/gopath/src/project/pkg/webhook/default_server/frigate/validating/update_webhook.go deleted file mode 100644 index e0187628ed1..00000000000 --- a/testdata/gopath/src/project/pkg/webhook/default_server/frigate/validating/update_webhook.go +++ /dev/null @@ -1,36 +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 validating - -import ( - admissionregistrationv1beta1 "k8s.io/api/admissionregistration/v1beta1" - "sigs.k8s.io/controller-runtime/pkg/webhook/admission/builder" - - shipv1beta1 "project/pkg/apis/ship/v1beta1" -) - -func init() { - builderName := "validating-update-frigate" - Builders[builderName] = builder. - NewWebhookBuilder(). - Name(builderName + ".testproject.org"). - Path("/" + builderName). - Validating(). - Operations(admissionregistrationv1beta1.Update). - FailurePolicy(admissionregistrationv1beta1.Fail). - ForType(&shipv1beta1.Frigate{}) -} diff --git a/testdata/gopath/src/project/pkg/webhook/default_server/frigate/validating/webhooks.go b/testdata/gopath/src/project/pkg/webhook/default_server/frigate/validating/webhooks.go deleted file mode 100644 index ac19d661388..00000000000 --- a/testdata/gopath/src/project/pkg/webhook/default_server/frigate/validating/webhooks.go +++ /dev/null @@ -1,29 +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 validating - -import ( - "sigs.k8s.io/controller-runtime/pkg/webhook/admission" - "sigs.k8s.io/controller-runtime/pkg/webhook/admission/builder" -) - -var ( - // Builders contain admission webhook builders - Builders = map[string]*builder.WebhookBuilder{} - // HandlerMap contains admission webhook handlers - HandlerMap = map[string][]admission.Handler{} -) diff --git a/testdata/gopath/src/project/pkg/webhook/default_server/kraken/validating/create_webhook.go b/testdata/gopath/src/project/pkg/webhook/default_server/kraken/validating/create_webhook.go deleted file mode 100644 index e895ad1c767..00000000000 --- a/testdata/gopath/src/project/pkg/webhook/default_server/kraken/validating/create_webhook.go +++ /dev/null @@ -1,36 +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 validating - -import ( - admissionregistrationv1beta1 "k8s.io/api/admissionregistration/v1beta1" - "sigs.k8s.io/controller-runtime/pkg/webhook/admission/builder" - - creaturesv2alpha1 "project/pkg/apis/creatures/v2alpha1" -) - -func init() { - builderName := "validating-create-kraken" - Builders[builderName] = builder. - NewWebhookBuilder(). - Name(builderName + ".testproject.org"). - Path("/" + builderName). - Validating(). - Operations(admissionregistrationv1beta1.Create). - FailurePolicy(admissionregistrationv1beta1.Fail). - ForType(&creaturesv2alpha1.Kraken{}) -} diff --git a/testdata/gopath/src/project/pkg/webhook/default_server/kraken/validating/kraken_create_handler.go b/testdata/gopath/src/project/pkg/webhook/default_server/kraken/validating/kraken_create_handler.go deleted file mode 100644 index 743bddbf68d..00000000000 --- a/testdata/gopath/src/project/pkg/webhook/default_server/kraken/validating/kraken_create_handler.go +++ /dev/null @@ -1,87 +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 validating - -import ( - "context" - "net/http" - - "sigs.k8s.io/controller-runtime/pkg/runtime/inject" - "sigs.k8s.io/controller-runtime/pkg/webhook/admission" - "sigs.k8s.io/controller-runtime/pkg/webhook/admission/types" - - creaturesv2alpha1 "project/pkg/apis/creatures/v2alpha1" -) - -func init() { - webhookName := "validating-create-kraken" - if HandlerMap[webhookName] == nil { - HandlerMap[webhookName] = []admission.Handler{} - } - HandlerMap[webhookName] = append(HandlerMap[webhookName], &KrakenCreateHandler{}) -} - -// KrakenCreateHandler handles Kraken -type KrakenCreateHandler struct { - // To use the client, you need to do the following: - // - uncomment it - // - import sigs.k8s.io/controller-runtime/pkg/client - // - uncomment the InjectClient method at the bottom of this file. - // Client client.Client - - // Decoder decodes objects - Decoder types.Decoder -} - -func (h *KrakenCreateHandler) validatingKrakenFn(ctx context.Context, obj *creaturesv2alpha1.Kraken) (bool, string, error) { - // TODO(user): implement your admission logic - return true, "allowed to be admitted", nil -} - -var _ admission.Handler = &KrakenCreateHandler{} - -// Handle handles admission requests. -func (h *KrakenCreateHandler) Handle(ctx context.Context, req types.Request) types.Response { - obj := &creaturesv2alpha1.Kraken{} - - err := h.Decoder.Decode(req, obj) - if err != nil { - return admission.ErrorResponse(http.StatusBadRequest, err) - } - - allowed, reason, err := h.validatingKrakenFn(ctx, obj) - if err != nil { - return admission.ErrorResponse(http.StatusInternalServerError, err) - } - return admission.ValidationResponse(allowed, reason) -} - -//var _ inject.Client = &KrakenCreateHandler{} -// -//// InjectClient injects the client into the KrakenCreateHandler -//func (h *KrakenCreateHandler) InjectClient(c client.Client) error { -// h.Client = c -// return nil -//} - -var _ inject.Decoder = &KrakenCreateHandler{} - -// InjectDecoder injects the decoder into the KrakenCreateHandler -func (h *KrakenCreateHandler) InjectDecoder(d types.Decoder) error { - h.Decoder = d - return nil -} diff --git a/testdata/gopath/src/project/pkg/webhook/default_server/kraken/validating/webhooks.go b/testdata/gopath/src/project/pkg/webhook/default_server/kraken/validating/webhooks.go deleted file mode 100644 index ac19d661388..00000000000 --- a/testdata/gopath/src/project/pkg/webhook/default_server/kraken/validating/webhooks.go +++ /dev/null @@ -1,29 +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 validating - -import ( - "sigs.k8s.io/controller-runtime/pkg/webhook/admission" - "sigs.k8s.io/controller-runtime/pkg/webhook/admission/builder" -) - -var ( - // Builders contain admission webhook builders - Builders = map[string]*builder.WebhookBuilder{} - // HandlerMap contains admission webhook handlers - HandlerMap = map[string][]admission.Handler{} -) diff --git a/testdata/gopath/src/project/pkg/webhook/default_server/namespace/mutating/namespace_update_handler.go b/testdata/gopath/src/project/pkg/webhook/default_server/namespace/mutating/namespace_update_handler.go deleted file mode 100644 index be800d3a957..00000000000 --- a/testdata/gopath/src/project/pkg/webhook/default_server/namespace/mutating/namespace_update_handler.go +++ /dev/null @@ -1,87 +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 mutating - -import ( - "context" - "net/http" - - corev1 "k8s.io/api/core/v1" - "sigs.k8s.io/controller-runtime/pkg/runtime/inject" - "sigs.k8s.io/controller-runtime/pkg/webhook/admission" - "sigs.k8s.io/controller-runtime/pkg/webhook/admission/types" -) - -func init() { - webhookName := "mutating-update-namespace" - if HandlerMap[webhookName] == nil { - HandlerMap[webhookName] = []admission.Handler{} - } - HandlerMap[webhookName] = append(HandlerMap[webhookName], &NamespaceUpdateHandler{}) -} - -// NamespaceUpdateHandler handles Namespace -type NamespaceUpdateHandler struct { - // To use the client, you need to do the following: - // - uncomment it - // - import sigs.k8s.io/controller-runtime/pkg/client - // - uncomment the InjectClient method at the bottom of this file. - // Client client.Client - - // Decoder decodes objects - Decoder types.Decoder -} - -func (h *NamespaceUpdateHandler) mutatingNamespaceFn(ctx context.Context, obj *corev1.Namespace) error { - // TODO(user): implement your admission logic - return nil -} - -var _ admission.Handler = &NamespaceUpdateHandler{} - -// Handle handles admission requests. -func (h *NamespaceUpdateHandler) Handle(ctx context.Context, req types.Request) types.Response { - obj := &corev1.Namespace{} - - err := h.Decoder.Decode(req, obj) - if err != nil { - return admission.ErrorResponse(http.StatusBadRequest, err) - } - copy := obj.DeepCopy() - - err = h.mutatingNamespaceFn(ctx, copy) - if err != nil { - return admission.ErrorResponse(http.StatusInternalServerError, err) - } - return admission.PatchResponse(obj, copy) -} - -//var _ inject.Client = &NamespaceUpdateHandler{} -// -//// InjectClient injects the client into the NamespaceUpdateHandler -//func (h *NamespaceUpdateHandler) InjectClient(c client.Client) error { -// h.Client = c -// return nil -//} - -var _ inject.Decoder = &NamespaceUpdateHandler{} - -// InjectDecoder injects the decoder into the NamespaceUpdateHandler -func (h *NamespaceUpdateHandler) InjectDecoder(d types.Decoder) error { - h.Decoder = d - return nil -} diff --git a/testdata/gopath/src/project/pkg/webhook/default_server/namespace/mutating/update_webhook.go b/testdata/gopath/src/project/pkg/webhook/default_server/namespace/mutating/update_webhook.go deleted file mode 100644 index 84331cc975c..00000000000 --- a/testdata/gopath/src/project/pkg/webhook/default_server/namespace/mutating/update_webhook.go +++ /dev/null @@ -1,35 +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 mutating - -import ( - admissionregistrationv1beta1 "k8s.io/api/admissionregistration/v1beta1" - corev1 "k8s.io/api/core/v1" - "sigs.k8s.io/controller-runtime/pkg/webhook/admission/builder" -) - -func init() { - builderName := "mutating-update-namespace" - Builders[builderName] = builder. - NewWebhookBuilder(). - Name(builderName + ".testproject.org"). - Path("/" + builderName). - Mutating(). - Operations(admissionregistrationv1beta1.Update). - FailurePolicy(admissionregistrationv1beta1.Fail). - ForType(&corev1.Namespace{}) -} diff --git a/testdata/gopath/src/project/pkg/webhook/default_server/namespace/mutating/webhooks.go b/testdata/gopath/src/project/pkg/webhook/default_server/namespace/mutating/webhooks.go deleted file mode 100644 index bf37f7ab4f2..00000000000 --- a/testdata/gopath/src/project/pkg/webhook/default_server/namespace/mutating/webhooks.go +++ /dev/null @@ -1,29 +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 mutating - -import ( - "sigs.k8s.io/controller-runtime/pkg/webhook/admission" - "sigs.k8s.io/controller-runtime/pkg/webhook/admission/builder" -) - -var ( - // Builders contain admission webhook builders - Builders = map[string]*builder.WebhookBuilder{} - // HandlerMap contains admission webhook handlers - HandlerMap = map[string][]admission.Handler{} -) diff --git a/testdata/gopath/src/project/pkg/webhook/default_server/server.go b/testdata/gopath/src/project/pkg/webhook/default_server/server.go deleted file mode 100644 index 242ebb8221e..00000000000 --- a/testdata/gopath/src/project/pkg/webhook/default_server/server.go +++ /dev/null @@ -1,91 +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 defaultserver - -import ( - "fmt" - "os" - - "k8s.io/apimachinery/pkg/types" - "sigs.k8s.io/controller-runtime/pkg/manager" - logf "sigs.k8s.io/controller-runtime/pkg/runtime/log" - "sigs.k8s.io/controller-runtime/pkg/webhook" - "sigs.k8s.io/controller-runtime/pkg/webhook/admission" - "sigs.k8s.io/controller-runtime/pkg/webhook/admission/builder" -) - -var ( - log = logf.Log.WithName("default_server") - builderMap = map[string]*builder.WebhookBuilder{} - // HandlerMap contains all admission webhook handlers. - HandlerMap = map[string][]admission.Handler{} -) - -// Add adds itself to the manager -func Add(mgr manager.Manager) error { - ns := os.Getenv("POD_NAMESPACE") - if len(ns) == 0 { - ns = "default" - } - secretName := os.Getenv("SECRET_NAME") - if len(secretName) == 0 { - secretName = "webhook-server-secret" - } - - svr, err := webhook.NewServer("foo-admission-server", mgr, webhook.ServerOptions{ - // TODO(user): change the configuration of ServerOptions based on your need. - Port: 9876, - CertDir: "/tmp/cert", - BootstrapOptions: &webhook.BootstrapOptions{ - Secret: &types.NamespacedName{ - Namespace: ns, - Name: secretName, - }, - - Service: &webhook.Service{ - Namespace: ns, - Name: "webhook-server-service", - // Selectors should select the pods that runs this webhook server. - Selectors: map[string]string{ - "control-plane": "controller-manager", - }, - }, - }, - }) - if err != nil { - return err - } - - var webhooks []webhook.Webhook - for k, builder := range builderMap { - handlers, ok := HandlerMap[k] - if !ok { - log.V(1).Info(fmt.Sprintf("can't find handlers for builder: %v", k)) - handlers = []admission.Handler{} - } - wh, err := builder. - Handlers(handlers...). - WithManager(mgr). - Build() - if err != nil { - return err - } - webhooks = append(webhooks, wh) - } - - return svr.Register(webhooks...) -} diff --git a/testdata/gopath/src/project/pkg/webhook/webhook.go b/testdata/gopath/src/project/pkg/webhook/webhook.go deleted file mode 100644 index 646d6d5f953..00000000000 --- a/testdata/gopath/src/project/pkg/webhook/webhook.go +++ /dev/null @@ -1,37 +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 ( - "sigs.k8s.io/controller-runtime/pkg/manager" -) - -// AddToManagerFuncs is a list of functions to add all Controllers to the Manager -var AddToManagerFuncs []func(manager.Manager) error - -// AddToManager adds all Controllers to the Manager -// +kubebuilder:rbac:groups=admissionregistration.k8s.io,resources=mutatingwebhookconfigurations;validatingwebhookconfigurations,verbs=get;list;watch;create;update;patch;delete -// +kubebuilder:rbac:groups="",resources=secrets,verbs=get;list;watch;create;update;patch;delete -// +kubebuilder:rbac:groups="",resources=services,verbs=get;list;watch;create;update;patch;delete -func AddToManager(m manager.Manager) error { - for _, f := range AddToManagerFuncs { - if err := f(m); err != nil { - return err - } - } - return nil -}