Skip to content

Commit ba974c6

Browse files
committed
some working stuff
1 parent 693fcfc commit ba974c6

File tree

7 files changed

+200
-139
lines changed

7 files changed

+200
-139
lines changed

cmd/go-cache-plugin/commands.go

Lines changed: 88 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,11 @@ import (
1010
"errors"
1111
"fmt"
1212
"github.com/grafana/go-cache-plugin/lib/otel"
13-
"github.com/grafana/go-cache-plugin/lib/toolexec"
1413
"io"
1514
"log"
1615
"net"
1716
"net/http"
1817
"os"
19-
"os/exec"
2018
"os/signal"
2119
"strconv"
2220
"strings"
@@ -35,7 +33,7 @@ var flags struct {
3533
S3Region string `flag:"region,default=$GOCACHE_S3_REGION,S3 region"`
3634
S3Endpoint string `flag:"s3-endpoint-url,default=$GOCACHE_S3_ENDPOINT_URL,S3 custom endpoint URL (if unset, use AWS default)"`
3735
S3PathStyle bool `flag:"s3-path-style,default=$GOCACHE_S3_PATH_STYLE,S3 path-style URLs (optional)"`
38-
LocalCache bool `flag:"local-cache,default=false,Runs in no cache mode (no S3)"`
36+
LocalCache bool `flag:"local-cache,default=$GOCACHE_LOCAL,Runs in no cache mode (no S3)"`
3937
KeyPrefix string `flag:"prefix,default=$GOCACHE_KEY_PREFIX,S3 key prefix (optional)"`
4038
MinUploadSize int64 `flag:"min-upload-size,default=$GOCACHE_MIN_SIZE,Minimum object size to upload to S3 (in bytes)"`
4139
Concurrency int `flag:"c,default=$GOCACHE_CONCURRENCY,Maximum number of concurrent requests"`
@@ -44,9 +42,15 @@ var flags struct {
4442
Expiration time.Duration `flag:"expiry,default=$GOCACHE_EXPIRY,Cache expiration period (optional)"`
4543
Verbose bool `flag:"v,default=$GOCACHE_VERBOSE,Enable verbose logging"`
4644
DebugLog int `flag:"debug,default=$GOCACHE_DEBUG,Enable detailed per-request debug logging (noisy)"`
47-
TracingEnabled bool `flag:"tracing,default=false,Enable tracing (optional)"`
48-
TracingContext string `flag:"context,default=runId:runAttempt:jobName:stepName:stepNumber,Tracing params"`
49-
OtelCollectorAddress string `flag:"otel-collector,default,OTEL collector address (optional)"`
45+
TracingEnabled bool `flag:"tracing,default=$ENABLE_TRACING,Enable tracing (optional)"`
46+
OtelCollectorAddress string `flag:"otel-collector,default=$OTEL_COLLECTOR_ADDRESS,OTEL collector address (optional)"`
47+
TraceId string `flag:"traceId,default=$TRACING_TRACE_ID,Trace Id (optional)"`
48+
ParentSpanId string `flag:"parentSpanId,default=$TRACING_PARENT_SPAN_ID,Parent Span Id (optional)"`
49+
RunId string `flag:"runId,default=$RUN_ID,Run ID (optional)"`
50+
RunAttempt string `flag:"runAttempt,default=$RUN_ATTEMPT,Run attempt (optional)"`
51+
JobName string `flag:"jobName,default=$JOB_NAME,Job name (optional)"`
52+
StepName string `flag:"stepName,default=$STEP_NAME,Step name (optional)"`
53+
StepNumber string `flag:"stepNumber,default=$STEP_NUMBER,Step number (optional)"`
5054
}
5155

5256
const (
@@ -75,18 +79,11 @@ var serveFlags struct {
7579
Plugin string `flag:"plugin,default=$GOCACHE_PLUGIN,Plugin service addr (or port) (required)"`
7680
HTTP string `flag:"http,default=$GOCACHE_HTTP,HTTP service address ([host]:port)"`
7781
ModProxy bool `flag:"modproxy,default=$GOCACHE_MODPROXY,Enable a Go module proxy (requires --http)"`
78-
ModNoCache bool `flag:"mod-nocache,default=false,Disable the local module cache (requires --modproxy)"`
82+
ModNoCache bool `flag:"mod-nocache,default=$GOCACHE_MODPROXY_NOCACHE,Disable the local module cache (requires --modproxy)"`
7983
RevProxy string `flag:"revproxy,default=$GOCACHE_REVPROXY,Reverse proxy these hosts (comma-separated; requires --http)"`
8084
SumDB string `flag:"sumdb,default=$GOCACHE_SUMDB,SumDB servers to proxy for (comma-separated)"`
8185
}
8286

83-
var toolexecFlags struct {
84-
LogFile string `flag:"log-file,default=trace.log,File used for logs"`
85-
TracingEnabled bool `flag:"tracing,default=false,Enable tracing (optional)"`
86-
TracingContext string `flag:"context,default=runId:runAttempt:jobName:stepName:stepNumber,Tracing params"`
87-
OtelCollectorAddress string `flag:"otel-collector,default,OTEL collector address (optional)"`
88-
}
89-
9087
func noopClose(context.Context) error { return nil }
9188

9289
// runServe runs a cache communicating over a local TCP socket.
@@ -144,7 +141,10 @@ func runServe(env *command.Env) error {
144141
// If an HTTP server is enabled, start it up with debug routes
145142
// and whatever other services were requested.
146143
if serveFlags.HTTP != "" {
147-
otelCleanup, tracingContext, err := initModTracing(ctx)
144+
otelCleanup, tracingContext, err := initModTracing(ctx, "gobuild-modcache")
145+
if err != nil {
146+
return fmt.Errorf("tracing: %w", err)
147+
}
148148
if err != nil {
149149
return fmt.Errorf("tracing: %w", err)
150150
}
@@ -195,7 +195,7 @@ func runServe(env *command.Env) error {
195195
func runConnect(env *command.Env, plugin string) error {
196196

197197
ctx := env.Context()
198-
shutdownTracer, reportSpan, err := initTracing(ctx)
198+
shutdownTracer, reportSpan, err := initTracing(ctx, "gobuild-gocacheprog-connect")
199199
if err != nil {
200200
return err
201201
}
@@ -228,44 +228,22 @@ func runConnect(env *command.Env, plugin string) error {
228228
conn.Close()
229229

230230
shutdownTracer(context.Background())
231-
println("@@@@@ - connection closed @@@@@")
232-
println(fmt.Sprintf("connection closed (%v elapsed)", time.Since(start)))
231+
vprintf(fmt.Sprintf("connection closed (%v elapsed)", time.Since(start)))
233232
return nil
234233
}
235234

236-
func runToolexec(env *command.Env) error {
237-
ctx := env.Context()
238-
shutdownTracer, tracingContext, err := initModTracing(ctx)
239-
if err != nil {
240-
return err
241-
}
242-
defer shutdownTracer(ctx)
243-
244-
tool := os.Args[1]
245-
args := os.Args[2:]
246-
247-
pkg := toolexec.GetPackage(os.Args)
248-
249-
_, span := tracingContext.SpanWithContext(ctx, fmt.Sprintf("%s: %s", toolexec.GetTool(tool), pkg))
250-
defer span.End()
251-
cmd := exec.Command(tool, args...)
252-
cmd.Stdout = os.Stdout
253-
cmd.Stderr = os.Stderr
254-
return cmd.Run()
255-
}
256-
257-
func initTracing(ctx context.Context) (func(context.Context) error, func([]byte), error) {
235+
func initTracing(ctx context.Context, service string) (func(context.Context) error, func([]byte), error) {
258236
if !flags.TracingEnabled {
259237
return func(context.Context) error { return nil }, func([]byte) {}, nil
260238
}
261239

262240
var shutdown func(context.Context) error
263241
var err error
264242
if flags.OtelCollectorAddress != "" {
265-
shutdown, err = otel.SetupOtelTraceProvider(ctx, flags.OtelCollectorAddress)
243+
shutdown, err = otel.SetupOtelTraceProvider(ctx, service, flags.OtelCollectorAddress)
266244
} else if flags.LogFile != "" {
267245
log.Printf("Otel Collector address not specified, starting with the logging reporter, log file: %s", flags.LogFile)
268-
shutdown, err = otel.SetupLoggingProvider(ctx, flags.LogFile)
246+
shutdown, err = otel.SetupLoggingProvider(ctx, service, flags.LogFile)
269247
} else {
270248
log.Printf("please specify either --otel-collector or --log-file to setup tracing or disable tracing")
271249
return nil, nil, errors.New("otel exporter not initialized")
@@ -274,42 +252,55 @@ func initTracing(ctx context.Context) (func(context.Context) error, func([]byte)
274252
return nil, nil, err
275253
}
276254

277-
tracingContext := otel.NewTracedFromString(flags.TracingContext)
278-
255+
tracingContext, err := initTracingContext()
256+
if err != nil {
257+
return nil, nil, err
258+
}
279259
spanner := otel.NewAwesomeSpanner(tracingContext)
280260

281261
spanReporter := func(buffer []byte) {
282262
id, err := parseId(buffer[:])
283263
if err != nil {
284-
log.Printf("failed to parse id from buffer: %v", err)
264+
return
285265
}
286266
spanner.ProcessId(ctx, id)
287267
}
288268

289269
return shutdown, spanReporter, err
290270
}
291-
func initModTracing(ctx context.Context) (func(context.Context) error, *otel.TracingContext, error) {
271+
func initModTracing(ctx context.Context, service string) (func(context.Context) error, *otel.TracingContext, error) {
292272
if !flags.TracingEnabled {
293273
return func(context.Context) error { return nil }, nil, nil
294274
}
295275

296276
var shutdown func(context.Context) error
297277
var err error
298278
if flags.OtelCollectorAddress != "" {
299-
shutdown, err = otel.SetupOtelTraceProvider(ctx, flags.OtelCollectorAddress)
279+
shutdown, err = otel.SetupOtelTraceProvider(ctx, service, flags.OtelCollectorAddress)
300280
} else if flags.LogFile != "" {
301281
log.Printf("Otel Collector address not specified, starting with the logging reporter, log file: %s", flags.LogFile)
302-
shutdown, err = otel.SetupLoggingProvider(ctx, flags.LogFile)
282+
shutdown, err = otel.SetupLoggingProvider(ctx, service, flags.LogFile)
303283
} else {
304284
log.Printf("please specify either --otel-collector or --log-file to setup tracing or disable tracing")
305285
return nil, nil, errors.New("otel exporter not initialized")
306286
}
307287

308-
tracingContext := otel.NewTracedFromString(flags.TracingContext)
288+
tracingContext, err := initTracingContext()
289+
if err != nil {
290+
return nil, nil, err
291+
}
309292

310293
return shutdown, tracingContext, err
311294
}
312295

296+
func initTracingContext() (*otel.TracingContext, error) {
297+
if flags.TraceId != "" && flags.ParentSpanId != "" {
298+
return otel.NewTracingContext(flags.TraceId, flags.ParentSpanId)
299+
} else {
300+
return otel.NewTracingContextFromRunData(flags.RunId, flags.RunAttempt, flags.JobName, flags.StepName, flags.StepNumber), nil
301+
}
302+
}
303+
313304
// copy emulates the base case of io.Copy, but does not attempt to use the
314305
// io.ReaderFrom or io.WriterTo implementations.
315306
//
@@ -336,20 +327,61 @@ func copy(w io.Writer, r io.Reader, reportTrace func([]byte)) error {
336327
}
337328
}
338329

339-
func parseId(buf []byte) (string, error) {
340-
map1 := make(map[string]any)
330+
type name struct {
331+
}
332+
333+
func parseId(buf []byte) (otel.CacheRequest, error) {
334+
var data map[string]any
341335

342-
err := json.Unmarshal(buf, &map1)
336+
err := json.Unmarshal(buf, &data)
343337
if err != nil {
344338
slice, _, found := bytes.Cut(buf, []byte{'\n'})
345339
if found {
346-
err2 := json.Unmarshal(slice, &map1)
340+
err2 := json.Unmarshal(slice, &data)
347341
if err2 != nil {
348-
return "", err
342+
return otel.CacheRequest{}, err
349343
}
350344
}
351345
}
352346

353-
value := map1["ID"]
354-
return fmt.Sprintf("map1 = %v", value), nil
347+
var id string
348+
var miss bool
349+
var command string
350+
var actionId string
351+
352+
id1, ok := data["ID"]
353+
if !ok {
354+
return otel.CacheRequest{}, errors.New("id not found in the request")
355+
} else {
356+
id = fmt.Sprint(id1)
357+
}
358+
359+
command1, ok := data["Command"]
360+
if !ok {
361+
command = ""
362+
} else {
363+
command = fmt.Sprint(command1)
364+
}
365+
366+
_, ok = data["Miss"]
367+
if !ok {
368+
miss = false
369+
} else {
370+
miss = true
371+
}
372+
373+
actionId1, ok := data["ActionID"]
374+
if !ok {
375+
actionId = ""
376+
} else {
377+
actionId = fmt.Sprint(actionId1)
378+
}
379+
380+
data2 := otel.CacheRequest{
381+
Id: id,
382+
ActionId: actionId,
383+
Miss: miss,
384+
Command: command,
385+
}
386+
return data2, nil
355387
}

cmd/go-cache-plugin/go-cache-plugin.go

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -74,11 +74,6 @@ This mode bridges stdin/stdout to a cache server (see the "serve" command)
7474
listening on the specified port.`,
7575
Run: command.Adapt(runConnect),
7676
},
77-
{
78-
Name: "toolexec",
79-
SetFlags: command.Flags(flax.MustBind, &toolexecFlags),
80-
Run: command.Adapt(runToolexec),
81-
},
8277
command.HelpCommand(helpTopics),
8378
command.VersionCommand(),
8479
},

lib/otel/collectors.go

Lines changed: 21 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -3,34 +3,30 @@ package otel
33
import (
44
"context"
55
"go.opentelemetry.io/otel"
6+
"go.opentelemetry.io/otel/attribute"
67
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
78
"go.opentelemetry.io/otel/exporters/stdout/stdouttrace"
89
"go.opentelemetry.io/otel/sdk/resource"
910
"go.opentelemetry.io/otel/sdk/trace"
11+
semconv "go.opentelemetry.io/otel/semconv/v1.37.0"
1012
"log"
1113
"os"
1214
)
1315

1416
var tp *trace.TracerProvider
1517

16-
func SetupLoggingProvider(ctx context.Context, file string) (func(context.Context) error, error) {
18+
func SetupLoggingProvider(ctx context.Context, service, file string) (func(context.Context) error, error) {
1719
f, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
1820
if err != nil {
1921
log.Fatalf("error opening file: %v", err)
2022
}
2123
exporter, err := stdouttrace.New(stdouttrace.WithWriter(f))
2224

23-
tp = trace.NewTracerProvider(
24-
trace.WithBatcher(exporter),
25-
trace.WithResource(resource.Default()),
26-
)
27-
28-
otel.SetTracerProvider(tp)
29-
30-
return tp.Shutdown, nil
25+
shutdownHook := setupTraceProvider(service, exporter)
26+
return shutdownHook, nil
3127
}
3228

33-
func SetupOtelTraceProvider(ctx context.Context, address string) (func(context.Context) error, error) {
29+
func SetupOtelTraceProvider(ctx context.Context, service, address string) (func(context.Context) error, error) {
3430
exporter, err := otlptracegrpc.New(ctx,
3531
otlptracegrpc.WithEndpoint(address),
3632
otlptracegrpc.WithInsecure(),
@@ -40,12 +36,24 @@ func SetupOtelTraceProvider(ctx context.Context, address string) (func(context.C
4036
return nil, err
4137
}
4238

39+
shutdownHook := setupTraceProvider(service, exporter)
40+
41+
return shutdownHook, nil
42+
}
43+
44+
func setupTraceProvider(service string, exporter trace.SpanExporter) func(ctx context.Context) error {
45+
46+
res := resource.NewWithAttributes(
47+
semconv.SchemaURL,
48+
semconv.ServiceName(service),
49+
attribute.String("env", "ci"),
50+
)
51+
4352
tp = trace.NewTracerProvider(
4453
trace.WithBatcher(exporter),
45-
trace.WithResource(resource.Default()),
54+
trace.WithResource(res),
4655
)
4756

4857
otel.SetTracerProvider(tp)
49-
50-
return tp.Shutdown, nil
58+
return tp.Shutdown
5159
}

lib/otel/intercept.go

Lines changed: 0 additions & 32 deletions
This file was deleted.

0 commit comments

Comments
 (0)