-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Copy pathmetadata.go
205 lines (177 loc) · 7.37 KB
/
metadata.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Package hostmetadata is responsible for collecting host metadata from different providers
// such as EC2, ECS, AWS, etc and pushing it to Datadog.
package hostmetadata // import "github.com/open-telemetry/opentelemetry-collector-contrib/exporter/datadogexporter/internal/hostmetadata"
import (
"bytes"
"compress/gzip"
"context"
"encoding/json"
"fmt"
"net/http"
"time"
"github.com/DataDog/opentelemetry-mapping-go/pkg/inframetadata"
"github.com/DataDog/opentelemetry-mapping-go/pkg/inframetadata/payload"
"github.com/DataDog/opentelemetry-mapping-go/pkg/otlp/attributes"
ec2Attributes "github.com/DataDog/opentelemetry-mapping-go/pkg/otlp/attributes/ec2"
"github.com/DataDog/opentelemetry-mapping-go/pkg/otlp/attributes/gcp"
"github.com/DataDog/opentelemetry-mapping-go/pkg/otlp/attributes/source"
"go.opentelemetry.io/collector/exporter"
"go.opentelemetry.io/collector/pdata/pcommon"
conventions "go.opentelemetry.io/collector/semconv/v1.6.1"
"go.uber.org/zap"
"github.com/open-telemetry/opentelemetry-collector-contrib/exporter/datadogexporter/internal/clientutil"
"github.com/open-telemetry/opentelemetry-collector-contrib/exporter/datadogexporter/internal/hostmetadata/internal/ec2"
"github.com/open-telemetry/opentelemetry-collector-contrib/exporter/datadogexporter/internal/hostmetadata/internal/gohai"
"github.com/open-telemetry/opentelemetry-collector-contrib/exporter/datadogexporter/internal/hostmetadata/internal/system"
"github.com/open-telemetry/opentelemetry-collector-contrib/exporter/datadogexporter/internal/scrub"
)
// metadataFromAttributes gets metadata info from attributes following
// OpenTelemetry semantic conventions
func metadataFromAttributes(attrs pcommon.Map) payload.HostMetadata {
hm := payload.HostMetadata{Meta: &payload.Meta{}, Tags: &payload.HostTags{}}
if src, ok := attributes.SourceFromAttrs(attrs); ok && src.Kind == source.HostnameKind {
hm.InternalHostname = src.Identifier
hm.Meta.Hostname = src.Identifier
}
// AWS EC2 resource metadata
cloudProvider, ok := attrs.Get(conventions.AttributeCloudProvider)
switch {
case ok && cloudProvider.Str() == conventions.AttributeCloudProviderAWS:
ec2HostInfo := ec2Attributes.HostInfoFromAttributes(attrs)
hm.Meta.InstanceID = ec2HostInfo.InstanceID
hm.Meta.EC2Hostname = ec2HostInfo.EC2Hostname
hm.Tags.OTel = append(hm.Tags.OTel, ec2HostInfo.EC2Tags...)
case ok && cloudProvider.Str() == conventions.AttributeCloudProviderGCP:
gcpHostInfo := gcp.HostInfoFromAttrs(attrs)
hm.Tags.GCP = gcpHostInfo.GCPTags
hm.Meta.HostAliases = append(hm.Meta.HostAliases, gcpHostInfo.HostAliases...)
}
return hm
}
func fillHostMetadata(params exporter.Settings, pcfg PusherConfig, p source.Provider, hm *payload.HostMetadata) {
// Could not get hostname from attributes
if hm.InternalHostname == "" {
if src, err := p.Source(context.TODO()); err == nil && src.Kind == source.HostnameKind {
hm.InternalHostname = src.Identifier
hm.Meta.Hostname = src.Identifier
}
}
// This information always gets filled in here
// since it does not come from OTEL conventions
hm.Flavor = params.BuildInfo.Command
hm.Version = params.BuildInfo.Version
hm.Tags.OTel = append(hm.Tags.OTel, pcfg.ConfigTags...)
hm.Payload = gohai.NewPayload(params.Logger)
hm.Processes = gohai.NewProcessesPayload(hm.Meta.Hostname, params.Logger)
// EC2 data was not set from attributes
if hm.Meta.EC2Hostname == "" {
ec2HostInfo := ec2.GetHostInfo(context.Background(), params.Logger)
hm.Meta.EC2Hostname = ec2HostInfo.EC2Hostname
hm.Meta.InstanceID = ec2HostInfo.InstanceID
}
// System data was not set from attributes
if hm.Meta.SocketHostname == "" {
systemHostInfo := system.GetHostInfo(params.Logger)
hm.Meta.SocketHostname = systemHostInfo.OS
hm.Meta.SocketFqdn = systemHostInfo.FQDN
}
}
func (p *pusher) pushMetadata(hm payload.HostMetadata) error {
path := p.pcfg.MetricsEndpoint + "/intake"
marshaled, err := json.Marshal(hm)
if err != nil {
return fmt.Errorf("error marshaling metadata payload: %w", err)
}
var buf bytes.Buffer
g := gzip.NewWriter(&buf)
if _, err = g.Write(marshaled); err != nil {
return fmt.Errorf("error compressing metadata payload: %w", err)
}
if err = g.Close(); err != nil {
return fmt.Errorf("error closing gzip writer: %w", err)
}
req, err := http.NewRequest(http.MethodPost, path, &buf)
if err != nil {
return fmt.Errorf("error creating metadata request: %w", err)
}
clientutil.SetDDHeaders(req.Header, p.params.BuildInfo, p.pcfg.APIKey)
// Set the content type to JSON and the content encoding to gzip
clientutil.SetExtraHeaders(req.Header, clientutil.JSONHeaders)
resp, err := p.httpClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
return fmt.Errorf(
"%q error when sending metadata payload to %s",
resp.Status,
path,
)
}
return nil
}
func (p *pusher) Push(_ context.Context, hm payload.HostMetadata) error {
if hm.Meta.Hostname == "" {
// if the hostname is empty, don't send metadata; we don't need it.
p.params.Logger.Debug("Skipping host metadata since the hostname is empty")
return nil
}
p.params.Logger.Debug("Sending host metadata payload", zap.Any("payload", hm))
_, err := p.retrier.DoWithRetries(context.Background(), func(context.Context) error {
return p.pushMetadata(hm)
})
return err
}
var _ inframetadata.Pusher = (*pusher)(nil)
type pusher struct {
params exporter.Settings
pcfg PusherConfig
retrier *clientutil.Retrier
httpClient *http.Client
}
// NewPusher creates a new inframetadata.Pusher that pushes metadata payloads
func NewPusher(params exporter.Settings, pcfg PusherConfig) inframetadata.Pusher {
return &pusher{
params: params,
pcfg: pcfg,
retrier: clientutil.NewRetrier(params.Logger, pcfg.RetrySettings, scrub.NewScrubber()),
httpClient: clientutil.NewHTTPClient(pcfg.ClientConfig),
}
}
// RunPusher to push host metadata payloads from the host where the Collector is running periodically to Datadog intake.
// This function is blocking and it is meant to be run on a goroutine.
func RunPusher(ctx context.Context, params exporter.Settings, pcfg PusherConfig, p source.Provider, attrs pcommon.Map, reporter *inframetadata.Reporter) {
// Push metadata every 30 minutes
ticker := time.NewTicker(30 * time.Minute)
defer ticker.Stop()
defer params.Logger.Debug("Shut down host metadata routine")
// Get host metadata from resources and fill missing info using our exporter.
// Currently we only retrieve it once but still send the same payload
// every 30 minutes for consistency with the Datadog Agent behavior.
//
// All fields that are being filled in by our exporter
// do not change over time. If this ever changes `hostMetadata`
// *must* be deep copied before calling `fillHostMetadata`.
hostMetadata := payload.NewEmpty()
if pcfg.UseResourceMetadata {
hostMetadata = metadataFromAttributes(attrs)
}
fillHostMetadata(params, pcfg, p, &hostMetadata)
// Consume one first time
if err := reporter.ConsumeHostMetadata(hostMetadata); err != nil {
params.Logger.Warn("Failed to consume host metadata", zap.Any("payload", hostMetadata))
}
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
if err := reporter.ConsumeHostMetadata(hostMetadata); err != nil {
params.Logger.Warn("Failed to consume host metadata", zap.Any("payload", hostMetadata))
}
}
}
}