Skip to content

Commit 7872d12

Browse files
committed
Declarative plugin
Signed-off-by: Adrian Orive Oneca <[email protected]>
1 parent 3f27f2a commit 7872d12

File tree

11 files changed

+568
-15
lines changed

11 files changed

+568
-15
lines changed

cmd/main.go

+2
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import (
2222
"sigs.k8s.io/kubebuilder/v3/pkg/cli"
2323
cfgv2 "sigs.k8s.io/kubebuilder/v3/pkg/config/v2"
2424
cfgv3 "sigs.k8s.io/kubebuilder/v3/pkg/config/v3"
25+
declarativev1 "sigs.k8s.io/kubebuilder/v3/pkg/plugins/declarative/v1"
2526
pluginv2 "sigs.k8s.io/kubebuilder/v3/pkg/plugins/golang/v2"
2627
pluginv3 "sigs.k8s.io/kubebuilder/v3/pkg/plugins/golang/v3"
2728
)
@@ -34,6 +35,7 @@ func main() {
3435
cli.WithPlugins(
3536
&pluginv2.Plugin{},
3637
&pluginv3.Plugin{},
38+
&declarativev1.Plugin{},
3739
),
3840
cli.WithDefaultPlugins(cfgv2.Version, &pluginv2.Plugin{}),
3941
cli.WithDefaultPlugins(cfgv3.Version, &pluginv3.Plugin{}),

pkg/plugins/declarative/v1/api.go

+107
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
/*
2+
Copyright 2021 The Kubernetes Authors.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package v1
18+
19+
import (
20+
"fmt"
21+
"path/filepath"
22+
"strings"
23+
24+
"github.com/spf13/afero"
25+
26+
"sigs.k8s.io/kubebuilder/v3/pkg/config"
27+
"sigs.k8s.io/kubebuilder/v3/pkg/model"
28+
"sigs.k8s.io/kubebuilder/v3/pkg/model/resource"
29+
"sigs.k8s.io/kubebuilder/v3/pkg/plugin"
30+
"sigs.k8s.io/kubebuilder/v3/pkg/plugins/declarative/v1/internal/templates"
31+
goPluginV3 "sigs.k8s.io/kubebuilder/v3/pkg/plugins/golang/v3"
32+
"sigs.k8s.io/kubebuilder/v3/pkg/plugins/internal/machinery"
33+
"sigs.k8s.io/kubebuilder/v3/pkg/plugins/internal/util"
34+
)
35+
36+
const (
37+
// kbDeclarativePattern is the sigs.k8s.io/kubebuilder-declarative-pattern version
38+
kbDeclarativePatternForV2 = "v0.0.0-20200522144838-848d48e5b073"
39+
kbDeclarativePatternForV3 = "v0.0.0-20210113160450-b84d99da0217"
40+
41+
exampleManifestVersion = "0.0.1"
42+
)
43+
44+
var _ plugin.CreateAPISubcommand = &createAPISubcommand{}
45+
46+
type createAPISubcommand struct {
47+
config config.Config
48+
49+
resource *resource.Resource
50+
}
51+
52+
func (p *createAPISubcommand) InjectConfig(c config.Config) error {
53+
p.config = c
54+
55+
return nil
56+
}
57+
58+
func (p *createAPISubcommand) InjectResource(res *resource.Resource) error {
59+
p.resource = res
60+
61+
if !p.resource.HasAPI() || !p.resource.HasController() {
62+
return plugin.ExitError{
63+
Plugin: pluginName,
64+
Reason: "declarative pattern is only supported when API and controller are scaffolded",
65+
}
66+
}
67+
68+
return nil
69+
}
70+
71+
func (p *createAPISubcommand) Scaffold(fs afero.Fs) error {
72+
fmt.Println("updating scaffold with declarative pattern...")
73+
74+
// Load the boilerplate
75+
bp, err := afero.ReadFile(fs, filepath.Join("hack", "boilerplate.go.txt"))
76+
if err != nil {
77+
return fmt.Errorf("error updating scaffold: unable to load boilerplate: %w", err)
78+
}
79+
boilerplate := string(bp)
80+
81+
if err := machinery.NewScaffold(fs).Execute(
82+
model.NewUniverse(
83+
model.WithConfig(p.config),
84+
model.WithBoilerplate(boilerplate),
85+
model.WithResource(p.resource),
86+
),
87+
&templates.Types{},
88+
&templates.Controller{},
89+
&templates.Channel{ManifestVersion: exampleManifestVersion},
90+
&templates.Manifest{ManifestVersion: exampleManifestVersion},
91+
); err != nil {
92+
return fmt.Errorf("error updating scaffold: %w", err)
93+
}
94+
95+
// Ensure that we are pinning sigs.k8s.io/kubebuilder-declarative-pattern version
96+
kbDeclarativePattern := kbDeclarativePatternForV2
97+
if strings.Split(p.config.GetLayout(), ",")[0] == plugin.KeyFor(goPluginV3.Plugin{}) {
98+
kbDeclarativePattern = kbDeclarativePatternForV3
99+
}
100+
err = util.RunCmd("Get declarative pattern", "go", "get",
101+
"sigs.k8s.io/kubebuilder-declarative-pattern@"+kbDeclarativePattern)
102+
if err != nil {
103+
return err
104+
}
105+
106+
return nil
107+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/*
2+
Copyright 2021 The Kubernetes Authors.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package templates
18+
19+
import (
20+
"fmt"
21+
"path/filepath"
22+
23+
"sigs.k8s.io/kubebuilder/v3/pkg/model/file"
24+
)
25+
26+
var _ file.Template = &Channel{}
27+
28+
// Channel scaffolds the file for the channel
29+
type Channel struct {
30+
file.TemplateMixin
31+
32+
ManifestVersion string
33+
}
34+
35+
// SetTemplateDefaults implements file.Template
36+
func (f *Channel) SetTemplateDefaults() error {
37+
if f.Path == "" {
38+
f.Path = filepath.Join("channels", "stable")
39+
}
40+
fmt.Println(f.Path)
41+
42+
f.TemplateBody = channelTemplate
43+
44+
f.IfExistsAction = file.Skip
45+
46+
return nil
47+
}
48+
49+
const channelTemplate = `# Versions for the stable channel
50+
manifests:
51+
- version: {{ .ManifestVersion }}
52+
`
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
/*
2+
Copyright 2021 The Kubernetes Authors.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package templates
18+
19+
import (
20+
"path/filepath"
21+
22+
"sigs.k8s.io/kubebuilder/v3/pkg/model/file"
23+
)
24+
25+
var _ file.Template = &Controller{}
26+
27+
// Controller scaffolds the file that defines the controller for a CRD or a builtin resource
28+
// nolint:maligned
29+
type Controller struct {
30+
file.TemplateMixin
31+
file.MultiGroupMixin
32+
file.BoilerplateMixin
33+
file.ResourceMixin
34+
}
35+
36+
// SetTemplateDefaults implements file.Template
37+
func (f *Controller) SetTemplateDefaults() error {
38+
if f.Path == "" {
39+
if f.MultiGroup {
40+
f.Path = filepath.Join("controllers", "%[group]", "%[kind]_controller.go")
41+
} else {
42+
f.Path = filepath.Join("controllers", "%[kind]_controller.go")
43+
}
44+
}
45+
f.Path = f.Resource.Replacer().Replace(f.Path)
46+
47+
f.TemplateBody = controllerTemplate
48+
49+
f.IfExistsAction = file.Overwrite
50+
51+
return nil
52+
}
53+
54+
//nolint:lll
55+
const controllerTemplate = `{{ .Boilerplate }}
56+
57+
package controllers
58+
59+
import (
60+
"github.com/go-logr/logr"
61+
"k8s.io/apimachinery/pkg/runtime"
62+
ctrl "sigs.k8s.io/controller-runtime"
63+
"sigs.k8s.io/controller-runtime/pkg/client"
64+
"sigs.k8s.io/controller-runtime/pkg/controller"
65+
"sigs.k8s.io/controller-runtime/pkg/handler"
66+
"sigs.k8s.io/controller-runtime/pkg/reconcile"
67+
"sigs.k8s.io/controller-runtime/pkg/source"
68+
"sigs.k8s.io/kubebuilder-declarative-pattern/pkg/patterns/addon"
69+
"sigs.k8s.io/kubebuilder-declarative-pattern/pkg/patterns/addon/pkg/status"
70+
"sigs.k8s.io/kubebuilder-declarative-pattern/pkg/patterns/declarative"
71+
72+
{{ .Resource.ImportAlias }} "{{ .Resource.Path }}"
73+
)
74+
75+
var _ reconcile.Reconciler = &{{ .Resource.Kind }}Reconciler{}
76+
77+
// {{ .Resource.Kind }}Reconciler reconciles a {{ .Resource.Kind }} object
78+
type {{ .Resource.Kind }}Reconciler struct {
79+
client.Client
80+
Log logr.Logger
81+
Scheme *runtime.Scheme
82+
83+
declarative.Reconciler
84+
}
85+
86+
//+kubebuilder:rbac:groups={{ .Resource.QualifiedGroup }},resources={{ .Resource.Plural }},verbs=get;list;watch;create;update;patch;delete
87+
//+kubebuilder:rbac:groups={{ .Resource.QualifiedGroup }},resources={{ .Resource.Plural }}/status,verbs=get;update;patch
88+
89+
// SetupWithManager sets up the controller with the Manager.
90+
func (r *{{ .Resource.Kind }}Reconciler) SetupWithManager(mgr ctrl.Manager) error {
91+
addon.Init()
92+
93+
labels := map[string]string{
94+
"k8s-app": "{{ lower .Resource.Kind }}",
95+
}
96+
97+
watchLabels := declarative.SourceLabel(mgr.GetScheme())
98+
99+
if err := r.Reconciler.Init(mgr, &{{ .Resource.ImportAlias }}.{{ .Resource.Kind }}{},
100+
declarative.WithObjectTransform(declarative.AddLabels(labels)),
101+
declarative.WithOwner(declarative.SourceAsOwner),
102+
declarative.WithLabels(watchLabels),
103+
declarative.WithStatus(status.NewBasic(mgr.GetClient())),
104+
// TODO: add an application to your manifest: declarative.WithObjectTransform(addon.TransformApplicationFromStatus),
105+
// TODO: add an application to your manifest: declarative.WithManagedApplication(watchLabels),
106+
declarative.WithObjectTransform(addon.ApplyPatches),
107+
); err != nil {
108+
return err
109+
}
110+
111+
c, err := controller.New("{{ lower .Resource.Kind }}-controller", mgr, controller.Options{Reconciler: r})
112+
if err != nil {
113+
return err
114+
}
115+
116+
// Watch for changes to {{ .Resource.Kind }}
117+
err = c.Watch(&source.Kind{Type: &{{ .Resource.ImportAlias }}.{{ .Resource.Kind }}{}}, &handler.EnqueueRequestForObject{})
118+
if err != nil {
119+
return err
120+
}
121+
122+
// Watch for changes to deployed objects
123+
_, err = declarative.WatchAll(mgr.GetConfig(), c, r, watchLabels)
124+
if err != nil {
125+
return err
126+
}
127+
128+
return nil
129+
}
130+
`
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/*
2+
Copyright 2021 The Kubernetes Authors.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package templates
18+
19+
import (
20+
"fmt"
21+
"path/filepath"
22+
23+
"sigs.k8s.io/kubebuilder/v3/pkg/model/file"
24+
)
25+
26+
var _ file.Template = &Manifest{}
27+
28+
// Manifest scaffolds the file that acts as a placeholder for the manifest
29+
type Manifest struct {
30+
file.TemplateMixin
31+
file.ResourceMixin
32+
33+
ManifestVersion string
34+
}
35+
36+
// SetTemplateDefaults implements file.Template
37+
func (f *Manifest) SetTemplateDefaults() error {
38+
if f.Path == "" {
39+
f.Path = filepath.Join("channels", "packages", "%[kind]", f.ManifestVersion, "manifest.yaml")
40+
}
41+
f.Path = f.Resource.Replacer().Replace(f.Path)
42+
fmt.Println(f.Path)
43+
44+
f.TemplateBody = manifestTemplate
45+
46+
f.IfExistsAction = file.Skip
47+
48+
return nil
49+
}
50+
51+
const manifestTemplate = `# Placeholder manifest - replace with the manifest for your addon
52+
`

0 commit comments

Comments
 (0)