/
endpoint_tracker.go
209 lines (189 loc) · 6.97 KB
/
endpoint_tracker.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
// Copyright Splunk, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package discoveryreceiver
import (
"fmt"
"time"
"github.com/open-telemetry/opentelemetry-collector-contrib/extension/observer"
"go.opentelemetry.io/collector/component"
"go.opentelemetry.io/collector/pdata/pcommon"
"go.opentelemetry.io/collector/pdata/plog"
"go.uber.org/multierr"
"go.uber.org/zap"
)
type endpointState string
const (
addedState endpointState = "added"
removedState endpointState = "removed"
changedState endpointState = "changed"
)
var (
_ observer.Notify = (*notify)(nil)
)
type endpointTracker struct {
logger *zap.Logger
pLogs chan plog.Logs
observables map[component.ID]observer.Observable
correlations correlationStore
notifies []*notify
logEndpoints bool
}
type notify struct {
observable observer.Observable
endpointTracker *endpointTracker
observerID component.ID
id observer.NotifyID
}
func newEndpointTracker(
observables map[component.ID]observer.Observable, config *Config, logger *zap.Logger,
pLogs chan plog.Logs, correlations correlationStore) *endpointTracker {
return &endpointTracker{
logEndpoints: config.LogEndpoints,
observables: observables,
logger: logger,
pLogs: pLogs,
correlations: correlations,
}
}
func (et *endpointTracker) start() {
for obs, observable := range et.observables {
et.logger.Debug("endpointTracker subscribing to observable", zap.Any("observer", obs.String()))
n := ¬ify{
id: observer.NotifyID(fmt.Sprintf("%p::endpoint_tracker::%s", et, obs.String())),
observerID: obs,
observable: observable,
endpointTracker: et,
}
et.notifies = append(et.notifies, n)
go observable.ListAndWatch(n)
}
et.correlations.Start()
}
func (et *endpointTracker) stop() {
for _, n := range et.notifies {
et.logger.Debug("endpointTracker unsubscribing from observable", zap.Any("observer", n.observerID))
go n.observable.Unsubscribe(n)
}
et.correlations.Stop()
}
func (et *endpointTracker) emitEndpointLogs(observerCID component.ID, eventType endpointState, endpoints []observer.Endpoint, received time.Time) {
if et.logEndpoints && et.pLogs != nil {
pLogs, numFailed, err := endpointToPLogs(observerCID, fmt.Sprintf("endpoint.%s", eventType), endpoints, received)
if err != nil {
et.logger.Warn(fmt.Sprintf("failed converting %v endpoints to log records", numFailed), zap.Error(err))
}
if pLogs.LogRecordCount() > 0 {
et.pLogs <- pLogs
}
}
}
func (et *endpointTracker) updateEndpoints(endpoints []observer.Endpoint, state endpointState, observerID component.ID) {
for _, endpoint := range endpoints {
et.correlations.UpdateEndpoint(endpoint, state, observerID)
}
}
func (n *notify) ID() observer.NotifyID {
return n.id
}
func (n *notify) OnAdd(added []observer.Endpoint) {
n.endpointTracker.emitEndpointLogs(n.observerID, addedState, added, time.Now())
n.endpointTracker.updateEndpoints(added, addedState, n.observerID)
}
func (n *notify) OnRemove(removed []observer.Endpoint) {
n.endpointTracker.emitEndpointLogs(n.observerID, removedState, removed, time.Now())
n.endpointTracker.updateEndpoints(removed, removedState, n.observerID)
}
func (n *notify) OnChange(changed []observer.Endpoint) {
n.endpointTracker.emitEndpointLogs(n.observerID, changedState, changed, time.Now())
n.endpointTracker.updateEndpoints(changed, changedState, n.observerID)
}
func endpointToPLogs(observerID component.ID, eventType string, endpoints []observer.Endpoint, received time.Time) (pLogs plog.Logs, failed int, err error) {
pLogs = plog.NewLogs()
rlog := pLogs.ResourceLogs().AppendEmpty()
rAttrs := rlog.Resource().Attributes()
rAttrs.PutStr(eventTypeAttr, eventType)
rAttrs.PutStr(observerNameAttr, observerID.Name())
rAttrs.PutStr(observerTypeAttr, observerID.Type().String())
sl := rlog.ScopeLogs().AppendEmpty()
for _, endpoint := range endpoints {
logRecord := sl.LogRecords().AppendEmpty()
logRecord.SetTimestamp(pcommon.NewTimestampFromTime(received))
logRecord.SetObservedTimestamp(pcommon.NewTimestampFromTime(time.Now()))
logRecord.SetSeverityText("info")
attrs := logRecord.Attributes()
if endpoint.Details != nil {
logRecord.Body().SetStr(fmt.Sprintf("%s %s endpoint %s", eventType, endpoint.Details.Type(), endpoint.ID))
if envAttrs, e := endpointEnvToAttrs(endpoint.Details.Type(), endpoint.Details.Env()); e != nil {
err = multierr.Combine(err, fmt.Errorf("failed determining attributes for %q: %w", endpoint.ID, e))
failed++
} else {
// this must be the first mutation of attrs since it's destructive
envAttrs.CopyTo(attrs)
}
attrs.PutStr("type", string(endpoint.Details.Type()))
} else {
logRecord.Body().SetStr(fmt.Sprintf("%s endpoint %s", eventType, endpoint.ID))
}
attrs.PutStr("endpoint", endpoint.Target)
attrs.PutStr("id", string(endpoint.ID))
}
return
}
func endpointEnvToAttrs(endpointType observer.EndpointType, endpointEnv observer.EndpointEnv) (pcommon.Map, error) {
attrs := pcommon.NewMap()
for k, v := range endpointEnv {
switch {
// labels and annotations for container/node types
// should result in a ValueMap
case shouldEmbedMap(endpointType, k):
if asMap, ok := v.(map[string]string); ok {
mapVal := attrs.PutEmptyMap(k)
for item, itemVal := range asMap {
mapVal.PutStr(item, itemVal)
}
} else {
return attrs, fmt.Errorf("failed parsing %v env attributes", endpointType)
}
// pod EndpointEnv is the value of the "pod" field for observer.PortType and should be
// embedded as ValueMap
case observer.EndpointType(k) == observer.PodType && endpointType == observer.PortType:
if podEnv, ok := v.(observer.EndpointEnv); ok {
podAttrs, e := endpointEnvToAttrs(observer.PodType, podEnv)
if e != nil {
return attrs, fmt.Errorf("failed parsing %v pod attributes ", endpointType)
}
podAttrs.CopyTo(attrs.PutEmptyMap(k))
} else {
return attrs, fmt.Errorf("failed parsing %v pod env %#v", endpointType, v)
}
default:
switch vVal := v.(type) {
case uint16:
attrs.PutInt(k, int64(vVal))
case bool:
attrs.PutBool(k, vVal)
default:
attrs.PutStr(k, fmt.Sprintf("%v", v))
}
}
}
return attrs, nil
}
func shouldEmbedMap(endpointType observer.EndpointType, k string) bool {
return (k == "annotations" && (endpointType == observer.PodType ||
endpointType == observer.K8sNodeType)) ||
(k == "labels" && (endpointType == observer.PodType ||
endpointType == observer.ContainerType ||
endpointType == observer.K8sNodeType))
}