-
Notifications
You must be signed in to change notification settings - Fork 74
/
instance_watcher_service.go
466 lines (395 loc) · 14.7 KB
/
instance_watcher_service.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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
// Copyright (c) F5, Inc.
//
// This source code is licensed under the Apache License, Version 2.0 license found in the
// LICENSE file in the root directory of this source tree.
package instance
import (
"context"
"log/slog"
"reflect"
"slices"
"sync"
"time"
mpi "github.com/nginx/agent/v3/api/grpc/mpi/v1"
"github.com/nginx/agent/v3/internal/config"
"github.com/nginx/agent/v3/internal/datasource/host/exec"
"github.com/nginx/agent/v3/internal/logger"
"github.com/nginx/agent/v3/internal/model"
"github.com/nginx/agent/v3/internal/watcher/process"
"google.golang.org/protobuf/types/known/structpb"
)
const defaultAgentPath = "/run/nginx-agent"
//go:generate go run github.com/maxbrunsfeld/counterfeiter/v6@v6.8.1 -generate
//counterfeiter:generate . processParser
//go:generate go run github.com/maxbrunsfeld/counterfeiter/v6@v6.8.1 -generate
//counterfeiter:generate . nginxConfigParser
type (
processParser interface {
Parse(ctx context.Context, processes []*model.Process) map[string]*mpi.Instance
}
nginxConfigParser interface {
Parse(ctx context.Context, instance *mpi.Instance) (*model.NginxConfigContext, error)
}
InstanceWatcherService struct {
processOperator process.ProcessOperatorInterface
nginxConfigParser nginxConfigParser
executer exec.ExecInterface
agentConfig *config.Config
instanceCache map[string]*mpi.Instance
nginxConfigCache map[string]*model.NginxConfigContext
instancesChannel chan<- InstanceUpdatesMessage
nginxConfigContextChannel chan<- NginxConfigContextMessage
processParsers []processParser
cacheMutex sync.Mutex
}
InstanceUpdates struct {
NewInstances []*mpi.Instance
UpdatedInstances []*mpi.Instance
DeletedInstances []*mpi.Instance
}
InstanceUpdatesMessage struct {
CorrelationID slog.Attr
InstanceUpdates InstanceUpdates
}
NginxConfigContextMessage struct {
CorrelationID slog.Attr
NginxConfigContext *model.NginxConfigContext
}
)
func NewInstanceWatcherService(agentConfig *config.Config) *InstanceWatcherService {
return &InstanceWatcherService{
agentConfig: agentConfig,
processOperator: process.NewProcessOperator(),
processParsers: []processParser{
NewNginxProcessParser(),
},
nginxConfigParser: NewNginxConfigParser(agentConfig),
instanceCache: make(map[string]*mpi.Instance),
cacheMutex: sync.Mutex{},
nginxConfigCache: make(map[string]*model.NginxConfigContext),
executer: &exec.Exec{},
}
}
func (iw *InstanceWatcherService) Watch(
ctx context.Context,
instancesChannel chan<- InstanceUpdatesMessage,
nginxConfigContextChannel chan<- NginxConfigContextMessage,
) {
monitoringFrequency := iw.agentConfig.Watchers.InstanceWatcher.MonitoringFrequency
slog.DebugContext(ctx, "Starting instance watcher monitoring", "monitoring_frequency", monitoringFrequency)
iw.instancesChannel = instancesChannel
iw.nginxConfigContextChannel = nginxConfigContextChannel
instanceWatcherTicker := time.NewTicker(monitoringFrequency)
defer instanceWatcherTicker.Stop()
for {
select {
case <-ctx.Done():
close(instancesChannel)
close(nginxConfigContextChannel)
return
case <-instanceWatcherTicker.C:
iw.checkForUpdates(ctx)
}
}
}
func (iw *InstanceWatcherService) ReparseConfigs(ctx context.Context) {
slog.DebugContext(ctx, "Reparsing all instance configurations")
for _, instance := range iw.instanceCache {
iw.ReparseConfig(ctx, instance.GetInstanceMeta().GetInstanceId())
}
slog.DebugContext(ctx, "Finished reparsing all instance configurations")
}
func (iw *InstanceWatcherService) ReparseConfig(ctx context.Context, instanceID string) {
iw.cacheMutex.Lock()
defer iw.cacheMutex.Unlock()
updatesRequired := false
instance := iw.instanceCache[instanceID]
instanceType := instance.GetInstanceMeta().GetInstanceType()
correlationID := logger.GetCorrelationIDAttr(ctx)
if instanceType == mpi.InstanceMeta_INSTANCE_TYPE_NGINX ||
instanceType == mpi.InstanceMeta_INSTANCE_TYPE_NGINX_PLUS {
slog.DebugContext(
ctx,
"Reparsing NGINX instance config",
"instance_id", instanceID,
)
nginxConfigContext, parseErr := iw.nginxConfigParser.Parse(ctx, instance)
if parseErr != nil {
slog.WarnContext(
ctx,
"Unable to parse NGINX instance config",
"config_path", instance.GetInstanceRuntime().GetConfigPath(),
"instance_id", instanceID,
"error", parseErr,
)
return
}
iw.sendNginxConfigContextUpdate(ctx, nginxConfigContext)
iw.nginxConfigCache[nginxConfigContext.InstanceID] = nginxConfigContext
updatesRequired = iw.updateNginxInstanceRuntime(instance, nginxConfigContext)
}
if updatesRequired {
instanceUpdates := InstanceUpdates{}
instanceUpdates.UpdatedInstances = append(instanceUpdates.UpdatedInstances, instance)
iw.instancesChannel <- InstanceUpdatesMessage{
CorrelationID: correlationID,
InstanceUpdates: instanceUpdates,
}
}
}
func (iw *InstanceWatcherService) checkForUpdates(
ctx context.Context,
) {
iw.cacheMutex.Lock()
defer iw.cacheMutex.Unlock()
var instancesToParse []*mpi.Instance
correlationID := logger.GenerateCorrelationID()
newCtx := context.WithValue(ctx, logger.CorrelationIDContextKey, correlationID)
instanceUpdates, err := iw.instanceUpdates(newCtx)
if err != nil {
slog.ErrorContext(newCtx, "Instance watcher updates", "error", err)
}
instancesToParse = append(instancesToParse, instanceUpdates.UpdatedInstances...)
instancesToParse = append(instancesToParse, instanceUpdates.NewInstances...)
for _, newInstance := range instancesToParse {
instanceType := newInstance.GetInstanceMeta().GetInstanceType()
slog.DebugContext(
newCtx,
"Parsing instance config",
"instance_id", newInstance.GetInstanceMeta().GetInstanceId(),
"instance_type", instanceType,
)
if instanceType == mpi.InstanceMeta_INSTANCE_TYPE_NGINX ||
instanceType == mpi.InstanceMeta_INSTANCE_TYPE_NGINX_PLUS {
nginxConfigContext, parseErr := iw.nginxConfigParser.Parse(newCtx, newInstance)
if parseErr != nil {
slog.WarnContext(
newCtx,
"Unable to parse NGINX instance config",
"config_path", newInstance.GetInstanceRuntime().GetConfigPath(),
"instance_id", newInstance.GetInstanceMeta().GetInstanceId(),
"instance_type", instanceType,
"error", parseErr,
)
} else {
iw.sendNginxConfigContextUpdate(newCtx, nginxConfigContext)
iw.nginxConfigCache[nginxConfigContext.InstanceID] = nginxConfigContext
iw.updateNginxInstanceRuntime(newInstance, nginxConfigContext)
iw.instanceCache[newInstance.GetInstanceMeta().GetInstanceId()] = newInstance
}
}
}
if len(instanceUpdates.NewInstances) > 0 || len(instanceUpdates.DeletedInstances) > 0 ||
len(instanceUpdates.UpdatedInstances) > 0 {
iw.instancesChannel <- InstanceUpdatesMessage{
CorrelationID: correlationID,
InstanceUpdates: instanceUpdates,
}
}
}
func (iw *InstanceWatcherService) sendNginxConfigContextUpdate(
ctx context.Context,
nginxConfigContext *model.NginxConfigContext,
) {
if iw.nginxConfigCache[nginxConfigContext.InstanceID] == nil ||
!iw.nginxConfigCache[nginxConfigContext.InstanceID].Equal(nginxConfigContext) {
slog.DebugContext(
ctx,
"New NGINX config context",
"instance_id", nginxConfigContext.InstanceID,
"nginx_config_context", nginxConfigContext,
)
iw.nginxConfigContextChannel <- NginxConfigContextMessage{
CorrelationID: logger.GetCorrelationIDAttr(ctx),
NginxConfigContext: nginxConfigContext,
}
}
}
func (iw *InstanceWatcherService) instanceUpdates(ctx context.Context) (
instanceUpdates InstanceUpdates,
err error,
) {
processes, err := iw.processOperator.Processes(ctx)
if err != nil {
return instanceUpdates, err
}
// NGINX Agent is always the first instance in the list
instancesFound := make(map[string]*mpi.Instance)
agentInstance := iw.agentInstance(ctx)
instancesFound[agentInstance.GetInstanceMeta().GetInstanceId()] = agentInstance
for _, parser := range iw.processParsers {
instances := parser.Parse(ctx, processes)
for _, instance := range instances {
instancesFound[instance.GetInstanceMeta().GetInstanceId()] = instance
}
}
newInstances, updatedInstances, deletedInstances := compareInstances(iw.instanceCache, instancesFound)
instanceUpdates.NewInstances = newInstances
instanceUpdates.UpdatedInstances = updatedInstances
instanceUpdates.DeletedInstances = deletedInstances
for _, instance := range slices.Concat[[]*mpi.Instance](newInstances, updatedInstances) {
iw.instanceCache[instance.GetInstanceMeta().GetInstanceId()] = instance
}
for _, instance := range deletedInstances {
delete(iw.instanceCache, instance.GetInstanceMeta().GetInstanceId())
}
return instanceUpdates, nil
}
func (iw *InstanceWatcherService) agentInstance(ctx context.Context) *mpi.Instance {
processPath, err := iw.executer.Executable()
if err != nil {
processPath = defaultAgentPath
slog.WarnContext(ctx, "Unable to read process location, defaulting to /var/run/nginx-agent", "error", err)
}
return &mpi.Instance{
InstanceMeta: &mpi.InstanceMeta{
InstanceId: iw.agentConfig.UUID,
InstanceType: mpi.InstanceMeta_INSTANCE_TYPE_AGENT,
Version: iw.agentConfig.Version,
},
InstanceConfig: &mpi.InstanceConfig{
Actions: []*mpi.InstanceAction{},
Config: &mpi.InstanceConfig_AgentConfig{
AgentConfig: &mpi.AgentConfig{
Command: config.ToCommandProto(iw.agentConfig.Command),
Metrics: &mpi.MetricsServer{},
File: &mpi.FileServer{},
Labels: []*structpb.Struct{},
Features: iw.agentConfig.Features,
MessageBufferSize: "",
},
},
},
InstanceRuntime: &mpi.InstanceRuntime{
ProcessId: iw.executer.ProcessID(),
BinaryPath: processPath,
ConfigPath: iw.agentConfig.Path,
Details: nil,
},
}
}
func compareInstances(oldInstancesMap, instancesMap map[string]*mpi.Instance) (
newInstances, updatedInstances, deletedInstances []*mpi.Instance,
) {
updatedInstancesMap := make(map[string]*mpi.Instance)
updatedOldInstancesMap := make(map[string]*mpi.Instance)
for instanceID, instance := range instancesMap {
_, ok := oldInstancesMap[instanceID]
if !ok {
newInstances = append(newInstances, instance)
} else {
updatedInstancesMap[instanceID] = instance
}
}
for instanceID, oldInstance := range oldInstancesMap {
_, ok := instancesMap[instanceID]
if !ok {
deletedInstances = append(deletedInstances, oldInstance)
} else {
updatedOldInstancesMap[instanceID] = oldInstance
}
}
updatedInstances = checkForProcessChanges(updatedInstancesMap, updatedOldInstancesMap)
return newInstances, updatedInstances, deletedInstances
}
func checkForProcessChanges(
updatedInstancesMap map[string]*mpi.Instance,
updatedOldInstancesMap map[string]*mpi.Instance,
) (updatedInstances []*mpi.Instance) {
for instanceID, instance := range updatedInstancesMap {
oldInstance := updatedOldInstancesMap[instanceID]
if !areInstancesEqual(oldInstance.GetInstanceRuntime(), instance.GetInstanceRuntime()) {
updatedInstances = append(updatedInstances, instance)
}
}
return updatedInstances
}
func areInstancesEqual(oldRuntime, currentRuntime *mpi.InstanceRuntime) (equal bool) {
if oldRuntime.GetProcessId() != currentRuntime.GetProcessId() {
return false
}
oldRuntimeChildren := oldRuntime.GetInstanceChildren()
currentRuntimeChildren := currentRuntime.GetInstanceChildren()
if len(oldRuntimeChildren) != len(currentRuntimeChildren) {
return false
}
for _, oldChild := range oldRuntimeChildren {
childFound := false
for _, currentChild := range currentRuntimeChildren {
if oldChild.GetProcessId() == currentChild.GetProcessId() {
childFound = true
break
}
}
if !childFound {
return false
}
}
return true
}
func (iw *InstanceWatcherService) updateNginxInstanceRuntime(
instance *mpi.Instance,
nginxConfigContext *model.NginxConfigContext,
) (updatesRequired bool) {
instanceType := instance.GetInstanceMeta().GetInstanceType()
accessLogs := convertAccessLogs(nginxConfigContext.AccessLogs)
errorLogs := convertErrorLogs(nginxConfigContext.ErrorLogs)
if instanceType == mpi.InstanceMeta_INSTANCE_TYPE_NGINX_PLUS {
nginxPlusRuntimeInfo := instance.GetInstanceRuntime().GetNginxPlusRuntimeInfo()
if nginxPlusRuntimeInfoEqual(nginxPlusRuntimeInfo, nginxConfigContext, accessLogs, errorLogs) {
nginxPlusRuntimeInfo.AccessLogs = accessLogs
nginxPlusRuntimeInfo.ErrorLogs = errorLogs
nginxPlusRuntimeInfo.StubStatus.Listen = nginxConfigContext.StubStatus.Listen
nginxPlusRuntimeInfo.PlusApi.Listen = nginxConfigContext.PlusAPI.Listen
nginxPlusRuntimeInfo.StubStatus.Location = nginxConfigContext.StubStatus.Location
nginxPlusRuntimeInfo.PlusApi.Location = nginxConfigContext.PlusAPI.Location
updatesRequired = true
}
} else {
nginxRuntimeInfo := instance.GetInstanceRuntime().GetNginxRuntimeInfo()
if nginxRuntimeInfoEqual(nginxRuntimeInfo, nginxConfigContext, accessLogs, errorLogs) {
nginxRuntimeInfo.AccessLogs = accessLogs
nginxRuntimeInfo.ErrorLogs = errorLogs
nginxRuntimeInfo.StubStatus.Location = nginxConfigContext.StubStatus.Location
nginxRuntimeInfo.StubStatus.Listen = nginxConfigContext.StubStatus.Listen
updatesRequired = true
}
}
return updatesRequired
}
func nginxPlusRuntimeInfoEqual(nginxPlusRuntimeInfo *mpi.NGINXPlusRuntimeInfo,
nginxConfigContext *model.NginxConfigContext, accessLogs, errorLogs []string,
) bool {
if !reflect.DeepEqual(nginxPlusRuntimeInfo.GetAccessLogs(), accessLogs) ||
!reflect.DeepEqual(nginxPlusRuntimeInfo.GetErrorLogs(), errorLogs) ||
nginxPlusRuntimeInfo.GetStubStatus().GetListen() != nginxConfigContext.StubStatus.Listen ||
nginxPlusRuntimeInfo.GetPlusApi().GetListen() != nginxConfigContext.PlusAPI.Listen ||
nginxPlusRuntimeInfo.GetStubStatus().GetLocation() != nginxConfigContext.StubStatus.Location ||
nginxPlusRuntimeInfo.GetPlusApi().GetLocation() != nginxConfigContext.PlusAPI.Location {
return true
}
return false
}
func nginxRuntimeInfoEqual(nginxRuntimeInfo *mpi.NGINXRuntimeInfo, nginxConfigContext *model.NginxConfigContext,
accessLogs, errorLogs []string,
) bool {
if !reflect.DeepEqual(nginxRuntimeInfo.GetAccessLogs(), accessLogs) ||
!reflect.DeepEqual(nginxRuntimeInfo.GetErrorLogs(), errorLogs) ||
nginxRuntimeInfo.GetStubStatus().GetListen() != nginxConfigContext.StubStatus.Listen ||
nginxRuntimeInfo.GetStubStatus().GetLocation() != nginxConfigContext.StubStatus.Location {
return true
}
return false
}
func convertAccessLogs(accessLogs []*model.AccessLog) (logs []string) {
for _, log := range accessLogs {
logs = append(logs, log.Name)
}
return logs
}
func convertErrorLogs(errorLogs []*model.ErrorLog) (logs []string) {
for _, log := range errorLogs {
logs = append(logs, log.Name)
}
return logs
}