Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion cmd/activator/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ func main() {
// Note: innermost handlers are specified first, ie. the last handler in the chain will be executed first
ah := activatorhandler.New(ctx, throttler, transport, logger)
ah = concurrencyReporter.Handler(ah)
ah = tracing.HTTPSpanMiddleware(ah)
ah = activatorhandler.NewTracingHandler(ah)
reqLogHandler, err := pkghttp.NewRequestLogHandler(ah, logging.NewSyncFileWriter(os.Stdout), "",
requestLogTemplateInputGetter, false /*enableProbeRequestLog*/)
if err != nil {
Expand Down
4 changes: 3 additions & 1 deletion cmd/queue/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,9 @@ func buildServer(ctx context.Context, env config, healthState *health.State, rp
if metricsSupported {
composedHandler = requestMetricsHandler(logger, composedHandler, env)
}
composedHandler = tracing.HTTPSpanMiddleware(composedHandler)
if tracingEnabled {
composedHandler = tracing.HTTPSpanMiddleware(composedHandler)
}

composedHandler = health.ProbeHandler(healthState, rp.ProbeContainer, rp.IsAggressive(), tracingEnabled, composedHandler)
composedHandler = network.NewProbeHandler(composedHandler)
Expand Down
3 changes: 1 addition & 2 deletions pkg/activator/handler/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ import (
"knative.dev/pkg/logging"
pkgnet "knative.dev/pkg/network"
rtesting "knative.dev/pkg/reconciler/testing"
"knative.dev/pkg/tracing"
"knative.dev/serving/pkg/activator"
asmetrics "knative.dev/serving/pkg/autoscaler/metrics"
pkghttp "knative.dev/serving/pkg/http"
Expand Down Expand Up @@ -72,7 +71,7 @@ func BenchmarkHandlerChain(b *testing.B) {
// Make sure to update this if the activator's main file changes.
ah := New(ctx, fakeThrottler{}, rt, logger)
ah = concurrencyReporter.Handler(ah)
ah = tracing.HTTPSpanMiddleware(ah)
ah = NewTracingHandler(ah)
ah, _ = pkghttp.NewRequestLogHandler(ah, ioutil.Discard, "", nil, false)
ah = NewMetricHandler(activatorPodName, ah)
ah = NewContextHandler(ctx, ah, configStore)
Expand Down
40 changes: 40 additions & 0 deletions pkg/activator/handler/tracing_handler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/*
Copyright 2021 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 handler

import (
"net/http"

"knative.dev/pkg/tracing"
tracingconfig "knative.dev/pkg/tracing/config"
activatorconfig "knative.dev/serving/pkg/activator/config"
)

// NewTracingHandler creates a wrapper around tracing.HTTPSpanMiddleware that completely
// bypasses said handler when tracing is disabled via the Activator's configuration.
func NewTracingHandler(next http.Handler) http.HandlerFunc {
tracingHandler := tracing.HTTPSpanMiddleware(next)
return func(w http.ResponseWriter, r *http.Request) {
tracingEnabled := activatorconfig.FromContext(r.Context()).Tracing.Backend != tracingconfig.None
if !tracingEnabled {
next.ServeHTTP(w, r)
return
}

tracingHandler.ServeHTTP(w, r)
}
}
116 changes: 116 additions & 0 deletions pkg/activator/handler/tracing_handler_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
/*
Copyright 2021 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 handler

import (
"net/http"
"net/http/httptest"
"testing"

corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"knative.dev/pkg/logging"
rtesting "knative.dev/pkg/reconciler/testing"
"knative.dev/pkg/tracing"
"knative.dev/pkg/tracing/config"
tracetesting "knative.dev/pkg/tracing/testing"
activatorconfig "knative.dev/serving/pkg/activator/config"
)

func TestTracingHandler(t *testing.T) {
tests := []struct {
name string
tracingEnabled bool
}{{
name: "enabled",
tracingEnabled: true,
}, {
name: "disabled",
tracingEnabled: false,
}}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
ctx, cancel, _ := rtesting.SetupFakeContextWithCancel(t)
defer cancel()

baseHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
handler := NewTracingHandler(baseHandler)

resp := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "http://example.com", nil)
const traceID = "821e0d50d931235a5ba3fa42eddddd8f"
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is very specific :)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is, but the thing wants something that looks like an actual ID. "foo" doesn't work 😂

req.Header["X-B3-Traceid"] = []string{traceID}
req.Header["X-B3-Spanid"] = []string{"b3bd5e1c4318c78a"}

cm := tracingConfig(test.tracingEnabled)
cfg, err := config.NewTracingConfigFromConfigMap(cm)
if err != nil {
t.Fatal("Failed to parse tracing config", err)
}

configStore := activatorconfig.NewStore(logging.FromContext(ctx))
configStore.OnConfigChanged(cm)
ctx = configStore.ToContext(ctx)

reporter, co := tracetesting.FakeZipkinExporter()
oct := tracing.NewOpenCensusTracer(co)
t.Cleanup(func() {
reporter.Close()
oct.Finish()
})

if err := oct.ApplyConfig(cfg); err != nil {
t.Error("Failed to apply tracer config:", err)
}

handler.ServeHTTP(resp, req.WithContext(ctx))

spans := reporter.Flush()

if test.tracingEnabled {
if len(spans) != 1 {
t.Errorf("Got %d spans, expected 1: spans = %v", len(spans), spans)
}
if got := spans[0].TraceID.String(); got != traceID {
t.Errorf("spans[0].TraceID = %s, want %s", got, traceID)
}
} else {
if len(spans) != 0 {
t.Errorf("Got %d spans, expected 0: spans = %v", len(spans), spans)
}
}
})
}
}

func tracingConfig(enabled bool) *corev1.ConfigMap {
cm := &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Namespace: "knative-serving",
Name: "config-tracing",
},
Data: map[string]string{
"backend": "none",
},
}
if enabled {
cm.Data["backend"] = "zipkin"
cm.Data["zipkin-endpoint"] = "foo.bar"
cm.Data["debug"] = "true"
}
return cm
}