diff --git a/Gopkg.lock b/Gopkg.lock index c6af90ad16..747ef6c81f 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -1438,7 +1438,7 @@ [[projects]] branch = "master" - digest = "1:970b0b39f05fb98a9e5927deb3e531f88250a95750fac802de9bd77c58ba764c" + digest = "1:213b2f54af186f00f05ece9a6d4f3d9e1a3cb713e535e655e23042dab5142ac1" name = "knative.dev/eventing" packages = [ "pkg/apis/config", @@ -1534,11 +1534,11 @@ "test/test_images/transformevents", ] pruneopts = "UT" - revision = "8b4a6f7b49643df73ae95d457181b6614e9d4f75" + revision = "bf7b1bcb500c0bd1ec2b9300ebbf246152a7ab7c" [[projects]] branch = "master" - digest = "1:9a3d6a5933182bb0ac923b36a7e581b19ea23edeb6684eabe14002758cd7b067" + digest = "1:664207d75dbcaeab206d93b3dcd8098c59e3b6b21378af02d686579e491fc859" name = "knative.dev/pkg" packages = [ "apis", @@ -1619,11 +1619,11 @@ "webhook/resourcesemantics/validation", ] pruneopts = "T" - revision = "9f9f7bea94e15840f36f08b90a2c03203e886f91" + revision = "8a6d25b30970038d1e24ddf5f6e0cec129c9564c" [[projects]] branch = "master" - digest = "1:a7e28db403d1991559122ff01ecd5724a5aef2c6f88f6a1227788f8145d0f76b" + digest = "1:4e2670fac5b2a25699102035493f3d4b9964fdcb87299d20ea37573a22b5db6c" name = "knative.dev/serving" packages = [ "pkg/apis/autoscaling", @@ -1672,7 +1672,7 @@ "pkg/client/listers/serving/v1beta1", ] pruneopts = "NUT" - revision = "aa3d5708fb6bc8e35324f3dab764c2ca0a7e6892" + revision = "54cbd0ecf2f8247b5a93a2c0e6785e541ad2d399" [[projects]] branch = "master" @@ -1683,7 +1683,7 @@ "tools/dep-collector", ] pruneopts = "UT" - revision = "9a501343b4dafbac1a1a5dcfe2cb46975a78abb5" + revision = "9a6c4b1d41ce980537cebe2b34c4b8c92fbd2b47" [[projects]] digest = "1:8730e0150dfb2b7e173890c8b9868e7a273082ef8e39f4940e3506a481cf895c" diff --git a/pkg/client/injection/reconciler/events/v1alpha1/cloudauditlogssource/reconciler.go b/pkg/client/injection/reconciler/events/v1alpha1/cloudauditlogssource/reconciler.go index 3e4e8b5f77..4d841e766a 100644 --- a/pkg/client/injection/reconciler/events/v1alpha1/cloudauditlogssource/reconciler.go +++ b/pkg/client/injection/reconciler/events/v1alpha1/cloudauditlogssource/reconciler.go @@ -121,14 +121,20 @@ func (r *reconcilerImpl) Reconcile(ctx context.Context, key string) error { ctx = controller.WithEventRecorder(ctx, r.Recorder) // 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 } // Get the resource with this namespace/name. - original, err := r.Lister.CloudAuditLogsSources(namespace).Get(name) + + getter := r.Lister.CloudAuditLogsSources(namespace) + + original, err := getter.Get(name) + if errors.IsNotFound(err) { // The resource may no longer exist, in which case we stop processing. logger.Errorf("resource %q no longer exists", key) @@ -200,7 +206,10 @@ func (r *reconcilerImpl) updateStatus(existing *v1alpha1.CloudAuditLogsSource, d 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 { - existing, err = r.Client.EventsV1alpha1().CloudAuditLogsSources(desired.Namespace).Get(desired.Name, metav1.GetOptions{}) + + getter := r.Client.EventsV1alpha1().CloudAuditLogsSources(desired.Namespace) + + existing, err = getter.Get(desired.Name, metav1.GetOptions{}) if err != nil { return err } @@ -212,7 +221,10 @@ func (r *reconcilerImpl) updateStatus(existing *v1alpha1.CloudAuditLogsSource, d } existing.Status = desired.Status - _, err = r.Client.EventsV1alpha1().CloudAuditLogsSources(existing.Namespace).UpdateStatus(existing) + + updater := r.Client.EventsV1alpha1().CloudAuditLogsSources(existing.Namespace) + + _, err = updater.UpdateStatus(existing) return err }) } @@ -223,7 +235,9 @@ func (r *reconcilerImpl) updateStatus(existing *v1alpha1.CloudAuditLogsSource, d func (r *reconcilerImpl) updateFinalizersFiltered(ctx context.Context, resource *v1alpha1.CloudAuditLogsSource) (*v1alpha1.CloudAuditLogsSource, error) { finalizerName := defaultFinalizerName - actual, err := r.Lister.CloudAuditLogsSources(resource.Namespace).Get(resource.Name) + getter := r.Lister.CloudAuditLogsSources(resource.Namespace) + + actual, err := getter.Get(resource.Name) if err != nil { return resource, err } @@ -266,7 +280,9 @@ func (r *reconcilerImpl) updateFinalizersFiltered(ctx context.Context, resource return resource, err } - resource, err = r.Client.EventsV1alpha1().CloudAuditLogsSources(resource.Namespace).Patch(resource.Name, types.MergePatchType, patch) + patcher := r.Client.EventsV1alpha1().CloudAuditLogsSources(resource.Namespace) + + resource, err = patcher.Patch(resource.Name, types.MergePatchType, patch) if err != nil { r.Recorder.Eventf(resource, v1.EventTypeWarning, "FinalizerUpdateFailed", "Failed to update finalizers for %q: %v", resource.Name, err) diff --git a/pkg/client/injection/reconciler/events/v1alpha1/cloudauditlogssource/stub/reconciler.go b/pkg/client/injection/reconciler/events/v1alpha1/cloudauditlogssource/stub/reconciler.go index 7e763b41c0..62ac753010 100644 --- a/pkg/client/injection/reconciler/events/v1alpha1/cloudauditlogssource/stub/reconciler.go +++ b/pkg/client/injection/reconciler/events/v1alpha1/cloudauditlogssource/stub/reconciler.go @@ -48,11 +48,13 @@ var _ cloudauditlogssource.Interface = (*Reconciler)(nil) // ReconcileKind implements Interface.ReconcileKind. func (r *Reconciler) ReconcileKind(ctx context.Context, o *v1alpha1.CloudAuditLogsSource) reconciler.Event { - o.Status.InitializeConditions() + // TODO: use this if the resource implements InitializeConditions. + // o.Status.InitializeConditions() // TODO: add custom reconciliation logic here. - o.Status.ObservedGeneration = o.Generation + // TODO: use this if the object has .status.ObservedGeneration. + // o.Status.ObservedGeneration = o.Generation return newReconciledNormal(o.Namespace, o.Name) } diff --git a/pkg/client/injection/reconciler/events/v1alpha1/cloudpubsubsource/reconciler.go b/pkg/client/injection/reconciler/events/v1alpha1/cloudpubsubsource/reconciler.go index 65907ea537..1fe022f506 100644 --- a/pkg/client/injection/reconciler/events/v1alpha1/cloudpubsubsource/reconciler.go +++ b/pkg/client/injection/reconciler/events/v1alpha1/cloudpubsubsource/reconciler.go @@ -121,14 +121,20 @@ func (r *reconcilerImpl) Reconcile(ctx context.Context, key string) error { ctx = controller.WithEventRecorder(ctx, r.Recorder) // 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 } // Get the resource with this namespace/name. - original, err := r.Lister.CloudPubSubSources(namespace).Get(name) + + getter := r.Lister.CloudPubSubSources(namespace) + + original, err := getter.Get(name) + if errors.IsNotFound(err) { // The resource may no longer exist, in which case we stop processing. logger.Errorf("resource %q no longer exists", key) @@ -200,7 +206,10 @@ func (r *reconcilerImpl) updateStatus(existing *v1alpha1.CloudPubSubSource, desi 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 { - existing, err = r.Client.EventsV1alpha1().CloudPubSubSources(desired.Namespace).Get(desired.Name, metav1.GetOptions{}) + + getter := r.Client.EventsV1alpha1().CloudPubSubSources(desired.Namespace) + + existing, err = getter.Get(desired.Name, metav1.GetOptions{}) if err != nil { return err } @@ -212,7 +221,10 @@ func (r *reconcilerImpl) updateStatus(existing *v1alpha1.CloudPubSubSource, desi } existing.Status = desired.Status - _, err = r.Client.EventsV1alpha1().CloudPubSubSources(existing.Namespace).UpdateStatus(existing) + + updater := r.Client.EventsV1alpha1().CloudPubSubSources(existing.Namespace) + + _, err = updater.UpdateStatus(existing) return err }) } @@ -223,7 +235,9 @@ func (r *reconcilerImpl) updateStatus(existing *v1alpha1.CloudPubSubSource, desi func (r *reconcilerImpl) updateFinalizersFiltered(ctx context.Context, resource *v1alpha1.CloudPubSubSource) (*v1alpha1.CloudPubSubSource, error) { finalizerName := defaultFinalizerName - actual, err := r.Lister.CloudPubSubSources(resource.Namespace).Get(resource.Name) + getter := r.Lister.CloudPubSubSources(resource.Namespace) + + actual, err := getter.Get(resource.Name) if err != nil { return resource, err } @@ -266,7 +280,9 @@ func (r *reconcilerImpl) updateFinalizersFiltered(ctx context.Context, resource return resource, err } - resource, err = r.Client.EventsV1alpha1().CloudPubSubSources(resource.Namespace).Patch(resource.Name, types.MergePatchType, patch) + patcher := r.Client.EventsV1alpha1().CloudPubSubSources(resource.Namespace) + + resource, err = patcher.Patch(resource.Name, types.MergePatchType, patch) if err != nil { r.Recorder.Eventf(resource, v1.EventTypeWarning, "FinalizerUpdateFailed", "Failed to update finalizers for %q: %v", resource.Name, err) diff --git a/pkg/client/injection/reconciler/events/v1alpha1/cloudpubsubsource/stub/reconciler.go b/pkg/client/injection/reconciler/events/v1alpha1/cloudpubsubsource/stub/reconciler.go index e53148978a..d609370455 100644 --- a/pkg/client/injection/reconciler/events/v1alpha1/cloudpubsubsource/stub/reconciler.go +++ b/pkg/client/injection/reconciler/events/v1alpha1/cloudpubsubsource/stub/reconciler.go @@ -48,11 +48,13 @@ var _ cloudpubsubsource.Interface = (*Reconciler)(nil) // ReconcileKind implements Interface.ReconcileKind. func (r *Reconciler) ReconcileKind(ctx context.Context, o *v1alpha1.CloudPubSubSource) reconciler.Event { - o.Status.InitializeConditions() + // TODO: use this if the resource implements InitializeConditions. + // o.Status.InitializeConditions() // TODO: add custom reconciliation logic here. - o.Status.ObservedGeneration = o.Generation + // TODO: use this if the object has .status.ObservedGeneration. + // o.Status.ObservedGeneration = o.Generation return newReconciledNormal(o.Namespace, o.Name) } diff --git a/pkg/client/injection/reconciler/events/v1alpha1/cloudschedulersource/reconciler.go b/pkg/client/injection/reconciler/events/v1alpha1/cloudschedulersource/reconciler.go index e441383416..ad6bd72346 100644 --- a/pkg/client/injection/reconciler/events/v1alpha1/cloudschedulersource/reconciler.go +++ b/pkg/client/injection/reconciler/events/v1alpha1/cloudschedulersource/reconciler.go @@ -121,14 +121,20 @@ func (r *reconcilerImpl) Reconcile(ctx context.Context, key string) error { ctx = controller.WithEventRecorder(ctx, r.Recorder) // 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 } // Get the resource with this namespace/name. - original, err := r.Lister.CloudSchedulerSources(namespace).Get(name) + + getter := r.Lister.CloudSchedulerSources(namespace) + + original, err := getter.Get(name) + if errors.IsNotFound(err) { // The resource may no longer exist, in which case we stop processing. logger.Errorf("resource %q no longer exists", key) @@ -200,7 +206,10 @@ func (r *reconcilerImpl) updateStatus(existing *v1alpha1.CloudSchedulerSource, d 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 { - existing, err = r.Client.EventsV1alpha1().CloudSchedulerSources(desired.Namespace).Get(desired.Name, metav1.GetOptions{}) + + getter := r.Client.EventsV1alpha1().CloudSchedulerSources(desired.Namespace) + + existing, err = getter.Get(desired.Name, metav1.GetOptions{}) if err != nil { return err } @@ -212,7 +221,10 @@ func (r *reconcilerImpl) updateStatus(existing *v1alpha1.CloudSchedulerSource, d } existing.Status = desired.Status - _, err = r.Client.EventsV1alpha1().CloudSchedulerSources(existing.Namespace).UpdateStatus(existing) + + updater := r.Client.EventsV1alpha1().CloudSchedulerSources(existing.Namespace) + + _, err = updater.UpdateStatus(existing) return err }) } @@ -223,7 +235,9 @@ func (r *reconcilerImpl) updateStatus(existing *v1alpha1.CloudSchedulerSource, d func (r *reconcilerImpl) updateFinalizersFiltered(ctx context.Context, resource *v1alpha1.CloudSchedulerSource) (*v1alpha1.CloudSchedulerSource, error) { finalizerName := defaultFinalizerName - actual, err := r.Lister.CloudSchedulerSources(resource.Namespace).Get(resource.Name) + getter := r.Lister.CloudSchedulerSources(resource.Namespace) + + actual, err := getter.Get(resource.Name) if err != nil { return resource, err } @@ -266,7 +280,9 @@ func (r *reconcilerImpl) updateFinalizersFiltered(ctx context.Context, resource return resource, err } - resource, err = r.Client.EventsV1alpha1().CloudSchedulerSources(resource.Namespace).Patch(resource.Name, types.MergePatchType, patch) + patcher := r.Client.EventsV1alpha1().CloudSchedulerSources(resource.Namespace) + + resource, err = patcher.Patch(resource.Name, types.MergePatchType, patch) if err != nil { r.Recorder.Eventf(resource, v1.EventTypeWarning, "FinalizerUpdateFailed", "Failed to update finalizers for %q: %v", resource.Name, err) diff --git a/pkg/client/injection/reconciler/events/v1alpha1/cloudschedulersource/stub/reconciler.go b/pkg/client/injection/reconciler/events/v1alpha1/cloudschedulersource/stub/reconciler.go index 03c5a4bc36..bbd65cd785 100644 --- a/pkg/client/injection/reconciler/events/v1alpha1/cloudschedulersource/stub/reconciler.go +++ b/pkg/client/injection/reconciler/events/v1alpha1/cloudschedulersource/stub/reconciler.go @@ -48,11 +48,13 @@ var _ cloudschedulersource.Interface = (*Reconciler)(nil) // ReconcileKind implements Interface.ReconcileKind. func (r *Reconciler) ReconcileKind(ctx context.Context, o *v1alpha1.CloudSchedulerSource) reconciler.Event { - o.Status.InitializeConditions() + // TODO: use this if the resource implements InitializeConditions. + // o.Status.InitializeConditions() // TODO: add custom reconciliation logic here. - o.Status.ObservedGeneration = o.Generation + // TODO: use this if the object has .status.ObservedGeneration. + // o.Status.ObservedGeneration = o.Generation return newReconciledNormal(o.Namespace, o.Name) } diff --git a/pkg/client/injection/reconciler/events/v1alpha1/cloudstoragesource/reconciler.go b/pkg/client/injection/reconciler/events/v1alpha1/cloudstoragesource/reconciler.go index 3181bb811d..1a4aee0dc7 100644 --- a/pkg/client/injection/reconciler/events/v1alpha1/cloudstoragesource/reconciler.go +++ b/pkg/client/injection/reconciler/events/v1alpha1/cloudstoragesource/reconciler.go @@ -121,14 +121,20 @@ func (r *reconcilerImpl) Reconcile(ctx context.Context, key string) error { ctx = controller.WithEventRecorder(ctx, r.Recorder) // 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 } // Get the resource with this namespace/name. - original, err := r.Lister.CloudStorageSources(namespace).Get(name) + + getter := r.Lister.CloudStorageSources(namespace) + + original, err := getter.Get(name) + if errors.IsNotFound(err) { // The resource may no longer exist, in which case we stop processing. logger.Errorf("resource %q no longer exists", key) @@ -200,7 +206,10 @@ func (r *reconcilerImpl) updateStatus(existing *v1alpha1.CloudStorageSource, des 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 { - existing, err = r.Client.EventsV1alpha1().CloudStorageSources(desired.Namespace).Get(desired.Name, metav1.GetOptions{}) + + getter := r.Client.EventsV1alpha1().CloudStorageSources(desired.Namespace) + + existing, err = getter.Get(desired.Name, metav1.GetOptions{}) if err != nil { return err } @@ -212,7 +221,10 @@ func (r *reconcilerImpl) updateStatus(existing *v1alpha1.CloudStorageSource, des } existing.Status = desired.Status - _, err = r.Client.EventsV1alpha1().CloudStorageSources(existing.Namespace).UpdateStatus(existing) + + updater := r.Client.EventsV1alpha1().CloudStorageSources(existing.Namespace) + + _, err = updater.UpdateStatus(existing) return err }) } @@ -223,7 +235,9 @@ func (r *reconcilerImpl) updateStatus(existing *v1alpha1.CloudStorageSource, des func (r *reconcilerImpl) updateFinalizersFiltered(ctx context.Context, resource *v1alpha1.CloudStorageSource) (*v1alpha1.CloudStorageSource, error) { finalizerName := defaultFinalizerName - actual, err := r.Lister.CloudStorageSources(resource.Namespace).Get(resource.Name) + getter := r.Lister.CloudStorageSources(resource.Namespace) + + actual, err := getter.Get(resource.Name) if err != nil { return resource, err } @@ -266,7 +280,9 @@ func (r *reconcilerImpl) updateFinalizersFiltered(ctx context.Context, resource return resource, err } - resource, err = r.Client.EventsV1alpha1().CloudStorageSources(resource.Namespace).Patch(resource.Name, types.MergePatchType, patch) + patcher := r.Client.EventsV1alpha1().CloudStorageSources(resource.Namespace) + + resource, err = patcher.Patch(resource.Name, types.MergePatchType, patch) if err != nil { r.Recorder.Eventf(resource, v1.EventTypeWarning, "FinalizerUpdateFailed", "Failed to update finalizers for %q: %v", resource.Name, err) diff --git a/pkg/client/injection/reconciler/events/v1alpha1/cloudstoragesource/stub/reconciler.go b/pkg/client/injection/reconciler/events/v1alpha1/cloudstoragesource/stub/reconciler.go index 9074c6eb4b..d3d13383d3 100644 --- a/pkg/client/injection/reconciler/events/v1alpha1/cloudstoragesource/stub/reconciler.go +++ b/pkg/client/injection/reconciler/events/v1alpha1/cloudstoragesource/stub/reconciler.go @@ -48,11 +48,13 @@ var _ cloudstoragesource.Interface = (*Reconciler)(nil) // ReconcileKind implements Interface.ReconcileKind. func (r *Reconciler) ReconcileKind(ctx context.Context, o *v1alpha1.CloudStorageSource) reconciler.Event { - o.Status.InitializeConditions() + // TODO: use this if the resource implements InitializeConditions. + // o.Status.InitializeConditions() // TODO: add custom reconciliation logic here. - o.Status.ObservedGeneration = o.Generation + // TODO: use this if the object has .status.ObservedGeneration. + // o.Status.ObservedGeneration = o.Generation return newReconciledNormal(o.Namespace, o.Name) } diff --git a/pkg/client/injection/reconciler/messaging/v1alpha1/channel/reconciler.go b/pkg/client/injection/reconciler/messaging/v1alpha1/channel/reconciler.go index 08fdc372d4..8c58868d42 100644 --- a/pkg/client/injection/reconciler/messaging/v1alpha1/channel/reconciler.go +++ b/pkg/client/injection/reconciler/messaging/v1alpha1/channel/reconciler.go @@ -121,14 +121,20 @@ func (r *reconcilerImpl) Reconcile(ctx context.Context, key string) error { ctx = controller.WithEventRecorder(ctx, r.Recorder) // 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 } // Get the resource with this namespace/name. - original, err := r.Lister.Channels(namespace).Get(name) + + getter := r.Lister.Channels(namespace) + + original, err := getter.Get(name) + if errors.IsNotFound(err) { // The resource may no longer exist, in which case we stop processing. logger.Errorf("resource %q no longer exists", key) @@ -200,7 +206,10 @@ func (r *reconcilerImpl) updateStatus(existing *v1alpha1.Channel, desired *v1alp 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 { - existing, err = r.Client.MessagingV1alpha1().Channels(desired.Namespace).Get(desired.Name, metav1.GetOptions{}) + + getter := r.Client.MessagingV1alpha1().Channels(desired.Namespace) + + existing, err = getter.Get(desired.Name, metav1.GetOptions{}) if err != nil { return err } @@ -212,7 +221,10 @@ func (r *reconcilerImpl) updateStatus(existing *v1alpha1.Channel, desired *v1alp } existing.Status = desired.Status - _, err = r.Client.MessagingV1alpha1().Channels(existing.Namespace).UpdateStatus(existing) + + updater := r.Client.MessagingV1alpha1().Channels(existing.Namespace) + + _, err = updater.UpdateStatus(existing) return err }) } @@ -223,7 +235,9 @@ func (r *reconcilerImpl) updateStatus(existing *v1alpha1.Channel, desired *v1alp func (r *reconcilerImpl) updateFinalizersFiltered(ctx context.Context, resource *v1alpha1.Channel) (*v1alpha1.Channel, error) { finalizerName := defaultFinalizerName - actual, err := r.Lister.Channels(resource.Namespace).Get(resource.Name) + getter := r.Lister.Channels(resource.Namespace) + + actual, err := getter.Get(resource.Name) if err != nil { return resource, err } @@ -266,7 +280,9 @@ func (r *reconcilerImpl) updateFinalizersFiltered(ctx context.Context, resource return resource, err } - resource, err = r.Client.MessagingV1alpha1().Channels(resource.Namespace).Patch(resource.Name, types.MergePatchType, patch) + patcher := r.Client.MessagingV1alpha1().Channels(resource.Namespace) + + resource, err = patcher.Patch(resource.Name, types.MergePatchType, patch) if err != nil { r.Recorder.Eventf(resource, v1.EventTypeWarning, "FinalizerUpdateFailed", "Failed to update finalizers for %q: %v", resource.Name, err) diff --git a/pkg/client/injection/reconciler/messaging/v1alpha1/channel/stub/reconciler.go b/pkg/client/injection/reconciler/messaging/v1alpha1/channel/stub/reconciler.go index e053845944..7268ada64c 100644 --- a/pkg/client/injection/reconciler/messaging/v1alpha1/channel/stub/reconciler.go +++ b/pkg/client/injection/reconciler/messaging/v1alpha1/channel/stub/reconciler.go @@ -48,11 +48,13 @@ var _ channel.Interface = (*Reconciler)(nil) // ReconcileKind implements Interface.ReconcileKind. func (r *Reconciler) ReconcileKind(ctx context.Context, o *v1alpha1.Channel) reconciler.Event { - o.Status.InitializeConditions() + // TODO: use this if the resource implements InitializeConditions. + // o.Status.InitializeConditions() // TODO: add custom reconciliation logic here. - o.Status.ObservedGeneration = o.Generation + // TODO: use this if the object has .status.ObservedGeneration. + // o.Status.ObservedGeneration = o.Generation return newReconciledNormal(o.Namespace, o.Name) } diff --git a/pkg/client/injection/reconciler/pubsub/v1alpha1/pullsubscription/reconciler.go b/pkg/client/injection/reconciler/pubsub/v1alpha1/pullsubscription/reconciler.go index 58fa68a0fc..7c7f6a31df 100644 --- a/pkg/client/injection/reconciler/pubsub/v1alpha1/pullsubscription/reconciler.go +++ b/pkg/client/injection/reconciler/pubsub/v1alpha1/pullsubscription/reconciler.go @@ -121,14 +121,20 @@ func (r *reconcilerImpl) Reconcile(ctx context.Context, key string) error { ctx = controller.WithEventRecorder(ctx, r.Recorder) // 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 } // Get the resource with this namespace/name. - original, err := r.Lister.PullSubscriptions(namespace).Get(name) + + getter := r.Lister.PullSubscriptions(namespace) + + original, err := getter.Get(name) + if errors.IsNotFound(err) { // The resource may no longer exist, in which case we stop processing. logger.Errorf("resource %q no longer exists", key) @@ -200,7 +206,10 @@ func (r *reconcilerImpl) updateStatus(existing *v1alpha1.PullSubscription, desir 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 { - existing, err = r.Client.PubsubV1alpha1().PullSubscriptions(desired.Namespace).Get(desired.Name, metav1.GetOptions{}) + + getter := r.Client.PubsubV1alpha1().PullSubscriptions(desired.Namespace) + + existing, err = getter.Get(desired.Name, metav1.GetOptions{}) if err != nil { return err } @@ -212,7 +221,10 @@ func (r *reconcilerImpl) updateStatus(existing *v1alpha1.PullSubscription, desir } existing.Status = desired.Status - _, err = r.Client.PubsubV1alpha1().PullSubscriptions(existing.Namespace).UpdateStatus(existing) + + updater := r.Client.PubsubV1alpha1().PullSubscriptions(existing.Namespace) + + _, err = updater.UpdateStatus(existing) return err }) } @@ -223,7 +235,9 @@ func (r *reconcilerImpl) updateStatus(existing *v1alpha1.PullSubscription, desir func (r *reconcilerImpl) updateFinalizersFiltered(ctx context.Context, resource *v1alpha1.PullSubscription) (*v1alpha1.PullSubscription, error) { finalizerName := defaultFinalizerName - actual, err := r.Lister.PullSubscriptions(resource.Namespace).Get(resource.Name) + getter := r.Lister.PullSubscriptions(resource.Namespace) + + actual, err := getter.Get(resource.Name) if err != nil { return resource, err } @@ -266,7 +280,9 @@ func (r *reconcilerImpl) updateFinalizersFiltered(ctx context.Context, resource return resource, err } - resource, err = r.Client.PubsubV1alpha1().PullSubscriptions(resource.Namespace).Patch(resource.Name, types.MergePatchType, patch) + patcher := r.Client.PubsubV1alpha1().PullSubscriptions(resource.Namespace) + + resource, err = patcher.Patch(resource.Name, types.MergePatchType, patch) if err != nil { r.Recorder.Eventf(resource, v1.EventTypeWarning, "FinalizerUpdateFailed", "Failed to update finalizers for %q: %v", resource.Name, err) diff --git a/pkg/client/injection/reconciler/pubsub/v1alpha1/pullsubscription/stub/reconciler.go b/pkg/client/injection/reconciler/pubsub/v1alpha1/pullsubscription/stub/reconciler.go index 644b35b77e..ce1e1df670 100644 --- a/pkg/client/injection/reconciler/pubsub/v1alpha1/pullsubscription/stub/reconciler.go +++ b/pkg/client/injection/reconciler/pubsub/v1alpha1/pullsubscription/stub/reconciler.go @@ -48,11 +48,13 @@ var _ pullsubscription.Interface = (*Reconciler)(nil) // ReconcileKind implements Interface.ReconcileKind. func (r *Reconciler) ReconcileKind(ctx context.Context, o *v1alpha1.PullSubscription) reconciler.Event { - o.Status.InitializeConditions() + // TODO: use this if the resource implements InitializeConditions. + // o.Status.InitializeConditions() // TODO: add custom reconciliation logic here. - o.Status.ObservedGeneration = o.Generation + // TODO: use this if the object has .status.ObservedGeneration. + // o.Status.ObservedGeneration = o.Generation return newReconciledNormal(o.Namespace, o.Name) } diff --git a/pkg/client/injection/reconciler/pubsub/v1alpha1/topic/reconciler.go b/pkg/client/injection/reconciler/pubsub/v1alpha1/topic/reconciler.go index 7e4285821d..6c08c7f346 100644 --- a/pkg/client/injection/reconciler/pubsub/v1alpha1/topic/reconciler.go +++ b/pkg/client/injection/reconciler/pubsub/v1alpha1/topic/reconciler.go @@ -121,14 +121,20 @@ func (r *reconcilerImpl) Reconcile(ctx context.Context, key string) error { ctx = controller.WithEventRecorder(ctx, r.Recorder) // 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 } // Get the resource with this namespace/name. - original, err := r.Lister.Topics(namespace).Get(name) + + getter := r.Lister.Topics(namespace) + + original, err := getter.Get(name) + if errors.IsNotFound(err) { // The resource may no longer exist, in which case we stop processing. logger.Errorf("resource %q no longer exists", key) @@ -200,7 +206,10 @@ func (r *reconcilerImpl) updateStatus(existing *v1alpha1.Topic, desired *v1alpha 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 { - existing, err = r.Client.PubsubV1alpha1().Topics(desired.Namespace).Get(desired.Name, metav1.GetOptions{}) + + getter := r.Client.PubsubV1alpha1().Topics(desired.Namespace) + + existing, err = getter.Get(desired.Name, metav1.GetOptions{}) if err != nil { return err } @@ -212,7 +221,10 @@ func (r *reconcilerImpl) updateStatus(existing *v1alpha1.Topic, desired *v1alpha } existing.Status = desired.Status - _, err = r.Client.PubsubV1alpha1().Topics(existing.Namespace).UpdateStatus(existing) + + updater := r.Client.PubsubV1alpha1().Topics(existing.Namespace) + + _, err = updater.UpdateStatus(existing) return err }) } @@ -223,7 +235,9 @@ func (r *reconcilerImpl) updateStatus(existing *v1alpha1.Topic, desired *v1alpha func (r *reconcilerImpl) updateFinalizersFiltered(ctx context.Context, resource *v1alpha1.Topic) (*v1alpha1.Topic, error) { finalizerName := defaultFinalizerName - actual, err := r.Lister.Topics(resource.Namespace).Get(resource.Name) + getter := r.Lister.Topics(resource.Namespace) + + actual, err := getter.Get(resource.Name) if err != nil { return resource, err } @@ -266,7 +280,9 @@ func (r *reconcilerImpl) updateFinalizersFiltered(ctx context.Context, resource return resource, err } - resource, err = r.Client.PubsubV1alpha1().Topics(resource.Namespace).Patch(resource.Name, types.MergePatchType, patch) + patcher := r.Client.PubsubV1alpha1().Topics(resource.Namespace) + + resource, err = patcher.Patch(resource.Name, types.MergePatchType, patch) if err != nil { r.Recorder.Eventf(resource, v1.EventTypeWarning, "FinalizerUpdateFailed", "Failed to update finalizers for %q: %v", resource.Name, err) diff --git a/pkg/client/injection/reconciler/pubsub/v1alpha1/topic/stub/reconciler.go b/pkg/client/injection/reconciler/pubsub/v1alpha1/topic/stub/reconciler.go index 3aeff06f12..1f1e51446b 100644 --- a/pkg/client/injection/reconciler/pubsub/v1alpha1/topic/stub/reconciler.go +++ b/pkg/client/injection/reconciler/pubsub/v1alpha1/topic/stub/reconciler.go @@ -48,11 +48,13 @@ var _ topic.Interface = (*Reconciler)(nil) // ReconcileKind implements Interface.ReconcileKind. func (r *Reconciler) ReconcileKind(ctx context.Context, o *v1alpha1.Topic) reconciler.Event { - o.Status.InitializeConditions() + // TODO: use this if the resource implements InitializeConditions. + // o.Status.InitializeConditions() // TODO: add custom reconciliation logic here. - o.Status.ObservedGeneration = o.Generation + // TODO: use this if the object has .status.ObservedGeneration. + // o.Status.ObservedGeneration = o.Generation return newReconciledNormal(o.Namespace, o.Name) } diff --git a/pkg/client/injection/reconciler/security/v1alpha1/eventpolicybinding/reconciler.go b/pkg/client/injection/reconciler/security/v1alpha1/eventpolicybinding/reconciler.go index a5a0246776..7bdffe3512 100644 --- a/pkg/client/injection/reconciler/security/v1alpha1/eventpolicybinding/reconciler.go +++ b/pkg/client/injection/reconciler/security/v1alpha1/eventpolicybinding/reconciler.go @@ -121,14 +121,20 @@ func (r *reconcilerImpl) Reconcile(ctx context.Context, key string) error { ctx = controller.WithEventRecorder(ctx, r.Recorder) // 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 } // Get the resource with this namespace/name. - original, err := r.Lister.EventPolicyBindings(namespace).Get(name) + + getter := r.Lister.EventPolicyBindings(namespace) + + original, err := getter.Get(name) + if errors.IsNotFound(err) { // The resource may no longer exist, in which case we stop processing. logger.Errorf("resource %q no longer exists", key) @@ -200,7 +206,10 @@ func (r *reconcilerImpl) updateStatus(existing *v1alpha1.EventPolicyBinding, des 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 { - existing, err = r.Client.SecurityV1alpha1().EventPolicyBindings(desired.Namespace).Get(desired.Name, metav1.GetOptions{}) + + getter := r.Client.SecurityV1alpha1().EventPolicyBindings(desired.Namespace) + + existing, err = getter.Get(desired.Name, metav1.GetOptions{}) if err != nil { return err } @@ -212,7 +221,10 @@ func (r *reconcilerImpl) updateStatus(existing *v1alpha1.EventPolicyBinding, des } existing.Status = desired.Status - _, err = r.Client.SecurityV1alpha1().EventPolicyBindings(existing.Namespace).UpdateStatus(existing) + + updater := r.Client.SecurityV1alpha1().EventPolicyBindings(existing.Namespace) + + _, err = updater.UpdateStatus(existing) return err }) } @@ -223,7 +235,9 @@ func (r *reconcilerImpl) updateStatus(existing *v1alpha1.EventPolicyBinding, des func (r *reconcilerImpl) updateFinalizersFiltered(ctx context.Context, resource *v1alpha1.EventPolicyBinding) (*v1alpha1.EventPolicyBinding, error) { finalizerName := defaultFinalizerName - actual, err := r.Lister.EventPolicyBindings(resource.Namespace).Get(resource.Name) + getter := r.Lister.EventPolicyBindings(resource.Namespace) + + actual, err := getter.Get(resource.Name) if err != nil { return resource, err } @@ -266,7 +280,9 @@ func (r *reconcilerImpl) updateFinalizersFiltered(ctx context.Context, resource return resource, err } - resource, err = r.Client.SecurityV1alpha1().EventPolicyBindings(resource.Namespace).Patch(resource.Name, types.MergePatchType, patch) + patcher := r.Client.SecurityV1alpha1().EventPolicyBindings(resource.Namespace) + + resource, err = patcher.Patch(resource.Name, types.MergePatchType, patch) if err != nil { r.Recorder.Eventf(resource, v1.EventTypeWarning, "FinalizerUpdateFailed", "Failed to update finalizers for %q: %v", resource.Name, err) diff --git a/pkg/client/injection/reconciler/security/v1alpha1/eventpolicybinding/stub/reconciler.go b/pkg/client/injection/reconciler/security/v1alpha1/eventpolicybinding/stub/reconciler.go index d024d13b6f..89dbf0b903 100644 --- a/pkg/client/injection/reconciler/security/v1alpha1/eventpolicybinding/stub/reconciler.go +++ b/pkg/client/injection/reconciler/security/v1alpha1/eventpolicybinding/stub/reconciler.go @@ -48,11 +48,13 @@ var _ eventpolicybinding.Interface = (*Reconciler)(nil) // ReconcileKind implements Interface.ReconcileKind. func (r *Reconciler) ReconcileKind(ctx context.Context, o *v1alpha1.EventPolicyBinding) reconciler.Event { - o.Status.InitializeConditions() + // TODO: use this if the resource implements InitializeConditions. + // o.Status.InitializeConditions() // TODO: add custom reconciliation logic here. - o.Status.ObservedGeneration = o.Generation + // TODO: use this if the object has .status.ObservedGeneration. + // o.Status.ObservedGeneration = o.Generation return newReconciledNormal(o.Namespace, o.Name) } diff --git a/pkg/client/injection/reconciler/security/v1alpha1/httppolicybinding/reconciler.go b/pkg/client/injection/reconciler/security/v1alpha1/httppolicybinding/reconciler.go index 8309836bfc..e5e83cbff6 100644 --- a/pkg/client/injection/reconciler/security/v1alpha1/httppolicybinding/reconciler.go +++ b/pkg/client/injection/reconciler/security/v1alpha1/httppolicybinding/reconciler.go @@ -121,14 +121,20 @@ func (r *reconcilerImpl) Reconcile(ctx context.Context, key string) error { ctx = controller.WithEventRecorder(ctx, r.Recorder) // 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 } // Get the resource with this namespace/name. - original, err := r.Lister.HTTPPolicyBindings(namespace).Get(name) + + getter := r.Lister.HTTPPolicyBindings(namespace) + + original, err := getter.Get(name) + if errors.IsNotFound(err) { // The resource may no longer exist, in which case we stop processing. logger.Errorf("resource %q no longer exists", key) @@ -200,7 +206,10 @@ func (r *reconcilerImpl) updateStatus(existing *v1alpha1.HTTPPolicyBinding, desi 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 { - existing, err = r.Client.SecurityV1alpha1().HTTPPolicyBindings(desired.Namespace).Get(desired.Name, metav1.GetOptions{}) + + getter := r.Client.SecurityV1alpha1().HTTPPolicyBindings(desired.Namespace) + + existing, err = getter.Get(desired.Name, metav1.GetOptions{}) if err != nil { return err } @@ -212,7 +221,10 @@ func (r *reconcilerImpl) updateStatus(existing *v1alpha1.HTTPPolicyBinding, desi } existing.Status = desired.Status - _, err = r.Client.SecurityV1alpha1().HTTPPolicyBindings(existing.Namespace).UpdateStatus(existing) + + updater := r.Client.SecurityV1alpha1().HTTPPolicyBindings(existing.Namespace) + + _, err = updater.UpdateStatus(existing) return err }) } @@ -223,7 +235,9 @@ func (r *reconcilerImpl) updateStatus(existing *v1alpha1.HTTPPolicyBinding, desi func (r *reconcilerImpl) updateFinalizersFiltered(ctx context.Context, resource *v1alpha1.HTTPPolicyBinding) (*v1alpha1.HTTPPolicyBinding, error) { finalizerName := defaultFinalizerName - actual, err := r.Lister.HTTPPolicyBindings(resource.Namespace).Get(resource.Name) + getter := r.Lister.HTTPPolicyBindings(resource.Namespace) + + actual, err := getter.Get(resource.Name) if err != nil { return resource, err } @@ -266,7 +280,9 @@ func (r *reconcilerImpl) updateFinalizersFiltered(ctx context.Context, resource return resource, err } - resource, err = r.Client.SecurityV1alpha1().HTTPPolicyBindings(resource.Namespace).Patch(resource.Name, types.MergePatchType, patch) + patcher := r.Client.SecurityV1alpha1().HTTPPolicyBindings(resource.Namespace) + + resource, err = patcher.Patch(resource.Name, types.MergePatchType, patch) if err != nil { r.Recorder.Eventf(resource, v1.EventTypeWarning, "FinalizerUpdateFailed", "Failed to update finalizers for %q: %v", resource.Name, err) diff --git a/pkg/client/injection/reconciler/security/v1alpha1/httppolicybinding/stub/reconciler.go b/pkg/client/injection/reconciler/security/v1alpha1/httppolicybinding/stub/reconciler.go index 47acd143a4..15a470ce8d 100644 --- a/pkg/client/injection/reconciler/security/v1alpha1/httppolicybinding/stub/reconciler.go +++ b/pkg/client/injection/reconciler/security/v1alpha1/httppolicybinding/stub/reconciler.go @@ -48,11 +48,13 @@ var _ httppolicybinding.Interface = (*Reconciler)(nil) // ReconcileKind implements Interface.ReconcileKind. func (r *Reconciler) ReconcileKind(ctx context.Context, o *v1alpha1.HTTPPolicyBinding) reconciler.Event { - o.Status.InitializeConditions() + // TODO: use this if the resource implements InitializeConditions. + // o.Status.InitializeConditions() // TODO: add custom reconciliation logic here. - o.Status.ObservedGeneration = o.Generation + // TODO: use this if the object has .status.ObservedGeneration. + // o.Status.ObservedGeneration = o.Generation return newReconciledNormal(o.Namespace, o.Name) } diff --git a/vendor/knative.dev/eventing/pkg/apis/eventing/v1alpha1/trigger_lifecycle.go b/vendor/knative.dev/eventing/pkg/apis/eventing/v1alpha1/trigger_lifecycle.go index 7a198dc514..cff1ab9245 100644 --- a/vendor/knative.dev/eventing/pkg/apis/eventing/v1alpha1/trigger_lifecycle.go +++ b/vendor/knative.dev/eventing/pkg/apis/eventing/v1alpha1/trigger_lifecycle.go @@ -31,7 +31,7 @@ const ( TriggerConditionBroker apis.ConditionType = "BrokerReady" - TriggerConditionSubscribed apis.ConditionType = "Subscribed" + TriggerConditionSubscribed apis.ConditionType = "SubscriptionReady" TriggerConditionDependency apis.ConditionType = "DependencyReady" diff --git a/vendor/knative.dev/eventing/pkg/apis/eventing/v1beta1/trigger_lifecycle.go b/vendor/knative.dev/eventing/pkg/apis/eventing/v1beta1/trigger_lifecycle.go index 31d6db5006..0e122a3748 100644 --- a/vendor/knative.dev/eventing/pkg/apis/eventing/v1beta1/trigger_lifecycle.go +++ b/vendor/knative.dev/eventing/pkg/apis/eventing/v1beta1/trigger_lifecycle.go @@ -31,7 +31,7 @@ const ( TriggerConditionBroker apis.ConditionType = "BrokerReady" - TriggerConditionSubscribed apis.ConditionType = "Subscribed" + TriggerConditionSubscribed apis.ConditionType = "SubscriptionReady" TriggerConditionDependency apis.ConditionType = "DependencyReady" diff --git a/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha2/ping_types.go b/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha2/ping_types.go index 737dcad32b..bd5823ae83 100644 --- a/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha2/ping_types.go +++ b/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha2/ping_types.go @@ -26,6 +26,7 @@ import ( ) // +genclient +// +genreconciler // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // +k8s:defaulter-gen=true diff --git a/vendor/knative.dev/eventing/pkg/client/injection/reconciler/eventing/v1alpha1/broker/reconciler.go b/vendor/knative.dev/eventing/pkg/client/injection/reconciler/eventing/v1alpha1/broker/reconciler.go index 69046da54f..827fcd0628 100644 --- a/vendor/knative.dev/eventing/pkg/client/injection/reconciler/eventing/v1alpha1/broker/reconciler.go +++ b/vendor/knative.dev/eventing/pkg/client/injection/reconciler/eventing/v1alpha1/broker/reconciler.go @@ -125,14 +125,20 @@ func (r *reconcilerImpl) Reconcile(ctx context.Context, key string) error { ctx = controller.WithEventRecorder(ctx, r.Recorder) // 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 } // Get the resource with this namespace/name. - original, err := r.Lister.Brokers(namespace).Get(name) + + getter := r.Lister.Brokers(namespace) + + original, err := getter.Get(name) + if errors.IsNotFound(err) { // The resource may no longer exist, in which case we stop processing. logger.Errorf("resource %q no longer exists", key) @@ -211,7 +217,10 @@ func (r *reconcilerImpl) updateStatus(existing *v1alpha1.Broker, desired *v1alph 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 { - existing, err = r.Client.EventingV1alpha1().Brokers(desired.Namespace).Get(desired.Name, metav1.GetOptions{}) + + getter := r.Client.EventingV1alpha1().Brokers(desired.Namespace) + + existing, err = getter.Get(desired.Name, metav1.GetOptions{}) if err != nil { return err } @@ -223,7 +232,10 @@ func (r *reconcilerImpl) updateStatus(existing *v1alpha1.Broker, desired *v1alph } existing.Status = desired.Status - _, err = r.Client.EventingV1alpha1().Brokers(existing.Namespace).UpdateStatus(existing) + + updater := r.Client.EventingV1alpha1().Brokers(existing.Namespace) + + _, err = updater.UpdateStatus(existing) return err }) } @@ -234,7 +246,9 @@ func (r *reconcilerImpl) updateStatus(existing *v1alpha1.Broker, desired *v1alph func (r *reconcilerImpl) updateFinalizersFiltered(ctx context.Context, resource *v1alpha1.Broker) (*v1alpha1.Broker, error) { finalizerName := defaultFinalizerName - actual, err := r.Lister.Brokers(resource.Namespace).Get(resource.Name) + getter := r.Lister.Brokers(resource.Namespace) + + actual, err := getter.Get(resource.Name) if err != nil { return resource, err } @@ -277,7 +291,9 @@ func (r *reconcilerImpl) updateFinalizersFiltered(ctx context.Context, resource return resource, err } - resource, err = r.Client.EventingV1alpha1().Brokers(resource.Namespace).Patch(resource.Name, types.MergePatchType, patch) + patcher := r.Client.EventingV1alpha1().Brokers(resource.Namespace) + + resource, err = patcher.Patch(resource.Name, types.MergePatchType, patch) if err != nil { r.Recorder.Eventf(resource, v1.EventTypeWarning, "FinalizerUpdateFailed", "Failed to update finalizers for %q: %v", resource.Name, err) diff --git a/vendor/knative.dev/eventing/pkg/utils/utils.go b/vendor/knative.dev/eventing/pkg/utils/utils.go index a1cebaca8a..3d756123ec 100644 --- a/vendor/knative.dev/eventing/pkg/utils/utils.go +++ b/vendor/knative.dev/eventing/pkg/utils/utils.go @@ -116,15 +116,20 @@ func ToDNS1123Subdomain(name string) string { // The name's length will be short enough to be valid for K8s Services. func GenerateFixedName(owner metav1.Object, prefix string) string { uid := string(owner.GetUID()) + + pl := validation.DNS1123LabelMaxLength - len(uid) + if pl < len(prefix) { + prefix = prefix[:pl] + } + // Make sure the UID is separated from the prefix by a leading dash. - if !strings.HasPrefix(uid, "-") { + if !strings.HasSuffix(prefix, "-") && !strings.HasPrefix(uid, "-") { uid = "-" + uid + if len(prefix) == pl { + prefix = prefix[:len(prefix)-1] + } } - // Trim any trailing dash from the prefix as the UID is now prepended with the dash. - prefix = strings.TrimSuffix(prefix, "-") - pl := validation.DNS1123LabelMaxLength - len(uid) - if pl > len(prefix) { - pl = len(prefix) - } - return prefix[:pl] + uid + + // A dot must be followed by [a-z0-9] to be DNS1123 compliant. Make sure we are not joining a dot and a dash. + return strings.TrimSuffix(prefix, ".") + uid } diff --git a/vendor/knative.dev/eventing/test/conformance/helpers/broker_tracing_test_helper.go b/vendor/knative.dev/eventing/test/conformance/helpers/broker_tracing_test_helper.go index 92e37df921..cf9eda5ddc 100644 --- a/vendor/knative.dev/eventing/test/conformance/helpers/broker_tracing_test_helper.go +++ b/vendor/knative.dev/eventing/test/conformance/helpers/broker_tracing_test_helper.go @@ -22,9 +22,11 @@ import ( "testing" ce "github.com/cloudevents/sdk-go/v1" + "github.com/openzipkin/zipkin-go/model" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/uuid" + "knative.dev/eventing/pkg/apis/eventing" "knative.dev/eventing/pkg/apis/eventing/v1alpha1" tracinghelper "knative.dev/eventing/test/conformance/helpers/tracing" "knative.dev/eventing/test/lib" @@ -36,20 +38,17 @@ import ( // the ChannelTestRunner. func BrokerTracingTestHelperWithChannelTestRunner( t *testing.T, + brokerClass string, channelTestRunner lib.ChannelTestRunner, setupClient lib.SetupClientOption, ) { - channelTestRunner.RunTests(t, lib.FeatureBasic, func(st *testing.T, channel metav1.TypeMeta) { - // Don't accidentally use t, use st instead. To ensure this, shadow 't' to a useless type. - t := struct{}{} - _ = fmt.Sprintf("%s", t) - - BrokerTracingTestHelper(st, channel, setupClient) + channelTestRunner.RunTests(t, lib.FeatureBasic, func(t *testing.T, channel metav1.TypeMeta) { + BrokerTracingTestHelper(t, brokerClass, channel, setupClient) }) } // BrokerTracingTestHelper runs the Broker tracing test using the given TypeMeta. -func BrokerTracingTestHelper(t *testing.T, channel metav1.TypeMeta, setupClient lib.SetupClientOption) { +func BrokerTracingTestHelper(t *testing.T, brokerClass string, channel metav1.TypeMeta, setupClient lib.SetupClientOption) { testCases := map[string]TracingTestCase{ "includes incoming trace id": { IncomingTraceId: true, @@ -58,7 +57,7 @@ func BrokerTracingTestHelper(t *testing.T, channel metav1.TypeMeta, setupClient for n, tc := range testCases { t.Run(n, func(t *testing.T) { - tracingTest(t, setupClient, setupBrokerTracing, channel, tc) + tracingTest(t, setupClient, setupBrokerTracing(brokerClass), channel, tc) }) } } @@ -70,274 +69,171 @@ func BrokerTracingTestHelper(t *testing.T, channel metav1.TypeMeta, setupClient // 4. Sender Pod which sends a 'foo' event. // It returns a string that is expected to be sent by the SendEvents Pod and should be present in // the LogEvents Pod logs. -func setupBrokerTracing( - t *testing.T, - channel *metav1.TypeMeta, - client *lib.Client, - loggerPodName string, - tc TracingTestCase, -) (tracinghelper.TestSpanTree, lib.EventMatchFunc) { +func setupBrokerTracing(brokerClass string) SetupInfrastructureFunc { const ( etTransformer = "transformer" etLogger = "logger" defaultCMPName = "eventing" ) - // Create the Broker. - client.CreateConfigMapPropagationOrFail(defaultCMPName) - client.CreateRBACResourcesForBrokers() - broker := client.CreateBrokerOrFail("br", resources.WithChannelTemplateForBroker(channel)) - - // Create a logger (EventRecord) Pod and a K8s Service that points to it. - logPod := resources.EventRecordPod(loggerPodName) - client.CreatePodOrFail(logPod, lib.WithService(loggerPodName)) - - // Create a Trigger that receives events (type=bar) and sends them to the logger Pod. - loggerTrigger := client.CreateTriggerOrFail( - "logger", - resources.WithBroker(broker.Name), - resources.WithAttributesTriggerFilter(v1alpha1.TriggerAnyFilter, etLogger, map[string]interface{}{}), - resources.WithSubscriberServiceRefForTrigger(loggerPodName), - ) - - // Create a transformer (EventTransfrmer) Pod that replies with the same event as the input, - // except the reply's event's type is changed to bar. - eventTransformerPod := resources.EventTransformationPod("transformer", &cloudevents.CloudEvent{ - EventContextV1: ce.EventContextV1{ - Type: etLogger, - }, - }) - client.CreatePodOrFail(eventTransformerPod, lib.WithService(eventTransformerPod.Name)) - - // Create a Trigger that receives events (type=foo) and sends them to the transformer Pod. - transformerTrigger := client.CreateTriggerOrFail( - "transformer", - resources.WithBroker(broker.Name), - resources.WithAttributesTriggerFilter(v1alpha1.TriggerAnyFilter, etTransformer, map[string]interface{}{}), - resources.WithSubscriberServiceRefForTrigger(eventTransformerPod.Name), - ) - - // Wait for all test resources to be ready, so that we can start sending events. - client.WaitForAllTestResourcesReadyOrFail() - - // Everything is setup to receive an event. Generate a CloudEvent. - senderName := "sender" - eventID := string(uuid.NewUUID()) - body := fmt.Sprintf("TestBrokerTracing %s", eventID) - event := cloudevents.New( - fmt.Sprintf(`{"msg":%q}`, body), - cloudevents.WithSource(senderName), - cloudevents.WithID(eventID), - cloudevents.WithType(etTransformer), - ) - - // Send the CloudEvent (either with or without tracing inside the SendEvents Pod). - sendEvent := client.SendFakeEventToAddressableOrFail - if tc.IncomingTraceId { - sendEvent = client.SendFakeEventWithTracingToAddressableOrFail - } - sendEvent(senderName, broker.Name, lib.BrokerTypeMeta, event) - - // TODO Actually determine the cluster's domain, similar to knative.dev/pkg/network/domain.go. - domain := "cluster.local" - - // We expect the following spans: - // 0. Artificial root span. - // 1. Send pod sends event to the Broker Ingress (only if the sending pod generates a span). - // 2. Broker Ingress receives the event from the sending pod. - // 3. Broker Ingress sends the event to the Broker's TrChannel (trigger channel). - // 4. Broker TrChannel receives the event from the Broker Ingress. - // 5. Broker TrChannel sends the event to the Broker Filter for the "logger" trigger. - // 6. Broker Filter for the "logger" trigger receives the event from the Broker TrChannel. - // This does not pass the filter, so this 'branch' ends here. - // 7. Broker TrChannel sends the event to the Broker Filter for the "transformer" trigger. - // 8. Broker Filter for the "transformer" trigger receives the event from the Broker TrChannel. - // 9. Broker Filter for the "transformer" trigger sends the event to the transformer pod. - // 10. Transformer pod receives the event from the Broker Filter for the "transformer" trigger. - // 11. Broker Filter for the "transformer" sends the transformer pod's reply to the Broker - // Ingress. - // 12. Broker Ingress receives the event from the Broker Filter for the "transformer" trigger. - // 13. Broker Ingress sends the event to the Broker's TrChannel. - // 14. Broker TrChannel receives the event from the Broker Ingress. - // 15. Broker TrChannel sends the event to the Broker Filter for the "transformer" trigger. - // 16. Broker Filter for the "transformer" trigger receives the event from the Broker - // TrChannel. This does not pass the filter, so this 'branch' ends here. - // 17. Broker TrChannel sends the event to the Broker Filter for the "logger" trigger. - // 18. Broker Filter for the "logger" trigger receives the event from the Broker TrChannel. - // 19. Broker Filter for the "logger" trigger sends the event to the logger pod. - // 20. Logger pod receives the event from the Broker Filter for the "logger" trigger. - - // Useful constants we will use below. - ingressHost := brokerIngressHost(domain, *broker) - triggerChanHost := brokerTriggerChannelHost(domain, *broker) - filterHost := brokerFilterHost(domain, *broker) - loggerTriggerPath := triggerPath(*loggerTrigger) - transformerTriggerPath := triggerPath(*transformerTrigger) - loggerSVCHost := k8sServiceHost(domain, client.Namespace, loggerPodName) - transformerSVCHost := k8sServiceHost(domain, client.Namespace, eventTransformerPod.Name) - - // This is very hard to read when written directly, so we will build piece by piece. - - // Steps 15-16: 'logger' event being sent to the 'transformer' Trigger. - loggerEventSentFromTrChannelToTransformer := tracinghelper.TestSpanTree{ - Note: "15. Broker TrChannel sends the event to the Broker Filter for the 'transformer' trigger.", - Span: tracinghelper.MatchHTTPClientSpanNoReply(filterHost, transformerTriggerPath), - Children: []tracinghelper.TestSpanTree{ - { - Note: "16. Broker Filter for the 'transformer' trigger receives the event from the Broker TrChannel. This does not pass the filter, so this 'branch' ends here.", - Span: tracinghelper.MatchHTTPServerSpanNoReply(filterHost, transformerTriggerPath), - }, - }, - } - - // Steps 17-20: 'logger' event being sent to the 'logger' Trigger. - loggerEventSentFromTrChannelToLogger := tracinghelper.TestSpanTree{ - Note: "17. Broker TrChannel sends the event to the Broker Filter for the 'logger' trigger.", - Span: tracinghelper.MatchHTTPClientSpanNoReply(filterHost, loggerTriggerPath), - Children: []tracinghelper.TestSpanTree{ - { - Note: "18. Broker Filter for the 'logger' trigger receives the event from the Broker TrChannel.", - Span: tracinghelper.MatchHTTPServerSpanNoReply(filterHost, loggerTriggerPath), - Children: []tracinghelper.TestSpanTree{ - { - Note: "19. Broker Filter for the 'logger' trigger sends the event to the logger pod.", - Span: tracinghelper.MatchHTTPClientSpanNoReply(loggerSVCHost, "/"), - Children: []tracinghelper.TestSpanTree{ - { - Note: "20. Logger pod receives the event from the Broker Filter for the 'logger' trigger.", - Span: tracinghelper.MatchHTTPServerSpanNoReply(loggerSVCHost, "/"), - }, - }, - }, - }, - }, - }, - } - - // Steps 13-20. Directly steps 15-16. 17-20 are included as children. - loggerEventIngressToTrigger := tracinghelper.TestSpanTree{ - Note: "13. Broker Ingress sends the event to the Broker's TrChannel.", - Span: tracinghelper.MatchHTTPClientSpanNoReply(triggerChanHost, "/"), - Children: []tracinghelper.TestSpanTree{ - { - Note: "14. Broker TrChannel receives the event from the Broker Ingress.", - Span: tracinghelper.MatchHTTPServerSpanNoReply(triggerChanHost, "/"), - Children: []tracinghelper.TestSpanTree{ - // Steps 15-16. - loggerEventSentFromTrChannelToTransformer, - // Steps 17-20. - loggerEventSentFromTrChannelToLogger, - }, - }, - }, - } - - // Steps 7-10: Event from TrChannel sent to transformer Trigger and its reply to the InChannel. - transformerEventSentFromTrChannelToTransformer := tracinghelper.TestSpanTree{ - Note: "7. Broker TrChannel sends the event to the Broker Filter for the 'transformer' trigger.", - Span: tracinghelper.MatchHTTPClientSpanNoReply(filterHost, transformerTriggerPath), - Children: []tracinghelper.TestSpanTree{ - { - Note: "8. Broker Filter for the 'transformer' trigger receives the event from the Broker TrChannel.", - Span: tracinghelper.MatchHTTPServerSpanNoReply(filterHost, transformerTriggerPath), - Children: []tracinghelper.TestSpanTree{ - { - Note: "9. Broker Filter for the 'transformer' trigger sends the event to the transformer pod.", - Span: tracinghelper.MatchHTTPClientSpanWithReply(transformerSVCHost, "/"), - Children: []tracinghelper.TestSpanTree{ - { - Note: "10. Transformer pod receives the event from the Broker Filter for the 'transformer' trigger.", - Span: tracinghelper.MatchHTTPServerSpanWithReply(transformerSVCHost, "/"), - }, - }, - }, - }, + return func( + t *testing.T, + channel *metav1.TypeMeta, + client *lib.Client, + loggerPodName string, + tc TracingTestCase, + ) (tracinghelper.TestSpanTree, lib.EventMatchFunc) { + // Create the Broker. + if brokerClass == eventing.ChannelBrokerClassValue { + // create required RBAC resources including ServiceAccounts and ClusterRoleBindings for Brokers + client.CreateConfigMapPropagationOrFail(defaultCMPName) + client.CreateRBACResourcesForBrokers() + } + broker := client.CreateBrokerOrFail( + "br", + resources.WithBrokerClassForBroker(brokerClass), + resources.WithChannelTemplateForBroker(channel), + ) + + // Create a logger (EventRecord) Pod and a K8s Service that points to it. + logPod := resources.EventRecordPod(loggerPodName) + client.CreatePodOrFail(logPod, lib.WithService(loggerPodName)) + + // Create a Trigger that receives events (type=bar) and sends them to the logger Pod. + client.CreateTriggerOrFail( + "logger", + resources.WithBroker(broker.Name), + resources.WithAttributesTriggerFilter(v1alpha1.TriggerAnyFilter, etLogger, map[string]interface{}{}), + resources.WithSubscriberServiceRefForTrigger(loggerPodName), + ) + + // Create a transformer (EventTransfrmer) Pod that replies with the same event as the input, + // except the reply's event's type is changed to bar. + eventTransformerPod := resources.EventTransformationPod("transformer", &cloudevents.CloudEvent{ + EventContextV1: ce.EventContextV1{ + Type: etLogger, }, - }, - } - - // Step 11-20. Directly steps 11-12. Steps 13-20 are children. - // Steps 11-12 Reply from the 'transformer' is sent by the Broker TrChannel to the Broker - // Ingress. - transformerEventResponseFromTrChannel := tracinghelper.TestSpanTree{ - Note: "11. Broker TrChannel for the 'transformer' sends the transformer pod's reply to the Broker Ingress.", - Span: tracinghelper.MatchHTTPClientSpanNoReply(ingressHost, ""), - Children: []tracinghelper.TestSpanTree{ - { - Note: "12. Broker Ingress receives the event from the Broker Filter for the 'transformer' trigger.", - Span: tracinghelper.MatchHTTPServerSpanNoReply(ingressHost, "/"), - Children: []tracinghelper.TestSpanTree{ - // Steps 13-20. - loggerEventIngressToTrigger, + }) + client.CreatePodOrFail(eventTransformerPod, lib.WithService(eventTransformerPod.Name)) + + // Create a Trigger that receives events (type=foo) and sends them to the transformer Pod. + client.CreateTriggerOrFail( + "transformer", + resources.WithBroker(broker.Name), + resources.WithAttributesTriggerFilter(v1alpha1.TriggerAnyFilter, etTransformer, map[string]interface{}{}), + resources.WithSubscriberServiceRefForTrigger(eventTransformerPod.Name), + ) + + // Wait for all test resources to be ready, so that we can start sending events. + client.WaitForAllTestResourcesReadyOrFail() + + // Everything is setup to receive an event. Generate a CloudEvent. + senderName := "sender" + eventID := string(uuid.NewUUID()) + body := fmt.Sprintf("TestBrokerTracing %s", eventID) + event := cloudevents.New( + fmt.Sprintf(`{"msg":%q}`, body), + cloudevents.WithSource(senderName), + cloudevents.WithID(eventID), + cloudevents.WithType(etTransformer), + ) + + // Send the CloudEvent (either with or without tracing inside the SendEvents Pod). + sendEvent := client.SendFakeEventToAddressableOrFail + if tc.IncomingTraceId { + sendEvent = client.SendFakeEventWithTracingToAddressableOrFail + } + sendEvent(senderName, broker.Name, lib.BrokerTypeMeta, event) + + // TODO Actually determine the cluster's domain, similar to knative.dev/pkg/network/domain.go. + domain := "cluster.local" + + // We expect the following spans: + // 1. Send pod sends event to the Broker Ingress (only if the sending pod generates a span). + // 2. Broker Ingress receives the event from the sending pod. + // 3. Broker Filter for the "transformer" trigger sends the event to the transformer pod. + // 4. Transformer pod receives the event from the Broker Filter for the "transformer" trigger. + // 5. Broker Filter for the "logger" trigger sends the event to the logger pod. + // 6. Logger pod receives the event from the Broker Filter for the "logger" trigger. + + // Useful constants we will use below. + loggerSVCHost := k8sServiceHost(domain, client.Namespace, loggerPodName) + transformerSVCHost := k8sServiceHost(domain, client.Namespace, eventTransformerPod.Name) + + // Steps 7-10: Event from TrChannel sent to transformer Trigger and its reply to the InChannel. + transformerEventSentFromTrChannelToTransformer := tracinghelper.TestSpanTree{ + Note: "3. Broker Filter for the 'transformer' trigger sends the event to the transformer pod.", + Span: tracinghelper.MatchHTTPSpanWithReply( + model.Client, + tracinghelper.WithHTTPHostAndPath(transformerSVCHost, "/"), + ), + Children: []tracinghelper.TestSpanTree{ + { + Note: "4. Transformer pod receives the event from the Broker Filter for the 'transformer' trigger.", + Span: tracinghelper.MatchHTTPSpanWithReply( + model.Server, + tracinghelper.WithHTTPHostAndPath(transformerSVCHost, "/"), + tracinghelper.WithLocalEndpointServiceName(eventTransformerPod.Name), + ), }, }, - }, - } - - // Steps 5-6: Event from TrChannel sent to logger Trigger. - transformerEventSentFromTrChannelToLogger := tracinghelper.TestSpanTree{ - Note: "5. Broker TrChannel sends the event to the Broker Filter for the 'logger' trigger.", - Span: tracinghelper.MatchHTTPClientSpanNoReply(filterHost, loggerTriggerPath), - Children: []tracinghelper.TestSpanTree{ - { - Note: "6. Broker Filter for the 'logger' trigger receives the event from the Broker TrChannel. This does not pass the filter, so this 'branch' ends here.", - Span: tracinghelper.MatchHTTPServerSpanNoReply(filterHost, loggerTriggerPath), - }, - }, - } + } - // Steps 0-22. Directly steps 0-4 (missing 1). - // Steps 0-4 (missing 1, which is optional and added below if present): Event sent to the Broker - // Ingress. - expected := tracinghelper.TestSpanTree{ - Note: "0. Artificial root span.", - Root: true, - Children: []tracinghelper.TestSpanTree{ - { - Note: "2. Broker Ingress receives the event from the sending pod.", - Span: tracinghelper.MatchHTTPServerSpanNoReply(ingressHost, "/"), - Children: []tracinghelper.TestSpanTree{ - { - Note: "3. Broker Ingress sends the event to the Broker's TrChannel (trigger channel).", - Span: tracinghelper.MatchHTTPClientSpanNoReply(triggerChanHost, "/"), - Children: []tracinghelper.TestSpanTree{ - { - Note: "4. Broker TrChannel receives the event from the Broker Ingress.", - Span: tracinghelper.MatchHTTPServerSpanNoReply(triggerChanHost, "/"), - Children: []tracinghelper.TestSpanTree{ - // Steps 5-6. - transformerEventSentFromTrChannelToLogger, - // Steps 7-10. - transformerEventSentFromTrChannelToTransformer, - // Steps 11-22 - transformerEventResponseFromTrChannel, - }, - }, - }, - }, + // Step 11-20. Directly steps 11-12. Steps 13-20 are children. + // Steps 11-12 Reply from the 'transformer' is sent by the Broker TrChannel to the Broker + // Ingress. + transformerEventResponseFromTrChannel := tracinghelper.TestSpanTree{ + Note: "5. Broker Filter for the 'logger' trigger sends the event to the logger pod.", + Span: tracinghelper.MatchHTTPSpanNoReply( + model.Client, + tracinghelper.WithHTTPHostAndPath(loggerSVCHost, "/"), + ), + Children: []tracinghelper.TestSpanTree{ + { + Note: "6. Logger pod receives the event from the Broker Filter for the 'logger' trigger.", + Span: tracinghelper.MatchHTTPSpanNoReply( + model.Server, + tracinghelper.WithHTTPHostAndPath(loggerSVCHost, "/"), + tracinghelper.WithLocalEndpointServiceName(loggerPodName), + ), }, }, - }, - } + } - if tc.IncomingTraceId { - expected.Children = []tracinghelper.TestSpanTree{ - { - Note: "1. Send pod sends event to the Broker Ingress (only if the sending pod generates a span).", - Span: tracinghelper.MatchHTTPClientSpanNoReply(ingressHost, ""), - Children: expected.Children, + // Steps 0-22. Directly steps 0-4 (missing 1). + // Steps 0-4 (missing 1, which is optional and added below if present): Event sent to the Broker + // Ingress. + expected := tracinghelper.TestSpanTree{ + Note: "2. Broker Ingress receives the event from the sending pod.", + Span: tracinghelper.MatchHTTPSpanNoReply(model.Server), + Children: []tracinghelper.TestSpanTree{ + // Steps 7-10. + transformerEventSentFromTrChannelToTransformer, + // Steps 11-22 + transformerEventResponseFromTrChannel, }, } - } - matchFunc := func(ev ce.Event) bool { - if ev.Source() != senderName { - return false + + if tc.IncomingTraceId { + expected = tracinghelper.TestSpanTree{ + Note: "1. Send pod sends event to the Broker Ingress (only if the sending pod generates a span).", + Span: tracinghelper.MatchHTTPSpanNoReply( + model.Client, + tracinghelper.WithLocalEndpointServiceName(senderName), + ), + Children: []tracinghelper.TestSpanTree{expected}, + } } - if ev.ID() != eventID { - return false + matchFunc := func(ev ce.Event) bool { + if ev.Source() != senderName { + return false + } + if ev.ID() != eventID { + return false + } + db, _ := ev.DataBytes() + return strings.Contains(string(db), body) } - db, _ := ev.DataBytes() - return strings.Contains(string(db), body) - } - return expected, matchFunc + return expected, matchFunc + } } diff --git a/vendor/knative.dev/eventing/test/conformance/helpers/channel_tracing_test_helper.go b/vendor/knative.dev/eventing/test/conformance/helpers/channel_tracing_test_helper.go index 7203ac9bb2..59a27a8f63 100644 --- a/vendor/knative.dev/eventing/test/conformance/helpers/channel_tracing_test_helper.go +++ b/vendor/knative.dev/eventing/test/conformance/helpers/channel_tracing_test_helper.go @@ -64,12 +64,8 @@ func ChannelTracingTestHelperWithChannelTestRunner( channelTestRunner lib.ChannelTestRunner, setupClient lib.SetupClientOption, ) { - channelTestRunner.RunTests(t, lib.FeatureBasic, func(st *testing.T, channel metav1.TypeMeta) { - // Don't accidentally use t, use st instead. To ensure this, shadow 't' to a useless type. - t := struct{}{} - _ = fmt.Sprintf("%s", t) - - ChannelTracingTestHelper(st, channel, setupClient) + channelTestRunner.RunTests(t, lib.FeatureBasic, func(t *testing.T, channel metav1.TypeMeta) { + ChannelTracingTestHelper(t, channel, setupClient) }) } @@ -232,7 +228,6 @@ func setupChannelTracingWithReply( sendEvent(senderName, channelName, channel, event) // We expect the following spans: - // 0. Artificial root span. // 1. Sending pod sends event to Channel (only if the sending pod generates a span). // 2. Channel receives event from sending pod. // 3. Channel sends event to transformer pod. @@ -242,53 +237,79 @@ func setupChannelTracingWithReply( // 7. Reply Channel sends event to the logging Pod. // 8. Logging pod receives event from Channel. expected := tracinghelper.TestSpanTree{ - // 0. Artificial root span. - Root: true, // 1 is added below if it is needed. + // 2. Channel receives event from sending pod. + Span: tracinghelper.MatchHTTPSpanNoReply( + model.Server, + tracinghelper.WithHTTPHostAndPath( + fmt.Sprintf("%s-kn-channel.%s.svc.cluster.local", channelName, client.Namespace), + "/", + ), + ), Children: []tracinghelper.TestSpanTree{ { - // 2. Channel receives event from sending pod. - Span: tracinghelper.MatchHTTPServerSpanNoReply(fmt.Sprintf("%s-kn-channel.%s.svc.cluster.local", channelName, client.Namespace), "/"), + // 3. Channel sends event to transformer pod. + Span: tracinghelper.MatchHTTPSpanWithReply( + model.Client, + tracinghelper.WithHTTPHostAndPath( + fmt.Sprintf("%s.%s.svc.cluster.local", transformerPod.Name, client.Namespace), + "/", + ), + ), Children: []tracinghelper.TestSpanTree{ { - // 3. Channel sends event to transformer pod. - Span: tracinghelper.MatchHTTPClientSpanWithReply( - fmt.Sprintf("%s.%s.svc.cluster.local", transformerPod.Name, client.Namespace), "/"), - Children: []tracinghelper.TestSpanTree{ - { - // 4. Transformer Pod receives event from Channel. - Span: tracinghelper.MatchHTTPServerSpanWithReply( - fmt.Sprintf("%s.%s.svc.cluster.local", transformerPod.Name, client.Namespace), - "/", - tracinghelper.WithLocalEndpointServiceName(transformerPod.Name), - ), - }, - }, + // 4. Transformer Pod receives event from Channel. + Span: tracinghelper.MatchHTTPSpanWithReply( + model.Server, + tracinghelper.WithHTTPHostAndPath( + fmt.Sprintf("%s.%s.svc.cluster.local", transformerPod.Name, client.Namespace), + "/", + ), + tracinghelper.WithLocalEndpointServiceName(transformerPod.Name), + ), }, + }, + }, + { + // 5. Channel sends reply from Transformer Pod to the reply Channel. + Span: tracinghelper.MatchHTTPSpanNoReply( + model.Client, + tracinghelper.WithHTTPHostAndPath( + fmt.Sprintf("%s-kn-channel.%s.svc.cluster.local", replyChannelName, client.Namespace), + "", + ), + ), + Children: []tracinghelper.TestSpanTree{ + // 6. Reply Channel receives event from the original Channel's reply. { - // 5. Channel sends reply from Transformer Pod to the reply Channel. - Span: tracinghelper.MatchHTTPClientSpanNoReply( - fmt.Sprintf("%s-kn-channel.%s.svc.cluster.local", replyChannelName, client.Namespace), ""), + Span: tracinghelper.MatchHTTPSpanNoReply( + model.Server, + tracinghelper.WithHTTPHostAndPath( + fmt.Sprintf("%s-kn-channel.%s.svc.cluster.local", replyChannelName, client.Namespace), + "/", + ), + ), Children: []tracinghelper.TestSpanTree{ - // 6. Reply Channel receives event from the original Channel's reply. { - Span: tracinghelper.MatchHTTPServerSpanNoReply( - fmt.Sprintf("%s-kn-channel.%s.svc.cluster.local", replyChannelName, client.Namespace), "/"), + // 7. Reply Channel sends event to the logging Pod. + Span: tracinghelper.MatchHTTPSpanNoReply( + model.Client, + tracinghelper.WithHTTPHostAndPath( + fmt.Sprintf("%s.%s.svc.cluster.local", loggerPod.Name, client.Namespace), + "/", + ), + ), Children: []tracinghelper.TestSpanTree{ { - // 7. Reply Channel sends event to the logging Pod. - Span: tracinghelper.MatchHTTPClientSpanNoReply( - fmt.Sprintf("%s.%s.svc.cluster.local", loggerPod.Name, client.Namespace), "/"), - Children: []tracinghelper.TestSpanTree{ - { - // 8. Logging pod receives event from Channel. - Span: tracinghelper.MatchHTTPServerSpanNoReply( - fmt.Sprintf("%s.%s.svc.cluster.local", loggerPod.Name, client.Namespace), - "/", - tracinghelper.WithLocalEndpointServiceName(loggerPod.Name), - ), - }, - }, + // 8. Logging pod receives event from Channel. + Span: tracinghelper.MatchHTTPSpanNoReply( + model.Server, + tracinghelper.WithHTTPHostAndPath( + fmt.Sprintf("%s.%s.svc.cluster.local", loggerPod.Name, client.Namespace), + "/", + ), + tracinghelper.WithLocalEndpointServiceName(loggerPod.Name), + ), }, }, }, @@ -300,16 +321,17 @@ func setupChannelTracingWithReply( } if tc.IncomingTraceId { - expected.Children = []tracinghelper.TestSpanTree{ - { - // 1. Sending pod sends event to Channel (only if the sending pod generates a span). - Span: tracinghelper.MatchHTTPClientSpanNoReply( + expected = tracinghelper.TestSpanTree{ + // 1. Sending pod sends event to Channel (only if the sending pod generates a span). + Span: tracinghelper.MatchHTTPSpanNoReply( + model.Client, + tracinghelper.WithHTTPHostAndPath( fmt.Sprintf("%s-kn-channel.%s.svc.cluster.local", channelName, client.Namespace), "", - tracinghelper.WithLocalEndpointServiceName("sender"), ), - Children: expected.Children, - }, + tracinghelper.WithLocalEndpointServiceName("sender"), + ), + Children: []tracinghelper.TestSpanTree{expected}, } } diff --git a/vendor/knative.dev/eventing/test/conformance/helpers/tracing/traces.go b/vendor/knative.dev/eventing/test/conformance/helpers/tracing/traces.go index 43953a0142..4718c36092 100644 --- a/vendor/knative.dev/eventing/test/conformance/helpers/tracing/traces.go +++ b/vendor/knative.dev/eventing/test/conformance/helpers/tracing/traces.go @@ -88,6 +88,19 @@ func WithLocalEndpointServiceName(s string) SpanMatcherOption { } } +func WithHTTPHostAndPath(host, path string) SpanMatcherOption { + return func(m *SpanMatcher) { + if m.Kind != nil { + if *m.Kind == model.Client { + m.Tags["http.url"] = fmt.Sprintf("http://%s%s", host, path) + } else if *m.Kind == model.Server { + m.Tags["http.host"] = host + m.Tags["http.path"] = path + } + } + } +} + func (m *SpanMatcher) MatchesSpan(span *model.SpanModel) error { if m == nil { return nil @@ -113,31 +126,12 @@ func (m *SpanMatcher) MatchesSpan(span *model.SpanModel) error { return nil } -func MatchHTTPClientSpanWithCode(host string, path string, statusCode int, opts ...SpanMatcherOption) *SpanMatcher { - kind := model.Client - m := &SpanMatcher{ - Kind: &kind, - Tags: map[string]string{ - "http.method": http.MethodPost, - "http.status_code": strconv.Itoa(statusCode), - "http.url": fmt.Sprintf("http://%s%s", host, path), - }, - } - for _, opt := range opts { - opt(m) - } - return m -} - -func MatchHTTPServerSpanWithCode(host string, path string, statusCode int, opts ...SpanMatcherOption) *SpanMatcher { - kind := model.Server +func MatchHTTPSpanWithCode(kind model.Kind, statusCode int, opts ...SpanMatcherOption) *SpanMatcher { m := &SpanMatcher{ Kind: &kind, Tags: map[string]string{ "http.method": http.MethodPost, "http.status_code": strconv.Itoa(statusCode), - "http.host": host, - "http.path": path, }, } for _, opt := range opts { @@ -146,20 +140,12 @@ func MatchHTTPServerSpanWithCode(host string, path string, statusCode int, opts return m } -func MatchHTTPClientSpanNoReply(host string, path string, opts ...SpanMatcherOption) *SpanMatcher { - return MatchHTTPClientSpanWithCode(host, path, 202, opts...) -} - -func MatchHTTPServerSpanNoReply(host string, path string, opts ...SpanMatcherOption) *SpanMatcher { - return MatchHTTPServerSpanWithCode(host, path, 202, opts...) +func MatchHTTPSpanNoReply(kind model.Kind, opts ...SpanMatcherOption) *SpanMatcher { + return MatchHTTPSpanWithCode(kind, 202) } -func MatchHTTPClientSpanWithReply(host string, path string, opts ...SpanMatcherOption) *SpanMatcher { - return MatchHTTPClientSpanWithCode(host, path, 200, opts...) -} - -func MatchHTTPServerSpanWithReply(host string, path string, opts ...SpanMatcherOption) *SpanMatcher { - return MatchHTTPServerSpanWithCode(host, path, 200, opts...) +func MatchHTTPSpanWithReply(kind model.Kind, opts ...SpanMatcherOption) *SpanMatcher { + return MatchHTTPSpanWithCode(kind, 200, opts...) } // TestSpanTree is the expected version of SpanTree used for assertions in testing. @@ -169,13 +155,12 @@ func MatchHTTPServerSpanWithReply(host string, path string, opts ...SpanMatcherO // prefixing the keys with a specific letter. The letter has no mean other than ordering. type TestSpanTree struct { Note string `json:"a_Note,omitempty"` - Root bool `json:"b_root"` Span *SpanMatcher `json:"c_Span"` Children []TestSpanTree `json:"z_Children,omitempty"` } -func (t TestSpanTree) String() string { - b, _ := json.MarshalIndent(t, "", " ") +func (tt TestSpanTree) String() string { + b, _ := json.MarshalIndent(tt, "", " ") return string(b) } @@ -193,7 +178,7 @@ func GetTraceTree(trace []model.SpanModel) (*SpanTree, error) { children, err := getChildren(parents, roots) if err != nil { - return nil, fmt.Errorf("Could not create span tree for %v: %v", PrettyPrintTrace(trace), err) + return nil, fmt.Errorf("could not create span tree for %v: %v", PrettyPrintTrace(trace), err) } tree := SpanTree{ @@ -201,7 +186,7 @@ func GetTraceTree(trace []model.SpanModel) (*SpanTree, error) { Children: children, } if len(parents) != 0 { - return nil, fmt.Errorf("Left over spans after generating the SpanTree: %v. Original: %v", parents, PrettyPrintTrace(trace)) + return nil, fmt.Errorf("left over spans after generating the SpanTree: %v. Original: %v", parents, PrettyPrintTrace(trace)) } return &tree, nil } @@ -223,19 +208,6 @@ func getChildren(parents map[model.ID][]model.SpanModel, current []model.SpanMod return children, nil } -// SpanCount gets the count of spans in this tree. -func (t TestSpanTree) SpanCount() int { - spans := 1 - if t.Root { - // The root span is artificial. It exits solely so we can easily pass around the tree. - spans = 0 - } - for _, child := range t.Children { - spans += child.SpanCount() - } - return spans -} - // MatchesSubtree checks to see if this TestSpanTree matches a subtree // of the actual SpanTree. It is intended to be used for assertions // while testing. Returns the set of possible subtree matches with the @@ -254,6 +226,8 @@ func (tt TestSpanTree) MatchesSubtree(t *testing.T, actual *SpanTree) (matches [ // A matching root leaves no unmatched siblings. matches = append(matches, nil) } + } else if t != nil { + t.Logf("%v does not match span %v: %v", tt.Span, actual.Span, err) } // Recursively match children. for i, child := range actual.Children { diff --git a/vendor/knative.dev/eventing/test/conformance/helpers/tracing/zipkin.go b/vendor/knative.dev/eventing/test/conformance/helpers/tracing/zipkin.go index f2d7ce8cb8..26c6bb2962 100644 --- a/vendor/knative.dev/eventing/test/conformance/helpers/tracing/zipkin.go +++ b/vendor/knative.dev/eventing/test/conformance/helpers/tracing/zipkin.go @@ -54,7 +54,7 @@ func setTracingConfigToZipkin(t *testing.T, client *lib.Client) { if err != nil { t.Fatalf("Unable to set the ConfigMap: %v", err) } - // Wait for 1 minute to let the ConfigMap be synced up. - time.Sleep(1 * time.Minute) + // Wait for 5 seconds to let the ConfigMap be synced up. + time.Sleep(5 * time.Second) }) } diff --git a/vendor/knative.dev/eventing/test/e2e-tests.sh b/vendor/knative.dev/eventing/test/e2e-tests.sh index 7dd6f4221b..1494239d78 100755 --- a/vendor/knative.dev/eventing/test/e2e-tests.sh +++ b/vendor/knative.dev/eventing/test/e2e-tests.sh @@ -43,10 +43,7 @@ uninstall_broker || fail_test "Could not uninstall Channel Based Broker" install_mt_broker || fail_test "Could not uninstall MT Channel Based Broker" -# TODO: Fix the traces so that we can run conformance tests -# https://github.com/knative/eventing/issues/2809 -# After that add ./test/conformance back to tests. echo "Running tests with Multi Tenant Channel Based Broker" -go_test_e2e -timeout=20m -parallel=12 ./test/e2e -brokerclass=MTChannelBasedBroker -channels=messaging.knative.dev/v1alpha1:InMemoryChannel,messaging.knative.dev/v1alpha1:Channel,messaging.knative.dev/v1beta1:InMemoryChannel || fail_test +go_test_e2e -timeout=20m -parallel=12 ./test/e2e ./test/conformance -brokerclass=MTChannelBasedBroker -channels=messaging.knative.dev/v1alpha1:InMemoryChannel,messaging.knative.dev/v1alpha1:Channel,messaging.knative.dev/v1beta1:InMemoryChannel || fail_test success diff --git a/vendor/knative.dev/eventing/test/e2e/helpers/channel_defaulter_test_helper.go b/vendor/knative.dev/eventing/test/e2e/helpers/channel_defaulter_test_helper.go index 8e94a0f80f..f0d19f1460 100644 --- a/vendor/knative.dev/eventing/test/e2e/helpers/channel_defaulter_test_helper.go +++ b/vendor/knative.dev/eventing/test/e2e/helpers/channel_defaulter_test_helper.go @@ -161,11 +161,11 @@ func updateDefaultChannelCM(client *lib.Client, updateConfig func(config *config // In cmd/webhook.go, configMapWatcher watches the configmap changes and set the config for channeldefaulter, // the resync time is set to 0, which means the the resync will be delayed as long as possible (until the upstream // source closes the watch or times out, or you stop the controller) - // Wait for 1 minute to let the ConfigMap be synced up. - // TODO(chizhg): 1 minute is an empirical duration, and does not solve the problem from the root. + // Wait for 5 seconds to let the ConfigMap be synced up. + // TODO(chizhg): 5 seconds is an empirical duration, and does not solve the problem from the root. // To make it work reliably, we may need to manually restart the controller. // https://github.com/knative/eventing/issues/2807 - time.Sleep(1 * time.Minute) + time.Sleep(5 * time.Second) return nil } diff --git a/vendor/knative.dev/pkg/Gopkg.lock b/vendor/knative.dev/pkg/Gopkg.lock index 01a0862e0e..a15b767718 100644 --- a/vendor/knative.dev/pkg/Gopkg.lock +++ b/vendor/knative.dev/pkg/Gopkg.lock @@ -1362,14 +1362,14 @@ [[projects]] branch = "master" - digest = "1:3f2366ce9a05503ac8da902b58e898c285cc9a972e0e89fda0b2a2fedcd4fb46" + digest = "1:2987a1db00b983af9e5d5281639a754fb6449eef01e6a375894829eaec17cb2a" name = "knative.dev/test-infra" packages = [ "scripts", "tools/dep-collector", ] pruneopts = "UT" - revision = "e7f947d615d5eb623e80824f71d139a958c4019f" + revision = "9a501343b4dafbac1a1a5dcfe2cb46975a78abb5" [[projects]] digest = "1:8730e0150dfb2b7e173890c8b9868e7a273082ef8e39f4940e3506a481cf895c" @@ -1459,6 +1459,7 @@ "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1", "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset", "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/fake", + "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/scheme", "k8s.io/apiextensions-apiserver/pkg/client/informers/externalversions", "k8s.io/apiextensions-apiserver/pkg/client/informers/externalversions/apiextensions/v1beta1", "k8s.io/apiextensions-apiserver/pkg/client/listers/apiextensions/v1beta1", diff --git a/vendor/knative.dev/pkg/apis/test/example/v1alpha1/fiz_types.go b/vendor/knative.dev/pkg/apis/test/example/v1alpha1/fiz_types.go new file mode 100644 index 0000000000..df1c054f24 --- /dev/null +++ b/vendor/knative.dev/pkg/apis/test/example/v1alpha1/fiz_types.go @@ -0,0 +1,94 @@ +/* +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. +*/ + +package v1alpha1 + +import ( + "context" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime/schema" + "knative.dev/pkg/apis" + duckv1 "knative.dev/pkg/apis/duck/v1" + "knative.dev/pkg/kmeta" +) + +// +genclient +// +genclient:nonNamespaced +// +genreconciler +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// ClusterFiz is for testing. +type ClusterFiz struct { + metav1.TypeMeta `json:",inline"` + // +optional + metav1.ObjectMeta `json:"metadata,omitempty"` + + // Spec holds the desired state of the ClusterFiz (from the client). + // +optional + Spec ClusterFizSpec `json:"spec,omitempty"` + + // Status communicates the observed state of the ClusterFiz (from the controller). + // +optional + Status ClusterFizStatus `json:"status,omitempty"` +} + +// Check that ClusterFiz can be validated and defaulted. +var _ apis.Validatable = (*ClusterFiz)(nil) +var _ apis.Defaultable = (*ClusterFiz)(nil) +var _ kmeta.OwnerRefable = (*ClusterFiz)(nil) + +// ClusterFizSpec holds the desired state of the ClusterFiz (from the client). +type ClusterFizSpec struct{} + +// ClusterFizStatus communicates the observed state of the ClusterFiz (from the controller). +type ClusterFizStatus struct { + duckv1.Status `json:",inline"` +} + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// ClusterFizList is a list of ClusterFiz resources +type ClusterFizList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata"` + + Items []ClusterFiz `json:"items"` +} + +// -- lifecycle -- + +func (fs *ClusterFizStatus) InitializeConditions() {} + +// GetGroupVersionKind implements kmeta.OwnerRefable +func (f *ClusterFiz) GetGroupVersionKind() schema.GroupVersionKind { + return SchemeGroupVersion.WithKind("Bar") +} + +// -- Defaults -- + +// SetDefaults implements apis.Defaultable +func (f *ClusterFiz) SetDefaults(ctx context.Context) { + // Nothing to default. +} + +// -- Validation -- + +// Validate implements apis.Validatable +func (f *ClusterFiz) Validate(ctx context.Context) *apis.FieldError { + // Nothing to validate. + return nil +} diff --git a/vendor/knative.dev/pkg/apis/test/example/v1alpha1/zz_generated.deepcopy.go b/vendor/knative.dev/pkg/apis/test/example/v1alpha1/zz_generated.deepcopy.go index 8b9b19b1de..3785e7b146 100644 --- a/vendor/knative.dev/pkg/apis/test/example/v1alpha1/zz_generated.deepcopy.go +++ b/vendor/knative.dev/pkg/apis/test/example/v1alpha1/zz_generated.deepcopy.go @@ -24,6 +24,100 @@ import ( runtime "k8s.io/apimachinery/pkg/runtime" ) +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClusterFiz) DeepCopyInto(out *ClusterFiz) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + out.Spec = in.Spec + in.Status.DeepCopyInto(&out.Status) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterFiz. +func (in *ClusterFiz) DeepCopy() *ClusterFiz { + if in == nil { + return nil + } + out := new(ClusterFiz) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ClusterFiz) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClusterFizList) DeepCopyInto(out *ClusterFizList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]ClusterFiz, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterFizList. +func (in *ClusterFizList) DeepCopy() *ClusterFizList { + if in == nil { + return nil + } + out := new(ClusterFizList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ClusterFizList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClusterFizSpec) DeepCopyInto(out *ClusterFizSpec) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterFizSpec. +func (in *ClusterFizSpec) DeepCopy() *ClusterFizSpec { + if in == nil { + return nil + } + out := new(ClusterFizSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClusterFizStatus) DeepCopyInto(out *ClusterFizStatus) { + *out = *in + in.Status.DeepCopyInto(&out.Status) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterFizStatus. +func (in *ClusterFizStatus) DeepCopy() *ClusterFizStatus { + if in == nil { + return nil + } + out := new(ClusterFizStatus) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Foo) DeepCopyInto(out *Foo) { *out = *in diff --git a/vendor/knative.dev/pkg/client/injection/apiextensions/reconciler/apiextensions/v1beta1/customresourcedefinition/controller.go b/vendor/knative.dev/pkg/client/injection/apiextensions/reconciler/apiextensions/v1beta1/customresourcedefinition/controller.go new file mode 100644 index 0000000000..4bf7f27a39 --- /dev/null +++ b/vendor/knative.dev/pkg/client/injection/apiextensions/reconciler/apiextensions/v1beta1/customresourcedefinition/controller.go @@ -0,0 +1,97 @@ +/* +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 customresourcedefinition + +import ( + context "context" + + corev1 "k8s.io/api/core/v1" + clientsetscheme "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/scheme" + 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" + apiextensionsclient "knative.dev/pkg/client/injection/apiextensions/client" + customresourcedefinition "knative.dev/pkg/client/injection/apiextensions/informers/apiextensions/v1beta1/customresourcedefinition" + client "knative.dev/pkg/client/injection/kube/client" + controller "knative.dev/pkg/controller" + logging "knative.dev/pkg/logging" +) + +const ( + defaultControllerAgentName = "customresourcedefinition-controller" + defaultFinalizerName = "customresourcedefinitions.apiextensions.k8s.io" + defaultQueueName = "customresourcedefinitions" +) + +// 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)) + } + + customresourcedefinitionInformer := customresourcedefinition.Get(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: defaultControllerAgentName}) + go func() { + <-ctx.Done() + for _, w := range watches { + w.Stop() + } + }() + } + + rec := &reconcilerImpl{ + Client: apiextensionsclient.Get(ctx), + Lister: customresourcedefinitionInformer.Lister(), + Recorder: recorder, + reconciler: r, + } + impl := controller.NewImpl(rec, logger, defaultQueueName) + + // Pass impl to the options. Save any optional results. + for _, fn := range optionsFns { + opts := fn(impl) + if opts.ConfigStore != nil { + rec.configStore = opts.ConfigStore + } + } + + return impl +} + +func init() { + clientsetscheme.AddToScheme(scheme.Scheme) +} diff --git a/vendor/knative.dev/pkg/client/injection/apiextensions/reconciler/apiextensions/v1beta1/customresourcedefinition/reconciler.go b/vendor/knative.dev/pkg/client/injection/apiextensions/reconciler/apiextensions/v1beta1/customresourcedefinition/reconciler.go new file mode 100644 index 0000000000..f8947493af --- /dev/null +++ b/vendor/knative.dev/pkg/client/injection/apiextensions/reconciler/apiextensions/v1beta1/customresourcedefinition/reconciler.go @@ -0,0 +1,339 @@ +/* +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 customresourcedefinition + +import ( + context "context" + "encoding/json" + "reflect" + + zap "go.uber.org/zap" + v1 "k8s.io/api/core/v1" + v1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1" + clientset "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset" + apiextensionsv1beta1 "k8s.io/apiextensions-apiserver/pkg/client/listers/apiextensions/v1beta1" + "k8s.io/apimachinery/pkg/api/equality" + errors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + sets "k8s.io/apimachinery/pkg/util/sets" + 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 v1beta1.CustomResourceDefinition. +type Interface interface { + // ReconcileKind implements custom logic to reconcile v1beta1.CustomResourceDefinition. 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 *v1beta1.CustomResourceDefinition) reconciler.Event +} + +// Finalizer defines the strongly typed interfaces to be implemented by a +// controller finalizing v1beta1.CustomResourceDefinition. +type Finalizer interface { + // FinalizeKind implements custom logic to finalize v1beta1.CustomResourceDefinition. 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 *v1beta1.CustomResourceDefinition) reconciler.Event +} + +// reconcilerImpl implements controller.Reconciler for v1beta1.CustomResourceDefinition resources. +type reconcilerImpl struct { + // Client is used to write back status updates. + Client clientset.Interface + + // Listers index properties about resources + Lister apiextensionsv1beta1.CustomResourceDefinitionLister + + // 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 +} + +// Check that our Reconciler implements controller.Reconciler +var _ controller.Reconciler = (*reconcilerImpl)(nil) + +func NewReconciler(ctx context.Context, logger *zap.SugaredLogger, client clientset.Interface, lister apiextensionsv1beta1.CustomResourceDefinitionLister, 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)) + } + + rec := &reconcilerImpl{ + Client: client, + Lister: lister, + Recorder: recorder, + reconciler: r, + } + + for _, opts := range options { + if opts.ConfigStore != nil { + rec.configStore = opts.ConfigStore + } + } + + return rec +} + +// Reconcile implements controller.Reconciler +func (r *reconcilerImpl) Reconcile(ctx context.Context, key string) error { + logger := logging.FromContext(ctx) + + // 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) + + // Convert the namespace/name string into a distinct namespace and name + + _, name, err := cache.SplitMetaNamespaceKey(key) + + if err != nil { + logger.Errorf("invalid resource key: %s", key) + return nil + } + + // Get the resource with this namespace/name. + + getter := r.Lister + + original, err := getter.Get(name) + + if errors.IsNotFound(err) { + // The resource may no longer exist, in which case we stop processing. + logger.Errorf("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() { + // 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 { + logger.Warnw("Failed to set finalizers", zap.Error(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 fin, ok := r.reconciler.(Finalizer); 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 { + logger.Warnw("Failed to clear finalizers", zap.Error(err)) + } + } + + // Synchronize the status. + if 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. + } else if err = r.updateStatus(original, resource); err != nil { + logger.Warnw("Failed to update resource status", zap.Error(err)) + r.Recorder.Eventf(resource, v1.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...) + return nil + } else { + logger.Errorw("returned an error", zap.Error(reconcileEvent)) + r.Recorder.Event(resource, v1.EventTypeWarning, "InternalError", reconcileEvent.Error()) + return reconcileEvent + } + } + return nil +} + +func (r *reconcilerImpl) updateStatus(existing *v1beta1.CustomResourceDefinition, desired *v1beta1.CustomResourceDefinition) 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.ApiextensionsV1beta1().CustomResourceDefinitions() + + 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.ApiextensionsV1beta1().CustomResourceDefinitions() + + _, 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. +func (r *reconcilerImpl) updateFinalizersFiltered(ctx context.Context, resource *v1beta1.CustomResourceDefinition) (*v1beta1.CustomResourceDefinition, error) { + finalizerName := defaultFinalizerName + + getter := r.Lister + + 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(finalizerName) { + if existingFinalizers.Has(finalizerName) { + // Nothing to do. + return resource, nil + } + // Add the finalizer. + finalizers = append(existing.Finalizers, finalizerName) + } else { + if !existingFinalizers.Has(finalizerName) { + // Nothing to do. + return resource, nil + } + // Remove the finalizer. + existingFinalizers.Delete(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.ApiextensionsV1beta1().CustomResourceDefinitions() + + resource, err = patcher.Patch(resource.Name, types.MergePatchType, patch) + if err != nil { + r.Recorder.Eventf(resource, v1.EventTypeWarning, "FinalizerUpdateFailed", + "Failed to update finalizers for %q: %v", resource.Name, err) + } else { + r.Recorder.Eventf(resource, v1.EventTypeNormal, "FinalizerUpdate", + "Updated %q finalizers", resource.GetName()) + } + return resource, err +} + +func (r *reconcilerImpl) setFinalizerIfFinalizer(ctx context.Context, resource *v1beta1.CustomResourceDefinition) (*v1beta1.CustomResourceDefinition, 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(defaultFinalizerName) + } + + resource.Finalizers = finalizers.List() + + // Synchronize the finalizers filtered by defaultFinalizerName. + return r.updateFinalizersFiltered(ctx, resource) +} + +func (r *reconcilerImpl) clearFinalizer(ctx context.Context, resource *v1beta1.CustomResourceDefinition, reconcileEvent reconciler.Event) (*v1beta1.CustomResourceDefinition, 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 == v1.EventTypeNormal { + finalizers.Delete(defaultFinalizerName) + } + } + } else { + finalizers.Delete(defaultFinalizerName) + } + + resource.Finalizers = finalizers.List() + + // Synchronize the finalizers filtered by defaultFinalizerName. + return r.updateFinalizersFiltered(ctx, resource) +} diff --git a/vendor/knative.dev/pkg/client/injection/apiextensions/reconciler/apiextensions/v1beta1/customresourcedefinition/stub/controller.go b/vendor/knative.dev/pkg/client/injection/apiextensions/reconciler/apiextensions/v1beta1/customresourcedefinition/stub/controller.go new file mode 100644 index 0000000000..4cabba261f --- /dev/null +++ b/vendor/knative.dev/pkg/client/injection/apiextensions/reconciler/apiextensions/v1beta1/customresourcedefinition/stub/controller.go @@ -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 customresourcedefinition + +import ( + context "context" + + customresourcedefinition "knative.dev/pkg/client/injection/apiextensions/informers/apiextensions/v1beta1/customresourcedefinition" + v1beta1customresourcedefinition "knative.dev/pkg/client/injection/apiextensions/reconciler/apiextensions/v1beta1/customresourcedefinition" + 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 CustomResourceDefinition and returns the result of NewImpl. +func NewController( + ctx context.Context, + cmw configmap.Watcher, +) *controller.Impl { + logger := logging.FromContext(ctx) + + customresourcedefinitionInformer := customresourcedefinition.Get(ctx) + + // TODO: setup additional informers here. + + r := &Reconciler{} + impl := v1beta1customresourcedefinition.NewImpl(ctx, r) + + logger.Info("Setting up event handlers.") + + customresourcedefinitionInformer.Informer().AddEventHandler(controller.HandleAll(impl.Enqueue)) + + // TODO: add additional informer event handlers here. + + return impl +} diff --git a/vendor/knative.dev/pkg/client/injection/apiextensions/reconciler/apiextensions/v1beta1/customresourcedefinition/stub/reconciler.go b/vendor/knative.dev/pkg/client/injection/apiextensions/reconciler/apiextensions/v1beta1/customresourcedefinition/stub/reconciler.go new file mode 100644 index 0000000000..be5bd027c6 --- /dev/null +++ b/vendor/knative.dev/pkg/client/injection/apiextensions/reconciler/apiextensions/v1beta1/customresourcedefinition/stub/reconciler.go @@ -0,0 +1,66 @@ +/* +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 customresourcedefinition + +import ( + context "context" + + v1 "k8s.io/api/core/v1" + v1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1" + customresourcedefinition "knative.dev/pkg/client/injection/apiextensions/reconciler/apiextensions/v1beta1/customresourcedefinition" + 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 CustomResourceDefinitionReconciled. +func newReconciledNormal(namespace, name string) reconciler.Event { + return reconciler.NewEvent(v1.EventTypeNormal, "CustomResourceDefinitionReconciled", "CustomResourceDefinition reconciled: \"%s/%s\"", namespace, name) +} + +// Reconciler implements controller.Reconciler for CustomResourceDefinition resources. +type Reconciler struct { + // TODO: add additional requirements here. +} + +// Check that our Reconciler implements Interface +var _ customresourcedefinition.Interface = (*Reconciler)(nil) + +// Optionally check that our Reconciler implements Finalizer +//var _ customresourcedefinition.Finalizer = (*Reconciler)(nil) + +// ReconcileKind implements Interface.ReconcileKind. +func (r *Reconciler) ReconcileKind(ctx context.Context, o *v1beta1.CustomResourceDefinition) 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 *v1beta1.CustomResourceDefinition) reconciler.Event { +// // TODO: add custom finalization logic here. +// return nil +//} diff --git a/vendor/knative.dev/pkg/client/injection/kube/reconciler/core/v1/namespace/controller.go b/vendor/knative.dev/pkg/client/injection/kube/reconciler/core/v1/namespace/controller.go new file mode 100644 index 0000000000..facba9cf4f --- /dev/null +++ b/vendor/knative.dev/pkg/client/injection/kube/reconciler/core/v1/namespace/controller.go @@ -0,0 +1,95 @@ +/* +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 namespace + +import ( + context "context" + + corev1 "k8s.io/api/core/v1" + 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" + namespace "knative.dev/pkg/client/injection/kube/informers/core/v1/namespace" + controller "knative.dev/pkg/controller" + logging "knative.dev/pkg/logging" +) + +const ( + defaultControllerAgentName = "namespace-controller" + defaultFinalizerName = "namespaces.core" + defaultQueueName = "namespaces" +) + +// 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)) + } + + namespaceInformer := namespace.Get(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: defaultControllerAgentName}) + go func() { + <-ctx.Done() + for _, w := range watches { + w.Stop() + } + }() + } + + rec := &reconcilerImpl{ + Client: client.Get(ctx), + Lister: namespaceInformer.Lister(), + Recorder: recorder, + reconciler: r, + } + impl := controller.NewImpl(rec, logger, defaultQueueName) + + // Pass impl to the options. Save any optional results. + for _, fn := range optionsFns { + opts := fn(impl) + if opts.ConfigStore != nil { + rec.configStore = opts.ConfigStore + } + } + + return impl +} + +func init() { + scheme.AddToScheme(scheme.Scheme) +} diff --git a/vendor/knative.dev/pkg/client/injection/kube/reconciler/core/v1/namespace/reconciler.go b/vendor/knative.dev/pkg/client/injection/kube/reconciler/core/v1/namespace/reconciler.go new file mode 100644 index 0000000000..64e2dc34e5 --- /dev/null +++ b/vendor/knative.dev/pkg/client/injection/kube/reconciler/core/v1/namespace/reconciler.go @@ -0,0 +1,338 @@ +/* +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 namespace + +import ( + context "context" + "encoding/json" + "reflect" + + zap "go.uber.org/zap" + v1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/equality" + errors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + sets "k8s.io/apimachinery/pkg/util/sets" + kubernetes "k8s.io/client-go/kubernetes" + corev1 "k8s.io/client-go/listers/core/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.Namespace. +type Interface interface { + // ReconcileKind implements custom logic to reconcile v1.Namespace. 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.Namespace) reconciler.Event +} + +// Finalizer defines the strongly typed interfaces to be implemented by a +// controller finalizing v1.Namespace. +type Finalizer interface { + // FinalizeKind implements custom logic to finalize v1.Namespace. 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.Namespace) reconciler.Event +} + +// reconcilerImpl implements controller.Reconciler for v1.Namespace resources. +type reconcilerImpl struct { + // Client is used to write back status updates. + Client kubernetes.Interface + + // Listers index properties about resources + Lister corev1.NamespaceLister + + // 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 +} + +// Check that our Reconciler implements controller.Reconciler +var _ controller.Reconciler = (*reconcilerImpl)(nil) + +func NewReconciler(ctx context.Context, logger *zap.SugaredLogger, client kubernetes.Interface, lister corev1.NamespaceLister, 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)) + } + + rec := &reconcilerImpl{ + Client: client, + Lister: lister, + Recorder: recorder, + reconciler: r, + } + + for _, opts := range options { + if opts.ConfigStore != nil { + rec.configStore = opts.ConfigStore + } + } + + return rec +} + +// Reconcile implements controller.Reconciler +func (r *reconcilerImpl) Reconcile(ctx context.Context, key string) error { + logger := logging.FromContext(ctx) + + // 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) + + // Convert the namespace/name string into a distinct namespace and name + + _, name, err := cache.SplitMetaNamespaceKey(key) + + if err != nil { + logger.Errorf("invalid resource key: %s", key) + return nil + } + + // Get the resource with this namespace/name. + + getter := r.Lister + + original, err := getter.Get(name) + + if errors.IsNotFound(err) { + // The resource may no longer exist, in which case we stop processing. + logger.Errorf("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() { + // 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 { + logger.Warnw("Failed to set finalizers", zap.Error(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 fin, ok := r.reconciler.(Finalizer); 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 { + logger.Warnw("Failed to clear finalizers", zap.Error(err)) + } + } + + // Synchronize the status. + if 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. + } else if err = r.updateStatus(original, resource); err != nil { + logger.Warnw("Failed to update resource status", zap.Error(err)) + r.Recorder.Eventf(resource, v1.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...) + return nil + } else { + logger.Errorw("returned an error", zap.Error(reconcileEvent)) + r.Recorder.Event(resource, v1.EventTypeWarning, "InternalError", reconcileEvent.Error()) + return reconcileEvent + } + } + return nil +} + +func (r *reconcilerImpl) updateStatus(existing *v1.Namespace, desired *v1.Namespace) 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.CoreV1().Namespaces() + + 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.CoreV1().Namespaces() + + _, 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. +func (r *reconcilerImpl) updateFinalizersFiltered(ctx context.Context, resource *v1.Namespace) (*v1.Namespace, error) { + finalizerName := defaultFinalizerName + + getter := r.Lister + + 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(finalizerName) { + if existingFinalizers.Has(finalizerName) { + // Nothing to do. + return resource, nil + } + // Add the finalizer. + finalizers = append(existing.Finalizers, finalizerName) + } else { + if !existingFinalizers.Has(finalizerName) { + // Nothing to do. + return resource, nil + } + // Remove the finalizer. + existingFinalizers.Delete(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.CoreV1().Namespaces() + + resource, err = patcher.Patch(resource.Name, types.MergePatchType, patch) + if err != nil { + r.Recorder.Eventf(resource, v1.EventTypeWarning, "FinalizerUpdateFailed", + "Failed to update finalizers for %q: %v", resource.Name, err) + } else { + r.Recorder.Eventf(resource, v1.EventTypeNormal, "FinalizerUpdate", + "Updated %q finalizers", resource.GetName()) + } + return resource, err +} + +func (r *reconcilerImpl) setFinalizerIfFinalizer(ctx context.Context, resource *v1.Namespace) (*v1.Namespace, 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(defaultFinalizerName) + } + + resource.Finalizers = finalizers.List() + + // Synchronize the finalizers filtered by defaultFinalizerName. + return r.updateFinalizersFiltered(ctx, resource) +} + +func (r *reconcilerImpl) clearFinalizer(ctx context.Context, resource *v1.Namespace, reconcileEvent reconciler.Event) (*v1.Namespace, 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 == v1.EventTypeNormal { + finalizers.Delete(defaultFinalizerName) + } + } + } else { + finalizers.Delete(defaultFinalizerName) + } + + resource.Finalizers = finalizers.List() + + // Synchronize the finalizers filtered by defaultFinalizerName. + return r.updateFinalizersFiltered(ctx, resource) +} diff --git a/vendor/knative.dev/pkg/client/injection/kube/reconciler/core/v1/namespace/stub/controller.go b/vendor/knative.dev/pkg/client/injection/kube/reconciler/core/v1/namespace/stub/controller.go new file mode 100644 index 0000000000..46236a59ed --- /dev/null +++ b/vendor/knative.dev/pkg/client/injection/kube/reconciler/core/v1/namespace/stub/controller.go @@ -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 namespace + +import ( + context "context" + + namespace "knative.dev/pkg/client/injection/kube/informers/core/v1/namespace" + v1namespace "knative.dev/pkg/client/injection/kube/reconciler/core/v1/namespace" + 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 Namespace and returns the result of NewImpl. +func NewController( + ctx context.Context, + cmw configmap.Watcher, +) *controller.Impl { + logger := logging.FromContext(ctx) + + namespaceInformer := namespace.Get(ctx) + + // TODO: setup additional informers here. + + r := &Reconciler{} + impl := v1namespace.NewImpl(ctx, r) + + logger.Info("Setting up event handlers.") + + namespaceInformer.Informer().AddEventHandler(controller.HandleAll(impl.Enqueue)) + + // TODO: add additional informer event handlers here. + + return impl +} diff --git a/vendor/knative.dev/pkg/client/injection/kube/reconciler/core/v1/namespace/stub/reconciler.go b/vendor/knative.dev/pkg/client/injection/kube/reconciler/core/v1/namespace/stub/reconciler.go new file mode 100644 index 0000000000..21f7882872 --- /dev/null +++ b/vendor/knative.dev/pkg/client/injection/kube/reconciler/core/v1/namespace/stub/reconciler.go @@ -0,0 +1,65 @@ +/* +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 namespace + +import ( + context "context" + + v1 "k8s.io/api/core/v1" + namespace "knative.dev/pkg/client/injection/kube/reconciler/core/v1/namespace" + 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 NamespaceReconciled. +func newReconciledNormal(namespace, name string) reconciler.Event { + return reconciler.NewEvent(v1.EventTypeNormal, "NamespaceReconciled", "Namespace reconciled: \"%s/%s\"", namespace, name) +} + +// Reconciler implements controller.Reconciler for Namespace resources. +type Reconciler struct { + // TODO: add additional requirements here. +} + +// Check that our Reconciler implements Interface +var _ namespace.Interface = (*Reconciler)(nil) + +// Optionally check that our Reconciler implements Finalizer +//var _ namespace.Finalizer = (*Reconciler)(nil) + +// ReconcileKind implements Interface.ReconcileKind. +func (r *Reconciler) ReconcileKind(ctx context.Context, o *v1.Namespace) 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 *v1.Namespace) reconciler.Event { +// // TODO: add custom finalization logic here. +// return nil +//} diff --git a/vendor/knative.dev/pkg/codegen/cmd/injection-gen/args/args.go b/vendor/knative.dev/pkg/codegen/cmd/injection-gen/args/args.go index 38b60630d1..7204770776 100644 --- a/vendor/knative.dev/pkg/codegen/cmd/injection-gen/args/args.go +++ b/vendor/knative.dev/pkg/codegen/cmd/injection-gen/args/args.go @@ -28,6 +28,7 @@ type CustomArgs struct { VersionedClientSetPackage string ExternalVersionsInformersPackage string ListersPackage string + ForceKinds string } // NewDefaults returns default arguments for the generator. @@ -43,6 +44,7 @@ func (ca *CustomArgs) AddFlags(fs *pflag.FlagSet) { fs.StringVar(&ca.VersionedClientSetPackage, "versioned-clientset-package", ca.VersionedClientSetPackage, "the full package name for the versioned injection clientset to use") fs.StringVar(&ca.ExternalVersionsInformersPackage, "external-versions-informers-package", ca.ExternalVersionsInformersPackage, "the full package name for the external versions injection informer to use") fs.StringVar(&ca.ListersPackage, "listers-package", ca.ListersPackage, "the full package name for client listers to use") + fs.StringVar(&ca.ForceKinds, "force-genreconciler-kinds", ca.ForceKinds, `force kinds will override the genreconciler tag setting for the given set of kinds, comma separated: "Foo,Bar,Baz"`) } // Validate checks the given arguments. diff --git a/vendor/knative.dev/pkg/codegen/cmd/injection-gen/generators/packages.go b/vendor/knative.dev/pkg/codegen/cmd/injection-gen/generators/packages.go index f65bc2ba7f..7590450232 100644 --- a/vendor/knative.dev/pkg/codegen/cmd/injection-gen/generators/packages.go +++ b/vendor/knative.dev/pkg/codegen/cmd/injection-gen/generators/packages.go @@ -95,7 +95,7 @@ func Packages(context *generator.Context, arguments *args.GeneratorArgs) generat if tags.NeedsDuckInjection() { duckTypes = append(duckTypes, t) } - if tags.NeedsReconciler() { + if tags.NeedsReconciler(t, customArgs) { reconcilerTypes = append(reconcilerTypes, t) } } @@ -154,7 +154,16 @@ func (t Tags) NeedsDuckInjection() bool { return t.GenerateDuck } -func (t Tags) NeedsReconciler() bool { +func (t Tags) NeedsReconciler(kind *types.Type, args *informergenargs.CustomArgs) bool { + // Overrides + kinds := strings.Split(args.ForceKinds, ",") + for _, k := range kinds { + if kind.Name.Name == k { + klog.V(5).Infof("Kind %s was forced to generate reconciler.", k) + return true + } + } + // Normal return t.GenerateReconciler } @@ -170,6 +179,7 @@ func MustParseClientGenTags(lines []string) Tags { _, genRec := values["genreconciler"] _, genRecClass := values["genreconciler:class"] + // Generate Reconciler code if genreconciler OR genreconciler:class exist. if genRec || genRecClass { ret.GenerateReconciler = true @@ -190,6 +200,12 @@ func extractReconcilerClassTag(t *types.Type) (string, bool) { return "", false } +func isNonNamespaced(t *types.Type) bool { + comments := append(append([]string{}, t.SecondClosestCommentLines...), t.CommentLines...) + _, nonNamespaced := types.ExtractCommentTags("+", comments)["genclient:nonNamespaced"] + return nonNamespaced +} + // isInternal returns true if the tags for a member do not contain a json tag func isInternal(m types.Member) bool { return !strings.Contains(m.Tags, "json") @@ -406,6 +422,7 @@ func reconcilerPackages(basePackage string, groupPkgName string, gv clientgentyp t := t reconcilerClass, hasReconcilerClass := extractReconcilerClassTag(t) + nonNamespaced := isNonNamespaced(t) packagePath := filepath.Join(packagePath, strings.ToLower(t.Name.Name)) @@ -440,7 +457,7 @@ func reconcilerPackages(basePackage string, groupPkgName string, gv clientgentyp }, FilterFunc: func(c *generator.Context, t *types.Type) bool { tags := MustParseClientGenTags(append(t.SecondClosestCommentLines, t.CommentLines...)) - return tags.NeedsReconciler() + return tags.NeedsReconciler(t, customArgs) }, }) @@ -468,7 +485,7 @@ func reconcilerPackages(basePackage string, groupPkgName string, gv clientgentyp }, FilterFunc: func(c *generator.Context, t *types.Type) bool { tags := MustParseClientGenTags(append(t.SecondClosestCommentLines, t.CommentLines...)) - return tags.NeedsReconciler() + return tags.NeedsReconciler(t, customArgs) }, }) @@ -493,13 +510,14 @@ func reconcilerPackages(basePackage string, groupPkgName string, gv clientgentyp groupVersion: gv, reconcilerClass: reconcilerClass, hasReconcilerClass: hasReconcilerClass, + nonNamespaced: nonNamespaced, }) return generators }, FilterFunc: func(c *generator.Context, t *types.Type) bool { tags := MustParseClientGenTags(append(t.SecondClosestCommentLines, t.CommentLines...)) - return tags.NeedsReconciler() + return tags.NeedsReconciler(t, customArgs) }, }) @@ -524,7 +542,7 @@ func reconcilerPackages(basePackage string, groupPkgName string, gv clientgentyp }, FilterFunc: func(c *generator.Context, t *types.Type) bool { tags := MustParseClientGenTags(append(t.SecondClosestCommentLines, t.CommentLines...)) - return tags.NeedsReconciler() + return tags.NeedsReconciler(t, customArgs) }, }) } diff --git a/vendor/knative.dev/pkg/codegen/cmd/injection-gen/generators/reconciler_reconciler.go b/vendor/knative.dev/pkg/codegen/cmd/injection-gen/generators/reconciler_reconciler.go index c3e08bdbf3..4f645a7fa8 100644 --- a/vendor/knative.dev/pkg/codegen/cmd/injection-gen/generators/reconciler_reconciler.go +++ b/vendor/knative.dev/pkg/codegen/cmd/injection-gen/generators/reconciler_reconciler.go @@ -39,6 +39,7 @@ type reconcilerReconcilerGenerator struct { reconcilerClass string hasReconcilerClass bool + nonNamespaced bool groupGoName string groupVersion clientgentypes.GroupVersion @@ -68,11 +69,12 @@ func (g *reconcilerReconcilerGenerator) GenerateType(c *generator.Context, t *ty klog.V(5).Infof("processing type %v", t) m := map[string]interface{}{ - "type": t, - "group": namer.IC(g.groupGoName), - "version": namer.IC(g.groupVersion.Version.String()), - "class": g.reconcilerClass, - "hasClass": g.hasReconcilerClass, + "type": t, + "group": namer.IC(g.groupGoName), + "version": namer.IC(g.groupVersion.Version.String()), + "class": g.reconcilerClass, + "hasClass": g.hasReconcilerClass, + "nonNamespaced": g.nonNamespaced, "controllerImpl": c.Universe.Type(types.Name{ Package: "knative.dev/pkg/controller", Name: "Impl", @@ -247,14 +249,25 @@ func (r *reconcilerImpl) Reconcile(ctx {{.contextContext|raw}}, key string) erro ctx = {{.controllerWithEventRecorder|raw}}(ctx, r.Recorder) // Convert the namespace/name string into a distinct namespace and name + {{if .nonNamespaced}} + _, name, err := {{.cacheSplitMetaNamespaceKey|raw}}(key) + {{else}} namespace, name, err := {{.cacheSplitMetaNamespaceKey|raw}}(key) + {{end}} if err != nil { logger.Errorf("invalid resource key: %s", key) return nil } // Get the resource with this namespace/name. - original, err := r.Lister.{{.type|apiGroup}}(namespace).Get(name) + + {{if .nonNamespaced}} + getter := r.Lister + {{else}} + getter := r.Lister.{{.type|apiGroup}}(namespace) + {{end}} + original, err := getter.Get(name) + if {{.apierrsIsNotFound|raw}}(err) { // The resource may no longer exist, in which case we stop processing. logger.Errorf("resource %q no longer exists", key) @@ -336,7 +349,12 @@ func (r *reconcilerImpl) updateStatus(existing *{{.type|raw}}, desired *{{.type| return {{.reconcilerRetryUpdateConflicts|raw}}(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 { - existing, err = r.Client.{{.group}}{{.version}}().{{.type|apiGroup}}(desired.Namespace).Get(desired.Name, {{.metav1GetOptions|raw}}{}) + {{if .nonNamespaced}} + getter := r.Client.{{.group}}{{.version}}().{{.type|apiGroup}}() + {{else}} + getter := r.Client.{{.group}}{{.version}}().{{.type|apiGroup}}(desired.Namespace) + {{end}} + existing, err = getter.Get(desired.Name, {{.metav1GetOptions|raw}}{}) if err != nil { return err } @@ -348,7 +366,13 @@ func (r *reconcilerImpl) updateStatus(existing *{{.type|raw}}, desired *{{.type| } existing.Status = desired.Status - _, err = r.Client.{{.group}}{{.version}}().{{.type|apiGroup}}(existing.Namespace).UpdateStatus(existing) + + {{if .nonNamespaced}} + updater := r.Client.{{.group}}{{.version}}().{{.type|apiGroup}}() + {{else}} + updater := r.Client.{{.group}}{{.version}}().{{.type|apiGroup}}(existing.Namespace) + {{end}} + _, err = updater.UpdateStatus(existing) return err }) } @@ -361,7 +385,12 @@ var reconcilerFinalizerFactory = ` func (r *reconcilerImpl) updateFinalizersFiltered(ctx {{.contextContext|raw}}, resource *{{.type|raw}}) (*{{.type|raw}}, error) { finalizerName := defaultFinalizerName - actual, err := r.Lister.{{.type|apiGroup}}(resource.Namespace).Get(resource.Name) + {{if .nonNamespaced}} + getter := r.Lister + {{else}} + getter := r.Lister.{{.type|apiGroup}}(resource.Namespace) + {{end}} + actual, err := getter.Get(resource.Name) if err != nil { return resource, err } @@ -404,7 +433,12 @@ func (r *reconcilerImpl) updateFinalizersFiltered(ctx {{.contextContext|raw}}, r return resource, err } - resource, err = r.Client.{{.group}}{{.version}}().{{.type|apiGroup}}(resource.Namespace).Patch(resource.Name, types.MergePatchType, patch) + {{if .nonNamespaced}} + patcher := r.Client.{{.group}}{{.version}}().{{.type|apiGroup}}() + {{else}} + patcher := r.Client.{{.group}}{{.version}}().{{.type|apiGroup}}(resource.Namespace) + {{end}} + resource, err = patcher.Patch(resource.Name, types.MergePatchType, patch) if err != nil { r.Recorder.Eventf(resource, {{.corev1EventTypeWarning|raw}}, "FinalizerUpdateFailed", "Failed to update finalizers for %q: %v", resource.Name, err) diff --git a/vendor/knative.dev/pkg/codegen/cmd/injection-gen/generators/reconciler_reconciler_stub.go b/vendor/knative.dev/pkg/codegen/cmd/injection-gen/generators/reconciler_reconciler_stub.go index 1f14194854..211b04080e 100644 --- a/vendor/knative.dev/pkg/codegen/cmd/injection-gen/generators/reconciler_reconciler_stub.go +++ b/vendor/knative.dev/pkg/codegen/cmd/injection-gen/generators/reconciler_reconciler_stub.go @@ -115,11 +115,13 @@ var _ {{.reconcilerInterface|raw}} = (*Reconciler)(nil) // ReconcileKind implements Interface.ReconcileKind. func (r *Reconciler) ReconcileKind(ctx {{.contextContext|raw}}, o *{{.type|raw}}) {{.reconcilerEvent|raw}} { - o.Status.InitializeConditions() + // TODO: use this if the resource implements InitializeConditions. + // o.Status.InitializeConditions() // TODO: add custom reconciliation logic here. - o.Status.ObservedGeneration = o.Generation + // TODO: use this if the object has .status.ObservedGeneration. + // o.Status.ObservedGeneration = o.Generation return newReconciledNormal(o.Namespace, o.Name) } diff --git a/vendor/knative.dev/pkg/hack/update-codegen.sh b/vendor/knative.dev/pkg/hack/update-codegen.sh index 631ef1d040..474fe44a48 100755 --- a/vendor/knative.dev/pkg/hack/update-codegen.sh +++ b/vendor/knative.dev/pkg/hack/update-codegen.sh @@ -42,7 +42,8 @@ EXTERNAL_INFORMER_PKG="k8s.io/client-go/informers" \ k8s.io/client-go \ k8s.io/api \ "admissionregistration:v1beta1 apps:v1 autoscaling:v1,v2beta1 batch:v1,v1beta1 core:v1 rbac:v1" \ - --go-header-file ${REPO_ROOT_DIR}/hack/boilerplate/boilerplate.go.txt + --go-header-file ${REPO_ROOT_DIR}/hack/boilerplate/boilerplate.go.txt \ + --force-genreconciler-kinds "Namespace" OUTPUT_PKG="knative.dev/pkg/client/injection/apiextensions" \ VERSIONED_CLIENTSET_PKG="k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset" \ @@ -50,7 +51,8 @@ VERSIONED_CLIENTSET_PKG="k8s.io/apiextensions-apiserver/pkg/client/clientset/cli k8s.io/apiextensions-apiserver/pkg/client \ k8s.io/apiextensions-apiserver/pkg/apis \ "apiextensions:v1beta1" \ - --go-header-file ${REPO_ROOT_DIR}/hack/boilerplate/boilerplate.go.txt + --go-header-file ${REPO_ROOT_DIR}/hack/boilerplate/boilerplate.go.txt \ + --force-genreconciler-kinds "CustomResourceDefinition" # Only deepcopy the Duck types, as they are not real resources. ${CODEGEN_PKG}/generate-groups.sh "deepcopy" \ diff --git a/vendor/knative.dev/pkg/test/test-reconciler-codegen.sh b/vendor/knative.dev/pkg/test/test-reconciler-codegen.sh index 598de24fbe..c5789beeb5 100755 --- a/vendor/knative.dev/pkg/test/test-reconciler-codegen.sh +++ b/vendor/knative.dev/pkg/test/test-reconciler-codegen.sh @@ -39,7 +39,8 @@ ${CODEGEN_PKG}/generate-groups.sh "deepcopy,client,informer,lister" \ ${KNATIVE_CODEGEN_PKG}/hack/generate-knative.sh "injection" \ ${GENCLIENT_PKG} knative.dev/pkg/apis/test \ "example:v1alpha1" \ - --go-header-file ${REPO_ROOT_DIR}/hack/boilerplate/boilerplate.go.txt + --go-header-file ${REPO_ROOT_DIR}/hack/boilerplate/boilerplate.go.txt \ + --force-genreconciler-kinds "Foo" ${CODEGEN_PKG}/generate-groups.sh "deepcopy,client,informer,lister" \ ${GENCLIENT_PKG}/pub knative.dev/pkg/apis/test \ diff --git a/vendor/knative.dev/serving/pkg/apis/networking/v1alpha1/serverlessservice_types.go b/vendor/knative.dev/serving/pkg/apis/networking/v1alpha1/serverlessservice_types.go index 3d2a64278e..0ffa9bcc81 100644 --- a/vendor/knative.dev/serving/pkg/apis/networking/v1alpha1/serverlessservice_types.go +++ b/vendor/knative.dev/serving/pkg/apis/networking/v1alpha1/serverlessservice_types.go @@ -101,6 +101,10 @@ type ServerlessServiceSpec struct { // The application-layer protocol. Matches `RevisionProtocolType` set on the owning pa/revision. // serving imports networking, so just use string. ProtocolType networking.ProtocolType + + // NumActivators contains number of Activators that this revision should be + // assigned. + NumActivators int32 `json:"numActivators,omitempty"` } // ServerlessServiceStatus describes the current state of the ServerlessService. diff --git a/vendor/knative.dev/serving/pkg/apis/networking/v1alpha1/serverlessservice_validation.go b/vendor/knative.dev/serving/pkg/apis/networking/v1alpha1/serverlessservice_validation.go index ebace729dc..b3c121c83a 100644 --- a/vendor/knative.dev/serving/pkg/apis/networking/v1alpha1/serverlessservice_validation.go +++ b/vendor/knative.dev/serving/pkg/apis/networking/v1alpha1/serverlessservice_validation.go @@ -46,6 +46,14 @@ func (spec *ServerlessServiceSpec) Validate(ctx context.Context) *apis.FieldErro all = all.Also(apis.ErrInvalidValue(spec.Mode, "mode")) } + switch { + case spec.NumActivators < 0: + all = all.Also(apis.ErrInvalidValue(spec.NumActivators, "numActivators")) + case spec.NumActivators == 0: + // TODO(vagababov): stop permitting after 0.16, since this is needed only for upgrades. + break + } + all = all.Also(serving.ValidateNamespacedObjectReference(&spec.ObjectRef).ViaField("objectRef")) return all.Also(spec.ProtocolType.Validate(ctx).ViaField("protocolType")) diff --git a/vendor/knative.dev/serving/pkg/autoscaler/config/config.go b/vendor/knative.dev/serving/pkg/autoscaler/config/config.go index 5adc823347..1263c6aaef 100644 --- a/vendor/knative.dev/serving/pkg/autoscaler/config/config.go +++ b/vendor/knative.dev/serving/pkg/autoscaler/config/config.go @@ -80,31 +80,46 @@ type Config struct { PodAutoscalerClass string } +func defaultConfig() *Config { + return &Config{ + EnableScaleToZero: true, + EnableGracefulScaledown: false, + ContainerConcurrencyTargetFraction: defaultTargetUtilization, + ContainerConcurrencyTargetDefault: 100, + // TODO(#1956): Tune target usage based on empirical data. + TargetUtilization: defaultTargetUtilization, + RPSTargetDefault: 200, + MaxScaleUpRate: 1000, + MaxScaleDownRate: 2, + TargetBurstCapacity: 200, + PanicWindowPercentage: 10, + ActivatorCapacity: 100, + PanicThresholdPercentage: 200, + StableWindow: 60 * time.Second, + ScaleToZeroGracePeriod: 30 * time.Second, + TickInterval: 2 * time.Second, + PodAutoscalerClass: autoscaling.KPA, + } +} + // NewConfigFromMap creates a Config from the supplied map func NewConfigFromMap(data map[string]string) (*Config, error) { - lc := &Config{ - TargetUtilization: defaultTargetUtilization, - } + lc := defaultConfig() // Process bool fields. for _, b := range []struct { - key string - field *bool - defaultValue bool + key string + field *bool }{ { - key: "enable-scale-to-zero", - field: &lc.EnableScaleToZero, - defaultValue: true, + key: "enable-scale-to-zero", + field: &lc.EnableScaleToZero, }, { - key: "enable-graceful-scaledown", - field: &lc.EnableGracefulScaledown, - defaultValue: false, + key: "enable-graceful-scaledown", + field: &lc.EnableGracefulScaledown, }} { - if raw, ok := data[b.key]; !ok { - *b.field = b.defaultValue - } else { + if raw, ok := data[b.key]; ok { *b.field = strings.EqualFold(raw, "true") } } @@ -113,51 +128,39 @@ func NewConfigFromMap(data map[string]string) (*Config, error) { for _, f64 := range []struct { key string field *float64 - // specified exactly when optional - defaultValue float64 }{{ - key: "max-scale-up-rate", - field: &lc.MaxScaleUpRate, - defaultValue: 1000.0, + key: "max-scale-up-rate", + field: &lc.MaxScaleUpRate, }, { - key: "max-scale-down-rate", - field: &lc.MaxScaleDownRate, - defaultValue: 2.0, + key: "max-scale-down-rate", + field: &lc.MaxScaleDownRate, }, { key: "container-concurrency-target-percentage", field: &lc.ContainerConcurrencyTargetFraction, - // TODO(#1956): Tune target usage based on empirical data. - defaultValue: defaultTargetUtilization, }, { - key: "container-concurrency-target-default", - field: &lc.ContainerConcurrencyTargetDefault, - defaultValue: 100.0, + key: "container-concurrency-target-default", + field: &lc.ContainerConcurrencyTargetDefault, }, { - key: "requests-per-second-target-default", - field: &lc.RPSTargetDefault, - defaultValue: 200.0, + key: "requests-per-second-target-default", + field: &lc.RPSTargetDefault, }, { - key: "target-burst-capacity", - field: &lc.TargetBurstCapacity, - defaultValue: 200, + key: "target-burst-capacity", + field: &lc.TargetBurstCapacity, }, { - key: "panic-window-percentage", - field: &lc.PanicWindowPercentage, - defaultValue: 10.0, + key: "panic-window-percentage", + field: &lc.PanicWindowPercentage, }, { - key: "activator-capacity", - field: &lc.ActivatorCapacity, - defaultValue: 100.0, + key: "activator-capacity", + field: &lc.ActivatorCapacity, }, { - key: "panic-threshold-percentage", - field: &lc.PanicThresholdPercentage, - defaultValue: 200.0, + key: "panic-threshold-percentage", + field: &lc.PanicThresholdPercentage, }} { - if raw, ok := data[f64.key]; !ok { - *f64.field = f64.defaultValue - } else if val, err := strconv.ParseFloat(raw, 64); err != nil { - return nil, err - } else { + if raw, ok := data[f64.key]; ok { + val, err := strconv.ParseFloat(raw, 64) + if err != nil { + return nil, err + } *f64.field = val } } @@ -172,32 +175,27 @@ func NewConfigFromMap(data map[string]string) (*Config, error) { // Process Duration fields for _, dur := range []struct { - key string - field *time.Duration - defaultValue time.Duration + key string + field *time.Duration }{{ - key: "stable-window", - field: &lc.StableWindow, - defaultValue: 60 * time.Second, + key: "stable-window", + field: &lc.StableWindow, }, { - key: "scale-to-zero-grace-period", - field: &lc.ScaleToZeroGracePeriod, - defaultValue: 30 * time.Second, + key: "scale-to-zero-grace-period", + field: &lc.ScaleToZeroGracePeriod, }, { - key: "tick-interval", - field: &lc.TickInterval, - defaultValue: 2 * time.Second, + key: "tick-interval", + field: &lc.TickInterval, }} { - if raw, ok := data[dur.key]; !ok { - *dur.field = dur.defaultValue - } else if val, err := time.ParseDuration(raw); err != nil { - return nil, err - } else { + if raw, ok := data[dur.key]; ok { + val, err := time.ParseDuration(raw) + if err != nil { + return nil, err + } *dur.field = val } } - lc.PodAutoscalerClass = autoscaling.KPA if pac, ok := data["pod-autoscaler-class"]; ok { lc.PodAutoscalerClass = pac } diff --git a/vendor/knative.dev/serving/third_party/istio-1.3-latest b/vendor/knative.dev/serving/third_party/istio-1.3-latest deleted file mode 120000 index 723670e520..0000000000 --- a/vendor/knative.dev/serving/third_party/istio-1.3-latest +++ /dev/null @@ -1 +0,0 @@ -istio-1.3.8 \ No newline at end of file diff --git a/vendor/knative.dev/serving/third_party/istio-stable b/vendor/knative.dev/serving/third_party/istio-stable new file mode 120000 index 0000000000..04a23d20f0 --- /dev/null +++ b/vendor/knative.dev/serving/third_party/istio-stable @@ -0,0 +1 @@ +istio-1.4-latest \ No newline at end of file