forked from open-telemetry/opentelemetry-collector-contrib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
opamp_agent.go
234 lines (194 loc) · 5.8 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
// 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"
"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/pdata/pcommon"
semconv "go.opentelemetry.io/collector/semconv/v1.18.0"
"go.uber.org/zap"
)
// TODO: Replace with https://github.com/open-telemetry/opentelemetry-collector-contrib/issues/27293
const localConfig = `
exporters:
otlp:
endpoint: localhost:1111
receivers:
otlp:
protocols:
grpc: {}
http: {}
service:
pipelines:
traces:
receivers: [otlp]
processors: []
exporters: [otlp]
`
type opampAgent struct {
cfg *Config
logger *zap.Logger
agentType string
agentVersion string
instanceID ulid.ULID
effectiveConfig string
agentDescription *protobufs.AgentDescription
opampClient client.OpAMPClient
}
func (o *opampAgent) Start(_ context.Context, _ component.Host) error {
// TODO: Add OpAMP HTTP transport support.
o.opampClient = client.NewWebSocket(o.logger.Sugar())
header := http.Header{}
for k, v := range o.cfg.Server.WS.Headers {
header.Set(k, string(v))
}
tls, err := o.cfg.Server.WS.TLSSetting.LoadTLSConfig()
if err != nil {
return err
}
settings := types.StartSettings{
Header: header,
TLSConfig: tls,
OpAMPServerURL: o.cfg.Server.WS.Endpoint,
InstanceUid: o.instanceID.String(),
Callbacks: types.CallbacksStruct{
OnConnectFunc: func() {
o.logger.Debug("Connected to the OpAMP server")
},
OnConnectFailedFunc: func(err error) {
o.logger.Error("Failed to connect to the OpAMP server", zap.Error(err))
},
OnErrorFunc: func(err *protobufs.ServerErrorResponse) {
o.logger.Error("OpAMP server returned an error response", zap.String("message", err.ErrorMessage))
},
GetEffectiveConfigFunc: func(ctx context.Context) (*protobufs.EffectiveConfig, error) {
return o.composeEffectiveConfig(), nil
},
OnMessageFunc: o.onMessage,
},
// TODO: Include ReportsEffectiveConfig once the extension has access to the
// collector's effective configuration.
Capabilities: protobufs.AgentCapabilities_AgentCapabilities_ReportsStatus,
}
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...")
return o.opampClient.Stop(ctx)
}
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 {
uuid, err := uuid.Parse(sid.AsString())
if err != nil {
return nil, err
}
uid = ulid.ULID(uuid)
}
}
agent := &opampAgent{
cfg: cfg,
logger: logger,
agentType: agentType,
agentVersion: agentVersion,
instanceID: uid,
effectiveConfig: localConfig, // TODO: Replace with https://github.com/open-telemetry/opentelemetry-collector-contrib/issues/27293
}
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),
}
nonIdent := []*protobufs.KeyValue{
stringKeyValue(semconv.AttributeOSType, runtime.GOOS),
stringKeyValue(semconv.AttributeHostArch, runtime.GOARCH),
stringKeyValue(semconv.AttributeHostName, hostname),
}
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 {
return &protobufs.EffectiveConfig{
ConfigMap: &protobufs.AgentConfigMap{
ConfigMap: map[string]*protobufs.AgentConfigFile{
"": {Body: []byte(o.effectiveConfig)},
},
},
}
}
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)
}