Datasets:
File size: 7,905 Bytes
0e239c6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 | package crossrepo_annotation_gate_test
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"reflect"
"strings"
"testing"
"time"
"github.com/go-logr/logr"
corev1 "k8s.io/api/core/v1"
eventsv1 "k8s.io/api/events/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/events"
"k8s.io/client-go/tools/record"
internalrecorder "sigs.k8s.io/controller-runtime/pkg/internal/recorder"
publicrecorder "sigs.k8s.io/controller-runtime/pkg/recorder"
)
// This interface describes the public callable contract without importing a
// newly added named interface. Missing support therefore fails an executed
// assertion in compilable worlds, rather than being a test-only compile error.
type annotatedRecorder interface {
AnnotatedEventf(runtime.Object, runtime.Object, map[string]string, string, string, string, string, ...interface{})
}
type eventSink struct{ received chan *eventsv1.Event }
func (s *eventSink) Create(_ context.Context, event *eventsv1.Event) (*eventsv1.Event, error) {
s.received <- event.DeepCopy()
return event.DeepCopy(), nil
}
func (s *eventSink) Update(_ context.Context, event *eventsv1.Event) (*eventsv1.Event, error) {
s.received <- event.DeepCopy()
return event.DeepCopy(), nil
}
func (s *eventSink) Patch(_ context.Context, event *eventsv1.Event, _ []byte) (*eventsv1.Event, error) {
s.received <- event.DeepCopy()
return event.DeepCopy(), nil
}
type transportFunc func(*http.Request) (*http.Response, error)
func (f transportFunc) RoundTrip(req *http.Request) (*http.Response, error) { return f(req) }
func newProvider(t *testing.T) (publicrecorder.Provider, *eventSink, <-chan *corev1.Event) {
t.Helper()
sink := &eventSink{received: make(chan *eventsv1.Event, 16)}
legacy := make(chan *corev1.Event, 16)
client := &http.Client{Transport: transportFunc(func(req *http.Request) (*http.Response, error) {
body, err := io.ReadAll(req.Body)
if err != nil {
return nil, err
}
if req.Method != http.MethodPost || req.URL.Path != "/api/v1/namespaces/contract-ns/events" {
return nil, fmt.Errorf("unexpected legacy request: %s %s", req.Method, req.URL.Path)
}
var event corev1.Event
if err := json.Unmarshal(body, &event); err != nil {
return nil, err
}
legacy <- event.DeepCopy()
return &http.Response{StatusCode: http.StatusCreated, Header: http.Header{"Content-Type": {"application/json"}}, Body: io.NopCloser(bytes.NewReader(body)), Request: req}, nil
})}
ctx, cancel := context.WithCancel(context.Background())
oldBroadcaster := record.NewBroadcaster(record.WithContext(ctx))
broadcaster := events.NewBroadcaster(sink)
provider, err := internalrecorder.NewProvider(
&rest.Config{Host: "http://contract.invalid", ContentConfig: rest.ContentConfig{ContentType: "application/json"}},
client, scheme.Scheme, logr.Discard(),
func() (record.EventBroadcaster, events.EventBroadcaster, bool) {
return oldBroadcaster, broadcaster, true
},
)
if err != nil {
cancel()
t.Fatalf("create actual controller-runtime provider: %v", err)
}
t.Cleanup(func() {
shutdown, stop := context.WithTimeout(context.Background(), 3*time.Second)
defer stop()
provider.Stop(shutdown)
cancel()
})
return provider, sink, legacy
}
func pod(name, uid string) *corev1.Pod {
return &corev1.Pod{TypeMeta: metav1.TypeMeta{APIVersion: "v1", Kind: "Pod"}, ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "contract-ns", UID: types.UID(uid)}}
}
func receive(t *testing.T, sink *eventSink) *eventsv1.Event {
t.Helper()
select {
case event := <-sink.received:
return event
case <-time.After(8 * time.Second):
t.Fatal("actual event broadcaster emitted no sink payload")
return nil
}
}
func checkEvent(t *testing.T, event *eventsv1.Event, reason, eventType string, annotations map[string]string, related bool) {
t.Helper()
if len(annotations) == 0 {
if len(event.Annotations) != 0 {
t.Fatalf("unexpected annotations: %#v", event.Annotations)
}
} else if !reflect.DeepEqual(event.Annotations, annotations) {
t.Fatalf("annotations lost or changed: got %#v, want %#v", event.Annotations, annotations)
}
if event.Type != eventType || event.Reason != reason || event.Action != "ContractAction" || event.Note != "emitted value 17" {
t.Fatalf("ordinary event fields changed: %#v", event)
}
if event.Namespace != "contract-ns" || event.Regarding.Kind != "Pod" || event.Regarding.APIVersion != "v1" || event.Regarding.Name != "subject" || event.Regarding.UID != "subject-uid" {
t.Fatalf("regarding reference or namespace changed: %#v", event)
}
if event.ReportingController != "crossrepo.example/recorder" || !strings.HasPrefix(event.ReportingInstance, "crossrepo.example/recorder-") || event.EventTime.IsZero() {
t.Fatalf("reporter or event timestamp missing: %#v", event)
}
if related {
if event.Related == nil || event.Related.Name != "related" || event.Related.UID != "related-uid" || event.Related.Kind != "Pod" {
t.Fatalf("related reference lost: %#v", event.Related)
}
} else if event.Related != nil {
t.Fatalf("unexpected related reference: %#v", event.Related)
}
}
func TestCrossRepoNativeAnnotatedProvider(t *testing.T) {
for _, tc := range []struct {
name string
annotations map[string]string
related bool
}{
{"custom", map[string]string{"crossrepo.example/source": "contract", "details": "punctuation: ✓"}, true},
{"nil", nil, false},
{"empty", map[string]string{}, false},
} {
t.Run(tc.name, func(t *testing.T) {
provider, sink, _ := newProvider(t)
// Call through the public provider surface and inspect the recorder it returns.
recorder := provider.GetEventRecorder("crossrepo.example/recorder")
annotated, ok := interface{}(recorder).(annotatedRecorder)
if !ok {
t.Fatal("returned recorder lacks callable AnnotatedEventf support")
}
var related runtime.Object
if tc.related {
related = pod("related", "related-uid")
}
reason := "Annotated" + tc.name
annotated.AnnotatedEventf(pod("subject", "subject-uid"), related, tc.annotations, corev1.EventTypeNormal, reason, "ContractAction", "emitted %s %d", "value", 17)
checkEvent(t, receive(t, sink), reason, corev1.EventTypeNormal, tc.annotations, tc.related)
// The same annotated recorder must continue to accept ordinary Eventf.
recorder.Eventf(pod("subject", "subject-uid"), nil, corev1.EventTypeWarning, "OrdinaryAfterAnnotated", "ContractAction", "emitted %s %d", "value", 17)
checkEvent(t, receive(t, sink), "OrdinaryAfterAnnotated", corev1.EventTypeWarning, nil, false)
})
}
}
func TestCrossRepoNativeProviderEventfP2P(t *testing.T) {
provider, sink, _ := newProvider(t)
recorder := provider.GetEventRecorder("crossrepo.example/recorder")
recorder.Eventf(pod("subject", "subject-uid"), pod("related", "related-uid"), corev1.EventTypeNormal, "OrdinaryBaseline", "ContractAction", "emitted %s %d", "value", 17)
checkEvent(t, receive(t, sink), "OrdinaryBaseline", corev1.EventTypeNormal, nil, true)
}
func TestCrossRepoNativeProviderLegacyP2P(t *testing.T) {
provider, _, legacy := newProvider(t)
recorder := provider.GetEventRecorderFor("crossrepo-legacy")
recorder.Eventf(pod("subject", "subject-uid"), corev1.EventTypeNormal, "LegacyBaseline", "legacy %s %d", "value", 17)
select {
case event := <-legacy:
if event.Reason != "LegacyBaseline" || event.Message != "legacy value 17" || event.Type != corev1.EventTypeNormal || event.InvolvedObject.Name != "subject" || event.InvolvedObject.UID != "subject-uid" || event.Source.Component != "crossrepo-legacy" || len(event.Annotations) != 0 {
t.Fatalf("legacy Eventf payload changed: %#v", event)
}
case <-time.After(8 * time.Second):
t.Fatal("legacy broadcaster emitted no serialized API request")
}
}
|