Skip to content

Commit

Permalink
Update context
Browse files Browse the repository at this point in the history
  • Loading branch information
ciarams87 committed May 22, 2023
1 parent 55c54be commit d361fc5
Show file tree
Hide file tree
Showing 2 changed files with 156 additions and 31 deletions.
154 changes: 154 additions & 0 deletions internal/certmanager/test_files/context.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
/*
Copyright 2020 The cert-manager 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 test

import (
"context"
"fmt"
"time"

corev1 "k8s.io/api/core/v1"
kubeinformers "k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/kubernetes/scheme"
clientv1 "k8s.io/client-go/kubernetes/typed/core/v1"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/tools/record"
"k8s.io/utils/clock"

clientset "github.com/cert-manager/cert-manager/pkg/client/clientset/versioned"
cmscheme "github.com/cert-manager/cert-manager/pkg/client/clientset/versioned/scheme"
informers "github.com/cert-manager/cert-manager/pkg/client/informers/externalversions"
"github.com/cert-manager/cert-manager/pkg/util"
)

const resyncPeriod = 10 * time.Hour

// Context contains various types that are used by controller implementations.
type Context struct {
// RootContext is the root context for the controller
RootContext context.Context

StopCh <-chan struct{}

FieldManager string
// RESTConfig is the loaded Kubernetes apiserver rest client configuration
RESTConfig *rest.Config
Client kubernetes.Interface
CMClient clientset.Interface

Recorder record.EventRecorder

KubeSharedInformerFactory kubeinformers.SharedInformerFactory
SharedInformerFactory informers.SharedInformerFactory

ContextOptions
}

// ContextOptions are static Controller Context options.
type ContextOptions struct {
// APIServerHost is the host address of the target Kubernetes API server.
APIServerHost string
Kubeconfig string
Namespace string
Clock clock.Clock
}

// ContextFactory is used for constructing new Contexts who's clients have been
// configured with a User Agent built from the component name.
type ContextFactory struct {
baseRestConfig *rest.Config
ctx *Context
}

// NewContextFactory builds a ContextFactory that builds controller Contexts
// that have been configured for that components User Agent.
func NewContextFactory(ctx context.Context, opts ContextOptions) (*ContextFactory, error) {
// Load the users Kubernetes config
restConfig, err := clientcmd.BuildConfigFromFlags(opts.APIServerHost, opts.Kubeconfig)
if err != nil {
return nil, fmt.Errorf("error creating rest config: %w", err)
}
restConfig = util.RestConfigWithUserAgent(restConfig)

clients, err := buildClients(restConfig)
if err != nil {
return nil, err
}

sharedInformerFactory := informers.NewSharedInformerFactoryWithOptions(clients.cmClient, resyncPeriod, informers.WithNamespace(opts.Namespace))
kubeSharedInformerFactory := kubeinformers.NewSharedInformerFactoryWithOptions(clients.kubeClient, resyncPeriod, kubeinformers.WithNamespace(opts.Namespace))

return &ContextFactory{
baseRestConfig: restConfig,
ctx: &Context{
RootContext: ctx,
StopCh: ctx.Done(),
KubeSharedInformerFactory: kubeSharedInformerFactory,
SharedInformerFactory: sharedInformerFactory,
ContextOptions: opts,
},
}, nil
}

// Build builds a new controller Context who's clients have a User Agent
// derived from the optional component name.
func (c *ContextFactory) Build(component ...string) (*Context, error) {
restConfig := util.RestConfigWithUserAgent(c.baseRestConfig, component...)

clients, err := buildClients(restConfig)
if err != nil {
return nil, err
}

// Create event broadcaster.
cmscheme.AddToScheme(scheme.Scheme)
eventBroadcaster := record.NewBroadcaster()
eventBroadcaster.StartRecordingToSink(&clientv1.EventSinkImpl{Interface: clients.kubeClient.CoreV1().Events("")})
recorder := eventBroadcaster.NewRecorder(scheme.Scheme, corev1.EventSource{Component: util.PrefixFromUserAgent(restConfig.UserAgent)})

ctx := *c.ctx
ctx.FieldManager = util.PrefixFromUserAgent(restConfig.UserAgent)
ctx.RESTConfig = restConfig
ctx.Client = clients.kubeClient
ctx.CMClient = clients.cmClient
ctx.Recorder = recorder

return &ctx, nil
}

// contextClients is a helper struct containing API clients.
type contextClients struct {
kubeClient kubernetes.Interface
cmClient clientset.Interface
}

// buildClients builds all required clients for the context using the given
// REST config.
func buildClients(restConfig *rest.Config) (contextClients, error) {
// Create a cert-manager api client
cmClient, err := clientset.NewForConfig(restConfig)
if err != nil {
return contextClients{}, fmt.Errorf("error creating internal group client: %w", err)
}
kubeClient, err := kubernetes.NewForConfig(restConfig)
if err != nil {
return contextClients{}, fmt.Errorf("error creating kubernetes client: %w", err)
}
return contextClients{kubeClient, cmClient}, nil
}
33 changes: 2 additions & 31 deletions internal/certmanager/test_files/context_builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ import (
"testing"
"time"

networkingv1 "k8s.io/api/networking/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
utilerrors "k8s.io/apimachinery/pkg/util/errors"
Expand All @@ -39,11 +38,7 @@ import (
apiutil "github.com/cert-manager/cert-manager/pkg/api/util"
cmfake "github.com/cert-manager/cert-manager/pkg/client/clientset/versioned/fake"
informers "github.com/cert-manager/cert-manager/pkg/client/informers/externalversions"
"github.com/cert-manager/cert-manager/pkg/controller"
"github.com/cert-manager/cert-manager/pkg/logs"
"github.com/cert-manager/cert-manager/pkg/metrics"
"github.com/cert-manager/cert-manager/pkg/util"
discoveryfake "github.com/cert-manager/cert-manager/test/unit/discovery"
k8s_nginx "github.com/nginxinc/kubernetes-ingress/pkg/client/clientset/versioned"
vsfake "github.com/nginxinc/kubernetes-ingress/pkg/client/clientset/versioned/fake"
vsinformers "github.com/nginxinc/kubernetes-ingress/pkg/client/informers/externalversions"
Expand Down Expand Up @@ -81,7 +76,7 @@ type Builder struct {
requiredReactors map[string]bool
additionalSyncFuncs []cache.InformerSynced

*controller.Context
*Context
}

func (b *Builder) generateNameReactor(action coretesting.Action) (handled bool, ret runtime.Object, err error) {
Expand All @@ -100,7 +95,7 @@ const informerResyncPeriod = time.Millisecond * 10
// for any unset fields.
func (b *Builder) Init() {
if b.Context == nil {
b.Context = &controller.Context{
b.Context = &Context{
RootContext: context.Background(),
}
}
Expand All @@ -111,29 +106,6 @@ func (b *Builder) Init() {
b.Client = kubefake.NewSimpleClientset(b.KubeObjects...)
b.CMClient = cmfake.NewSimpleClientset(b.CertManagerObjects...)
b.VSClient = vsfake.NewSimpleClientset(b.VSObjects...)
b.DiscoveryClient = discoveryfake.NewDiscovery().WithServerResourcesForGroupVersion(func(groupVersion string) (*metav1.APIResourceList, error) {
if groupVersion == networkingv1.SchemeGroupVersion.String() {
return &metav1.APIResourceList{
TypeMeta: metav1.TypeMeta{},
GroupVersion: networkingv1.SchemeGroupVersion.String(),
APIResources: []metav1.APIResource{
{
Name: "ingresses",
SingularName: "Ingress",
Namespaced: true,
Group: networkingv1.GroupName,
Version: networkingv1.SchemeGroupVersion.Version,
Kind: networkingv1.SchemeGroupVersion.WithKind("Ingress").Kind,
Verbs: metav1.Verbs{"get", "list", "watch", "create", "update", "patch", "delete", "deletecollection"},
ShortNames: []string{"ing"},
Categories: []string{"all"},
StorageVersionHash: "testing",
},
},
}, nil
}
return &metav1.APIResourceList{}, nil
})
b.Recorder = new(FakeRecorder)
b.FakeKubeClient().PrependReactor("create", "*", b.generateNameReactor)
b.FakeCMClient().PrependReactor("create", "*", b.generateNameReactor)
Expand All @@ -142,7 +114,6 @@ func (b *Builder) Init() {
b.SharedInformerFactory = informers.NewSharedInformerFactory(b.CMClient, informerResyncPeriod)
b.VsSharedInformerFactory = vsinformers.NewSharedInformerFactory(b.VSClient, informerResyncPeriod)
b.stopCh = make(chan struct{})
b.Metrics = metrics.New(logs.Log, clock.RealClock{})

// set the Clock on the context
if b.Clock == nil {
Expand Down

0 comments on commit d361fc5

Please sign in to comment.