|
| 1 | +package terraform |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "slices" |
| 7 | + "strings" |
| 8 | + "unicode" |
| 9 | + |
| 10 | + "go.opentelemetry.io/otel" |
| 11 | + "go.opentelemetry.io/otel/propagation" |
| 12 | +) |
| 13 | + |
| 14 | +// TODO: replace this with the upstream OTEL env propagation when it is |
| 15 | +// released. |
| 16 | + |
| 17 | +// envCarrier is a propagation.TextMapCarrier that is used to extract or |
| 18 | +// inject tracing environment variables. This is used with a |
| 19 | +// propagation.TextMapPropagator |
| 20 | +type envCarrier struct { |
| 21 | + Env []string |
| 22 | +} |
| 23 | + |
| 24 | +var _ propagation.TextMapCarrier = (*envCarrier)(nil) |
| 25 | + |
| 26 | +func toKey(key string) string { |
| 27 | + key = strings.ToUpper(key) |
| 28 | + key = strings.ReplaceAll(key, "-", "_") |
| 29 | + return strings.Map(func(r rune) rune { |
| 30 | + if unicode.IsLetter(r) || unicode.IsNumber(r) || r == '_' { |
| 31 | + return r |
| 32 | + } |
| 33 | + return -1 |
| 34 | + }, key) |
| 35 | +} |
| 36 | + |
| 37 | +func (c *envCarrier) Set(key, value string) { |
| 38 | + if c == nil { |
| 39 | + return |
| 40 | + } |
| 41 | + key = toKey(key) |
| 42 | + for i, e := range c.Env { |
| 43 | + if strings.HasPrefix(e, key+"=") { |
| 44 | + // don't directly update the slice so we don't modify the slice |
| 45 | + // passed in |
| 46 | + newEnv := slices.Clone(c.Env) |
| 47 | + newEnv = append(newEnv[:i], append([]string{fmt.Sprintf("%s=%s", key, value)}, newEnv[i+1:]...)...) |
| 48 | + c.Env = newEnv |
| 49 | + return |
| 50 | + } |
| 51 | + } |
| 52 | + c.Env = append(c.Env, fmt.Sprintf("%s=%s", key, value)) |
| 53 | +} |
| 54 | + |
| 55 | +func (_ *envCarrier) Get(_ string) string { |
| 56 | + // Get not necessary to inject environment variables |
| 57 | + panic("Not implemented") |
| 58 | +} |
| 59 | + |
| 60 | +func (_ *envCarrier) Keys() []string { |
| 61 | + // Keys not necessary to inject environment variables |
| 62 | + panic("Not implemented") |
| 63 | +} |
| 64 | + |
| 65 | +// otelEnvInject will add add any necessary environment variables for the span |
| 66 | +// found in the Context. If environment variables are already present |
| 67 | +// in `environ` then they will be updated. If no variables are found the |
| 68 | +// new ones will be appended. The new environment will be returned, `environ` |
| 69 | +// will never be modified. |
| 70 | +func otelEnvInject(ctx context.Context, environ []string) []string { |
| 71 | + c := &envCarrier{Env: environ} |
| 72 | + otel.GetTextMapPropagator().Inject(ctx, c) |
| 73 | + return c.Env |
| 74 | +} |
0 commit comments