|
| 1 | +// Copyright The OpenTelemetry Authors |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +package gcp |
| 16 | + |
| 17 | +import ( |
| 18 | + "context" |
| 19 | + "fmt" |
| 20 | + "os" |
| 21 | + |
| 22 | + "cloud.google.com/go/compute/metadata" |
| 23 | + |
| 24 | + "go.opentelemetry.io/otel/api/kv" |
| 25 | + "go.opentelemetry.io/otel/api/standard" |
| 26 | + "go.opentelemetry.io/otel/sdk/resource" |
| 27 | +) |
| 28 | + |
| 29 | +// GKE collects resource information of GKE computing instances |
| 30 | +type GKE struct{} |
| 31 | + |
| 32 | +// compile time assertion that GCE implements the resource.Detector interface. |
| 33 | +var _ resource.Detector = (*GKE)(nil) |
| 34 | + |
| 35 | +// Detect detects associated resources when running in GKE environment. |
| 36 | +func (gke *GKE) Detect(ctx context.Context) (*resource.Resource, error) { |
| 37 | + gcpDetecor := GCE{} |
| 38 | + gceLablRes, err := gcpDetecor.Detect(ctx) |
| 39 | + |
| 40 | + if os.Getenv("KUBERNETES_SERVICE_HOST") == "" { |
| 41 | + return gceLablRes, err |
| 42 | + } |
| 43 | + |
| 44 | + var errInfo []string |
| 45 | + if err != nil { |
| 46 | + errInfo = append(errInfo, err.Error()) |
| 47 | + } |
| 48 | + |
| 49 | + labels := []kv.KeyValue{ |
| 50 | + standard.K8SNamespaceNameKey.String(os.Getenv("NAMESPACE")), |
| 51 | + standard.K8SPodNameKey.String(os.Getenv("HOSTNAME")), |
| 52 | + } |
| 53 | + |
| 54 | + if containerName := os.Getenv("CONTAINER_NAME"); containerName != "" { |
| 55 | + labels = append(labels, standard.ContainerNameKey.String(containerName)) |
| 56 | + } |
| 57 | + |
| 58 | + if clusterName, err := metadata.InstanceAttributeValue("cluster-name"); hasProblem(err) { |
| 59 | + errInfo = append(errInfo, err.Error()) |
| 60 | + } else if clusterName != "" { |
| 61 | + labels = append(labels, standard.K8SClusterNameKey.String(clusterName)) |
| 62 | + } |
| 63 | + |
| 64 | + k8sLabelRes := resource.New(labels...) |
| 65 | + var aggregatedErr error |
| 66 | + if len(errInfo) > 0 { |
| 67 | + aggregatedErr = fmt.Errorf("detecting GKE resources: %s", errInfo) |
| 68 | + } |
| 69 | + |
| 70 | + return resource.Merge(gceLablRes, k8sLabelRes), aggregatedErr |
| 71 | +} |
0 commit comments