mirror of https://github.com/knative/pkg.git
generating reconciler for deploymnets (#1502)
This commit is contained in:
parent
8d80e63709
commit
096656a2d4
|
@ -0,0 +1,140 @@
|
|||
/*
|
||||
Copyright 2020 The Knative 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.
|
||||
*/
|
||||
|
||||
// Code generated by injection-gen. DO NOT EDIT.
|
||||
|
||||
package deployment
|
||||
|
||||
import (
|
||||
context "context"
|
||||
fmt "fmt"
|
||||
reflect "reflect"
|
||||
strings "strings"
|
||||
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
labels "k8s.io/apimachinery/pkg/labels"
|
||||
types "k8s.io/apimachinery/pkg/types"
|
||||
watch "k8s.io/apimachinery/pkg/watch"
|
||||
scheme "k8s.io/client-go/kubernetes/scheme"
|
||||
v1 "k8s.io/client-go/kubernetes/typed/core/v1"
|
||||
record "k8s.io/client-go/tools/record"
|
||||
client "knative.dev/pkg/client/injection/kube/client"
|
||||
deployment "knative.dev/pkg/client/injection/kube/informers/apps/v1/deployment"
|
||||
controller "knative.dev/pkg/controller"
|
||||
logging "knative.dev/pkg/logging"
|
||||
reconciler "knative.dev/pkg/reconciler"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultControllerAgentName = "deployment-controller"
|
||||
defaultFinalizerName = "deployments.apps"
|
||||
)
|
||||
|
||||
// NewImpl returns a controller.Impl that handles queuing and feeding work from
|
||||
// the queue through an implementation of controller.Reconciler, delegating to
|
||||
// the provided Interface and optional Finalizer methods. OptionsFn is used to return
|
||||
// controller.Options to be used but the internal reconciler.
|
||||
func NewImpl(ctx context.Context, r Interface, optionsFns ...controller.OptionsFn) *controller.Impl {
|
||||
logger := logging.FromContext(ctx)
|
||||
|
||||
// Check the options function input. It should be 0 or 1.
|
||||
if len(optionsFns) > 1 {
|
||||
logger.Fatalf("up to one options function is supported, found %d", len(optionsFns))
|
||||
}
|
||||
|
||||
deploymentInformer := deployment.Get(ctx)
|
||||
|
||||
lister := deploymentInformer.Lister()
|
||||
|
||||
rec := &reconcilerImpl{
|
||||
LeaderAwareFuncs: reconciler.LeaderAwareFuncs{
|
||||
PromoteFunc: func(bkt reconciler.Bucket, enq func(reconciler.Bucket, types.NamespacedName)) error {
|
||||
all, err := lister.List(labels.Everything())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, elt := range all {
|
||||
// TODO: Consider letting users specify a filter in options.
|
||||
enq(bkt, types.NamespacedName{
|
||||
Namespace: elt.GetNamespace(),
|
||||
Name: elt.GetName(),
|
||||
})
|
||||
}
|
||||
return nil
|
||||
},
|
||||
},
|
||||
Client: client.Get(ctx),
|
||||
Lister: lister,
|
||||
reconciler: r,
|
||||
finalizerName: defaultFinalizerName,
|
||||
}
|
||||
|
||||
t := reflect.TypeOf(r).Elem()
|
||||
queueName := fmt.Sprintf("%s.%s", strings.ReplaceAll(t.PkgPath(), "/", "-"), t.Name())
|
||||
|
||||
impl := controller.NewImpl(rec, logger, queueName)
|
||||
agentName := defaultControllerAgentName
|
||||
|
||||
// Pass impl to the options. Save any optional results.
|
||||
for _, fn := range optionsFns {
|
||||
opts := fn(impl)
|
||||
if opts.ConfigStore != nil {
|
||||
rec.configStore = opts.ConfigStore
|
||||
}
|
||||
if opts.FinalizerName != "" {
|
||||
rec.finalizerName = opts.FinalizerName
|
||||
}
|
||||
if opts.AgentName != "" {
|
||||
agentName = opts.AgentName
|
||||
}
|
||||
if opts.SkipStatusUpdates {
|
||||
rec.skipStatusUpdates = true
|
||||
}
|
||||
}
|
||||
|
||||
rec.Recorder = createRecorder(ctx, agentName)
|
||||
|
||||
return impl
|
||||
}
|
||||
|
||||
func createRecorder(ctx context.Context, agentName string) record.EventRecorder {
|
||||
logger := logging.FromContext(ctx)
|
||||
|
||||
recorder := controller.GetEventRecorder(ctx)
|
||||
if recorder == nil {
|
||||
// Create event broadcaster
|
||||
logger.Debug("Creating event broadcaster")
|
||||
eventBroadcaster := record.NewBroadcaster()
|
||||
watches := []watch.Interface{
|
||||
eventBroadcaster.StartLogging(logger.Named("event-broadcaster").Infof),
|
||||
eventBroadcaster.StartRecordingToSink(
|
||||
&v1.EventSinkImpl{Interface: client.Get(ctx).CoreV1().Events("")}),
|
||||
}
|
||||
recorder = eventBroadcaster.NewRecorder(scheme.Scheme, corev1.EventSource{Component: agentName})
|
||||
go func() {
|
||||
<-ctx.Done()
|
||||
for _, w := range watches {
|
||||
w.Stop()
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
return recorder
|
||||
}
|
||||
|
||||
func init() {
|
||||
scheme.AddToScheme(scheme.Scheme)
|
||||
}
|
|
@ -0,0 +1,444 @@
|
|||
/*
|
||||
Copyright 2020 The Knative 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.
|
||||
*/
|
||||
|
||||
// Code generated by injection-gen. DO NOT EDIT.
|
||||
|
||||
package deployment
|
||||
|
||||
import (
|
||||
context "context"
|
||||
json "encoding/json"
|
||||
fmt "fmt"
|
||||
reflect "reflect"
|
||||
|
||||
zap "go.uber.org/zap"
|
||||
v1 "k8s.io/api/apps/v1"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
equality "k8s.io/apimachinery/pkg/api/equality"
|
||||
errors "k8s.io/apimachinery/pkg/api/errors"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
labels "k8s.io/apimachinery/pkg/labels"
|
||||
types "k8s.io/apimachinery/pkg/types"
|
||||
sets "k8s.io/apimachinery/pkg/util/sets"
|
||||
kubernetes "k8s.io/client-go/kubernetes"
|
||||
appsv1 "k8s.io/client-go/listers/apps/v1"
|
||||
cache "k8s.io/client-go/tools/cache"
|
||||
record "k8s.io/client-go/tools/record"
|
||||
controller "knative.dev/pkg/controller"
|
||||
logging "knative.dev/pkg/logging"
|
||||
reconciler "knative.dev/pkg/reconciler"
|
||||
)
|
||||
|
||||
// Interface defines the strongly typed interfaces to be implemented by a
|
||||
// controller reconciling v1.Deployment.
|
||||
type Interface interface {
|
||||
// ReconcileKind implements custom logic to reconcile v1.Deployment. Any changes
|
||||
// to the objects .Status or .Finalizers will be propagated to the stored
|
||||
// object. It is recommended that implementors do not call any update calls
|
||||
// for the Kind inside of ReconcileKind, it is the responsibility of the calling
|
||||
// controller to propagate those properties. The resource passed to ReconcileKind
|
||||
// will always have an empty deletion timestamp.
|
||||
ReconcileKind(ctx context.Context, o *v1.Deployment) reconciler.Event
|
||||
}
|
||||
|
||||
// Finalizer defines the strongly typed interfaces to be implemented by a
|
||||
// controller finalizing v1.Deployment.
|
||||
type Finalizer interface {
|
||||
// FinalizeKind implements custom logic to finalize v1.Deployment. Any changes
|
||||
// to the objects .Status or .Finalizers will be ignored. Returning a nil or
|
||||
// Normal type reconciler.Event will allow the finalizer to be deleted on
|
||||
// the resource. The resource passed to FinalizeKind will always have a set
|
||||
// deletion timestamp.
|
||||
FinalizeKind(ctx context.Context, o *v1.Deployment) reconciler.Event
|
||||
}
|
||||
|
||||
// ReadOnlyInterface defines the strongly typed interfaces to be implemented by a
|
||||
// controller reconciling v1.Deployment if they want to process resources for which
|
||||
// they are not the leader.
|
||||
type ReadOnlyInterface interface {
|
||||
// ObserveKind implements logic to observe v1.Deployment.
|
||||
// This method should not write to the API.
|
||||
ObserveKind(ctx context.Context, o *v1.Deployment) reconciler.Event
|
||||
}
|
||||
|
||||
// ReadOnlyFinalizer defines the strongly typed interfaces to be implemented by a
|
||||
// controller finalizing v1.Deployment if they want to process tombstoned resources
|
||||
// even when they are not the leader. Due to the nature of how finalizers are handled
|
||||
// there are no guarantees that this will be called.
|
||||
type ReadOnlyFinalizer interface {
|
||||
// ObserveFinalizeKind implements custom logic to observe the final state of v1.Deployment.
|
||||
// This method should not write to the API.
|
||||
ObserveFinalizeKind(ctx context.Context, o *v1.Deployment) reconciler.Event
|
||||
}
|
||||
|
||||
// reconcilerImpl implements controller.Reconciler for v1.Deployment resources.
|
||||
type reconcilerImpl struct {
|
||||
// LeaderAwareFuncs is inlined to help us implement reconciler.LeaderAware
|
||||
reconciler.LeaderAwareFuncs
|
||||
|
||||
// Client is used to write back status updates.
|
||||
Client kubernetes.Interface
|
||||
|
||||
// Listers index properties about resources
|
||||
Lister appsv1.DeploymentLister
|
||||
|
||||
// Recorder is an event recorder for recording Event resources to the
|
||||
// Kubernetes API.
|
||||
Recorder record.EventRecorder
|
||||
|
||||
// configStore allows for decorating a context with config maps.
|
||||
// +optional
|
||||
configStore reconciler.ConfigStore
|
||||
|
||||
// reconciler is the implementation of the business logic of the resource.
|
||||
reconciler Interface
|
||||
|
||||
// finalizerName is the name of the finalizer to reconcile.
|
||||
finalizerName string
|
||||
|
||||
// skipStatusUpdates configures whether or not this reconciler automatically updates
|
||||
// the status of the reconciled resource.
|
||||
skipStatusUpdates bool
|
||||
}
|
||||
|
||||
// Check that our Reconciler implements controller.Reconciler
|
||||
var _ controller.Reconciler = (*reconcilerImpl)(nil)
|
||||
|
||||
// Check that our generated Reconciler is always LeaderAware.
|
||||
var _ reconciler.LeaderAware = (*reconcilerImpl)(nil)
|
||||
|
||||
func NewReconciler(ctx context.Context, logger *zap.SugaredLogger, client kubernetes.Interface, lister appsv1.DeploymentLister, recorder record.EventRecorder, r Interface, options ...controller.Options) controller.Reconciler {
|
||||
// Check the options function input. It should be 0 or 1.
|
||||
if len(options) > 1 {
|
||||
logger.Fatalf("up to one options struct is supported, found %d", len(options))
|
||||
}
|
||||
|
||||
// Fail fast when users inadvertently implement the other LeaderAware interface.
|
||||
// For the typed reconcilers, Promote shouldn't take any arguments.
|
||||
if _, ok := r.(reconciler.LeaderAware); ok {
|
||||
logger.Fatalf("%T implements the incorrect LeaderAware interface. Promote() should not take an argument as genreconciler handles the enqueuing automatically.", r)
|
||||
}
|
||||
// TODO: Consider validating when folks implement ReadOnlyFinalizer, but not Finalizer.
|
||||
|
||||
rec := &reconcilerImpl{
|
||||
LeaderAwareFuncs: reconciler.LeaderAwareFuncs{
|
||||
PromoteFunc: func(bkt reconciler.Bucket, enq func(reconciler.Bucket, types.NamespacedName)) error {
|
||||
all, err := lister.List(labels.Everything())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, elt := range all {
|
||||
// TODO: Consider letting users specify a filter in options.
|
||||
enq(bkt, types.NamespacedName{
|
||||
Namespace: elt.GetNamespace(),
|
||||
Name: elt.GetName(),
|
||||
})
|
||||
}
|
||||
return nil
|
||||
},
|
||||
},
|
||||
Client: client,
|
||||
Lister: lister,
|
||||
Recorder: recorder,
|
||||
reconciler: r,
|
||||
finalizerName: defaultFinalizerName,
|
||||
}
|
||||
|
||||
for _, opts := range options {
|
||||
if opts.ConfigStore != nil {
|
||||
rec.configStore = opts.ConfigStore
|
||||
}
|
||||
if opts.FinalizerName != "" {
|
||||
rec.finalizerName = opts.FinalizerName
|
||||
}
|
||||
if opts.SkipStatusUpdates {
|
||||
rec.skipStatusUpdates = true
|
||||
}
|
||||
}
|
||||
|
||||
return rec
|
||||
}
|
||||
|
||||
// Reconcile implements controller.Reconciler
|
||||
func (r *reconcilerImpl) Reconcile(ctx context.Context, key string) error {
|
||||
logger := logging.FromContext(ctx)
|
||||
|
||||
// Convert the namespace/name string into a distinct namespace and name
|
||||
namespace, name, err := cache.SplitMetaNamespaceKey(key)
|
||||
if err != nil {
|
||||
logger.Errorf("invalid resource key: %s", key)
|
||||
return nil
|
||||
}
|
||||
// Establish whether we are the leader for use below.
|
||||
isLeader := r.IsLeaderFor(types.NamespacedName{
|
||||
Namespace: namespace,
|
||||
Name: name,
|
||||
})
|
||||
roi, isROI := r.reconciler.(ReadOnlyInterface)
|
||||
rof, isROF := r.reconciler.(ReadOnlyFinalizer)
|
||||
if !isLeader && !isROI && !isROF {
|
||||
// If we are not the leader, and we don't implement either ReadOnly
|
||||
// interface, then take a fast-path out.
|
||||
return nil
|
||||
}
|
||||
|
||||
// If configStore is set, attach the frozen configuration to the context.
|
||||
if r.configStore != nil {
|
||||
ctx = r.configStore.ToContext(ctx)
|
||||
}
|
||||
|
||||
// Add the recorder to context.
|
||||
ctx = controller.WithEventRecorder(ctx, r.Recorder)
|
||||
|
||||
// Get the resource with this namespace/name.
|
||||
|
||||
getter := r.Lister.Deployments(namespace)
|
||||
|
||||
original, err := getter.Get(name)
|
||||
|
||||
if errors.IsNotFound(err) {
|
||||
// The resource may no longer exist, in which case we stop processing.
|
||||
logger.Debugf("resource %q no longer exists", key)
|
||||
return nil
|
||||
} else if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Don't modify the informers copy.
|
||||
resource := original.DeepCopy()
|
||||
|
||||
var reconcileEvent reconciler.Event
|
||||
if resource.GetDeletionTimestamp().IsZero() {
|
||||
if isLeader {
|
||||
// Append the target method to the logger.
|
||||
logger = logger.With(zap.String("targetMethod", "ReconcileKind"))
|
||||
|
||||
// Set and update the finalizer on resource if r.reconciler
|
||||
// implements Finalizer.
|
||||
if resource, err = r.setFinalizerIfFinalizer(ctx, resource); err != nil {
|
||||
return fmt.Errorf("failed to set finalizers: %w", err)
|
||||
}
|
||||
|
||||
// Reconcile this copy of the resource and then write back any status
|
||||
// updates regardless of whether the reconciliation errored out.
|
||||
reconcileEvent = r.reconciler.ReconcileKind(ctx, resource)
|
||||
|
||||
} else if isROI {
|
||||
// Append the target method to the logger.
|
||||
logger = logger.With(zap.String("targetMethod", "ObserveKind"))
|
||||
|
||||
// Observe any changes to this resource, since we are not the leader.
|
||||
reconcileEvent = roi.ObserveKind(ctx, resource)
|
||||
}
|
||||
} else if fin, ok := r.reconciler.(Finalizer); isLeader && ok {
|
||||
// Append the target method to the logger.
|
||||
logger = logger.With(zap.String("targetMethod", "FinalizeKind"))
|
||||
|
||||
// For finalizing reconcilers, if this resource being marked for deletion
|
||||
// and reconciled cleanly (nil or normal event), remove the finalizer.
|
||||
reconcileEvent = fin.FinalizeKind(ctx, resource)
|
||||
if resource, err = r.clearFinalizer(ctx, resource, reconcileEvent); err != nil {
|
||||
return fmt.Errorf("failed to clear finalizers: %w", err)
|
||||
}
|
||||
} else if !isLeader && isROF {
|
||||
// Append the target method to the logger.
|
||||
logger = logger.With(zap.String("targetMethod", "ObserveFinalizeKind"))
|
||||
|
||||
// For finalizing reconcilers, just observe when we aren't the leader.
|
||||
reconcileEvent = rof.ObserveFinalizeKind(ctx, resource)
|
||||
}
|
||||
|
||||
// Synchronize the status.
|
||||
switch {
|
||||
case r.skipStatusUpdates:
|
||||
// This reconciler implementation is configured to skip resource updates.
|
||||
// This may mean this reconciler does not observe spec, but reconciles external changes.
|
||||
case equality.Semantic.DeepEqual(original.Status, resource.Status):
|
||||
// If we didn't change anything then don't call updateStatus.
|
||||
// This is important because the copy we loaded from the injectionInformer's
|
||||
// cache may be stale and we don't want to overwrite a prior update
|
||||
// to status with this stale state.
|
||||
case !isLeader:
|
||||
// High-availability reconcilers may have many replicas watching the resource, but only
|
||||
// the elected leader is expected to write modifications.
|
||||
logger.Warn("Saw status changes when we aren't the leader!")
|
||||
default:
|
||||
if err = r.updateStatus(original, resource); err != nil {
|
||||
logger.Warnw("Failed to update resource status", zap.Error(err))
|
||||
r.Recorder.Eventf(resource, corev1.EventTypeWarning, "UpdateFailed",
|
||||
"Failed to update status for %q: %v", resource.Name, err)
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// Report the reconciler event, if any.
|
||||
if reconcileEvent != nil {
|
||||
var event *reconciler.ReconcilerEvent
|
||||
if reconciler.EventAs(reconcileEvent, &event) {
|
||||
logger.Infow("Returned an event", zap.Any("event", reconcileEvent))
|
||||
r.Recorder.Eventf(resource, event.EventType, event.Reason, event.Format, event.Args...)
|
||||
|
||||
// the event was wrapped inside an error, consider the reconciliation as failed
|
||||
if _, isEvent := reconcileEvent.(*reconciler.ReconcilerEvent); !isEvent {
|
||||
return reconcileEvent
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
logger.Errorw("Returned an error", zap.Error(reconcileEvent))
|
||||
r.Recorder.Event(resource, corev1.EventTypeWarning, "InternalError", reconcileEvent.Error())
|
||||
return reconcileEvent
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *reconcilerImpl) updateStatus(existing *v1.Deployment, desired *v1.Deployment) error {
|
||||
existing = existing.DeepCopy()
|
||||
return reconciler.RetryUpdateConflicts(func(attempts int) (err error) {
|
||||
// The first iteration tries to use the injectionInformer's state, subsequent attempts fetch the latest state via API.
|
||||
if attempts > 0 {
|
||||
|
||||
getter := r.Client.AppsV1().Deployments(desired.Namespace)
|
||||
|
||||
existing, err = getter.Get(desired.Name, metav1.GetOptions{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// If there's nothing to update, just return.
|
||||
if reflect.DeepEqual(existing.Status, desired.Status) {
|
||||
return nil
|
||||
}
|
||||
|
||||
existing.Status = desired.Status
|
||||
|
||||
updater := r.Client.AppsV1().Deployments(existing.Namespace)
|
||||
|
||||
_, err = updater.UpdateStatus(existing)
|
||||
return err
|
||||
})
|
||||
}
|
||||
|
||||
// updateFinalizersFiltered will update the Finalizers of the resource.
|
||||
// TODO: this method could be generic and sync all finalizers. For now it only
|
||||
// updates defaultFinalizerName or its override.
|
||||
func (r *reconcilerImpl) updateFinalizersFiltered(ctx context.Context, resource *v1.Deployment) (*v1.Deployment, error) {
|
||||
|
||||
getter := r.Lister.Deployments(resource.Namespace)
|
||||
|
||||
actual, err := getter.Get(resource.Name)
|
||||
if err != nil {
|
||||
return resource, err
|
||||
}
|
||||
|
||||
// Don't modify the informers copy.
|
||||
existing := actual.DeepCopy()
|
||||
|
||||
var finalizers []string
|
||||
|
||||
// If there's nothing to update, just return.
|
||||
existingFinalizers := sets.NewString(existing.Finalizers...)
|
||||
desiredFinalizers := sets.NewString(resource.Finalizers...)
|
||||
|
||||
if desiredFinalizers.Has(r.finalizerName) {
|
||||
if existingFinalizers.Has(r.finalizerName) {
|
||||
// Nothing to do.
|
||||
return resource, nil
|
||||
}
|
||||
// Add the finalizer.
|
||||
finalizers = append(existing.Finalizers, r.finalizerName)
|
||||
} else {
|
||||
if !existingFinalizers.Has(r.finalizerName) {
|
||||
// Nothing to do.
|
||||
return resource, nil
|
||||
}
|
||||
// Remove the finalizer.
|
||||
existingFinalizers.Delete(r.finalizerName)
|
||||
finalizers = existingFinalizers.List()
|
||||
}
|
||||
|
||||
mergePatch := map[string]interface{}{
|
||||
"metadata": map[string]interface{}{
|
||||
"finalizers": finalizers,
|
||||
"resourceVersion": existing.ResourceVersion,
|
||||
},
|
||||
}
|
||||
|
||||
patch, err := json.Marshal(mergePatch)
|
||||
if err != nil {
|
||||
return resource, err
|
||||
}
|
||||
|
||||
patcher := r.Client.AppsV1().Deployments(resource.Namespace)
|
||||
|
||||
resourceName := resource.Name
|
||||
resource, err = patcher.Patch(resourceName, types.MergePatchType, patch)
|
||||
if err != nil {
|
||||
r.Recorder.Eventf(resource, corev1.EventTypeWarning, "FinalizerUpdateFailed",
|
||||
"Failed to update finalizers for %q: %v", resourceName, err)
|
||||
} else {
|
||||
r.Recorder.Eventf(resource, corev1.EventTypeNormal, "FinalizerUpdate",
|
||||
"Updated %q finalizers", resource.GetName())
|
||||
}
|
||||
return resource, err
|
||||
}
|
||||
|
||||
func (r *reconcilerImpl) setFinalizerIfFinalizer(ctx context.Context, resource *v1.Deployment) (*v1.Deployment, error) {
|
||||
if _, ok := r.reconciler.(Finalizer); !ok {
|
||||
return resource, nil
|
||||
}
|
||||
|
||||
finalizers := sets.NewString(resource.Finalizers...)
|
||||
|
||||
// If this resource is not being deleted, mark the finalizer.
|
||||
if resource.GetDeletionTimestamp().IsZero() {
|
||||
finalizers.Insert(r.finalizerName)
|
||||
}
|
||||
|
||||
resource.Finalizers = finalizers.List()
|
||||
|
||||
// Synchronize the finalizers filtered by r.finalizerName.
|
||||
return r.updateFinalizersFiltered(ctx, resource)
|
||||
}
|
||||
|
||||
func (r *reconcilerImpl) clearFinalizer(ctx context.Context, resource *v1.Deployment, reconcileEvent reconciler.Event) (*v1.Deployment, error) {
|
||||
if _, ok := r.reconciler.(Finalizer); !ok {
|
||||
return resource, nil
|
||||
}
|
||||
if resource.GetDeletionTimestamp().IsZero() {
|
||||
return resource, nil
|
||||
}
|
||||
|
||||
finalizers := sets.NewString(resource.Finalizers...)
|
||||
|
||||
if reconcileEvent != nil {
|
||||
var event *reconciler.ReconcilerEvent
|
||||
if reconciler.EventAs(reconcileEvent, &event) {
|
||||
if event.EventType == corev1.EventTypeNormal {
|
||||
finalizers.Delete(r.finalizerName)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
finalizers.Delete(r.finalizerName)
|
||||
}
|
||||
|
||||
resource.Finalizers = finalizers.List()
|
||||
|
||||
// Synchronize the finalizers filtered by r.finalizerName.
|
||||
return r.updateFinalizersFiltered(ctx, resource)
|
||||
}
|
|
@ -0,0 +1,54 @@
|
|||
/*
|
||||
Copyright 2020 The Knative 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.
|
||||
*/
|
||||
|
||||
// Code generated by injection-gen. DO NOT EDIT.
|
||||
|
||||
package deployment
|
||||
|
||||
import (
|
||||
context "context"
|
||||
|
||||
deployment "knative.dev/pkg/client/injection/kube/informers/apps/v1/deployment"
|
||||
v1deployment "knative.dev/pkg/client/injection/kube/reconciler/apps/v1/deployment"
|
||||
configmap "knative.dev/pkg/configmap"
|
||||
controller "knative.dev/pkg/controller"
|
||||
logging "knative.dev/pkg/logging"
|
||||
)
|
||||
|
||||
// TODO: PLEASE COPY AND MODIFY THIS FILE AS A STARTING POINT
|
||||
|
||||
// NewController creates a Reconciler for Deployment and returns the result of NewImpl.
|
||||
func NewController(
|
||||
ctx context.Context,
|
||||
cmw configmap.Watcher,
|
||||
) *controller.Impl {
|
||||
logger := logging.FromContext(ctx)
|
||||
|
||||
deploymentInformer := deployment.Get(ctx)
|
||||
|
||||
// TODO: setup additional informers here.
|
||||
|
||||
r := &Reconciler{}
|
||||
impl := v1deployment.NewImpl(ctx, r)
|
||||
|
||||
logger.Info("Setting up event handlers.")
|
||||
|
||||
deploymentInformer.Informer().AddEventHandler(controller.HandleAll(impl.Enqueue))
|
||||
|
||||
// TODO: add additional informer event handlers here.
|
||||
|
||||
return impl
|
||||
}
|
|
@ -0,0 +1,87 @@
|
|||
/*
|
||||
Copyright 2020 The Knative 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.
|
||||
*/
|
||||
|
||||
// Code generated by injection-gen. DO NOT EDIT.
|
||||
|
||||
package deployment
|
||||
|
||||
import (
|
||||
context "context"
|
||||
|
||||
appsv1 "k8s.io/api/apps/v1"
|
||||
v1 "k8s.io/api/core/v1"
|
||||
deployment "knative.dev/pkg/client/injection/kube/reconciler/apps/v1/deployment"
|
||||
reconciler "knative.dev/pkg/reconciler"
|
||||
)
|
||||
|
||||
// TODO: PLEASE COPY AND MODIFY THIS FILE AS A STARTING POINT
|
||||
|
||||
// newReconciledNormal makes a new reconciler event with event type Normal, and
|
||||
// reason DeploymentReconciled.
|
||||
func newReconciledNormal(namespace, name string) reconciler.Event {
|
||||
return reconciler.NewEvent(v1.EventTypeNormal, "DeploymentReconciled", "Deployment reconciled: \"%s/%s\"", namespace, name)
|
||||
}
|
||||
|
||||
// Reconciler implements controller.Reconciler for Deployment resources.
|
||||
type Reconciler struct {
|
||||
// TODO: add additional requirements here.
|
||||
}
|
||||
|
||||
// Check that our Reconciler implements Interface
|
||||
var _ deployment.Interface = (*Reconciler)(nil)
|
||||
|
||||
// Optionally check that our Reconciler implements Finalizer
|
||||
//var _ deployment.Finalizer = (*Reconciler)(nil)
|
||||
|
||||
// Optionally check that our Reconciler implements ReadOnlyInterface
|
||||
// Implement this to observe resources even when we are not the leader.
|
||||
//var _ deployment.ReadOnlyInterface = (*Reconciler)(nil)
|
||||
|
||||
// Optionally check that our Reconciler implements ReadOnlyFinalizer
|
||||
// Implement this to observe tombstoned resources even when we are not
|
||||
// the leader (best effort).
|
||||
//var _ deployment.ReadOnlyFinalizer = (*Reconciler)(nil)
|
||||
|
||||
// ReconcileKind implements Interface.ReconcileKind.
|
||||
func (r *Reconciler) ReconcileKind(ctx context.Context, o *appsv1.Deployment) reconciler.Event {
|
||||
// TODO: use this if the resource implements InitializeConditions.
|
||||
// o.Status.InitializeConditions()
|
||||
|
||||
// TODO: add custom reconciliation logic here.
|
||||
|
||||
// TODO: use this if the object has .status.ObservedGeneration.
|
||||
// o.Status.ObservedGeneration = o.Generation
|
||||
return newReconciledNormal(o.Namespace, o.Name)
|
||||
}
|
||||
|
||||
// Optionally, use FinalizeKind to add finalizers. FinalizeKind will be called
|
||||
// when the resource is deleted.
|
||||
//func (r *Reconciler) FinalizeKind(ctx context.Context, o *appsv1.Deployment) reconciler.Event {
|
||||
// // TODO: add custom finalization logic here.
|
||||
// return nil
|
||||
//}
|
||||
|
||||
// Optionally, use ObserveKind to observe the resource when we are not the leader.
|
||||
// func (r *Reconciler) ObserveKind(ctx context.Context, o *appsv1.Deployment) reconciler.Event {
|
||||
// // TODO: add custom observation logic here.
|
||||
// return nil
|
||||
// }
|
||||
|
||||
// Optionally, use ObserveFinalizeKind to observe resources being finalized when we are no the leader.
|
||||
//func (r *Reconciler) ObserveFinalizeKind(ctx context.Context, o *appsv1.Deployment) reconciler.Event {
|
||||
// // TODO: add custom observation logic here.
|
||||
// return nil
|
||||
//}
|
|
@ -49,7 +49,7 @@ EXTERNAL_INFORMER_PKG="k8s.io/client-go/informers" \
|
|||
k8s.io/api \
|
||||
"admissionregistration:v1beta1,v1 apps:v1 autoscaling:v1,v2beta1 batch:v1,v1beta1 core:v1 rbac:v1" \
|
||||
--go-header-file ${REPO_ROOT_DIR}/hack/boilerplate/boilerplate.go.txt \
|
||||
--force-genreconciler-kinds "Namespace"
|
||||
--force-genreconciler-kinds "Namespace,Deployment"
|
||||
|
||||
OUTPUT_PKG="knative.dev/pkg/client/injection/apiextensions" \
|
||||
VERSIONED_CLIENTSET_PKG="k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset" \
|
||||
|
|
Loading…
Reference in New Issue