<commit_before>/*
Copyright 2019 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 helpers

import (
	"fmt"
	"strings"
	"testing"

	ce "github.com/cloudevents/sdk-go"
	"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/v1alpha1"
	"knative.dev/eventing/pkg/apis/eventing/v1beta1"
	tracinghelper "knative.dev/eventing/test/conformance/helpers/tracing"
	"knative.dev/eventing/test/lib"
	"knative.dev/eventing/test/lib/cloudevents"
	"knative.dev/eventing/test/lib/resources"
)

// BrokerTracingTestHelperWithChannelTestRunner runs the Broker tracing tests for all Channels in
// the ChannelTestRunner.
func BrokerTracingTestHelperWithChannelTestRunner(
	t *testing.T,
	brokerClass string,
	channelTestRunner lib.ChannelTestRunner,
	setupClient lib.SetupClientOption,
) {
	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, brokerClass string, channel metav1.TypeMeta, setupClient lib.SetupClientOption) {
	testCases := map[string]TracingTestCase{
		"includes incoming trace id": {
			IncomingTraceId: true,
		},
	}

	for n, tc := range testCases {
		t.Run(n, func(t *testing.T) {
			tracingTest(t, setupClient, setupBrokerTracing(brokerClass), channel, tc)
		})
	}
}

// setupBrokerTracing is the general setup for TestBrokerTracing. It creates the following:
// 1. Broker.
// 2. Trigger on 'foo' events -> K8s Service -> transformer Pod (which replies with a 'bar' event).
// 3. Trigger on 'bar' events -> K8s Service -> eventdetails Pod.
// 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(brokerClass string) SetupInfrastructureFunc {
	const (
		etTransformer  = "transformer"
		etLogger       = "logger"
		defaultCMPName = "eventing"
	)
	return func(
		t *testing.T,
		channel *metav1.TypeMeta,
		client *lib.Client,
		loggerPodName string,
		tc TracingTestCase,
	) (tracinghelper.TestSpanTree, lib.EventMatchFunc) {
		// Create a configmap used by the broker.
		client.CreateBrokerConfigMapOrFail("br", channel)

		broker := client.CreateBrokerV1Beta1OrFail(
			"br",
			resources.WithBrokerClassForBrokerV1Beta1(brokerClass),
			resources.WithConfigMapForBrokerConfig(),
		)

		// 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:
		// 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)<commit_msg>Broker Tracing Test: Get actual cluster domain name (#3252)<commit_after>/*
Copyright 2019 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 helpers

import (
	"fmt"
	"strings"
	"testing"

	ce "github.com/cloudevents/sdk-go"
	"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/v1alpha1"
	"knative.dev/eventing/pkg/apis/eventing/v1beta1"
	"knative.dev/eventing/pkg/utils"
	tracinghelper "knative.dev/eventing/test/conformance/helpers/tracing"
	"knative.dev/eventing/test/lib"
	"knative.dev/eventing/test/lib/cloudevents"
	"knative.dev/eventing/test/lib/resources"
)

// BrokerTracingTestHelperWithChannelTestRunner runs the Broker tracing tests for all Channels in
// the ChannelTestRunner.
func BrokerTracingTestHelperWithChannelTestRunner(
	t *testing.T,
	brokerClass string,
	channelTestRunner lib.ChannelTestRunner,
	setupClient lib.SetupClientOption,
) {
	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, brokerClass string, channel metav1.TypeMeta, setupClient lib.SetupClientOption) {
	testCases := map[string]TracingTestCase{
		"includes incoming trace id": {
			IncomingTraceId: true,
		},
	}

	for n, tc := range testCases {
		t.Run(n, func(t *testing.T) {
			tracingTest(t, setupClient, setupBrokerTracing(brokerClass), channel, tc)
		})
	}
}

// setupBrokerTracing is the general setup for TestBrokerTracing. It creates the following:
// 1. Broker.
// 2. Trigger on 'foo' events -> K8s Service -> transformer Pod (which replies with a 'bar' event).
// 3. Trigger on 'bar' events -> K8s Service -> eventdetails Pod.
// 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(brokerClass string) SetupInfrastructureFunc {
	const (
		etTransformer  = "transformer"
		etLogger       = "logger"
		defaultCMPName = "eventing"
	)
	return func(
		t *testing.T,
		channel *metav1.TypeMeta,
		client *lib.Client,
		loggerPodName string,
		tc TracingTestCase,
	) (tracinghelper.TestSpanTree, lib.EventMatchFunc) {
		// Create a configmap used by the broker.
		client.CreateBrokerConfigMapOrFail("br", channel)

		broker := client.CreateBrokerV1Beta1OrFail(
			"br",
			resources.WithBrokerClassForBrokerV1Beta1(brokerClass),
			resources.WithConfigMapForBrokerConfig(),
		)

		// 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)

		domain := utils.GetClusterDomainName()

		// 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)
{'fraction_non_alphanumeric': 0.09420408163265306, 'fraction_numerical': 0.007510204081632653, 'mean_word_length': 4.617148097203118, 'pattern_counts': {'":': 4, '<': 3, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5447382', 'n_tokens_mistral': 4017, 'n_tokens_neox': 3736, 'n_words': 1101}