/
message_handlers.go
264 lines (197 loc) · 10.2 KB
/
message_handlers.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
package cloud_connector
import (
"context"
"encoding/json"
"errors"
"github.com/RedHatInsights/cloud-connector/internal/cloud_connector/protocol"
"github.com/RedHatInsights/cloud-connector/internal/config"
"github.com/RedHatInsights/cloud-connector/internal/connection_repository"
"github.com/RedHatInsights/cloud-connector/internal/controller"
"github.com/RedHatInsights/cloud-connector/internal/domain"
"github.com/RedHatInsights/cloud-connector/internal/mqtt"
"github.com/RedHatInsights/cloud-connector/internal/platform/logger"
MQTT "github.com/eclipse/paho.mqtt.golang"
"github.com/sirupsen/logrus"
)
var (
errDuplicateOrOldMQTTMessage = errors.New("duplicate or old message")
)
const (
canonicalFactsKey = "canonical_facts"
dispatchersKey = "dispatchers"
tagsKey = "tags"
catalogDispatcherKey = "catalog"
catalogApplicationType = "ApplicationType"
catalogSourceName = "SrcName"
catalogSourceRef = "SourceRef"
catalogSourceType = "SrcType"
playbookWorkerDispatcherKey = "rhc-worker-playbook"
)
// HandleControlMessage returns a function that processes control messages.
// The returned function should only return an error in the case where the
// message should get processed again. In other words, if the message
// processing function returns an error ...do not commit the kafka message.
func HandleControlMessage(cfg *config.Config, mqttClient MQTT.Client, topicBuilder *mqtt.TopicBuilder, connectionRegistrar connection_repository.ConnectionRegistrar, accountResolver controller.AccountIdResolver, connectedClientRecorder controller.ConnectedClientRecorder, sourcesRecorder controller.SourcesRecorder) func(MQTT.Client, domain.ClientID, string) error {
return func(client MQTT.Client, clientID domain.ClientID, payload string) error {
metrics.controlMessageReceivedCounter.Inc()
logger := logger.Log.WithFields(logrus.Fields{"client_id": clientID})
if len(payload) == 0 {
// This will happen when a retained message is removed
logger.Trace("client sent an empty payload")
return nil
}
var controlMsg protocol.ControlMessage
if err := json.Unmarshal([]byte(payload), &controlMsg); err != nil {
logger.WithFields(logrus.Fields{"error": err}).Error("Failed to unmarshal control message")
return nil
}
logger = logger.WithFields(logrus.Fields{"message_id": controlMsg.MessageID})
logger.Debug("Got a control message:", controlMsg)
switch controlMsg.MessageType {
case "connection-status":
return handleConnectionStatusMessage(logger, client, clientID, controlMsg, cfg, topicBuilder, connectionRegistrar, accountResolver, connectedClientRecorder, sourcesRecorder)
case "event":
return handleEventMessage(logger, client, clientID, controlMsg)
default:
logger.Debug("Received an invalid message type:", controlMsg.MessageType)
return nil
}
}
}
func handleConnectionStatusMessage(logger *logrus.Entry, client MQTT.Client, clientID domain.ClientID, msg protocol.ControlMessage, cfg *config.Config, topicBuilder *mqtt.TopicBuilder, connectionRegistrar connection_repository.ConnectionRegistrar, accountResolver controller.AccountIdResolver, connectedClientRecorder controller.ConnectedClientRecorder, sourcesRecorder controller.SourcesRecorder) error {
logger.Debug("handling connection status control message")
handshakePayload := msg.Content.(map[string]interface{})
connectionState, gotConnectionState := handshakePayload["state"]
if gotConnectionState == false {
logger.Debug("Client did not send the connection state as part of the online message")
// For now, ignore the invalid message. In the future, maybe ask the client
// to resend that online message?
return nil
}
clientName, _ := protocol.GetClientVersionFromConnectionStatusContent(handshakePayload)
clientVersion, _ := protocol.GetClientNameFromConnectionStatusContent(handshakePayload)
logger = logger.WithFields(logrus.Fields{"client_name": clientName, "client_version": clientVersion})
var err error
if connectionState == "online" {
err = handleOnlineMessage(logger, client, clientID, msg, cfg, topicBuilder, accountResolver, connectionRegistrar, connectedClientRecorder, sourcesRecorder)
} else if connectionState == "offline" {
err = handleOfflineMessage(logger, client, clientID, msg, connectionRegistrar)
} else {
logger.Debug("Invalid connection state from connection-status message.")
return nil
}
if err == errDuplicateOrOldMQTTMessage {
// Ignore duplicate or old mqtt messages
return nil
}
return err
}
func handleOnlineMessage(logger *logrus.Entry, client MQTT.Client, clientID domain.ClientID, msg protocol.ControlMessage, cfg *config.Config, topicBuilder *mqtt.TopicBuilder, accountResolver controller.AccountIdResolver, connectionRegistrar connection_repository.ConnectionRegistrar, connectedClientRecorder controller.ConnectedClientRecorder, sourcesRecorder controller.SourcesRecorder) error {
logger.Debug("handling online connection-status message")
ctx := context.Background()
err := checkForDuplicateOnlineMessage(logger, ctx, connectionRegistrar, clientID, msg)
if err != nil {
return err
}
identity, account, orgID, err := accountResolver.MapClientIdToAccountId(context.Background(), clientID)
if err != nil {
logger.WithFields(logrus.Fields{"error": err}).Error("Failed to resolve client id to account number")
mqtt.SendReconnectMessageToClient(client, logger, topicBuilder, cfg.MqttControlPublishQoS, cfg.MqttPublishTimeout, clientID, cfg.InvalidHandshakeReconnectDelay)
return nil
}
logger = logger.WithFields(logrus.Fields{"account": account, "org_id": orgID})
handshakePayload := msg.Content.(map[string]interface{})
rhcClient := domain.ConnectorClientState{ClientID: clientID,
Account: account,
OrgID: orgID,
Dispatchers: handshakePayload[dispatchersKey],
CanonicalFacts: handshakePayload[canonicalFactsKey],
Tags: handshakePayload[tagsKey],
MessageMetadata: domain.MessageMetadata{LatestMessageID: msg.MessageID,
LatestTimestamp: msg.Sent},
}
err = connectionRegistrar.Register(context.Background(), rhcClient)
if err != nil {
if errors.As(err, &connection_repository.FatalError{}) {
return err
}
mqtt.SendReconnectMessageToClient(client, logger, topicBuilder, cfg.MqttControlPublishQoS, cfg.MqttPublishTimeout, clientID, cfg.InvalidHandshakeReconnectDelay)
return nil
}
err = connectedClientRecorder.RecordConnectedClient(context.Background(), identity, rhcClient)
if err != nil {
logger.WithFields(logrus.Fields{"error": err}).Error("Failed to record client id within the platform")
// If we cannot "register" the connection with inventory, then send a disconnect message
mqtt.SendReconnectMessageToClient(client, logger, topicBuilder, cfg.MqttControlPublishQoS, cfg.MqttPublishTimeout, clientID, cfg.InvalidHandshakeReconnectDelay)
return nil
}
processDispatchers(logger, sourcesRecorder, identity, account, orgID, clientID, handshakePayload)
return nil
}
func checkForDuplicateOnlineMessage(logger *logrus.Entry, ctx context.Context, connectionRegistrar connection_repository.ConnectionRegistrar, clientID domain.ClientID, incomingMsg protocol.ControlMessage) error {
connectionState, err := connectionRegistrar.FindConnectionByClientID(ctx, clientID)
if err != nil {
if errors.Is(err, connection_repository.NotFoundError) {
return nil
}
if errors.As(err, &connection_repository.FatalError{}) {
return err
}
logger.WithFields(logrus.Fields{"error": err}).Error("Error during duplicate message check")
// If there is a non-fatal error during the client lookup,
// ignore it and continue processing the incoming message.
// The idea here is that (hopefully) we will overwrite "bad"
// data with good data from the new message.
}
if isDuplicateOrOldMessage(connectionState, incomingMsg) {
logger.Debug("ignoring message - duplicate or old message")
return errDuplicateOrOldMQTTMessage
}
return nil
}
func isDuplicateOrOldMessage(currentConnectionState domain.ConnectorClientState, incomingMsg protocol.ControlMessage) bool {
if currentConnectionState.MessageMetadata.LatestMessageID == incomingMsg.MessageID || incomingMsg.Sent.Before(currentConnectionState.MessageMetadata.LatestTimestamp) {
// Duplicate or old message
return true
}
return false
}
func processDispatchers(logger *logrus.Entry, sourcesRecorder controller.SourcesRecorder, identity domain.Identity, account domain.AccountID, orgID domain.OrgID, clientId domain.ClientID, handshakePayload map[string]interface{}) {
dispatchers, gotDispatchers := handshakePayload[dispatchersKey]
if gotDispatchers == false {
logger.Debug("No dispatchers found")
return
}
dispatchersMap := dispatchers.(map[string]interface{})
catalog, gotCatalog := dispatchersMap[catalogDispatcherKey]
if gotCatalog == false {
logger.Debug("No catalog dispatcher found")
return
}
catalogMap := catalog.(map[string]interface{})
applicationType, gotApplicationType := catalogMap[catalogApplicationType]
sourceType, gotSourceType := catalogMap[catalogSourceType]
sourceRef, gotSourceRef := catalogMap[catalogSourceRef]
sourceName, gotSourceName := catalogMap[catalogSourceName]
if gotApplicationType != true || gotSourceType != true || gotSourceRef != true || gotSourceName != true {
// MISSING FIELDS
logger.Debug("Found a catalog dispatcher, but missing some of the required fields")
return
}
err := sourcesRecorder.RegisterWithSources(identity, account, orgID, clientId, sourceRef.(string), sourceName.(string), sourceType.(string), applicationType.(string))
if err != nil {
logger.WithFields(logrus.Fields{"error": err}).Error("Failed to register catalog with sources")
}
}
func handleOfflineMessage(logger *logrus.Entry, client MQTT.Client, clientID domain.ClientID, msg protocol.ControlMessage, connectionRegistrar connection_repository.ConnectionRegistrar) error {
logger.Debug("handling offline connection-status message")
err := connectionRegistrar.Unregister(context.Background(), clientID)
if errors.As(err, &connection_repository.FatalError{}) {
return err
}
return nil
}
func handleEventMessage(logger *logrus.Entry, client MQTT.Client, clientID domain.ClientID, msg protocol.ControlMessage) error {
logger.Debugf("Received an event message from client: %v\n", msg)
return nil
}