Skip to content

Commit

Permalink
Implement CloudEvents for Runs
Browse files Browse the repository at this point in the history
Emit CloudEvents for Runs. This is achieved by:
- add a new read-only controller for Runs
- emit CloudEvents only (no k8s events) on every reconcile of a Run
- use an ephemeral cache to store sent events across reconcile runs.
  This is required because since the Runs controller only observes
  Runs, it does not have the context to know what was changed in the
  Run and though if a new event is required.

The ephemeral cache logic is largely taken from the same
functionality implemented in tektoncd/experimental/cloudevents

Fixes #3862

Signed-off-by: Andrea Frittoli <[email protected]>
  • Loading branch information
afrittoli committed Mar 11, 2022
1 parent bfa77be commit c7fb98e
Show file tree
Hide file tree
Showing 19 changed files with 918 additions and 11 deletions.
2 changes: 2 additions & 0 deletions cmd/controller/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import (
"github.com/tektoncd/pipeline/pkg/apis/pipeline"
"github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1"
"github.com/tektoncd/pipeline/pkg/reconciler/pipelinerun"
"github.com/tektoncd/pipeline/pkg/reconciler/run"
"github.com/tektoncd/pipeline/pkg/reconciler/taskrun"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/util/clock"
Expand Down Expand Up @@ -104,6 +105,7 @@ func main() {
sharedmain.MainWithConfig(ctx, ControllerLogKey, cfg,
taskrun.NewController(opts, clock.RealClock{}),
pipelinerun.NewController(opts, clock.RealClock{}),
run.NewController(),
)
}

Expand Down
3 changes: 3 additions & 0 deletions config/config-feature-flags.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -74,3 +74,6 @@ data:
# its dependent Tasks. This flag defaults to "true"; when expressions guard
# the Task only. See TEP-0059 and Pipeline documentation for more details.
scope-when-expressions-to-task: "true"
# Setting this flag to "true" enables CloudEvents for Runs, as long as a
# CloudEvents sink is configured in the config-defaults config map
send-cloudevents-for-runs: "false"
6 changes: 5 additions & 1 deletion docs/events.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,11 @@ Resource |Event |Event Type
`Run` | `Succeed` | `dev.tekton.event.run.successful.v1`
`Run` | `Failed` | `dev.tekton.event.run.failed.v1`

`CloudEvents` for `Runs` are defined but not sent yet.
`CloudEvents` for `Runs` are only sent when enabled in the [configuration](./install.md#configuring-cloudevents-notifications).

**Note**: `CloudEvents` for `Runs` rely on an ephemeral cache to avoid duplicate
events. In case of controller restart, the cache is reset and duplicate events
may be sent.

## Format of `CloudEvents`

Expand Down
25 changes: 21 additions & 4 deletions docs/install.md
Original file line number Diff line number Diff line change
Expand Up @@ -268,11 +268,11 @@ data:

## Configuring CloudEvents notifications

When configured so, Tekton can generate `CloudEvents` for `TaskRun` and `PipelineRun` lifecycle
events. The only configuration parameter is the URL of the sink. When not set, no notification is
generated.
When configured so, Tekton can generate `CloudEvents` for `TaskRun`,
`PipelineRun` and `Run`lifecycle events. The main configuration parameter is the
URL of the sink. When not set, no notification is generated.

```
```yaml
apiVersion: v1
kind: ConfigMap
metadata:
Expand All @@ -285,6 +285,23 @@ data:
default-cloud-events-sink: https://my-sink-url
```

Additionally, CloudEvents for `Runs` require an extra configuration to be
enabled. This setting exists to avoid collisions with CloudEvents that might
be sent by custom task controllers:

```yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: feature-flags
namespace: tekton-pipelines
labels:
app.kubernetes.io/instance: default
app.kubernetes.io/part-of: tekton-pipelines
data:
send-cloudevents-for-runs: true
```

## Configuring self-signed cert for private registry

The `SSL_CERT_DIR` is set to `/etc/ssl/certs` as the default cert directory. If you are using a self-signed cert for private registry and the cert file is not under the default cert directory, configure your registry cert in the `config-registry-cert` `ConfigMap` with the key `cert`.
Expand Down
7 changes: 7 additions & 0 deletions pkg/apis/config/feature_flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ const (
DefaultScopeWhenExpressionsToTask = true
// DefaultEnableAPIFields is the default value for "enable-api-fields".
DefaultEnableAPIFields = StableAPIFields
// DefaultSendCloudEventsForRuns is the default value for "send-cloudevents-for-runs".
DefaultSendCloudEventsForRuns = false

disableAffinityAssistantKey = "disable-affinity-assistant"
disableCredsInitKey = "disable-creds-init"
Expand All @@ -55,6 +57,7 @@ const (
enableCustomTasks = "enable-custom-tasks"
enableAPIFields = "enable-api-fields"
scopeWhenExpressionsToTask = "scope-when-expressions-to-task"
sendCloudEventsForRuns = "send-cloudevents-for-runs"
)

// FeatureFlags holds the features configurations
Expand All @@ -68,6 +71,7 @@ type FeatureFlags struct {
EnableCustomTasks bool
ScopeWhenExpressionsToTask bool
EnableAPIFields string
SendCloudEventsForRuns bool
}

// GetFeatureFlagsConfigName returns the name of the configmap containing all
Expand Down Expand Up @@ -113,6 +117,9 @@ func NewFeatureFlagsFromMap(cfgMap map[string]string) (*FeatureFlags, error) {
if err := setEnabledAPIFields(cfgMap, DefaultEnableAPIFields, &tc.EnableAPIFields); err != nil {
return nil, err
}
if err := setFeature(sendCloudEventsForRuns, DefaultSendCloudEventsForRuns, &tc.SendCloudEventsForRuns); err != nil {
return nil, err
}

// Given that they are alpha features, Tekton Bundles and Custom Tasks should be switched on if
// enable-api-fields is "alpha". If enable-api-fields is not "alpha" then fall back to the value of
Expand Down
1 change: 1 addition & 0 deletions pkg/apis/config/feature_flags_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ func TestNewFeatureFlagsFromConfigMap(t *testing.T) {
EnableCustomTasks: true,
ScopeWhenExpressionsToTask: true,
EnableAPIFields: "alpha",
SendCloudEventsForRuns: true,
},
fileName: "feature-flags-all-flags-set",
},
Expand Down
1 change: 1 addition & 0 deletions pkg/apis/config/testdata/feature-flags-all-flags-set.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,4 @@ data:
enable-custom-tasks: "true"
scope-when-expressions-to-task: "true"
enable-api-fields: "alpha"
send-cloudevents-for-runs: "true"
78 changes: 78 additions & 0 deletions pkg/reconciler/events/cache/cache.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/*
Copyright 2022 The Tekton 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 cache

import (
"encoding/json"
"errors"
"fmt"

cloudevents "github.com/cloudevents/sdk-go/v2"
lru "github.com/hashicorp/golang-lru"
"github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1"
)

// Struct to unmarshal the event data
type eventData struct {
Run *v1alpha1.Run `json:"run,omitempty"`
}

// AddEventSentToCache adds the particular object to cache marking it as sent
func AddEventSentToCache(cacheClient *lru.Cache, event *cloudevents.Event) error {
if cacheClient == nil {
return errors.New("cache client is nil")
}
eventKey, err := EventKey(event)
if err != nil {
return err
}
cacheClient.Add(eventKey, nil)
return nil
}

// IsCloudEventSent checks if the event exists in the cache
func IsCloudEventSent(cacheClient *lru.Cache, event *cloudevents.Event) (bool, error) {
if cacheClient == nil {
return false, errors.New("cache client is nil")
}
eventKey, err := EventKey(event)
if err != nil {
return false, err
}
return cacheClient.Contains(eventKey), nil
}

// EventKey defines whether an event is considered different from another
// in future we might want to let specific event types override this
func EventKey(event *cloudevents.Event) (string, error) {
var (
data eventData
resourceName string
resourceNamespace string
)
err := json.Unmarshal(event.Data(), &data)
if err != nil {
return "", err
}
if data.Run == nil {
return "", fmt.Errorf("Invalid Run data in %v", event)
}
resourceName = data.Run.Name
resourceNamespace = data.Run.Namespace
eventType := event.Type()
return fmt.Sprintf("%s/run/%s/%s", eventType, resourceNamespace, resourceName), nil
}
156 changes: 156 additions & 0 deletions pkg/reconciler/events/cache/cache_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
/*
Copyright 2022 The Tekton 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 cache

import (
"net/url"
"testing"
"time"

cloudevents "github.com/cloudevents/sdk-go/v2"
lru "github.com/hashicorp/golang-lru"

"github.com/cloudevents/sdk-go/v2/event"
cetypes "github.com/cloudevents/sdk-go/v2/types"
"github.com/google/go-cmp/cmp"
"github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1"
"github.com/tektoncd/pipeline/test/diff"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

func strptr(s string) *string { return &s }

func getEventData(run interface{}) map[string]interface{} {
cloudEventData := map[string]interface{}{}
if v, ok := run.(*v1alpha1.Run); ok {
cloudEventData["run"] = v
}
return cloudEventData
}

func getEventToTest(eventtype string, run interface{}) *event.Event {
e := event.Event{
Context: event.EventContextV1{
Type: eventtype,
Source: cetypes.URIRef{URL: url.URL{Path: "/foo/bar/source"}},
ID: "test-event",
Time: &cetypes.Timestamp{Time: time.Now()},
Subject: strptr("topic"),
}.AsV1(),
}
if err := e.SetData(cloudevents.ApplicationJSON, getEventData(run)); err != nil {
panic(err)
}
return &e
}

func getRunByMeta(name string, namespace string) *v1alpha1.Run {
return &v1alpha1.Run{
TypeMeta: metav1.TypeMeta{
Kind: "Run",
APIVersion: "v1alpha1",
},
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: namespace,
},
Spec: v1alpha1.RunSpec{},
Status: v1alpha1.RunStatus{},
}
}

// TestEventsKey verifies that keys are extracted correctly from events
func TestEventsKey(t *testing.T) {
testcases := []struct {
name string
eventtype string
run interface{}
wantKey string
wantErr bool
}{{
name: "run event",
eventtype: "my.test.run.event",
run: getRunByMeta("myrun", "mynamespace"),
wantKey: "my.test.run.event/run/mynamespace/myrun",
wantErr: false,
}, {
name: "run event missing data",
eventtype: "my.test.run.event",
run: nil,
wantKey: "",
wantErr: true,
}}

for _, tc := range testcases {
t.Run(tc.name, func(t *testing.T) {
gotEvent := getEventToTest(tc.eventtype, tc.run)
gotKey, err := EventKey(gotEvent)
if err != nil {
if !tc.wantErr {
t.Fatalf("Expecting an error, got none")
}
}
if d := cmp.Diff(tc.wantKey, gotKey); d != "" {
t.Errorf("Wrong Event key %s", diff.PrintWantGot(d))
}
})
}
}

func TestAddCheckEvent(t *testing.T) {
run := getRunByMeta("arun", "anamespace")
runb := getRunByMeta("arun", "bnamespace")
baseEvent := getEventToTest("some.event.type", run)

testcases := []struct {
name string
firstEvent *event.Event
secondEvent *event.Event
wantFound bool
}{{
name: "identical events",
firstEvent: baseEvent,
secondEvent: baseEvent,
wantFound: true,
}, {
name: "new timestamp event",
firstEvent: baseEvent,
secondEvent: getEventToTest("some.event.type", run),
wantFound: true,
}, {
name: "different namespace",
firstEvent: baseEvent,
secondEvent: getEventToTest("some.event.type", runb),
wantFound: false,
}, {
name: "different event type",
firstEvent: baseEvent,
secondEvent: getEventToTest("some.other.event.type", run),
wantFound: false,
}}

for _, tc := range testcases {
t.Run(tc.name, func(t *testing.T) {
testCache, _ := lru.New(10)
AddEventSentToCache(testCache, tc.firstEvent)
found, _ := IsCloudEventSent(testCache, tc.secondEvent)
if d := cmp.Diff(tc.wantFound, found); d != "" {
t.Errorf("Cache check failure %s", diff.PrintWantGot(d))
}
})
}
}
Loading

0 comments on commit c7fb98e

Please sign in to comment.