-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Copy pathreceiver.go
284 lines (261 loc) · 8.43 KB
/
receiver.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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package cloudfoundryreceiver // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/cloudfoundryreceiver"
import (
"context"
"errors"
"fmt"
"reflect"
"sync"
"time"
"code.cloudfoundry.org/go-loggregator"
"code.cloudfoundry.org/go-loggregator/rpc/loggregator_v2"
"go.opentelemetry.io/collector/component"
"go.opentelemetry.io/collector/component/componentstatus"
"go.opentelemetry.io/collector/consumer"
"go.opentelemetry.io/collector/pdata/plog"
"go.opentelemetry.io/collector/pdata/pmetric"
"go.opentelemetry.io/collector/receiver"
"go.opentelemetry.io/collector/receiver/receiverhelper"
"go.uber.org/zap"
"github.com/open-telemetry/opentelemetry-collector-contrib/receiver/cloudfoundryreceiver/internal/metadata"
)
const (
transport = "http"
dataFormat = "cloudfoundry"
)
var (
_ receiver.Metrics = (*cloudFoundryReceiver)(nil)
_ receiver.Logs = (*cloudFoundryReceiver)(nil)
)
// newCloudFoundryReceiver implements the receiver.Metrics and receiver.Logs for the Cloud Foundry protocol.
type cloudFoundryReceiver struct {
settings component.TelemetrySettings
cancel context.CancelFunc
config Config
nextMetrics consumer.Metrics
nextLogs consumer.Logs
obsrecv *receiverhelper.ObsReport
goroutines sync.WaitGroup
receiverStartTime time.Time
}
// newCloudFoundryMetricsReceiver creates the Cloud Foundry receiver with the given parameters.
func newCloudFoundryMetricsReceiver(
settings receiver.Settings,
config Config,
nextConsumer consumer.Metrics,
) (*cloudFoundryReceiver, error) {
obsrecv, err := receiverhelper.NewObsReport(receiverhelper.ObsReportSettings{
ReceiverID: settings.ID,
Transport: transport,
ReceiverCreateSettings: settings,
})
if err != nil {
return nil, err
}
result := &cloudFoundryReceiver{
settings: settings.TelemetrySettings,
config: config,
nextMetrics: nextConsumer,
obsrecv: obsrecv,
receiverStartTime: time.Now(),
}
return result, nil
}
// newCloudFoundryLogsReceiver creates the Cloud Foundry logs receiver with the given parameters.
func newCloudFoundryLogsReceiver(
settings receiver.Settings,
config Config,
nextConsumer consumer.Logs,
) (*cloudFoundryReceiver, error) {
obsrecv, err := receiverhelper.NewObsReport(receiverhelper.ObsReportSettings{
ReceiverID: settings.ID,
Transport: transport,
ReceiverCreateSettings: settings,
})
if err != nil {
return nil, err
}
result := &cloudFoundryReceiver{
settings: settings.TelemetrySettings,
config: config,
nextLogs: nextConsumer,
obsrecv: obsrecv,
receiverStartTime: time.Now(),
}
return result, nil
}
func (cfr *cloudFoundryReceiver) Start(ctx context.Context, host component.Host) error {
tokenProvider, tokenErr := newUAATokenProvider(
cfr.settings.Logger,
cfr.config.UAA.LimitedClientConfig,
cfr.config.UAA.Username,
string(cfr.config.UAA.Password),
)
if tokenErr != nil {
return fmt.Errorf("cloudfoundry receiver failed to create UAA token provider: %w", tokenErr)
}
streamFactory, streamErr := newEnvelopeStreamFactory(
ctx,
cfr.settings,
tokenProvider,
cfr.config.RLPGateway.ClientConfig,
host,
)
if streamErr != nil {
return fmt.Errorf("cloudfoundry receiver failed to create RLP envelope stream factory: %w", streamErr)
}
innerCtx, cancel := context.WithCancel(ctx)
cfr.cancel = cancel
cfr.goroutines.Add(1)
go func() {
defer cfr.goroutines.Done()
cfr.settings.Logger.Debug("cloudfoundry receiver starting")
_, tokenErr = tokenProvider.ProvideToken()
if tokenErr != nil {
componentstatus.ReportStatus(
host,
componentstatus.NewFatalErrorEvent(
fmt.Errorf("cloudfoundry receiver failed to fetch initial token from UAA: %w", tokenErr),
),
)
return
}
if cfr.nextLogs != nil {
cfr.streamLogs(innerCtx, streamFactory.CreateLogsStream(innerCtx, cfr.config.RLPGateway.ShardID), host)
} else if cfr.nextMetrics != nil {
cfr.streamMetrics(innerCtx, streamFactory.CreateMetricsStream(innerCtx, cfr.config.RLPGateway.ShardID), host)
}
cfr.settings.Logger.Debug("cloudfoundry receiver stopped")
}()
return nil
}
func (cfr *cloudFoundryReceiver) Shutdown(_ context.Context) error {
if cfr.cancel == nil {
return nil
}
cfr.cancel()
cfr.goroutines.Wait()
return nil
}
func (cfr *cloudFoundryReceiver) streamMetrics(
ctx context.Context,
stream loggregator.EnvelopeStream,
host component.Host,
) {
for {
// Blocks until non-empty result or context is cancelled (returns nil in that case)
envelopes := stream()
if envelopes == nil {
// If context has not been cancelled, then nil means the shutdown was due to an error within stream
if ctx.Err() == nil {
componentstatus.ReportStatus(
host,
componentstatus.NewFatalErrorEvent(
errors.New("RLP gateway metrics streamer shut down due to an error"),
),
)
}
break
}
metrics := pmetric.NewMetrics()
for _, envelope := range envelopes {
if envelope != nil {
buildMetrics(metrics, envelope, cfr.receiverStartTime)
}
}
if metrics.ResourceMetrics().Len() > 0 {
obsCtx := cfr.obsrecv.StartMetricsOp(ctx)
err := cfr.nextMetrics.ConsumeMetrics(ctx, metrics)
if err != nil {
cfr.settings.Logger.Error("Failed to consume metrics", zap.Error(err))
}
cfr.obsrecv.EndMetricsOp(obsCtx, dataFormat, metrics.DataPointCount(), err)
}
}
}
func (cfr *cloudFoundryReceiver) streamLogs(
ctx context.Context,
stream loggregator.EnvelopeStream,
host component.Host,
) {
for {
envelopes := stream()
if envelopes == nil {
if ctx.Err() == nil {
componentstatus.ReportStatus(
host,
componentstatus.NewFatalErrorEvent(
errors.New("RLP gateway log streamer shut down due to an error"),
),
)
}
break
}
logs := plog.NewLogs()
observedTime := time.Now()
for _, envelope := range envelopes {
if envelope != nil {
buildLogs(logs, envelope, observedTime)
}
}
if logs.ResourceLogs().Len() > 0 {
obsCtx := cfr.obsrecv.StartLogsOp(ctx)
err := cfr.nextLogs.ConsumeLogs(ctx, logs)
if err != nil {
cfr.settings.Logger.Error("Failed to consume logs", zap.Error(err))
}
cfr.obsrecv.EndLogsOp(obsCtx, dataFormat, logs.LogRecordCount(), err)
}
}
}
func buildLogs(logs plog.Logs, envelope *loggregator_v2.Envelope, observedTime time.Time) {
resourceLogs := getResourceLogs(logs, envelope)
setupLogsScope(resourceLogs)
_ = convertEnvelopeToLogs(envelope, resourceLogs.ScopeLogs().At(0).LogRecords(), observedTime)
}
func buildMetrics(metrics pmetric.Metrics, envelope *loggregator_v2.Envelope, observedTime time.Time) {
resourceMetrics := getResourceMetrics(metrics, envelope)
setupMetricsScope(resourceMetrics)
convertEnvelopeToMetrics(envelope, resourceMetrics.ScopeMetrics().At(0).Metrics(), observedTime)
}
func setupMetricsScope(resourceMetrics pmetric.ResourceMetrics) {
if resourceMetrics.ScopeMetrics().Len() == 0 {
libraryMetrics := resourceMetrics.ScopeMetrics().AppendEmpty()
libraryMetrics.Scope().SetName(metadata.ScopeName)
}
}
func getResourceMetrics(metrics pmetric.Metrics, envelope *loggregator_v2.Envelope) pmetric.ResourceMetrics {
if !allowResourceAttributes.IsEnabled() {
return metrics.ResourceMetrics().AppendEmpty()
}
attrs := getEnvelopeResourceAttributes(envelope)
for i := 0; i < metrics.ResourceMetrics().Len(); i++ {
if reflect.DeepEqual(metrics.ResourceMetrics().At(i).Resource().Attributes().AsRaw(), attrs.AsRaw()) {
return metrics.ResourceMetrics().At(i)
}
}
resource := metrics.ResourceMetrics().AppendEmpty()
attrs.CopyTo(resource.Resource().Attributes())
return resource
}
func setupLogsScope(resourceLogs plog.ResourceLogs) {
if resourceLogs.ScopeLogs().Len() == 0 {
libraryLogs := resourceLogs.ScopeLogs().AppendEmpty()
libraryLogs.Scope().SetName(metadata.ScopeName)
}
}
func getResourceLogs(logs plog.Logs, envelope *loggregator_v2.Envelope) plog.ResourceLogs {
if !allowResourceAttributes.IsEnabled() {
return logs.ResourceLogs().AppendEmpty()
}
attrs := getEnvelopeResourceAttributes(envelope)
for i := 0; i < logs.ResourceLogs().Len(); i++ {
if reflect.DeepEqual(logs.ResourceLogs().At(i).Resource().Attributes().AsRaw(), attrs.AsRaw()) {
return logs.ResourceLogs().At(i)
}
}
resource := logs.ResourceLogs().AppendEmpty()
attrs.CopyTo(resource.Resource().Attributes())
return resource
}