forked from open-telemetry/opentelemetry-collector-contrib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
opamp_agent.go
270 lines (222 loc) · 6.93 KB
/
opamp_agent.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
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package opampextension // import "github.com/open-telemetry/opentelemetry-collector-contrib/extension/opampextension"
import (
"context"
"net/http"
"os"
"runtime"
"sort"
"strings"
"sync"
"github.com/google/uuid"
"github.com/oklog/ulid/v2"
"github.com/open-telemetry/opamp-go/client"
"github.com/open-telemetry/opamp-go/client/types"
"github.com/open-telemetry/opamp-go/protobufs"
"go.opentelemetry.io/collector/component"
"go.opentelemetry.io/collector/confmap"
"go.opentelemetry.io/collector/pdata/pcommon"
semconv "go.opentelemetry.io/collector/semconv/v1.18.0"
"go.uber.org/zap"
"golang.org/x/exp/maps"
"gopkg.in/yaml.v3"
)
type opampAgent struct {
cfg *Config
logger *zap.Logger
agentType string
agentVersion string
instanceID ulid.ULID
eclk sync.RWMutex
effectiveConfig *confmap.Conf
capabilities Capabilities
agentDescription *protobufs.AgentDescription
opampClient client.OpAMPClient
}
func (o *opampAgent) Start(ctx context.Context, _ component.Host) error {
header := http.Header{}
for k, v := range o.cfg.Server.GetHeaders() {
header.Set(k, string(v))
}
tls, err := o.cfg.Server.GetTLSSetting().LoadTLSConfigContext(ctx)
if err != nil {
return err
}
settings := types.StartSettings{
Header: header,
TLSConfig: tls,
OpAMPServerURL: o.cfg.Server.GetEndpoint(),
InstanceUid: o.instanceID.String(),
Callbacks: types.CallbacksStruct{
OnConnectFunc: func(_ context.Context) {
o.logger.Debug("Connected to the OpAMP server")
},
OnConnectFailedFunc: func(_ context.Context, err error) {
o.logger.Error("Failed to connect to the OpAMP server", zap.Error(err))
},
OnErrorFunc: func(_ context.Context, err *protobufs.ServerErrorResponse) {
o.logger.Error("OpAMP server returned an error response", zap.String("message", err.ErrorMessage))
},
GetEffectiveConfigFunc: func(_ context.Context) (*protobufs.EffectiveConfig, error) {
return o.composeEffectiveConfig(), nil
},
OnMessageFunc: o.onMessage,
},
Capabilities: o.capabilities.toAgentCapabilities(),
}
if err := o.createAgentDescription(); err != nil {
return err
}
if err := o.opampClient.SetAgentDescription(o.agentDescription); err != nil {
return err
}
o.logger.Debug("Starting OpAMP client...")
if err := o.opampClient.Start(context.Background(), settings); err != nil {
return err
}
o.logger.Debug("OpAMP client started")
return nil
}
func (o *opampAgent) Shutdown(ctx context.Context) error {
o.logger.Debug("OpAMP agent shutting down...")
if o.opampClient == nil {
return nil
}
o.logger.Debug("Stopping OpAMP client...")
err := o.opampClient.Stop(ctx)
// Opamp-go considers this an error, but the collector does not.
// https://github.com/open-telemetry/opamp-go/issues/255
if err != nil && strings.EqualFold(err.Error(), "cannot stop because not started") {
return nil
}
return err
}
func (o *opampAgent) NotifyConfig(ctx context.Context, conf *confmap.Conf) error {
if o.capabilities.ReportsEffectiveConfig {
o.updateEffectiveConfig(conf)
return o.opampClient.UpdateEffectiveConfig(ctx)
}
return nil
}
func (o *opampAgent) updateEffectiveConfig(conf *confmap.Conf) {
o.eclk.Lock()
defer o.eclk.Unlock()
o.effectiveConfig = conf
}
func newOpampAgent(cfg *Config, logger *zap.Logger, build component.BuildInfo, res pcommon.Resource) (*opampAgent, error) {
agentType := build.Command
sn, ok := res.Attributes().Get(semconv.AttributeServiceName)
if ok {
agentType = sn.AsString()
}
agentVersion := build.Version
sv, ok := res.Attributes().Get(semconv.AttributeServiceVersion)
if ok {
agentVersion = sv.AsString()
}
uid := ulid.Make()
if cfg.InstanceUID != "" {
puid, err := ulid.Parse(cfg.InstanceUID)
if err != nil {
return nil, err
}
uid = puid
} else {
sid, ok := res.Attributes().Get(semconv.AttributeServiceInstanceID)
if ok {
parsedUUID, err := uuid.Parse(sid.AsString())
if err != nil {
return nil, err
}
uid = ulid.ULID(parsedUUID)
}
}
agent := &opampAgent{
cfg: cfg,
logger: logger,
agentType: agentType,
agentVersion: agentVersion,
instanceID: uid,
capabilities: cfg.Capabilities,
opampClient: cfg.Server.GetClient(logger),
}
return agent, nil
}
func stringKeyValue(key, value string) *protobufs.KeyValue {
return &protobufs.KeyValue{
Key: key,
Value: &protobufs.AnyValue{
Value: &protobufs.AnyValue_StringValue{StringValue: value},
},
}
}
func (o *opampAgent) createAgentDescription() error {
hostname, err := os.Hostname()
if err != nil {
return err
}
ident := []*protobufs.KeyValue{
stringKeyValue(semconv.AttributeServiceInstanceID, o.instanceID.String()),
stringKeyValue(semconv.AttributeServiceName, o.agentType),
stringKeyValue(semconv.AttributeServiceVersion, o.agentVersion),
}
// Initially construct using a map to properly deduplicate any keys that
// are both automatically determined and defined in the config
nonIdentifyingAttributeMap := map[string]string{}
nonIdentifyingAttributeMap[semconv.AttributeOSType] = runtime.GOOS
nonIdentifyingAttributeMap[semconv.AttributeHostArch] = runtime.GOARCH
nonIdentifyingAttributeMap[semconv.AttributeHostName] = hostname
for k, v := range o.cfg.AgentDescription.NonIdentifyingAttributes {
nonIdentifyingAttributeMap[k] = v
}
// Sort the non identifying attributes to give them a stable order for tests
keys := maps.Keys(nonIdentifyingAttributeMap)
sort.Strings(keys)
nonIdent := make([]*protobufs.KeyValue, 0, len(nonIdentifyingAttributeMap))
for _, k := range keys {
v := nonIdentifyingAttributeMap[k]
nonIdent = append(nonIdent, stringKeyValue(k, v))
}
o.agentDescription = &protobufs.AgentDescription{
IdentifyingAttributes: ident,
NonIdentifyingAttributes: nonIdent,
}
return nil
}
func (o *opampAgent) updateAgentIdentity(instanceID ulid.ULID) {
o.logger.Debug("OpAMP agent identity is being changed",
zap.String("old_id", o.instanceID.String()),
zap.String("new_id", instanceID.String()))
o.instanceID = instanceID
}
func (o *opampAgent) composeEffectiveConfig() *protobufs.EffectiveConfig {
o.eclk.RLock()
defer o.eclk.RUnlock()
if !o.capabilities.ReportsEffectiveConfig || o.effectiveConfig == nil {
return nil
}
conf, err := yaml.Marshal(o.effectiveConfig.ToStringMap())
if err != nil {
o.logger.Error("cannot unmarshal effectiveConfig", zap.Any("conf", o.effectiveConfig), zap.Error(err))
return nil
}
return &protobufs.EffectiveConfig{
ConfigMap: &protobufs.AgentConfigMap{
ConfigMap: map[string]*protobufs.AgentConfigFile{
"": {Body: conf},
},
},
}
}
func (o *opampAgent) onMessage(_ context.Context, msg *types.MessageData) {
if msg.AgentIdentification == nil {
return
}
instanceID, err := ulid.Parse(msg.AgentIdentification.NewInstanceUid)
if err != nil {
o.logger.Error("Failed to parse a new agent identity", zap.Error(err))
return
}
o.updateAgentIdentity(instanceID)
}