Skip to content

Commit

Permalink
adding support for scaffolding a componentconfig type
Browse files Browse the repository at this point in the history
Signed-off-by: Chris Hein <me@chrishein.com>
  • Loading branch information
christopherhein committed Nov 5, 2020
1 parent a4ff1b6 commit 1ec2d75
Show file tree
Hide file tree
Showing 11 changed files with 232 additions and 71 deletions.
11 changes: 11 additions & 0 deletions pkg/model/file/funcmap.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ limitations under the License.
package file

import (
"fmt"
"hash/fnv"
"strings"
"text/template"
)
Expand All @@ -26,5 +28,14 @@ func DefaultFuncMap() template.FuncMap {
return template.FuncMap{
"title": strings.Title,
"lower": strings.ToLower,
"hash": hash,
}
}

func hash(s string) (string, error) {
hasher := fnv.New32a()
if _, err := hasher.Write([]byte(s)); err != nil {
return "", err
}
return fmt.Sprintf("%x", hasher.Sum(nil)), nil
}
24 changes: 3 additions & 21 deletions pkg/plugin/v2/scaffolds/internal/templates/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,14 @@ package templates

import (
"fmt"
"hash/fnv"
"path/filepath"
"text/template"

"sigs.k8s.io/kubebuilder/pkg/model/file"
)

const defaultMainPath = "main.go"

var _ file.Template = &Main{}
var _ file.UseCustomFuncMap = &Main{}

// Main scaffolds the controller manager entry point
type Main struct {
Expand All @@ -53,21 +50,6 @@ func (f *Main) SetTemplateDefaults() error {
return nil
}

func hash(s string) (string, error) {
hasher := fnv.New32a()
if _, err := hasher.Write([]byte(s)); err != nil {
return "", err
}
return fmt.Sprintf("%x", hasher.Sum(nil)), nil
}

// GetFuncMap implements file.UseCustomFuncMap
func (f *Main) GetFuncMap() template.FuncMap {
fm := file.DefaultFuncMap()
fm["hash"] = hash
return fm
}

var _ file.Inserter = &MainUpdater{}

// MainUpdater updates main.go to run Controllers
Expand Down Expand Up @@ -236,13 +218,13 @@ func main() {
"Enabling this will ensure there is only one active controller manager.")
flag.Parse()
ctrl.SetLogger(zap.New(zap.UseDevMode(true)))
ctrl.SetLogger(zap.New(zap.UseDevMode(true)))
mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{
Scheme: scheme,
MetricsBindAddress: metricsAddr,
Port: 9443,
LeaderElection: enableLeaderElection,
Port: 9443,
LeaderElection: enableLeaderElection,
LeaderElectionID: "{{ hash .Repo }}.{{ .Domain }}",
})
if err != nil {
Expand Down
9 changes: 6 additions & 3 deletions pkg/plugin/v3/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,9 @@ type initPlugin struct {
commandName string

// boilerplate options
license string
owner string
license string
owner string
componentConfig bool

// flags
fetchDeps bool
Expand Down Expand Up @@ -87,6 +88,8 @@ func (p *initPlugin) BindFlags(fs *pflag.FlagSet) {
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")
fs.BoolVar(&p.componentConfig, "component-config", false,
"component config name, may be 'true' or 'false'")

// project args
fs.StringVar(&p.config.Repo, "repo", "", "name to use for go module (e.g., github.com/user/repo), "+
Expand Down Expand Up @@ -142,7 +145,7 @@ func (p *initPlugin) Validate() error {
}

func (p *initPlugin) GetScaffolder() (scaffold.Scaffolder, error) {
return scaffolds.NewInitScaffolder(p.config, p.license, p.owner), nil
return scaffolds.NewInitScaffolder(p.config, p.license, p.owner, p.componentConfig), nil
}

func (p *initPlugin) PostScaffold() error {
Expand Down
21 changes: 16 additions & 5 deletions pkg/plugin/v3/scaffolds/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ import (

const (
// ControllerRuntimeVersion is the kubernetes-sigs/controller-runtime version to be used in the project
ControllerRuntimeVersion = "v0.6.3"
ControllerRuntimeVersion = "v0.7.0-alpha.6"
// ControllerToolsVersion is the kubernetes-sigs/controller-tools version to be used in the project
ControllerToolsVersion = "v0.3.0"
// KustomizeVersion is the kubernetes-sigs/kustomize version to be used in the project
Expand All @@ -53,15 +53,17 @@ type initScaffolder struct {
boilerplatePath string
license string
owner string
componentConfig bool
}

// NewInitScaffolder returns a new Scaffolder for project initialization operations
func NewInitScaffolder(config *config.Config, license, owner string) scaffold.Scaffolder {
func NewInitScaffolder(config *config.Config, license, owner string, componentConfig bool) scaffold.Scaffolder {
return &initScaffolder{
config: config,
boilerplatePath: filepath.Join("hack", "boilerplate.go.txt"),
license: license,
owner: owner,
componentConfig: componentConfig,
}
}

Expand Down Expand Up @@ -101,11 +103,18 @@ func (s *initScaffolder) scaffold() error {
&templates.GitIgnore{},
&rbac.AuthProxyRole{},
&rbac.AuthProxyRoleBinding{},
&kdefault.AuthProxyPatch{},
&kdefault.AuthProxyPatch{
ComponentConfig: s.componentConfig,
},
&rbac.AuthProxyService{},
&rbac.ClientClusterRole{},
&manager.Config{Image: imageName},
&templates.Main{},
&manager.Config{
Image: imageName,
ComponentConfig: s.componentConfig,
},
&templates.Main{
ComponentConfig: s.componentConfig,
},
&templates.GoMod{ControllerRuntimeVersion: ControllerRuntimeVersion},
&templates.Makefile{
Image: imageName,
Expand All @@ -118,11 +127,13 @@ func (s *initScaffolder) scaffold() error {
&templates.DockerignoreFile{},
&kdefault.Kustomize{},
&kdefault.ManagerWebhookPatch{},
&kdefault.ManagerConfigPatch{},
&rbac.ManagerRoleBinding{},
&rbac.LeaderElectionRole{},
&rbac.LeaderElectionRoleBinding{},
&rbac.KustomizeRBAC{},
&manager.Kustomization{},
&manager.ComponentConfig{},
&webhook.Kustomization{},
&webhook.KustomizeConfigWebhook{},
&webhook.Service{},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ limitations under the License.
package kdefault

import (
"fmt"
"path/filepath"

"sigs.k8s.io/kubebuilder/pkg/model/file"
Expand All @@ -28,6 +29,9 @@ var _ file.Template = &AuthProxyPatch{}
// prometheus metrics for manager Pod.
type AuthProxyPatch struct {
file.TemplateMixin

// ComponentConfig defines that this should be configured with a file
ComponentConfig bool
}

// SetTemplateDefaults implements input.Template
Expand All @@ -36,14 +40,25 @@ func (f *AuthProxyPatch) SetTemplateDefaults() error {
f.Path = filepath.Join("config", "default", "manager_auth_proxy_patch.yaml")
}

f.TemplateBody = kustomizeAuthProxyPatchTemplate
args := argsFragment
if f.ComponentConfig {
args = ""
}

f.TemplateBody = fmt.Sprintf(kustomizeAuthProxyPatchTemplate, args)

f.IfExistsAction = file.Error

return nil
}

const kustomizeAuthProxyPatchTemplate = `# This patch inject a sidecar container which is a HTTP proxy for the
const argsFragment = `- name: manager
args:
- "--metrics-addr=127.0.0.1:8080"
- "--enable-leader-election"
`

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: Deployment
Expand All @@ -64,8 +79,5 @@ spec:
ports:
- containerPort: 8443
name: https
- name: manager
args:
- "--metrics-addr=127.0.0.1:8080"
- "--enable-leader-election"
%s
`
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/*
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 kdefault

import (
"path/filepath"

"sigs.k8s.io/kubebuilder/pkg/model/file"
)

var _ file.Template = &ManagerConfigPatch{}

// ManagerConfigPatch scaffolds a ManagerConfigPatch for a Resource
type ManagerConfigPatch struct {
file.TemplateMixin
}

// SetTemplateDefaults implements input.Template
func (f *ManagerConfigPatch) SetTemplateDefaults() error {
if f.Path == "" {
f.Path = filepath.Join("config", "default", "manager_config_patch.yaml")
}

f.TemplateBody = managerConfigPatchTemplate

return nil
}

const managerConfigPatchTemplate = `apiVersion: apps/v1
kind: Deployment
metadata:
name: controller-manager
namespace: system
spec:
template:
spec:
containers:
- name: manager
volumeMounts:
- name: config
mountPath: /config.yaml
subPath: config.yaml
volumes:
- name: config
configMap:
name: controller-config
`
Original file line number Diff line number Diff line change
Expand Up @@ -70,11 +70,15 @@ bases:
#- ../prometheus
patchesStrategicMerge:
# Protect the /metrics endpoint by putting it behind auth.
# If you want your controller-manager to expose the /metrics
# endpoint w/o any authn/z, please comment the following line.
# Protect the /metrics endpoint by putting it behind auth.
# If you want your controller-manager to expose the /metrics
# endpoint w/o any authn/z, please comment the following line.
- manager_auth_proxy_patch.yaml
# Mount the controller config file for loading manager configurations
# through a ComponentConfig type
- manager_config_patch.yaml
# [WEBHOOK] To enable webhook, uncomment all the sections with [WEBHOOK] prefix including the one in
# crd/kustomization.yaml
#- manager_webhook_patch.yaml
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/*
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 manager

import (
"path/filepath"

"sigs.k8s.io/kubebuilder/pkg/model/file"
)

var _ file.Template = &ComponentConfig{}

// ComponentConfig scaffolds the ComponentConfig file in manager folder.
type ComponentConfig struct {
file.TemplateMixin
file.DomainMixin
file.RepositoryMixin
}

// SetTemplateDefaults implements input.Template
func (f *ComponentConfig) SetTemplateDefaults() error {
if f.Path == "" {
f.Path = filepath.Join("config", "manager", "config.yaml")
}

f.TemplateBody = componentConfigTemplate

f.IfExistsAction = file.Error

return nil
}

const componentConfigTemplate = `apiVersion: controller-runtime.sigs.k8s.io/v1alpha1
kind: ControllerManagerConfiguration
metrics:
bindAddress: :8080
webhook:
port: 9443
leaderElection:
leaderElect: true
resourceLock: configmaps
resourceName: {{ hash .Repo }}.{{ .Domain }}",
`
Loading

0 comments on commit 1ec2d75

Please sign in to comment.