|
| 1 | +// Copyright The OpenTelemetry Authors |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +package otelsdk_test |
| 5 | + |
| 6 | +import ( |
| 7 | + "context" |
| 8 | + "os/signal" |
| 9 | + "sync" |
| 10 | + "syscall" |
| 11 | + |
| 12 | + "go.opentelemetry.io/auto" |
| 13 | + "go.opentelemetry.io/auto/pipeline/otelsdk" |
| 14 | +) |
| 15 | + |
| 16 | +func Example_multiplex() { |
| 17 | + // Create a context that cancels when a SIGTERM is received. This ensures |
| 18 | + // that each instrumentation goroutine below can shut down cleanly. |
| 19 | + ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM) |
| 20 | + defer stop() |
| 21 | + |
| 22 | + // Create a new multiplexer to handle instrumentation events from multiple |
| 23 | + // sources. This will act as a central router for telemetry handlers. |
| 24 | + m, err := otelsdk.NewMultiplexer(ctx) |
| 25 | + if err != nil { |
| 26 | + panic(err) |
| 27 | + } |
| 28 | + |
| 29 | + // Simulated process IDs to be instrumented. These would typically be real |
| 30 | + // process IDs in a production scenario. |
| 31 | + pids := []int{1297, 1331, 9827} |
| 32 | + |
| 33 | + var wg sync.WaitGroup |
| 34 | + for _, pid := range pids { |
| 35 | + wg.Add(1) |
| 36 | + |
| 37 | + go func(id int) { |
| 38 | + defer wg.Done() |
| 39 | + |
| 40 | + // Create a new instrumentation session for the process. |
| 41 | + // |
| 42 | + // NOTE: Error handling is omitted here for brevity. In production |
| 43 | + // code, always check and handle errors. |
| 44 | + inst, _ := auto.NewInstrumentation( |
| 45 | + ctx, |
| 46 | + auto.WithPID(id), |
| 47 | + auto.WithHandler(m.Handler(id)), |
| 48 | + ) |
| 49 | + |
| 50 | + // Load and start the instrumentation for the process. |
| 51 | + _ = inst.Load(ctx) |
| 52 | + _ = inst.Run(ctx) |
| 53 | + }(pid) |
| 54 | + } |
| 55 | + |
| 56 | + // Wait for all instrumentation goroutines to complete. |
| 57 | + wg.Wait() |
| 58 | + |
| 59 | + // Shut down the multiplexer, cleaning up any remaining resources. |
| 60 | + _ = m.Shutdown(ctx) |
| 61 | +} |
0 commit comments