-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
provider.go
85 lines (69 loc) · 2.45 KB
/
provider.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Package gcp contains the GCP hostname provider
package gcp // import "github.com/open-telemetry/opentelemetry-collector-contrib/exporter/datadogexporter/internal/hostmetadata/internal/gcp"
import (
"context"
"fmt"
"strings"
"github.com/DataDog/opentelemetry-mapping-go/pkg/otlp/attributes/source"
"github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp"
"github.com/open-telemetry/opentelemetry-collector-contrib/exporter/datadogexporter/internal/hostmetadata/provider"
)
var _ source.Provider = (*Provider)(nil)
var _ provider.ClusterNameProvider = (*Provider)(nil)
var _ gcpDetector = gcp.NewDetector()
type gcpDetector interface {
ProjectID() (string, error)
CloudPlatform() gcp.Platform
GCEHostName() (string, error)
GKEClusterName() (string, error)
}
type Provider struct {
detector gcpDetector
}
func platformDescription(platform gcp.Platform) string {
switch platform {
case gcp.UnknownPlatform:
return "Unknown platform"
case gcp.GKE:
return "Google Kubernetes Engine"
case gcp.GCE:
return "Google Cloud Engine"
case gcp.CloudRun:
return "Google Cloud Run"
case gcp.CloudFunctions:
return "Google Cloud Functions"
case gcp.AppEngineStandard, gcp.AppEngineFlex:
return "Google AppEngine"
case gcp.CloudRunJob:
return "Cloud Run Job"
}
return "Unrecognized platform"
}
// Hostname returns the GCP cloud integration hostname.
func (p *Provider) Source(context.Context) (source.Source, error) {
if platform := p.detector.CloudPlatform(); platform != gcp.GCE && platform != gcp.GKE {
return source.Source{}, fmt.Errorf("not on GCE or GKE (platform: %s)", platformDescription(platform))
}
name, err := p.detector.GCEHostName()
if err != nil {
return source.Source{}, fmt.Errorf("failed to get instance name: %w", err)
}
// Use the same logic as in the metadata from attributes logic.
if strings.Count(name, ".") >= 3 {
name = strings.SplitN(name, ".", 2)[0]
}
cloudAccount, err := p.detector.ProjectID()
if err != nil {
return source.Source{}, fmt.Errorf("failed to get project ID: %w", err)
}
return source.Source{Kind: source.HostnameKind, Identifier: fmt.Sprintf("%s.%s", name, cloudAccount)}, nil
}
func (p *Provider) ClusterName(_ context.Context) (string, error) {
return p.detector.GKEClusterName()
}
// NewProvider creates a new GCP hostname provider.
func NewProvider() *Provider {
return &Provider{detector: gcp.NewDetector()}
}