| 1 |
// Copyright The OpenTelemetry Authors |
| 2 |
// SPDX-License-Identifier: Apache-2.0 |
| 3 |
|
| 4 |
package gcp // import "go.opentelemetry.io/contrib/detectors/gcp" |
| 5 |
|
| 6 |
import ( |
| 7 |
"context" |
| 8 |
"fmt" |
| 9 |
"os" |
| 10 |
|
| 11 |
"cloud.google.com/go/compute/metadata" |
| 12 |
"go.opentelemetry.io/otel/attribute" |
| 13 |
"go.opentelemetry.io/otel/sdk/resource" |
| 14 |
semconv "go.opentelemetry.io/otel/semconv/v1.40.0" |
| 15 |
) |
| 16 |
|
| 17 |
// GKE collects resource information of GKE computing instances. |
| 18 |
// |
| 19 |
// Deprecated: Use gcp.NewDetector() instead, which does NOT detect container, pod, and namespace attributes. |
| 20 |
// Set those using name using the OTEL_RESOURCE_ATTRIBUTES env var instead. |
| 21 |
type GKE struct{} |
| 22 |
|
| 23 |
// compile time assertion that GKE implements the resource.Detector interface. |
| 24 |
var _ resource.Detector = (*GKE)(nil) |
| 25 |
|
| 26 |
// Detect detects associated resources when running in GKE environment. |
| 27 |
func (*GKE) Detect(ctx context.Context) (*resource.Resource, error) { |
| 28 |
gcpDetecor := GCE{} |
| 29 |
gceLablRes, err := gcpDetecor.Detect(ctx) |
| 30 |
|
| 31 |
if os.Getenv("KUBERNETES_SERVICE_HOST") == "" { |
| 32 |
return gceLablRes, err |
| 33 |
} |
| 34 |
|
| 35 |
var errInfo []string |
| 36 |
if err != nil { |
| 37 |
errInfo = append(errInfo, err.Error()) |
| 38 |
} |
| 39 |
|
| 40 |
attributes := []attribute.KeyValue{ |
| 41 |
semconv.K8SNamespaceName(os.Getenv("NAMESPACE")), |
| 42 |
semconv.K8SPodName(os.Getenv("HOSTNAME")), |
| 43 |
} |
| 44 |
|
| 45 |
if containerName := os.Getenv("CONTAINER_NAME"); containerName != "" { |
| 46 |
attributes = append(attributes, semconv.ContainerName(containerName)) |
| 47 |
} |
| 48 |
|
| 49 |
if clusterName, err := metadata.InstanceAttributeValueWithContext(ctx, "cluster-name"); hasProblem(err) { |
| 50 |
errInfo = append(errInfo, err.Error()) |
| 51 |
} else if clusterName != "" { |
| 52 |
attributes = append(attributes, semconv.K8SClusterName(clusterName)) |
| 53 |
} |
| 54 |
|
| 55 |
k8sattributeRes := resource.NewWithAttributes(semconv.SchemaURL, attributes...) |
| 56 |
|
| 57 |
res, err := resource.Merge(gceLablRes, k8sattributeRes) |
| 58 |
if err != nil { |
| 59 |
errInfo = append(errInfo, err.Error()) |
| 60 |
} |
| 61 |
|
| 62 |
var aggregatedErr error |
| 63 |
if len(errInfo) > 0 { |
| 64 |
aggregatedErr = fmt.Errorf("detecting GKE resources: %s", errInfo) |
| 65 |
} |
| 66 |
|
| 67 |
return res, aggregatedErr |
| 68 |
} |