Skip to content

Add simple application pattern package #26

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 27, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
178 changes: 178 additions & 0 deletions pkg/patterns/application/application.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
/*
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 application

import (
"fmt"
"strings"

"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/rest"
"sigs.k8s.io/controller-runtime/pkg/client/apiutil"
"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/predicate"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"sigs.k8s.io/controller-runtime/pkg/source"
)

// application is a simple Controller for a single API type. It will create a Manager for itself
// if one is not provided.
type application struct {
mgr manager.Manager
ctrl controller.Controller
}

// Supporting mocking out functions for testing
var getConfig = config.GetConfig
var newController = controller.New
var newManager = manager.New
var getGvk = apiutil.GVKForObject

// Builder builds an Application Controller (e.g. Operator) and returns a manager.Manager to start it.
type Builder struct {
apiType runtime.Object
mgr manager.Manager
predicates []predicate.Predicate
managedObjects []runtime.Object
config *rest.Config
reconcile reconcile.Reconciler
ctrl controller.Controller
}

// BuilderFor returns a new Builder for and BuilderFor
func BuilderFor(apiType runtime.Object) *Builder {
return &Builder{apiType: apiType}
}

// Owns configures the Application Controller to respond to create / delete / update events for objects it managedObjects
// - e.g. creates. apiType is an empty instance of an object matching the managed object type.
func (b *Builder) Owns(apiType runtime.Object) *Builder {
b.managedObjects = append(b.managedObjects, apiType)
return b
}

// WithConfig sets the Config to use for configuring clients. Defaults to the in-cluster config or to ~/.kube/config.
func (b *Builder) WithConfig(config *rest.Config) *Builder {
b.config = config
return b
}

// WithManager sets the Manager to use for registering the Controller. Defaults to a new manager.Manager.
func (b *Builder) WithManager(m manager.Manager) *Builder {
b.mgr = m
return b
}

// WithEventFilter sets the event filters, to filter which create/update/delete/generic events eventually
// trigger reconciliations. For example, filtering on whether the resource version has changed.
// Defaults to the empty list.
func (b *Builder) WithEventFilter(p predicate.Predicate) *Builder {
b.predicates = append(b.predicates, p)
return b
}

// WithReconciler sets the Reconcile called in response to create / update / delete events for the
// BuilderFor type or Created object types.
func (b *Builder) WithReconciler(r reconcile.Reconciler) *Builder {
b.reconcile = r
return b
}

// Build builds the Application Controller and returns the Manager used to start it.
func (b *Builder) Build() (manager.Manager, error) {
if b.reconcile == nil {
return nil, fmt.Errorf("must call WithReconciler to set Reconciler")
}

// Set the Config
if err := b.doConfig(); err != nil {
return nil, err
}

// Set the Manager
if err := b.doManager(); err != nil {
return nil, err
}

// Set the Controller
if err := b.doController(); err != nil {
return nil, err
}

a := &application{mgr: b.mgr, ctrl: b.ctrl}

// Reconcile type
s := &source.Kind{Type: b.apiType}
h := &handler.EnqueueRequestForObject{}
err := a.ctrl.Watch(s, h, b.predicates...)
if err != nil {
return nil, err
}

// Watch the managed types
for _, t := range b.managedObjects {
s := &source.Kind{Type: t}
h := &handler.EnqueueRequestForOwner{
OwnerType: b.apiType,
IsController: true,
}
if err := a.ctrl.Watch(s, h, b.predicates...); err != nil {
return nil, err
}
}

return a.mgr, nil
}

func (b *Builder) doConfig() error {
if b.config != nil {
return nil
}
var err error
b.config, err = getConfig()
return err
}

func (b *Builder) doManager() error {
if b.mgr != nil {
return nil
}
var err error
b.mgr, err = newManager(b.config, manager.Options{})
return err
}

func (b *Builder) getControllerName() (string, error) {
gvk, err := getGvk(b.apiType, b.mgr.GetScheme())
if err != nil {
return "", err
}
name := fmt.Sprintf("%s-application", strings.ToLower(gvk.Kind))
return name, nil
}

func (b *Builder) doController() error {
name, err := b.getControllerName()
if err != nil {
return err
}
b.ctrl, err = newController(name, b.mgr, controller.Options{Reconciler: b.reconcile})
return err
}
35 changes: 35 additions & 0 deletions pkg/patterns/application/application_suite_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package application

import (
"testing"

. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"k8s.io/client-go/rest"
"sigs.k8s.io/controller-runtime/pkg/envtest"
logf "sigs.k8s.io/controller-runtime/pkg/runtime/log"
)

func TestSource(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecsWithDefaultAndCustomReporters(t, "application Suite", []Reporter{envtest.NewlineReporter{}})
}

var testenv *envtest.Environment
var cfg *rest.Config

var _ = BeforeSuite(func(done Done) {
logf.SetLogger(logf.ZapLogger(false))

testenv = &envtest.Environment{}

var err error
cfg, err = testenv.Start()
Expect(err).NotTo(HaveOccurred())

close(done)
}, 60)

var _ = AfterSuite(func() {
testenv.Stop()
})
Loading