Skip to content

Commit 6ab1a65

Browse files
committed
Declarative plugin
Signed-off-by: Adrian Orive Oneca <[email protected]>
1 parent d17eb4e commit 6ab1a65

File tree

7 files changed

+523
-0
lines changed

7 files changed

+523
-0
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

+104
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
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+
23+
"github.com/spf13/afero"
24+
25+
"sigs.k8s.io/kubebuilder/v3/pkg/config"
26+
"sigs.k8s.io/kubebuilder/v3/pkg/model"
27+
"sigs.k8s.io/kubebuilder/v3/pkg/model/resource"
28+
"sigs.k8s.io/kubebuilder/v3/pkg/plugin"
29+
"sigs.k8s.io/kubebuilder/v3/pkg/plugins/declarative/v1/internal/templates"
30+
"sigs.k8s.io/kubebuilder/v3/pkg/plugins/internal/machinery"
31+
"sigs.k8s.io/kubebuilder/v3/pkg/plugins/internal/util"
32+
)
33+
34+
const (
35+
// kbDeclarativePattern is the sigs.k8s.io/kubebuilder-declarative-pattern version
36+
kbDeclarativePattern = "v0.0.0-20200522144838-848d48e5b073"
37+
38+
exampleManifestVersion = "0.0.1"
39+
)
40+
41+
var _ plugin.CreateAPISubcommand = &createAPISubcommand{}
42+
43+
type createAPISubcommand struct {
44+
config config.Config
45+
46+
resource *resource.Resource
47+
}
48+
49+
func (p *createAPISubcommand) InjectConfig(c config.Config) error {
50+
p.config = c
51+
52+
return nil
53+
}
54+
55+
func (p *createAPISubcommand) InjectResource(res *resource.Resource) error {
56+
p.resource = res
57+
58+
if !p.resource.HasAPI() || !p.resource.HasController() {
59+
return plugin.ExitError{
60+
Plugin: pluginName,
61+
Reason: "declarative pattern is only supported when API and controller are scaffolded",
62+
}
63+
}
64+
65+
return nil
66+
}
67+
68+
func (p *createAPISubcommand) Scaffold(fs afero.Fs) error {
69+
fmt.Println("updating scaffold with declarative pattern...")
70+
71+
// Load the boilerplate
72+
bp, err := afero.ReadFile(fs, filepath.Join("hack", "boilerplate.go.txt"))
73+
if err != nil {
74+
return fmt.Errorf("error updating scaffold: unable to load boilerplate: %w", err)
75+
}
76+
boilerplate := string(bp)
77+
78+
if err := machinery.NewScaffold(fs).Execute(
79+
model.NewUniverse(
80+
model.WithConfig(p.config),
81+
model.WithBoilerplate(boilerplate),
82+
model.WithResource(p.resource),
83+
),
84+
&templates.Types{},
85+
&templates.Controller{},
86+
&templates.Channel{ManifestVersion: exampleManifestVersion},
87+
&templates.Manifest{ManifestVersion: exampleManifestVersion},
88+
); err != nil {
89+
return fmt.Errorf("error updating scaffold: %w", err)
90+
}
91+
92+
return nil
93+
}
94+
95+
func (p *createAPISubcommand) PostScaffold() error {
96+
// Ensure that we are pinning sigs.k8s.io/kubebuilder-declarative-pattern version
97+
err := util.RunCmd("Get controller runtime", "go", "get",
98+
"sigs.k8s.io/kubebuilder-declarative-pattern@"+kbDeclarativePattern)
99+
if err != nil {
100+
return err
101+
}
102+
103+
return nil
104+
}
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)