-
Notifications
You must be signed in to change notification settings - Fork 105
Expand file tree
/
Copy pathfile_plugin.go
More file actions
417 lines (347 loc) · 12.6 KB
/
file_plugin.go
File metadata and controls
417 lines (347 loc) · 12.6 KB
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
// 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 file
import (
"context"
"log/slog"
"github.com/nginx/agent/v3/pkg/files"
"github.com/nginx/agent/v3/pkg/id"
mpi "github.com/nginx/agent/v3/api/grpc/mpi/v1"
"github.com/nginx/agent/v3/internal/bus"
"github.com/nginx/agent/v3/internal/config"
"github.com/nginx/agent/v3/internal/grpc"
"github.com/nginx/agent/v3/internal/logger"
"github.com/nginx/agent/v3/internal/model"
"google.golang.org/protobuf/types/known/timestamppb"
)
var _ bus.Plugin = (*FilePlugin)(nil)
// The file plugin only writes, deletes and checks hashes of files
// the file plugin does not care about the instance type
type FilePlugin struct {
messagePipe bus.MessagePipeInterface
config *config.Config
conn grpc.GrpcConnectionInterface
fileManagerService fileManagerServiceInterface
serverType model.ServerType
}
func NewFilePlugin(agentConfig *config.Config, grpcConnection grpc.GrpcConnectionInterface,
serverType model.ServerType,
) *FilePlugin {
return &FilePlugin{
config: agentConfig,
conn: grpcConnection,
serverType: serverType,
}
}
func (fp *FilePlugin) Init(ctx context.Context, messagePipe bus.MessagePipeInterface) error {
ctx = context.WithValue(
ctx,
logger.ServerTypeContextKey, slog.Any(logger.ServerTypeKey, fp.serverType.String()),
)
slog.DebugContext(ctx, "Starting file plugin")
fp.messagePipe = messagePipe
fp.fileManagerService = NewFileManagerService(fp.conn.FileServiceClient(), fp.config)
return nil
}
func (fp *FilePlugin) Close(ctx context.Context) error {
ctx = context.WithValue(
ctx,
logger.ServerTypeContextKey, slog.Any(logger.ServerTypeKey, fp.serverType.String()),
)
slog.InfoContext(ctx, "Closing file plugin")
return fp.conn.Close(ctx)
}
func (fp *FilePlugin) Info() *bus.Info {
name := "file"
if fp.serverType.String() == model.Auxiliary.String() {
name = "auxiliary-file"
}
return &bus.Info{
Name: name,
}
}
// nolint: cyclop, revive
func (fp *FilePlugin) Process(ctx context.Context, msg *bus.Message) {
if logger.ServerType(ctx) == "" {
ctx = context.WithValue(
ctx,
logger.ServerTypeContextKey, slog.Any(logger.ServerTypeKey, fp.serverType.String()),
)
}
if logger.ServerType(ctx) == fp.serverType.String() {
switch msg.Topic {
case bus.ConnectionResetTopic:
fp.handleConnectionReset(ctx, msg)
case bus.ConnectionCreatedTopic:
slog.DebugContext(ctx, "File plugin received connection created message")
fp.fileManagerService.SetIsConnected(true)
case bus.NginxConfigUpdateTopic:
fp.handleNginxConfigUpdate(ctx, msg)
case bus.ConfigUploadRequestTopic:
fp.handleConfigUploadRequest(ctx, msg)
case bus.ConfigApplyRequestTopic:
fp.handleConfigApplyRequest(ctx, msg)
case bus.ConfigApplyCompleteTopic:
fp.handleConfigApplyComplete(ctx, msg)
case bus.ConfigApplySuccessfulTopic:
fp.handleConfigApplySuccess(ctx, msg)
case bus.ConfigApplyFailedTopic:
fp.handleConfigApplyFailedRequest(ctx, msg)
default:
slog.DebugContext(ctx, "File plugin received unknown topic", "topic", msg.Topic)
}
}
}
func (fp *FilePlugin) Subscriptions() []string {
if fp.serverType == model.Auxiliary {
return []string{
bus.ConnectionResetTopic,
bus.ConnectionCreatedTopic,
bus.NginxConfigUpdateTopic,
bus.ConfigUploadRequestTopic,
}
}
return []string{
bus.ConnectionResetTopic,
bus.ConnectionCreatedTopic,
bus.NginxConfigUpdateTopic,
bus.ConfigUploadRequestTopic,
bus.ConfigApplyRequestTopic,
bus.ConfigApplyFailedTopic,
bus.ConfigApplySuccessfulTopic,
bus.ConfigApplyCompleteTopic,
}
}
func (fp *FilePlugin) handleConnectionReset(ctx context.Context, msg *bus.Message) {
slog.DebugContext(ctx, "File plugin received connection reset message")
if newConnection, ok := msg.Data.(grpc.GrpcConnectionInterface); ok {
var reconnect bool
err := fp.conn.Close(ctx)
if err != nil {
slog.ErrorContext(ctx, "File plugin: unable to close connection", "error", err)
}
fp.conn = newConnection
reconnect = fp.fileManagerService.IsConnected()
fp.fileManagerService = NewFileManagerService(fp.conn.FileServiceClient(), fp.config)
fp.fileManagerService.SetIsConnected(reconnect)
slog.DebugContext(ctx, "File manager service client reset successfully")
}
}
func (fp *FilePlugin) handleConfigApplyComplete(ctx context.Context, msg *bus.Message) {
slog.DebugContext(ctx, "File plugin received config apply complete message")
response, ok := msg.Data.(*mpi.DataPlaneResponse)
if !ok {
slog.ErrorContext(ctx, "Unable to cast message payload to *mpi.DataPlaneResponse", "payload", msg.Data)
return
}
fp.fileManagerService.ClearCache()
fp.messagePipe.Process(ctx, &bus.Message{Topic: bus.DataPlaneResponseTopic, Data: response})
}
func (fp *FilePlugin) handleConfigApplySuccess(ctx context.Context, msg *bus.Message) {
slog.DebugContext(ctx, "File plugin received config success message")
successMessage, ok := msg.Data.(*model.ConfigApplySuccess)
if !ok {
slog.ErrorContext(ctx, "Unable to cast message payload to *model.ConfigApplySuccess", "payload", msg.Data)
return
}
fp.fileManagerService.ClearCache()
if successMessage.ConfigContext.Files != nil {
slog.DebugContext(ctx, "Changes made during config apply, update files on disk")
updateError := fp.fileManagerService.UpdateCurrentFilesOnDisk(
ctx,
files.ConvertToMapOfFiles(successMessage.ConfigContext.Files),
true,
)
if updateError != nil {
slog.ErrorContext(ctx, "Unable to update current files on disk", "error", updateError)
}
}
fp.messagePipe.Process(ctx, &bus.Message{Topic: bus.DataPlaneResponseTopic, Data: successMessage.DataPlaneResponse})
}
func (fp *FilePlugin) handleConfigApplyFailedRequest(ctx context.Context, msg *bus.Message) {
slog.DebugContext(ctx, "File plugin received config failed message")
data, ok := msg.Data.(*model.ConfigApplyMessage)
if data.InstanceID == "" || !ok {
slog.ErrorContext(ctx, "Unable to cast message payload to *model.ConfigApplyMessage",
"payload", msg.Data)
fp.fileManagerService.ClearCache()
return
}
err := fp.fileManagerService.Rollback(ctx, data.InstanceID)
if err != nil {
rollbackResponse := fp.createDataPlaneResponse(data.CorrelationID,
mpi.CommandResponse_COMMAND_STATUS_ERROR,
"Rollback failed", data.InstanceID, err.Error())
applyResponse := fp.createDataPlaneResponse(data.CorrelationID,
mpi.CommandResponse_COMMAND_STATUS_FAILURE,
"Config apply failed, rollback failed", data.InstanceID, data.Error.Error())
fp.fileManagerService.ClearCache()
fp.messagePipe.Process(ctx, &bus.Message{Topic: bus.DataPlaneResponseTopic, Data: rollbackResponse})
fp.messagePipe.Process(ctx, &bus.Message{Topic: bus.ConfigApplyCompleteTopic, Data: applyResponse})
return
}
// Send RollbackWriteTopic with Correlation and Instance ID for use by resource plugin
fp.messagePipe.Process(ctx, &bus.Message{Topic: bus.RollbackWriteTopic, Data: data})
}
func (fp *FilePlugin) handleConfigApplyRequest(ctx context.Context, msg *bus.Message) {
slog.DebugContext(ctx, "File plugin received config apply request message")
var response *mpi.DataPlaneResponse
correlationID := logger.CorrelationID(ctx)
managementPlaneRequest, ok := msg.Data.(*mpi.ManagementPlaneRequest)
if !ok {
slog.ErrorContext(ctx, "Unable to cast message payload to *mpi.ManagementPlaneRequest",
"payload", msg.Data)
return
}
request, requestOk := managementPlaneRequest.GetRequest().(*mpi.ManagementPlaneRequest_ConfigApplyRequest)
if !requestOk {
slog.ErrorContext(ctx, "Unable to cast message payload to *mpi.ManagementPlaneRequest_ConfigApplyRequest",
"payload", msg.Data)
return
}
configApplyRequest := request.ConfigApplyRequest
instanceID := configApplyRequest.GetOverview().GetConfigVersion().GetInstanceId()
writeStatus, err := fp.fileManagerService.ConfigApply(ctx, configApplyRequest)
switch writeStatus {
case model.NoChange:
slog.DebugContext(ctx, "No changes required for config apply request")
dpResponse := fp.createDataPlaneResponse(
correlationID,
mpi.CommandResponse_COMMAND_STATUS_OK,
"Config apply successful, no files to change",
instanceID,
"",
)
successMessage := &model.ConfigApplySuccess{
ConfigContext: &model.NginxConfigContext{},
DataPlaneResponse: dpResponse,
}
fp.fileManagerService.ClearCache()
fp.messagePipe.Process(ctx, &bus.Message{Topic: bus.ConfigApplySuccessfulTopic, Data: successMessage})
return
case model.Error:
slog.ErrorContext(
ctx,
"Failed to apply config changes",
"instance_id", instanceID,
"error", err,
)
response = fp.createDataPlaneResponse(
correlationID,
mpi.CommandResponse_COMMAND_STATUS_FAILURE,
"Config apply failed",
instanceID,
err.Error(),
)
fp.fileManagerService.ClearCache()
fp.messagePipe.Process(ctx, &bus.Message{Topic: bus.ConfigApplyCompleteTopic, Data: response})
return
case model.RollbackRequired:
slog.ErrorContext(
ctx,
"Failed to apply config changes, rolling back",
"instance_id", instanceID,
"error", err,
)
response = fp.createDataPlaneResponse(
correlationID,
mpi.CommandResponse_COMMAND_STATUS_ERROR,
"Config apply failed, rolling back config",
instanceID,
err.Error(),
)
fp.messagePipe.Process(ctx, &bus.Message{Topic: bus.DataPlaneResponseTopic, Data: response})
rollbackErr := fp.fileManagerService.Rollback(
ctx,
instanceID,
)
if rollbackErr != nil {
rollbackResponse := fp.createDataPlaneResponse(
correlationID,
mpi.CommandResponse_COMMAND_STATUS_FAILURE,
"Config apply failed, rollback failed",
instanceID,
rollbackErr.Error())
fp.fileManagerService.ClearCache()
fp.messagePipe.Process(ctx, &bus.Message{Topic: bus.ConfigApplyCompleteTopic, Data: rollbackResponse})
return
}
response = fp.createDataPlaneResponse(
correlationID,
mpi.CommandResponse_COMMAND_STATUS_FAILURE,
"Config apply failed, rollback successful",
instanceID,
err.Error())
fp.fileManagerService.ClearCache()
fp.messagePipe.Process(ctx, &bus.Message{Topic: bus.ConfigApplyCompleteTopic, Data: response})
return
case model.OK:
slog.DebugContext(ctx, "Changes required for config apply request")
// Send WriteConfigSuccessfulTopic with Correlation and Instance ID for use by resource plugin
data := &model.ConfigApplyMessage{
CorrelationID: correlationID,
InstanceID: instanceID,
}
fp.messagePipe.Process(ctx, &bus.Message{Topic: bus.WriteConfigSuccessfulTopic, Data: data})
}
}
func (fp *FilePlugin) handleNginxConfigUpdate(ctx context.Context, msg *bus.Message) {
slog.DebugContext(ctx, "File plugin received nginx config update message")
nginxConfigContext, ok := msg.Data.(*model.NginxConfigContext)
if !ok {
slog.ErrorContext(ctx, "Unable to cast message payload to *model.NginxConfigContext", "payload", msg.Data)
return
}
fp.fileManagerService.ConfigUpdate(ctx, nginxConfigContext)
}
func (fp *FilePlugin) handleConfigUploadRequest(ctx context.Context, msg *bus.Message) {
slog.DebugContext(ctx, "File plugin received config upload request message")
managementPlaneRequest, ok := msg.Data.(*mpi.ManagementPlaneRequest)
if !ok {
slog.ErrorContext(
ctx,
"Unable to cast message payload to *mpi.ManagementPlaneRequest",
"payload", msg.Data,
)
return
}
configUploadRequest := managementPlaneRequest.GetConfigUploadRequest()
correlationID := logger.CorrelationID(ctx)
updatingFilesError := fp.fileManagerService.ConfigUpload(ctx, configUploadRequest)
response := &mpi.DataPlaneResponse{
MessageMeta: &mpi.MessageMeta{
MessageId: id.GenerateMessageID(),
CorrelationId: correlationID,
Timestamp: timestamppb.Now(),
},
CommandResponse: &mpi.CommandResponse{
Status: mpi.CommandResponse_COMMAND_STATUS_OK,
Message: "Successfully updated all files",
},
}
if updatingFilesError != nil {
response.CommandResponse.Status = mpi.CommandResponse_COMMAND_STATUS_FAILURE
response.CommandResponse.Message = "Failed to update all files"
response.CommandResponse.Error = updatingFilesError.Error()
}
fp.messagePipe.Process(ctx, &bus.Message{Topic: bus.DataPlaneResponseTopic, Data: response})
}
func (fp *FilePlugin) createDataPlaneResponse(correlationID string, status mpi.CommandResponse_CommandStatus,
message, instanceID, err string,
) *mpi.DataPlaneResponse {
return &mpi.DataPlaneResponse{
MessageMeta: &mpi.MessageMeta{
MessageId: id.GenerateMessageID(),
CorrelationId: correlationID,
Timestamp: timestamppb.Now(),
},
CommandResponse: &mpi.CommandResponse{
Status: status,
Message: message,
Error: err,
},
InstanceId: instanceID,
}
}