Create a receive adapter
As part of the source reconciliation process, you must create and deploy the underlying receive adapter.
The receive adapter requires an injection-based main
method that is located in cmd/receiver_adapter/main.go
:
// This Adapter generates events at a regular interval.
package main
import (
"knative.dev/eventing/pkg/adapter"
myadapter "knative.dev/sample-source/pkg/adapter"
)
func main() {
adapter.Main("sample-source", myadapter.NewEnv, myadapter.NewAdapter)
}
The receive adapter’s pkg
implementation consists of two main functions:
A
NewAdapter(ctx context.Context, aEnv adapter.EnvConfigAccessor, ceClient cloudevents.Client) adapter.Adapter {}
call, which creates the new adapter with passed variables via theEnvConfigAccessor
. The created adapter is passed the CloudEvents client (which is where the events are forwarded to). This is sometimes referred to as a sink, orceClient
in the Knative ecosystem. The return value is a reference to the adapter as defined by the adapter’s local struct.In the case of the sample source:
// Adapter generates events at a regular interval.
type Adapter struct {
logger *zap.Logger
interval time.Duration
nextID int
client cloudevents.Client
}
A
Start
function, implemented as an interface to the adapterstruct
:func (a *Adapter) Start(stopCh <-chan struct{}) error {
stopCh
is the signal to stop the adapter. Otherwise, the role of the function is to process the next event.In the case of the
sample-source
, this function creates a CloudEvent to forward to the specified sink every X interval, as specified by theEnvConfigAccessor
parameter, which is loaded by the resource YAML:func (a *Adapter) Start(stopCh <-chan struct{}) error {
a.logger.Infow("Starting heartbeat", zap.String("interval", a.interval.String()))
for {
select {
case <-time.After(a.interval):
event := a.newEvent()
a.logger.Infow("Sending new event", zap.String("event", event.String()))
if result := a.client.Send(context.Background(), event); !cloudevents.IsACK(result) {
a.logger.Infow("failed to send event", zap.String("event", event.String()), zap.Error(result))
// We got an error but it could be transient, try again next interval.
continue
}
case <-stopCh:
a.logger.Info("Shutting down...")
return nil
}
}
}
Managing the Receive Adapter in the Controller
Update the
ObservedGeneration
and initialize theStatus
conditions, as defined in thesamplesource_lifecycle.go
andsamplesource_types.go
files:src.Status.InitializeConditions()
src.Status.ObservedGeneration = src.Generation
Create a receive adapter.
Verify that the specified Kubernetes resources are valid, and update the
Status
accordingly.Assemble the
ReceiveAdapterArgs
:raArgs := resources.ReceiveAdapterArgs{
EventSource: src.Namespace + "/" + src.Name,
Image: r.ReceiveAdapterImage,
Source: src,
Labels: resources.Labels(src.Name),
AdditionalEnvs: r.configAccessor.ToEnvVars(), // Grab config envs for tracing/logging/metrics
}
Note
The exact arguments may change based on functional requirements. Create the underlying deployment from the arguments provided, matching pod templates, labels, owner references, etc as needed to fill out the deployment. Example: pkg/reconciler/sample/resources/receive_adapter.go
Fetch the existing receive adapter deployment:
namespace := owner.GetObjectMeta().GetNamespace()
ra, err := r.KubeClientSet.AppsV1().Deployments(namespace).Get(expected.Name, metav1.GetOptions{})
If there is no existing receive adapter deployment, create one:
ra, err = r.KubeClientSet.AppsV1().Deployments(namespace).Create(expected)
Check if the expected spec is different from the existing spec, and update the deployment if required:
} else if r.podSpecImageSync(expected.Spec.Template.Spec, ra.Spec.Template.Spec) {
ra.Spec.Template.Spec = expected.Spec.Template.Spec
if ra, err = r.KubeClientSet.AppsV1().Deployments(namespace).Update(ra); err != nil {
return ra, err
}
If updated, record the event:
return pkgreconciler.NewEvent(corev1.EventTypeNormal, "DeploymentUpdated", "updated deployment: \"%s/%s\"", namespace, name)
If successful, update the
Status
andMarkDeployed
:src.Status.PropagateDeploymentAvailability(ra)
Create a SinkBinding to bind the receive adapter with the sink.
Create a
Reference
for the receive adapter deployment. This deployment is the SinkBinding’s source:tracker.Reference{
APIVersion: appsv1.SchemeGroupVersion.String(),
Kind: "Deployment",
Namespace: ra.Namespace,
Name: ra.Name,
}
Fetch the existing SinkBinding:
namespace := owner.GetObjectMeta().GetNamespace()
sb, err := r.EventingClientSet.SourcesV1alpha2().SinkBindings(namespace).Get(expected.Name, metav1.GetOptions{})
If there is no existing SinkBinding, create one:
sb, err = r.EventingClientSet.SourcesV1alpha2().SinkBindings(namespace).Create(expected)
Check if the expected spec is different to the existing spec, and update the SinkBinding if required:
else if r.specChanged(sb.Spec, expected.Spec) {
sb.Spec = expected.Spec
if sb, err = r.EventingClientSet.SourcesV1alpha2().SinkBindings(namespace).Update(sb); err != nil {
return sb, err
}
If updated, record the event:
return pkgreconciler.NewEvent(corev1.EventTypeNormal, "SinkBindingUpdated", "updated SinkBinding: \"%s/%s\"", namespace, name)
MarkSink
with the result:src.Status.MarkSink(sb.Status.SinkURI)
Return a new reconciler event stating that the process is done:
return pkgreconciler.NewEvent(corev1.EventTypeNormal, "SampleSourceReconciled", "SampleSource reconciled: \"%s/%s\"", namespace, name)