forked from open-horizon/edge-sync-service
-
Notifications
You must be signed in to change notification settings - Fork 0
/
notification.go
333 lines (299 loc) · 12.7 KB
/
notification.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
package communications
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"github.com/open-horizon/edge-sync-service/common"
"github.com/open-horizon/edge-sync-service/core/leader"
"github.com/open-horizon/edge-utilities/logger"
"github.com/open-horizon/edge-utilities/logger/log"
"github.com/open-horizon/edge-utilities/logger/trace"
)
type invalidNotification struct {
message string
}
func (e *invalidNotification) Error() string {
return e.message
}
// PrepareObjectNotifications sends notifications to object’s destinations
// This function should not acquire an object lock (common.ObjectLocks) as the caller has already acquired one.
func PrepareObjectNotifications(metaData common.MetaData) ([]common.NotificationInfo, common.SyncServiceError) {
destinations, err := Store.GetObjectDestinations(metaData)
if err == nil {
err = Store.UpdateObjectDelivering(metaData.DestOrgID, metaData.ObjectType, metaData.ObjectID)
if err != nil && log.IsLogging(logger.ERROR) {
log.Error("Failed to update object's delivery status. Error: " + err.Error())
}
return PrepareUpdateNotification(metaData, destinations)
}
return nil, nil
}
// PrepareDeleteNotifications prepares the delete notification message
// This function should not acquire an object lock (common.ObjectLocks) as the caller has already acquired one.
func PrepareDeleteNotifications(metaData common.MetaData) ([]common.NotificationInfo, common.SyncServiceError) {
destinations, err := Store.GetObjectDestinations(metaData)
if err != nil {
return nil, err
}
return prepareNotifications(common.Delete, metaData, destinations)
}
// PrepareNotificationsForDestinations prepares notification messages for the destinations if necessary
// This function should not acquire an object lock (common.ObjectLocks) as the caller has already acquired one.
func PrepareNotificationsForDestinations(metaData common.MetaData, destinations []common.StoreDestinationStatus, topic string) ([]common.NotificationInfo,
common.SyncServiceError) {
dests := make([]common.Destination, 0)
for _, dest := range destinations {
if topic != common.Delete || (dest.Status == common.Delivering || dest.Status == common.Delivered || dest.Status == common.Consumed ||
dest.Status == common.Error) {
dests = append(dests, dest.Destination)
}
}
return prepareNotifications(topic, metaData, dests)
}
func prepareNotifications(topic string, metaData common.MetaData, destinations []common.Destination) ([]common.NotificationInfo, common.SyncServiceError) {
result := make([]common.NotificationInfo, 0)
// Create an initial notification record for each destination
for _, destination := range destinations {
notification := common.Notification{ObjectID: metaData.ObjectID, ObjectType: metaData.ObjectType,
DestOrgID: metaData.DestOrgID, DestID: destination.DestID, DestType: destination.DestType,
Status: topic, InstanceID: metaData.InstanceID, DataID: metaData.DataID}
// Store the notification records in storage as part of the object
if err := Store.UpdateNotificationRecord(notification); err != nil {
return nil, err
}
// Set the DestID in case the object was for destinations of a type or a destinations list
metaData.DestType = destination.DestType
metaData.DestID = destination.DestID
notificationInfo := common.NotificationInfo{NotificationTopic: topic, DestType: metaData.DestType, DestID: metaData.DestID,
InstanceID: metaData.InstanceID, DataID: metaData.DataID, MetaData: &metaData}
result = append(result, notificationInfo)
}
return result, nil
}
// PrepareUpdateNotification prepares the notification message from object's meta data
// This function should not acquire an object lock (common.ObjectLocks) as the caller has already acquired one.
func PrepareUpdateNotification(metaData common.MetaData, destinations []common.Destination) ([]common.NotificationInfo, common.SyncServiceError) {
return prepareNotifications(common.Update, metaData, destinations)
}
// PrepareObjectStatusNotification sends an object status message to the other side
// This function should not acquire an object lock (common.ObjectLocks) as the caller has already acquired one.
func PrepareObjectStatusNotification(metaData common.MetaData, status string) ([]common.NotificationInfo, common.SyncServiceError) {
notification := common.Notification{ObjectID: metaData.ObjectID, ObjectType: metaData.ObjectType,
DestOrgID: metaData.DestOrgID, DestID: metaData.OriginID, DestType: metaData.OriginType,
Status: status, InstanceID: metaData.InstanceID, DataID: metaData.DataID}
// Store the notification records in storage as part of the object
if err := Store.UpdateNotificationRecord(notification); err != nil {
return nil, err
}
notificationInfo := common.NotificationInfo{NotificationTopic: status, DestType: metaData.OriginType, DestID: metaData.OriginID,
InstanceID: metaData.InstanceID, DataID: metaData.DataID, MetaData: &metaData}
return []common.NotificationInfo{notificationInfo}, nil
}
// SendNotifications calls the communication to send the notification messages
func SendNotifications(notifications []common.NotificationInfo) common.SyncServiceError {
for _, notification := range notifications {
if err := Comm.SendNotificationMessage(notification.NotificationTopic, notification.DestType, notification.DestID,
notification.InstanceID, notification.DataID, notification.MetaData); err != nil {
return &Error{err.Error()}
}
}
return nil
}
func resendNotificationsForDestination(dest common.Destination, resendReceivedObjects bool) common.SyncServiceError {
notifications, err := Store.RetrieveNotifications(dest.DestOrgID, dest.DestType, dest.DestID, resendReceivedObjects)
if err != nil {
message := fmt.Sprintf("Error in resendNotificationsForDestination. Error: %s\n", err)
if log.IsLogging(logger.ERROR) {
log.Error(message)
}
return &invalidNotification{message}
}
if len(notifications) > 0 {
for _, notification := range notifications {
// Retrieve the notification in case it was changed since the call to RetrieveNotifications
lockIndex := common.HashStrings(notification.DestOrgID, notification.ObjectType, notification.ObjectID)
common.ObjectLocks.Lock(lockIndex)
n, _ := Store.RetrieveNotificationRecord(notification.DestOrgID, notification.ObjectType, notification.ObjectID,
notification.DestType, notification.DestID)
if n == nil || n.Status != notification.Status || n.ResendTime != notification.ResendTime {
common.ObjectLocks.Unlock(lockIndex)
continue
}
metaData, status, err := Store.RetrieveObjectAndStatus(n.DestOrgID, n.ObjectType, n.ObjectID)
if err != nil {
message := fmt.Sprintf("Error in resendNotificationsForDestination. Error: %s\n", err)
if log.IsLogging(logger.ERROR) {
log.Error(message)
}
common.ObjectLocks.Unlock(lockIndex)
return &invalidNotification{message}
}
if metaData == nil {
Store.DeleteNotificationRecords(n.DestOrgID, n.ObjectType, n.ObjectID, "", "")
common.ObjectLocks.Unlock(lockIndex)
continue
}
if err := Store.UpdateNotificationResendTime(*n); err != nil {
if log.IsLogging(logger.ERROR) {
log.Error(err.Error())
}
common.ObjectLocks.Unlock(lockIndex)
continue
}
switch n.Status {
case common.Getdata:
if status != common.PartiallyReceived {
common.ObjectLocks.Unlock(lockIndex)
continue
}
common.ObjectLocks.Unlock(lockIndex)
Comm.LockDataChunks(lockIndex, metaData)
offsets := getOffsetsToResend(*n, *metaData)
for _, offset := range offsets {
if trace.IsLogging(logger.TRACE) {
trace.Trace("Resending GetData request for offset %d of %s:%s:%s\n", offset, n.DestOrgID, n.ObjectType, n.ObjectID)
}
if err = Comm.GetData(*metaData, offset); err != nil {
if common.IsNotFound(err) {
deleteObjectInfo("", "", "", n.DestType, n.DestID, metaData, true)
}
break
}
}
Comm.UnlockDataChunks(lockIndex, metaData)
case common.ReceivedByDestination:
fallthrough
case common.Data:
if dest.DestType == "" {
common.ObjectLocks.Unlock(lockIndex)
continue
}
// We get here only when an ESS without persistent storage reconnects,
// and the CSS has a notification with "data" or "received by destination" status.
// Send update notification for this object.
n.Status = common.Update
n.ResendTime = 0
if err := Store.UpdateNotificationRecord(*n); err != nil && log.IsLogging(logger.ERROR) {
log.Error("Failed to update notification record. Error: " + err.Error())
}
common.ObjectLocks.Unlock(lockIndex)
metaData.DestType = n.DestType
metaData.DestID = n.DestID
err = Comm.SendNotificationMessage(common.Update, dest.DestType, dest.DestID, metaData.InstanceID, metaData.DataID, metaData)
default:
common.ObjectLocks.Unlock(lockIndex)
metaData.DestType = n.DestType
metaData.DestID = n.DestID
err = Comm.SendNotificationMessage(n.Status, n.DestType, n.DestID, n.InstanceID, n.DataID, metaData)
}
if err != nil {
message := fmt.Sprintf("Error in resendNotificationsForDestination. Error: %s\n", err)
if log.IsLogging(logger.ERROR) {
log.Error(message)
}
return &invalidNotification{message}
}
}
}
return nil
}
// ResendNotifications resends notications that haven't been acknowledged
func ResendNotifications() common.SyncServiceError {
if common.Configuration.NodeType == common.ESS && !common.Registered {
if registerAsNew {
Comm.RegisterNew()
} else {
Comm.Register()
}
}
if common.Configuration.NodeType == common.ESS && !common.ResendAcked {
Comm.ResendObjects()
}
if leader.CheckIfLeader() {
if trace.IsLogging(logger.TRACE) {
trace.Trace("About to resend notifications.")
}
return resendNotificationsForDestination(common.Destination{}, false)
}
return nil
}
// ActivateObjects looks for objects that are ready to be activated, marks them as active, and sends
// object notifications to their destinations
func ActivateObjects() {
objects, err := Store.GetObjectsToActivate()
if err != nil && log.IsLogging(logger.ERROR) {
log.Error("Error in ActivateObjects, failed to retrieve objects. Error: %s\n", err)
}
for _, object := range objects {
if trace.IsLogging(logger.TRACE) {
trace.Trace("Activating object %s:%s:%s", object.DestOrgID, object.ObjectType, object.ObjectID)
}
lockIndex := common.HashStrings(object.DestOrgID, object.ObjectType, object.ObjectID)
common.ObjectLocks.Lock(lockIndex)
storedObject, status, err := Store.RetrieveObjectAndStatus(object.DestOrgID, object.ObjectType, object.ObjectID)
if err != nil || storedObject == nil || status == "" ||
storedObject.ActivationTime != object.ActivationTime {
common.ObjectLocks.Unlock(lockIndex)
continue
}
if err := Store.ActivateObject(object.DestOrgID, object.ObjectType, object.ObjectID); err != nil {
if log.IsLogging(logger.ERROR) {
log.Error("Error in ActivateObjects. Error: %s\n", err)
}
common.ObjectLocks.Unlock(lockIndex)
} else if status == common.ReadyToSend {
object.Inactive = false
notificationsInfo, err := PrepareObjectNotifications(object)
common.ObjectLocks.Unlock(lockIndex)
if err == nil {
if err := SendNotifications(notificationsInfo); err != nil && log.IsLogging(logger.ERROR) {
log.Error("Error in ActivateObjects: %s\n", err)
}
} else if log.IsLogging(logger.ERROR) {
log.Error("Error in ActivateObjects: %s\n", err)
}
} else {
common.ObjectLocks.Unlock(lockIndex)
}
}
}
// ResendObjects requests to resend all the relevant objects
func ResendObjects() common.SyncServiceError {
common.ResendAcked = false
return Comm.ResendObjects()
}
func callWebhooks(metaData *common.MetaData) {
if webhooks, err := Store.RetrieveWebhooks(metaData.DestOrgID, metaData.ObjectType); err == nil {
body, err := json.MarshalIndent(metaData, "", " ")
if err != nil {
if log.IsLogging(logger.ERROR) {
log.Error("Error in callWebhooks, failed to marshal meta data: %s\n", err)
}
return
}
for _, url := range webhooks {
request, err := http.NewRequest("POST", url, bytes.NewReader(body))
request.ContentLength = int64(len(body))
request.Header.Add("Content-Type", "Application/JSON")
response, err := http.DefaultClient.Do(request)
if err != nil {
if log.IsLogging(logger.ERROR) {
log.Error("Error in callWebhooks, failed to post meta data to %s: %s\n", url, err)
}
continue
}
if response.StatusCode != http.StatusOK &&
response.StatusCode != http.StatusNoContent &&
log.IsLogging(logger.ERROR) {
log.Error("Error in callWebhooks: received status: %d for %s\n", response.StatusCode, url)
}
err = response.Body.Close()
if err != nil {
if log.IsLogging(logger.ERROR) {
log.Error("Error in callWebhooks, failed to close response body")
}
}
}
}
}