Skip to content

Commit 4461e43

Browse files
checking with master
1 parent d8434a8 commit 4461e43

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

43 files changed

+199
-102
lines changed

pkg/model/resource/utils.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,10 +24,13 @@ import (
2424
"github.com/gobuffalo/flect"
2525
)
2626

27+
const V1beta1 = "v1beta1"
28+
const V1 = "v1"
29+
2730
// validateAPIVersion validates CRD or Webhook versions
2831
func validateAPIVersion(version string) error {
2932
switch version {
30-
case "v1beta1", "v1":
33+
case V1beta1, V1:
3134
return nil
3235
default:
3336
return fmt.Errorf("API version must be one of: v1beta1, v1")

pkg/plugins/golang/v3/api.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import (
2121
"errors"
2222
"fmt"
2323
"os"
24+
"sigs.k8s.io/kubebuilder/v3/pkg/utils"
2425

2526
"github.com/spf13/pflag"
2627

@@ -182,6 +183,28 @@ func (p *createAPISubcommand) Scaffold(fs machinery.Filesystem) error {
182183
}
183184

184185
func (p *createAPISubcommand) PostScaffold() error {
186+
187+
// Update the makefile to allow generate CRD to ensure backwards compatibility
188+
// todo: it should be removed for go/v4
189+
if p.config.ResourcesLength() == 1 && p.resource.API.CRDVersion == "V1beta1" {
190+
const makefileTarget = `$(CONTROLLER_GEN) rbac:roleName=manager-role crd webhook paths="./..." output:crd:artifacts:config=config/crd/bases`
191+
const makefileTargetForV1beta1 = `$(CONTROLLER_GEN) $(CRD_OPTIONS) rbac:roleName=manager-role webhook paths="./..." output:crd:artifacts:config=config/crd/bases`
192+
193+
utils.ReplaceInFile("makefile", makefileTarget, makefileTargetForV1beta1)
194+
195+
const makegentarget = `
196+
manifests: controller-gen`
197+
const makegenV1beta1Options = `# Produce CRDs that work back to Kubernetes 1.11 (no version conversion)
198+
CRD_OPTIONS ?= "crd:trivialVersions=true,preserveUnknownFields=false"
199+
manifests: controller-gen`
200+
201+
utils.ReplaceInFile("makefile", makegentarget, makegenV1beta1Options)
202+
203+
const controllerToolsVersionForVBeta1 = "v0.6.2"
204+
utils.ReplaceInFile("makefile", fmt.Sprintf("controller-gen@%s", scaffolds.ControllerToolsVersion), controllerToolsVersionForVBeta1)
205+
206+
}
207+
185208
err := util.RunCmd("Update dependencies", "go", "mod", "tidy")
186209
if err != nil {
187210
return err

pkg/plugins/golang/v3/scaffolds/init.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ const (
3232
// ControllerRuntimeVersion is the kubernetes-sigs/controller-runtime version to be used in the project
3333
ControllerRuntimeVersion = "v0.10.0"
3434
// ControllerToolsVersion is the kubernetes-sigs/controller-tools version to be used in the project
35-
ControllerToolsVersion = "v0.6.1"
35+
ControllerToolsVersion = "master"
3636
// KustomizeVersion is the kubernetes-sigs/kustomize version to be used in the project
3737
KustomizeVersion = "v3.8.7"
3838

pkg/plugins/golang/v3/scaffolds/internal/templates/api/webhook.go

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,9 @@ type Webhook struct { // nolint:maligned
3636
// Is the Group domain for the Resource replacing '.' with '-'
3737
QualifiedGroupWithDash string
3838

39+
// Define value for AdmissionReviewVersions marker
40+
AdmissionReviewVersions string
41+
3942
Force bool
4043
}
4144

@@ -70,6 +73,11 @@ func (f *Webhook) SetTemplateDefaults() error {
7073
f.IfExistsAction = machinery.Error
7174
}
7275

76+
f.AdmissionReviewVersions = "v1"
77+
if f.Resource.Webhooks.WebhookVersion == "v1beta1" {
78+
f.AdmissionReviewVersions = "{v1,v1beta1}"
79+
}
80+
7381
f.QualifiedGroupWithDash = strings.Replace(f.Resource.QualifiedGroup(), ".", "-", -1)
7482

7583
return nil
@@ -103,10 +111,9 @@ func (r *{{ .Resource.Kind }}) SetupWebhookWithManager(mgr ctrl.Manager) error {
103111
// EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN!
104112
`
105113

106-
// TODO(estroz): update admissionReviewVersions to include v1 when controller-runtime supports that version.
107114
//nolint:lll
108115
defaultingWebhookTemplate = `
109-
//+kubebuilder:webhook:{{ if ne .Resource.Webhooks.WebhookVersion "v1" }}webhookVersions={{"{"}}{{ .Resource.Webhooks.WebhookVersion }}{{"}"}},{{ end }}path=/mutate-{{ .QualifiedGroupWithDash }}-{{ .Resource.Version }}-{{ lower .Resource.Kind }},mutating=true,failurePolicy=fail,sideEffects=None,groups={{ .Resource.QualifiedGroup }},resources={{ .Resource.Plural }},verbs=create;update,versions={{ .Resource.Version }},name=m{{ lower .Resource.Kind }}.kb.io,admissionReviewVersions={v1,v1beta1}
116+
//+kubebuilder:webhook:{{ if ne .Resource.Webhooks.WebhookVersion "v1" }}webhookVersions={{"{"}}{{ .Resource.Webhooks.WebhookVersion }}{{"}"}},{{ end }}path=/mutate-{{ .QualifiedGroupWithDash }}-{{ .Resource.Version }}-{{ lower .Resource.Kind }},mutating=true,failurePolicy=fail,sideEffects=None,groups={{ .Resource.QualifiedGroup }},resources={{ .Resource.Plural }},verbs=create;update,versions={{ .Resource.Version }},name=m{{ lower .Resource.Kind }}.kb.io,admissionReviewVersions={{ .AdmissionReviewVersions }}
110117
111118
var _ webhook.Defaulter = &{{ .Resource.Kind }}{}
112119
@@ -118,11 +125,10 @@ func (r *{{ .Resource.Kind }}) Default() {
118125
}
119126
`
120127

121-
// TODO(estroz): update admissionReviewVersions to include v1 when controller-runtime supports that version.
122128
//nolint:lll
123129
validatingWebhookTemplate = `
124130
// TODO(user): change verbs to "verbs=create;update;delete" if you want to enable deletion validation.
125-
//+kubebuilder:webhook:{{ if ne .Resource.Webhooks.WebhookVersion "v1" }}webhookVersions={{"{"}}{{ .Resource.Webhooks.WebhookVersion }}{{"}"}},{{ end }}path=/validate-{{ .QualifiedGroupWithDash }}-{{ .Resource.Version }}-{{ lower .Resource.Kind }},mutating=false,failurePolicy=fail,sideEffects=None,groups={{ .Resource.QualifiedGroup }},resources={{ .Resource.Plural }},verbs=create;update,versions={{ .Resource.Version }},name=v{{ lower .Resource.Kind }}.kb.io,admissionReviewVersions={v1,v1beta1}
131+
//+kubebuilder:webhook:{{ if ne .Resource.Webhooks.WebhookVersion "v1" }}webhookVersions={{"{"}}{{ .Resource.Webhooks.WebhookVersion }}{{"}"}},{{ end }}path=/validate-{{ .QualifiedGroupWithDash }}-{{ .Resource.Version }}-{{ lower .Resource.Kind }},mutating=false,failurePolicy=fail,sideEffects=None,groups={{ .Resource.QualifiedGroup }},resources={{ .Resource.Plural }},verbs=create;update,versions={{ .Resource.Version }},name=v{{ lower .Resource.Kind }}.kb.io,admissionReviewVersions={{ .AdmissionReviewVersions }}
126132
127133
var _ webhook.Validator = &{{ .Resource.Kind }}{}
128134

pkg/plugins/golang/v3/scaffolds/internal/templates/makefile.go

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,9 @@ type Makefile struct {
3333
BoilerplatePath string
3434
// Controller tools version to use in the project
3535
ControllerToolsVersion string
36+
// Controller tools version to use when the v1beta1 is scaffold to ensure
37+
// backwards compatibility
38+
ControllerToolsVersionForVBeta1 string
3639
// Kustomize version to use in the project
3740
KustomizeVersion string
3841
// ControllerRuntimeVersion version to be used to download the envtest setup script
@@ -60,8 +63,6 @@ func (f *Makefile) SetTemplateDefaults() error {
6063
const makefileTemplate = `
6164
# Image URL to use all building/pushing image targets
6265
IMG ?= {{ .Image }}
63-
# Produce CRDs that work back to Kubernetes 1.11 (no version conversion)
64-
CRD_OPTIONS ?= "crd:trivialVersions=true,preserveUnknownFields=false"
6566
# ENVTEST_K8S_VERSION refers to the version of kubebuilder assets to be downloaded by envtest binary.
6667
ENVTEST_K8S_VERSION = 1.21
6768
@@ -99,7 +100,7 @@ help: ## Display this help.
99100
##@ Development
100101
101102
manifests: controller-gen ## Generate WebhookConfiguration, ClusterRole and CustomResourceDefinition objects.
102-
$(CONTROLLER_GEN) $(CRD_OPTIONS) rbac:roleName=manager-role webhook paths="./..." output:crd:artifacts:config=config/crd/bases
103+
$(CONTROLLER_GEN) rbac:roleName=manager-role crd webhook paths="./..." output:crd:artifacts:config=config/crd/bases
103104
104105
generate: controller-gen ## Generate code containing DeepCopy, DeepCopyInto, and DeepCopyObject method implementations.
105106
$(CONTROLLER_GEN) object:headerFile={{printf "%q" .BoilerplatePath}} paths="./..."

pkg/plugins/golang/v3/webhook.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,7 @@ package v3
1818

1919
import (
2020
"fmt"
21-
2221
"github.com/spf13/pflag"
23-
2422
"sigs.k8s.io/kubebuilder/v3/pkg/config"
2523
"sigs.k8s.io/kubebuilder/v3/pkg/machinery"
2624
"sigs.k8s.io/kubebuilder/v3/pkg/model/resource"
@@ -122,3 +120,4 @@ func (p *createWebhookSubcommand) Scaffold(fs machinery.Filesystem) error {
122120
scaffolder.InjectFS(fs)
123121
return scaffolder.Scaffold()
124122
}
123+

test/e2e/utils/util.go renamed to pkg/utils/util.go

Lines changed: 65 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,15 @@ limitations under the License.
1717
package utils
1818

1919
import (
20+
"bufio"
2021
"bytes"
2122
"crypto/rand"
23+
"errors"
2224
"fmt"
2325
"io/ioutil"
2426
"math/big"
27+
"os"
28+
"regexp"
2529
"strings"
2630
)
2731

@@ -83,7 +87,7 @@ func UncommentCode(filename, target, prefix string) error {
8387

8488
idx := strings.Index(strContent, target)
8589
if idx < 0 {
86-
return nil
90+
return fmt.Errorf("unable to find the code %s to be uncomment", target)
8791
}
8892

8993
out := new(bytes.Buffer)
@@ -92,12 +96,22 @@ func UncommentCode(filename, target, prefix string) error {
9296
return err
9397
}
9498

95-
strs := strings.Split(target, "\n")
96-
for _, str := range strs {
97-
_, err := out.WriteString(strings.TrimPrefix(str, prefix) + "\n")
99+
scanner := bufio.NewScanner(bytes.NewBufferString(target))
100+
if !scanner.Scan() {
101+
return nil
102+
}
103+
for {
104+
_, err := out.WriteString(strings.TrimPrefix(scanner.Text(), prefix))
98105
if err != nil {
99106
return err
100107
}
108+
// Avoid writing a newline in case the previous line was the last in target.
109+
if !scanner.Scan() {
110+
break
111+
}
112+
if _, err := out.WriteString("\n"); err != nil {
113+
return err
114+
}
101115
}
102116

103117
_, err = out.Write(content[idx+len(target):])
@@ -168,3 +182,50 @@ func EnsureExistAndReplace(input, match, replace string) (string, error) {
168182
}
169183
return strings.Replace(input, match, replace, -1), nil
170184
}
185+
186+
// ReplaceInFile replaces all instances of old with new in the file at path.
187+
func ReplaceInFile(path, old, new string) error {
188+
info, err := os.Stat(path)
189+
if err != nil {
190+
return err
191+
}
192+
b, err := ioutil.ReadFile(path)
193+
if err != nil {
194+
return err
195+
}
196+
if !strings.Contains(string(b), old) {
197+
return errors.New("unable to find the content to be replaced")
198+
}
199+
s := strings.Replace(string(b), old, new, -1)
200+
err = ioutil.WriteFile(path, []byte(s), info.Mode())
201+
if err != nil {
202+
return err
203+
}
204+
return nil
205+
}
206+
207+
// ReplaceRegexInFile finds all strings that match `match` and replaces them
208+
// with `replace` in the file at path.
209+
func ReplaceRegexInFile(path, match, replace string) error {
210+
matcher, err := regexp.Compile(match)
211+
if err != nil {
212+
return err
213+
}
214+
info, err := os.Stat(path)
215+
if err != nil {
216+
return err
217+
}
218+
b, err := ioutil.ReadFile(path)
219+
if err != nil {
220+
return err
221+
}
222+
s := matcher.ReplaceAllString(string(b), replace)
223+
if s == string(b) {
224+
return errors.New("unable to find the content to be replaced")
225+
}
226+
err = ioutil.WriteFile(path, []byte(s), info.Mode())
227+
if err != nil {
228+
return err
229+
}
230+
return nil
231+
}

test/e2e/utils/test_context.go

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,11 @@ package utils
1919
import (
2020
"fmt"
2121
"io"
22+
"io/ioutil"
2223
"os"
2324
"os/exec"
2425
"path/filepath"
26+
"sigs.k8s.io/kubebuilder/v3/pkg/utils"
2527
"strings"
2628

2729
. "github.com/onsi/ginkgo" //nolint:golint,revive
@@ -45,7 +47,7 @@ type TestContext struct {
4547
// NewTestContext init with a random suffix for test TestContext stuff,
4648
// to avoid conflict when running tests synchronously.
4749
func NewTestContext(binaryName string, env ...string) (*TestContext, error) {
48-
testSuffix, err := RandomSuffix()
50+
testSuffix, err := utils.RandomSuffix()
4951
if err != nil {
5052
return nil, err
5153
}
@@ -274,3 +276,22 @@ func (cc *CmdContext) Run(cmd *exec.Cmd) ([]byte, error) {
274276

275277
return output, nil
276278
}
279+
280+
281+
// AllowProjectBeMultiGroup will update the PROJECT file with the information to allow we scaffold
282+
// apis with different groups. be available.
283+
func (t *TestContext) AllowProjectBeMultiGroup() error {
284+
const multiGroup = `multigroup: true
285+
`
286+
projectBytes, err := ioutil.ReadFile(filepath.Join(t.Dir, "PROJECT"))
287+
if err != nil {
288+
return err
289+
}
290+
291+
projectBytes = append([]byte(multiGroup), projectBytes...)
292+
err = ioutil.WriteFile(filepath.Join(t.Dir, "PROJECT"), projectBytes, 0644)
293+
if err != nil {
294+
return err
295+
}
296+
return nil
297+
}

test/e2e/v2/plugin_cluster_test.go

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import (
2121
"fmt"
2222
"os"
2323
"path/filepath"
24+
utils2 "sigs.k8s.io/kubebuilder/v3/pkg/utils"
2425
"strconv"
2526
"strings"
2627
"time"
@@ -40,7 +41,7 @@ var _ = Describe("kubebuilder", func() {
4041
var kbc *utils.TestContext
4142
BeforeEach(func() {
4243
var err error
43-
kbc, err = utils.NewTestContext(utils.KubebuilderBinName, "GO111MODULE=on")
44+
kbc, err = utils.NewTestContext(utils2.KubebuilderBinName, "GO111MODULE=on")
4445
Expect(err).NotTo(HaveOccurred())
4546
Expect(kbc.Prepare()).To(Succeed())
4647

@@ -89,7 +90,7 @@ var _ = Describe("kubebuilder", func() {
8990
Expect(err).Should(Succeed())
9091

9192
By("implementing the API")
92-
Expect(utils.InsertCode(
93+
Expect(utils2.InsertCode(
9394
filepath.Join(kbc.Dir, "api", kbc.Version, fmt.Sprintf("%s_types.go", strings.ToLower(kbc.Kind))),
9495
fmt.Sprintf(`type %sSpec struct {
9596
`, kbc.Kind),
@@ -107,28 +108,28 @@ var _ = Describe("kubebuilder", func() {
107108
Expect(err).Should(Succeed())
108109

109110
By("implementing the mutating and validating webhooks")
110-
err = utils.ImplementWebhooks(filepath.Join(
111+
err = utils2.ImplementWebhooks(filepath.Join(
111112
kbc.Dir, "api", kbc.Version,
112113
fmt.Sprintf("%s_webhook.go", strings.ToLower(kbc.Kind))))
113114
Expect(err).Should(Succeed())
114115

115116
By("uncomment kustomization.yaml to enable webhook and ca injection")
116-
Expect(utils.UncommentCode(
117+
Expect(utils2.UncommentCode(
117118
filepath.Join(kbc.Dir, "config", "default", "kustomization.yaml"),
118119
"#- ../webhook", "#")).To(Succeed())
119-
Expect(utils.UncommentCode(
120+
Expect(utils2.UncommentCode(
120121
filepath.Join(kbc.Dir, "config", "default", "kustomization.yaml"),
121122
"#- ../certmanager", "#")).To(Succeed())
122-
Expect(utils.UncommentCode(
123+
Expect(utils2.UncommentCode(
123124
filepath.Join(kbc.Dir, "config", "default", "kustomization.yaml"),
124125
"#- ../prometheus", "#")).To(Succeed())
125-
Expect(utils.UncommentCode(
126+
Expect(utils2.UncommentCode(
126127
filepath.Join(kbc.Dir, "config", "default", "kustomization.yaml"),
127128
"#- manager_webhook_patch.yaml", "#")).To(Succeed())
128-
Expect(utils.UncommentCode(
129+
Expect(utils2.UncommentCode(
129130
filepath.Join(kbc.Dir, "config", "default", "kustomization.yaml"),
130131
"#- webhookcainjection_patch.yaml", "#")).To(Succeed())
131-
Expect(utils.UncommentCode(filepath.Join(kbc.Dir, "config", "default", "kustomization.yaml"),
132+
Expect(utils2.UncommentCode(filepath.Join(kbc.Dir, "config", "default", "kustomization.yaml"),
132133
`#- name: CERTIFICATE_NAMESPACE # namespace of the certificate CR
133134
# objref:
134135
# kind: Certificate
@@ -182,7 +183,7 @@ var _ = Describe("kubebuilder", func() {
182183
"-o", "go-template={{ range .items }}{{ if not .metadata.deletionTimestamp }}{{ .metadata.name }}"+
183184
"{{ \"\\n\" }}{{ end }}{{ end }}")
184185
Expect(err).NotTo(HaveOccurred())
185-
podNames := utils.GetNonEmptyLines(podOutput)
186+
podNames := utils2.GetNonEmptyLines(podOutput)
186187
if len(podNames) != 1 {
187188
return fmt.Errorf("expect 1 controller pods running, but got %d", len(podNames))
188189
}

0 commit comments

Comments
 (0)