Skip to content

testctx: represent subtests as cause/effect - #8120

Closed
vito wants to merge 76 commits into
dagger:mainfrom
vito:testctx-effects
Closed

vito wants to merge 76 commits into
dagger:mainfrom
vito:testctx-effects

Conversation

@vito

@vito vito commented Aug 7, 2024

Copy link
Copy Markdown
Contributor

This fixes the hyper inflated test runtimes due to tests actually blocking on t.Parallel.

This use case actually perfectly aligns with the cause/effect system built to handle async Buildkit work. But, Cloud needs more changes to fully support and properly represent it, which is WIP.

vito and others added 30 commits August 9, 2024 11:15
just squinting at everything

Signed-off-by: Alex Suraci <[email protected]>
TODO:

* direct logs to DB (somehow - ctx LoggerProvider?)
* reimplement subscribing, just go over HTTP (SSE?)
* determine how/when subscribing should detach
* set X-Dagger-Client-ID header (or remove if redundant)

Signed-off-by: Alex Suraci <[email protected]>
* no more gRPC telemetry servers
* clients subscribe to export requests via SSE

Signed-off-by: Alex Suraci <[email protected]>
this stopped working mysteriously, probably a rogue import. gross.

Signed-off-by: Alex Suraci <[email protected]>
withExec sets CallerClientID, which is used by setupOTel. Previously setupOTel
used ClientID, not CallerClientID, but ClientID is specifically the newly-nested
ClientID, so I'm not sure yet if it was incorrect before or if ClientID should
take precedence.

along the way, tweak OTel config setup to respect OTEL_EXPORTER_OTLP_HEADERS,
even though we didn't end up using it, since doing it in the handler is neater.

Signed-off-by: Alex Suraci <[email protected]>

diff --git a/core/container_exec.go b/core/container_exec.go
index 3f8bdbd..c42a872 100644
--- a/core/container_exec.go
+++ b/core/container_exec.go
@@ -80,6 +80,7 @@ func (container *Container) WithExec(ctx context.Context, opts ContainerExecOpts
 	}
 	execMD.CallID = dagql.CurrentID(ctx)
 	execMD.ExecID = identity.NewID()
+	execMD.CallerClientID = clientMetadata.ClientID
 	execMD.SessionID = clientMetadata.SessionID
 	if execMD.HostAliases == nil {
 		execMD.HostAliases = make(map[string][]string)
@@ -107,9 +108,6 @@ func (container *Container) WithExec(ctx context.Context, opts ContainerExecOpts
 		if execMD.ClientID == "" {
 			execMD.ClientID = identity.NewID()
 		}
-		if execMD.CallerClientID == "" {
-			execMD.CallerClientID = clientMetadata.ClientID
-		}

 		// include the engine version so that these execs get invalidated if the engine/API change
 		runOpts = append(runOpts, llb.AddEnv(buildkit.DaggerEngineVersionEnv, engine.Version))
diff --git a/engine/buildkit/executor_spec.go b/engine/buildkit/executor_spec.go
index eea98b1..b3dd2e59d 100644
--- a/engine/buildkit/executor_spec.go
+++ b/engine/buildkit/executor_spec.go
@@ -8,6 +8,7 @@ import (
 	"errors"
 	"fmt"
 	"io"
+	"log/slog"
 	"net"
 	"net/http"
 	"os"
@@ -31,8 +32,6 @@ import (
 	bknetwork "github.com/moby/buildkit/util/network"
 	"github.com/opencontainers/runtime-spec/specs-go"
 	"github.com/sourcegraph/conc/pool"
-	"go.opentelemetry.io/otel"
-	"go.opentelemetry.io/otel/log"
 	"golang.org/x/net/http2"
 	"golang.org/x/net/http2/h2c"

@@ -64,6 +63,7 @@ const (
 	OTelTraceParentEnv      = "TRACEPARENT"
 	OTelExporterProtocolEnv = "OTEL_EXPORTER_OTLP_PROTOCOL"
 	OTelExporterEndpointEnv = "OTEL_EXPORTER_OTLP_ENDPOINT"
+	OTelExporterHeadersEnv  = "OTEL_EXPORTER_OTLP_HEADERS"
 	OTelTracesProtocolEnv   = "OTEL_EXPORTER_OTLP_TRACES_PROTOCOL"
 	OTelTracesEndpointEnv   = "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT"
 	OTelTracesLiveEnv       = "OTEL_EXPORTER_OTLP_TRACES_LIVE"
@@ -631,15 +631,17 @@ func (w *Worker) setupOTel(ctx context.Context, state *execState) error {
 		return nil
 	}

-	logAttrs := []log.KeyValue{}
+	var clientID string
 	if w.execMD != nil {
+		clientID = w.execMD.CallerClientID
 		if w.execMD.SpanContext != nil {
-			ctx = otel.GetTextMapPropagator().Extract(ctx, w.execMD.SpanContext)
+			ctx = telemetry.Propagator.Extract(ctx, w.execMD.SpanContext)
 		}
-		logAttrs = append(logAttrs, log.String(telemetry.ClientIDAttr, w.execMD.ClientID))
+	} else {
+		slog.Warn("!!! NO EXECMD FOR", "args", state.procInfo.Meta.Args)
 	}

-	stdio := telemetry.SpanStdio(ctx, InstrumentationLibrary, logAttrs...)
+	stdio := telemetry.SpanStdio(ctx, InstrumentationLibrary)
 	state.cleanups.Add("close logs", stdio.Close)

 	state.procInfo.Stdout = nopCloser{io.MultiWriter(stdio.Stdout, state.procInfo.Stdout)}
@@ -652,7 +654,14 @@ func (w *Worker) setupOTel(ctx context.Context, state *execState) error {
 		return fmt.Errorf("otel tcp proxy listen: %w", err)
 	}
 	otelSrv := &http.Server{
-		Handler:           w.telemetryPubSub,
+		Handler: http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
+			if r.Header == nil {
+				r.Header = http.Header{}
+			}
+			slog.Warn("!!! OTEL PROXY ADDING HEADER", "clientID", clientID, "execMD", fmt.Sprintf("%+v", w.execMD))
+			r.Header.Set("X-Dagger-Client-ID", clientID)
+			w.telemetryPubSub.ServeHTTP(rw, r)
+		}),
 		ReadHeaderTimeout: 10 * time.Second, // for gocritic
 	}
 	listenerPool := pool.New().WithErrors()
diff --git a/engine/client/client.go b/engine/client/client.go
index e2a0b0264..389470bc9 100644
--- a/engine/client/client.go
+++ b/engine/client/client.go
@@ -555,7 +555,7 @@ func (c *otlpConsumer) Consume(ctx context.Context, cb func([]byte) error) (rerr
 		if rerr != nil {
 			slog.Error("consume failed", "err", rerr)
 		} else {
-			slog.Warn("consumed", "ctxErr", ctx.Err())
+			slog.ExtraDebug("done consuming", "ctxErr", ctx.Err())
 		}
 	}()

@@ -574,7 +574,7 @@ func (c *otlpConsumer) Consume(ctx context.Context, cb func([]byte) error) (rerr
 	}
 	defer sseConn.Close()

-	slog.Warn("consuming")
+	slog.ExtraDebug("consuming")

 	for {
 		event, err := sseConn.Next()
@@ -587,7 +587,7 @@ func (c *otlpConsumer) Consume(ctx context.Context, cb func([]byte) error) (rerr

 		data := event.Data

-		slog.ExtraDebug("consuming data", "bytes", len(data))
+		slog.ExtraDebug("received "+event.Name, "cursor", event.ID, "bytes", len(data))

 		if len(data) == 0 {
 			continue
diff --git a/engine/clientdb/dbs.go b/engine/clientdb/dbs.go
index d1c1aab..b45f660 100644
--- a/engine/clientdb/dbs.go
+++ b/engine/clientdb/dbs.go
@@ -24,7 +24,6 @@ func NewDBs(root string) *DBs {
 var Schema string

 func (dbs *DBs) Create(clientID string) (*sql.DB, error) {
-	slog.Warn("!!! CREATE DB", "clientID", clientID)
 	db, err := dbs.Open(clientID)
 	if err != nil {
 		return nil, err
@@ -36,7 +35,6 @@ func (dbs *DBs) Create(clientID string) (*sql.DB, error) {
 }

 func (dbs *DBs) Open(clientID string) (*sql.DB, error) {
-	slog.Warn("!!! OPEN DB", "clientID", clientID)
 	dbPath := dbs.path(clientID)
 	if err := os.MkdirAll(filepath.Dir(dbPath), 0700); err != nil {
 		return nil, fmt.Errorf("mkdir %s: %w", filepath.Dir(dbPath), err)
diff --git a/engine/telemetry/pubsub.go b/engine/telemetry/pubsub.go
index e37e9fd..b9dcdbc7e 100644
--- a/engine/telemetry/pubsub.go
+++ b/engine/telemetry/pubsub.go
@@ -339,8 +339,6 @@ func (ps *PubSub) TracesSubscribeHandler(w http.ResponseWriter, r *http.Request)
 				return
 			}

-			slog.Warn("!!! PUBSUB GOT SPANS", "spans", len(spans))
-
 			if len(spans) == 0 {
 				_, ok := <-notify
 				if ok {
@@ -427,8 +425,6 @@ func (ps *PubSub) LogsSubscribeHandler(w http.ResponseWriter, r *http.Request) {
 				return
 			}

-			slog.Warn("!!! PUBSUB GOT LOGS", "spans", len(logs))
-
 			if len(logs) == 0 {
 				_, ok := <-notify
 				if ok {
diff --git a/sdk/go/telemetry/init.go b/sdk/go/telemetry/init.go
index e8a3a74..8d2a5ba 100644
--- a/sdk/go/telemetry/init.go
+++ b/sdk/go/telemetry/init.go
@@ -73,8 +73,16 @@ func ConfiguredSpanExporter(ctx context.Context) (sdktrace.SpanExporter, bool) {

 		switch proto {
 		case "http/protobuf", "http":
+			headers := map[string]string{}
+			if hs := os.Getenv("OTEL_EXPORTER_OTLP_HEADERS"); hs != "" {
+				for _, header := range strings.Split(hs, ",") {
+					name, value, _ := strings.Cut(header, "=")
+					headers[name] = value
+				}
+			}
 			configuredSpanExporter, err = otlptracehttp.New(ctx,
-				otlptracehttp.WithEndpointURL(endpoint))
+				otlptracehttp.WithEndpointURL(endpoint),
+				otlptracehttp.WithHeaders(headers))
 		case "grpc":
 			var u *url.URL
 			u, err = url.Parse(endpoint)
Signed-off-by: Alex Suraci <[email protected]>
it's still very much possible and in fact normal to leave some spans unfinished -
in particular /shutdown, /v1/traces, /v1/logs, and /sessionAttachables - but we
should at least be guaranteed to flush whatever work completed prior to closing
the client.

we probably need to wait for services to exit, though.

Signed-off-by: Alex Suraci <[email protected]>
everything else is internal, and most of them don't complete anyway

Signed-off-by: Alex Suraci <[email protected]>
removed likely-overkill advanced tuning

Signed-off-by: Alex Suraci <[email protected]>
Signed-off-by: Alex Suraci <[email protected]>
otherwise these logs go to Container.sync

Signed-off-by: Alex Suraci <[email protected]>
no longer load bearing (client ID attr is no more)

Signed-off-by: Alex Suraci <[email protected]>
otherwise we don't see telemetry of nested clients (e.g. module function calls)

Signed-off-by: Alex Suraci <[email protected]>
This fixes custom spans not being visible to the parent of a nested call.

Signed-off-by: Alex Suraci <[email protected]>
(also move entire method teehee)

Signed-off-by: Alex Suraci <[email protected]>
now that client requests respect trace context propagation, client
telemetry is outside of the primary span, so nothing ends up being
printed.

now dagger session will tell the frontend to just show everything.

Signed-off-by: Alex Suraci <[email protected]>
see comment for explanation

Signed-off-by: Alex Suraci <[email protected]>
vito added 17 commits August 9, 2024 11:15
we have a SQLite database per-client and intentionally separate
read/write connections, meanwhile most desktops default to 1024 which is
too low. meanwhile, production settings routinely set a higher limit,
such as this one, copy-pasted from our CI runners.

(also: made sure that it's not a silly leak first.)

Signed-off-by: Alex Suraci <[email protected]>
haven't confirmed this is an issue, but seems sensible

Signed-off-by: Alex Suraci <[email protected]>
I added instrumentation (included) to the subscribing process which revealed
that we "hang" on GET /v1/logs, but not /v1/traces. When I modified it to send
a no-op SSE event every 100ms, it was fixed after ~16s. When I bumped the size
of the event, it was "fixed" immediately.

Turns out that while the server-side was doing the right thing by using a
http.Flusher, the io.Copy in the middle was ruining everything. Using a
writeFlusher that calls Flush() after every Write() fixes everything and helps
ensure a safe orderly client initialization sequence.

_Hopefully_ this explains the weirdness in CI, but honestly I'm not sure, it
might just be unrelated weirdness, but this seems like a good idea in its own
right.

Signed-off-by: Alex Suraci <[email protected]>
Signed-off-by: Alex Suraci <[email protected]>
this re-evaluates when the same client initializes again, which is
currently the case for repeated sequential calls in certain scenarios

Signed-off-by: Alex Suraci <[email protected]>
was causing a 'failed to marshal log record body' error in logs

Signed-off-by: Alex Suraci <[email protected]>
there's no need to require these to be UTF-8 (unintended consequence of
protojson), and no need to query these structurally, so let's just keep
it BLOBby

Signed-off-by: Alex Suraci <[email protected]>
we can't always expect the caller to have configured trace context, and
this isn't really an appropriate spot to be generating a ton of traces,
so skip creating the span instead

Signed-off-by: Alex Suraci <[email protected]>
github's secret scrubbing currently chokes on large output, and you have
to 'view raw logs' to see everything anyway, might as well just download
an artifact instead.

Signed-off-by: Alex Suraci <[email protected]>
also make sure to keep still-active clients in case there's one sitting
around for an hour

Signed-off-by: Alex Suraci <[email protected]>
otherwise skipped/panicked tests won't run the hook

Signed-off-by: Alex Suraci <[email protected]>
otherwise things get REALLY confusing when you --count=100

the index is probably useless now, btw

Signed-off-by: Alex Suraci <[email protected]>
@vito
vito force-pushed the testctx-effects branch from 26cadd5 to 5accf03 Compare August 9, 2024 15:58
@jedevc jedevc mentioned this pull request Aug 20, 2024
2 of 5 tasks
@github-actions

Copy link
Copy Markdown
Contributor

This PR is stale because it has been open 14 days with no activity. Remove stale label or comment or this will be closed in 7 days.

@github-actions

Copy link
Copy Markdown
Contributor

This PR was closed because it has been stalled for 7 days with no activity.

@github-actions github-actions Bot closed this Aug 31, 2024
@vito

vito commented Sep 16, 2024

Copy link
Copy Markdown
Contributor Author

Still relevant - but should be done via span links instead following #8442

@vito vito reopened this Sep 16, 2024
@github-actions

github-actions Bot commented Oct 1, 2024

Copy link
Copy Markdown
Contributor

This PR is stale because it has been open 14 days with no activity. Remove stale label or comment or this will be closed in 7 days.

@github-actions

github-actions Bot commented Oct 9, 2024

Copy link
Copy Markdown
Contributor

This PR was closed because it has been stalled for 7 days with no activity.

@github-actions github-actions Bot closed this Oct 9, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant