Skip to content
Closed
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
254 changes: 221 additions & 33 deletions agent/integration/internal_tracing_integration_test.go
Original file line number Diff line number Diff line change
@@ -1,19 +1,27 @@
package integration

import (
"bytes"
"context"
"encoding/pem"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"runtime"
"strings"
"sync"
"testing"
"time"

"github.com/buildkite/agent/v4/agent"
"github.com/buildkite/agent/v4/api"
"github.com/buildkite/osc7501"
collector "go.opentelemetry.io/proto/otlp/collector/trace/v1"
tracepb "go.opentelemetry.io/proto/otlp/trace/v1"
"google.golang.org/protobuf/proto"
)

func TestBootstrapInternalTracing(t *testing.T) {
Expand All @@ -28,22 +36,34 @@ func TestBootstrapInternalTracing(t *testing.T) {
t.Fatal(err)
}
for _, tc := range []struct {
name string
pty, largeConfig bool
name string
customer, internal, config bool
customerSink string
failSink string
failJob bool
invalidCustomerHeaders bool
pty, largeConfig bool
http2Debug string
}{
{name: "internal only"},
{name: "internal only with PTY", pty: true},
{name: "large internal config", largeConfig: true},
{name: "neither"},
{name: "customer only", customer: true},
{name: "slow customer only", customer: true, customerSink: "slow"},
{name: "internal only", internal: true, config: true},
{name: "internal only with PTY", internal: true, config: true, pty: true},
{name: "large internal config", internal: true, config: true, largeConfig: true},
{name: "internal only with invalid customer headers", internal: true, config: true, invalidCustomerHeaders: true},
{name: "both", customer: true, internal: true, config: true},
{name: "HTTP2 debug headers", customer: true, internal: true, config: true, http2Debug: "1"},
{name: "HTTP2 debug frames", customer: true, internal: true, config: true, http2Debug: "2"},
{name: "next job flag off", customer: true, config: true},
{name: "flag without registration", internal: true},
{name: "internal sink fails", customer: true, internal: true, config: true, failSink: "unavailable"},
{name: "internal sink stalls", customer: true, internal: true, config: true, failSink: "timeout"},
{name: "job fails", customer: true, internal: true, config: true, failJob: true},
} {
t.Run(tc.name, func(t *testing.T) {
requests := make(chan struct{}, 1)
collector := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
select {
case requests <- struct{}{}:
default:
}
}))
defer collector.Close()
customer := newTraceSink(t, "Bearer customer-token", tc.customerSink, tc.http2Debug != "")
internal := newTraceSink(t, "Bearer internal-token", tc.failSink, tc.http2Debug != "")
root := t.TempDir()
checkEnv := `test -z "${BUILDKITE_INTERNAL_TRACING_EXPORTER+x}" || exit 91
! grep -qi '^BUILDKITE_INTERNAL_TRACING_EXPORTER=' "$BUILDKITE_ENV_FILE" || exit 92
Expand All @@ -57,7 +77,11 @@ if tr '\000' '\n' < "/proc/$PPID/environ" | grep '^BUILDKITE_INTERNAL_TRACING_EX
fi
`
}
command := checkEnv + "echo WORKLOAD_RAN"
report := osc7501.Report{ID: "private-status-id", State: "working", Progress: -1, Msg: "private-osc-message"}
command := checkEnv + fmt.Sprintf("printf '%%s' '%s'\necho WORKLOAD_RAN", report.Encode())
if tc.failJob {
command += "\nexit 7"
}
hooks := filepath.Join(root, "hooks")
if err := os.Mkdir(hooks, 0o700); err != nil {
t.Fatal(err)
Expand All @@ -66,51 +90,129 @@ fi
t.Fatal(err)
}
conf := agent.AgentConfiguration{
BootstrapScript: fmt.Sprintf("%q bootstrap --phases command --no-job-api --disable-warnings-for job-api-disabled --cancel-signal SIGTERM", executable),
BootstrapScript: fmt.Sprintf("%q bootstrap --phases command --no-job-api --disable-warnings-for job-api-disabled --cancel-signal SIGTERM --experiment program-status", executable),
BuildPath: root, HooksPath: hooks, LocalHooksEnabled: true,
CommandEval: true, Shell: "/bin/sh -e -c",
CommandEval: true, Shell: "/bin/sh -e -c", OpenTelemetryTracing: tc.customer,
TelemetryServiceName: "customer-service",
GitCommitVerification: "off", GitMirrorCheckoutMode: "reference",
RunInPty: tc.pty,
InternalTracingExporter: &api.TracingExporter{
Endpoint: collector.URL + "/v1/traces", Protocol: "http/protobuf",
Headers: map[string]string{"Authorization": "Bearer internal-token"},
},
}
if tc.largeConfig {
conf.InternalTracingExporter.Headers["X-Internal-Context"] = strings.Repeat("x", 128*1024)
if tc.config {
conf.InternalTracingExporter = &api.TracingExporter{
Endpoint: internal.server.URL + "/v1/traces", Protocol: "http/protobuf",
Headers: map[string]string{"Authorization": "Bearer internal-token"},
}
if tc.largeConfig {
conf.InternalTracingExporter.Headers["X-Internal-Context"] = strings.Repeat("x", 128*1024)
}
}
j := &api.Job{
ID: defaultJobID, ChunksMaxSizeBytes: 1024, Token: "bkaj_job-token",
InternalTracing: true,
InternalTracing: tc.internal,
TraceParent: "00-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-bbbbbbbbbbbbbbbb-01",
TraceState: "customer=private-tracestate",
Env: map[string]string{
"BUILDKITE_COMMAND": command, "BUILDKITE_JOB_ID": defaultJobID,
"BUILDKITE_REPO": ".", "BUILDKITE_COMMIT": "HEAD", "BUILDKITE_BRANCH": "main",
"BUILDKITE_AGENT_NAME": "test-agent", "BUILDKITE_ORGANIZATION_SLUG": "test-org",
"BUILDKITE_PIPELINE_SLUG": "test-pipeline", "BUILDKITE_PIPELINE_PROVIDER": "custom",
"BUILDKITE_BUILD_CHECKOUT_PATH": root,
"BUILDKITE_REPO": ".", "BUILDKITE_COMMIT": "HEAD", "BUILDKITE_BRANCH": "private-branch",
"BUILDKITE_AGENT_NAME": "test-agent", "BUILDKITE_ORGANIZATION_SLUG": "private-org",
"BUILDKITE_PIPELINE_SLUG": "private-pipeline", "BUILDKITE_PIPELINE_PROVIDER": "custom",
"BUILDKITE_BUILD_CHECKOUT_PATH": root, "BUILDKITE_BUILD_AUTHOR": "private-author",
"BUILDKITE_LABEL": "private-label", "BUILDKITE_AGENT_META_DATA_CUSTOM": "private-metadata",
"OTEL_RESOURCE_ATTRIBUTES": "custom=private-resource",
"OTEL_EXPORTER_OTLP_TRACES_ENDPOINT": customer.server.URL + "/v1/traces",
"OTEL_EXPORTER_OTLP_TRACES_PROTOCOL": "http/protobuf",
"OTEL_EXPORTER_OTLP_TRACES_HEADERS": "Authorization=Bearer%20customer-token",
"BUILDKITE_INTERNAL_TRACING_EXPORTER": "job-supplied-untrusted-config",
},
}
if tc.http2Debug != "" {
var certs []byte
for _, sink := range []*traceSink{customer, internal} {
certs = append(certs, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: sink.server.Certificate().Raw})...)
}
certFile := filepath.Join(root, "collector-ca.pem")
if err := os.WriteFile(certFile, certs, 0o600); err != nil {
t.Fatal(err)
}
j.Env["GODEBUG"] = "http2debug=" + tc.http2Debug
j.Env["SSL_CERT_FILE"] = certFile
j.Env["SSL_CERT_DIR"] = root
}
if tc.invalidCustomerHeaders {
j.Env["OTEL_EXPORTER_OTLP_HEADERS"] = "Authorization=Bearer%20customer-env-secret%ZZ"
j.Env["OTEL_EXPORTER_OTLP_TRACES_HEADERS"] = "Authorization=Bearer%20customer-env-secret%ZZ"
}
e := createTestAgentEndpoint()
server := e.server()
defer server.Close()
// Allow startup time in addition to the CLI's five-second trace flush
// budget, but reject waiting for the SDK's longer export timeout.
ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second)
defer cancel()
if err := runJob(t, ctx, testRunJobConfig{job: j, server: server, agentCfg: conf}); err != nil {
t.Fatal(err)
}
if err := ctx.Err(); err != nil {
t.Fatalf("credential transport delayed job completion: %v", err)
t.Fatalf("collector failure delayed job completion beyond the trace flush budget: %v", err)
}
logs := e.logsFor(t, defaultJobID)
if finish := e.finishesFor(t, defaultJobID)[0]; finish.ExitStatus != "0" {
t.Fatalf("job exit = %q, want 0\n%s", finish.ExitStatus, logs)
wantExit := "0"
if tc.failJob {
wantExit = "7"
}
if !strings.Contains(logs, "WORKLOAD_RAN") || !strings.Contains(logs, "HOOK_RAN") || strings.Contains(logs, "internal-token") {
if finish := e.finishesFor(t, defaultJobID)[0]; finish.ExitStatus != wantExit {
t.Fatalf("job exit = %q, want %q\n%s", finish.ExitStatus, wantExit, logs)
}
if !strings.Contains(logs, "WORKLOAD_RAN") || !strings.Contains(logs, "HOOK_RAN") || strings.Contains(logs, "internal-token") || strings.Contains(logs, "customer-env-secret") {
t.Fatalf("unexpected job log: %s", logs)
}
if len(requests) != 0 {
t.Fatal("credential delivery activated internal export")
customerSpans := customer.spans()
internalSpans := internal.spans()
if got := len(customerSpans) > 0; got != tc.customer {
t.Fatalf("customer spans present = %t, want %t", got, tc.customer)
}
if got, want := len(internalSpans) > 0, tc.internal && tc.config; got != want {
t.Fatalf("internal spans present = %t, want %t", got, want)
}
if tc.http2Debug != "" {
for _, destination := range []struct {
name string
sink *traceSink
protocol int
}{{"customer", customer, 2}, {"internal", internal, 1}} {
destination.sink.mu.Lock()
if got := destination.sink.protocols; len(got) != 1 || !got[destination.protocol] {
t.Errorf("%s HTTP protocol versions = %v, want only %d", destination.name, got, destination.protocol)
}
destination.sink.mu.Unlock()
}
}
if tc.customer {
body := customer.body()
for _, want := range []string{"private-author", "private-branch", "private-label", "private-metadata", "private-resource", "private-tracestate", "private-osc-message"} {
if !bytes.Contains(body, []byte(want)) {
t.Errorf("customer export lost %q", want)
}
}
}
for _, span := range internalSpans {
if got := fmt.Sprintf("%x", span.TraceId); got != "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" {
t.Errorf("internal trace ID = %s, want server trace ID", got)
}
if tc.customer {
other := customerSpans[string(span.SpanId)]
if other == nil || !bytes.Equal(other.TraceId, span.TraceId) || !bytes.Equal(other.ParentSpanId, span.ParentSpanId) || other.StartTimeUnixNano != span.StartTimeUnixNano || other.EndTimeUnixNano != span.EndTimeUnixNano || other.Status.GetCode() != span.Status.GetCode() {
t.Errorf("internal span does not match customer span: %v / %v", span, other)
}
}
if len(span.Attributes) != 0 || len(span.Events) != 0 || len(span.Links) != 0 || span.Status.GetMessage() != "" || span.TraceState != "" {
t.Errorf("internal span contains customer detail: %v", span)
}
}
for _, banned := range []string{"private-", "customer-token", "internal-token", "customer-service", "job-supplied-untrusted-config"} {
if bytes.Contains(internal.body(), []byte(banned)) {
t.Errorf("internal export contains %q", banned)
}
}
})
}
Expand Down Expand Up @@ -161,3 +263,89 @@ func TestInternalTracingBootstrapFailure(t *testing.T) {
})
}
}

type traceSink struct {
server *httptest.Server
mu sync.Mutex
requests []*collector.ExportTraceServiceRequest
protocols map[int]bool
}

func newTraceSink(t *testing.T, auth, fail string, https bool) *traceSink {
t.Helper()
s := &traceSink{protocols: make(map[int]bool)}
s.server = httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/v1/traces" || r.Header.Get("Authorization") != auth || r.Header.Get("Content-Type") != "application/x-protobuf" {
t.Errorf("unexpected OTLP request: %s %s auth=%q content-type=%q", r.Method, r.URL, r.Header.Get("Authorization"), r.Header.Get("Content-Type"))
}
body, err := io.ReadAll(r.Body)
if err != nil {
t.Error(err)
return
}
var request collector.ExportTraceServiceRequest
if err := proto.Unmarshal(body, &request); err != nil {
t.Error(err)
return
}
if fail == "slow" {
// Bootstrap must not impose a five-second deadline on the
// customer's final export when internal tracing is disabled.
timer := time.NewTimer(6 * time.Second)
defer timer.Stop()
select {
case <-timer.C:
case <-r.Context().Done():
return
}
}
s.mu.Lock()
s.protocols[r.ProtoMajor] = true
s.requests = append(s.requests, &request)
s.mu.Unlock()
if fail == "unavailable" {
http.Error(w, "private-sink-error internal-token", http.StatusServiceUnavailable)
return
}
if fail == "timeout" {
<-r.Context().Done()
return
}
w.Header().Set("Content-Type", "application/x-protobuf")
}))
if https {
s.server.EnableHTTP2 = true
s.server.StartTLS()
} else {
s.server.Start()
}
t.Cleanup(s.server.Close)
return s
}

func (s *traceSink) spans() map[string]*tracepb.Span {
s.mu.Lock()
defer s.mu.Unlock()
spans := make(map[string]*tracepb.Span)
for _, request := range s.requests {
for _, resource := range request.ResourceSpans {
for _, scope := range resource.ScopeSpans {
for _, span := range scope.Spans {
spans[string(span.SpanId)] = span
}
}
}
}
return spans
}

func (s *traceSink) body() []byte {
s.mu.Lock()
defer s.mu.Unlock()
var body []byte
for _, request := range s.requests {
data, _ := proto.Marshal(request)
body = append(body, data...)
}
return body
}
5 changes: 5 additions & 0 deletions clicommand/agent_start.go
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,10 @@ func (asc AgentStartConfig) Features(ctx context.Context) []string {
// the registration response (design:
// https://linear.app/buildkite/issue/A-1641).
features = append(features, "control-plane-otlp-tracing")
// Container executors cannot carry private collector credentials.
if !asc.KubernetesExec && (asc.Executor == "" || asc.Executor == agent.ExecutorExec) {
features = append(features, "internal-otlp-tracing")
}

if asc.DisconnectAfterJob {
features = append(features, "disconnect-after-job")
Expand Down Expand Up @@ -1425,6 +1429,7 @@ var AgentStartCommand = &cli.Command{
// merged in; the shared agentConf is never mutated.
workerConf := agentConf
agent.ApplyControlPlaneTracing(wl, &workerConf, reg.Tracing, localTracing)
workerConf.InternalTracingExporter = reg.InternalTracingExporter

// Create an agent worker to run the agent
return agent.NewAgentWorker(
Expand Down
17 changes: 17 additions & 0 deletions clicommand/agent_start_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,23 @@ func TestAgentStartFeatures_OpenTelemetryTracing(t *testing.T) {
if !slices.Contains(features, "opentelemetry-tracing") {
t.Fatalf("Features() = %v, want opentelemetry-tracing", features)
}
for _, enabled := range []bool{false, true} {
features := AgentStartConfig{OpenTelemetryTracing: enabled}.Features(t.Context())
if !slices.Contains(features, "internal-otlp-tracing") {
t.Errorf("Features() with customer tracing %t = %v, want internal-otlp-tracing", enabled, features)
}
}
if features := (AgentStartConfig{NoFeatureReporting: true}).Features(t.Context()); len(features) != 0 {
t.Errorf("Features() with reporting disabled = %v, want none", features)
}
if features := (AgentStartConfig{KubernetesExec: true}).Features(t.Context()); slices.Contains(features, "internal-otlp-tracing") {
t.Errorf("Features() advertises internal tracing without a private credential transport: %v", features)
}
for _, executor := range []string{agent.ExecutorKubernetes, agent.ExecutorDocker} {
if features := (AgentStartConfig{Executor: executor}).Features(t.Context()); slices.Contains(features, "internal-otlp-tracing") {
t.Errorf("Features() with executor %s advertises internal tracing without a private credential transport: %v", executor, features)
}
}
}

func setupHooksPath(t *testing.T) (string, func()) {
Expand Down
3 changes: 2 additions & 1 deletion clicommand/bootstrap.go
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,7 @@ type BootstrapConfig struct {
JobLogsOTLP bool `cli:"job-logs-otlp"`
DisableWarningsFor []string `cli:"disable-warnings-for" normalize:"list"`
CheckoutAttempts int `cli:"checkout-attempts"`
internalTracing bool
}

// checkoutOverrideMode resolves the configured mode, forcing strict when command-eval is off.
Expand Down Expand Up @@ -476,7 +477,7 @@ var BootstrapCommand = &cli.Command{
}

tracingBackend := tracetools.BackendNone
if cfg.OpenTelemetryTracing {
if cfg.OpenTelemetryTracing || cfg.internalTracing {

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.

Won't this set TRACEPARENT on customer jobs which only have internal tracing on? Should we care about that?

tracingBackend = tracetools.BackendOpenTelemetry
}

Expand Down
Loading