forked from open-horizon/edge-sync-service
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mongoStorage.go
2100 lines (1901 loc) · 78.2 KB
/
mongoStorage.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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package storage
import (
"crypto/tls"
"crypto/x509"
"fmt"
"io"
"io/ioutil"
"net"
"os"
"strings"
"time"
"github.com/globalsign/mgo"
"github.com/globalsign/mgo/bson"
"github.com/open-horizon/edge-sync-service/common"
"github.com/open-horizon/edge-utilities/logger"
"github.com/open-horizon/edge-utilities/logger/log"
"github.com/open-horizon/edge-utilities/logger/trace"
)
type fileHandle struct {
file *mgo.GridFile
session *mgo.Session
offset int64
chunks map[int64][]byte
}
// MongoStorage is a MongoDB based store
type MongoStorage struct {
session *mgo.Session
dialInfo *mgo.DialInfo
openFiles map[string]*fileHandle
connected bool
lockChannel chan int
mapLock chan int
sessionCache []*mgo.Session
cacheSize int
cacheIndex int
}
type object struct {
ID string `bson:"_id"`
MetaData common.MetaData `bson:"metadata"`
Status string `bson:"status"`
PolicyReceived bool `bson:"policy-received"`
RemainingConsumers int `bson:"remaining-consumers"`
RemainingReceivers int `bson:"remaining-receivers"`
Destinations []common.StoreDestinationStatus `bson:"destinations"`
LastUpdate bson.MongoTimestamp `bson:"last-update"`
}
type destinationObject struct {
ID string `bson:"_id"`
Destination common.Destination `bson:"destination"`
LastPingTime bson.MongoTimestamp `bson:"last-ping-time"`
}
type notificationObject struct {
ID string `bson:"_id"`
Notification common.Notification `bson:"notification"`
}
type leaderDocument struct {
ID int32 `bson:"_id"`
UUID string `bson:"uuid"`
LastHeartbeatTS bson.MongoTimestamp `bson:"last-heartbeat-ts"`
HeartbeatTimeout int32 `bson:"heartbeat-timeout"`
Version int64 `bson:"version"`
}
type isMasterResult struct {
IsMaster bool `bson:"isMaster"`
LocalTime time.Time `bson:"localTime"`
OK bool `bson:"ok"`
}
type messagingGroupObject struct {
ID string `bson:"_id"`
GroupName string `bson:"group-name"`
LastUpdate bson.MongoTimestamp `bson:"last-update"`
}
// This is almost the same type as common.StoredOrganization except for the timestamp type.
// We use this type here to avoid dependency on bson in common.
type organizationObject struct {
ID string `bson:"_id"`
Organization common.Organization `bson:"org"`
LastUpdate bson.MongoTimestamp `bson:"last-update"`
}
type webhookObject struct {
ID string `bson:"_id"`
Hooks []string `bson:"hooks"`
LastUpdate bson.MongoTimestamp `bson:"last-update"`
}
type aclObject struct {
ID string `bson:"_id"`
Users []common.ACLentry `bson:"users"`
OrgID string `bson:"org-id"`
ACLType string `bson:"acl-type"`
LastUpdate bson.MongoTimestamp `bson:"last-update"`
}
const maxUpdateTries = 5
var sleepInMS int
// Init initializes the MongoStorage store
func (store *MongoStorage) Init() common.SyncServiceError {
store.lockChannel = make(chan int, 1)
store.lockChannel <- 1
store.mapLock = make(chan int, 1)
store.mapLock <- 1
store.dialInfo = &mgo.DialInfo{
Addrs: strings.Split(common.Configuration.MongoAddressCsv, ","),
Source: common.Configuration.MongoAuthDbName,
Username: common.Configuration.MongoUsername,
Password: common.Configuration.MongoPassword,
Timeout: time.Duration(20 * time.Second),
ReadTimeout: time.Duration(60 * time.Second),
WriteTimeout: time.Duration(60 * time.Second),
}
if common.Configuration.MongoUseSSL {
tlsConfig := &tls.Config{}
if common.Configuration.MongoCACertificate != "" {
var caFile string
if strings.HasPrefix(common.Configuration.MongoCACertificate, "/") {
caFile = common.Configuration.MongoCACertificate
} else {
caFile = common.Configuration.PersistenceRootPath + common.Configuration.MongoCACertificate
}
serverCaCert, err := ioutil.ReadFile(caFile)
if err != nil {
if _, ok := err.(*os.PathError); ok {
serverCaCert = []byte(common.Configuration.MongoCACertificate)
err = nil
} else {
message := fmt.Sprintf("Failed to find mongo SSL CA file. Error: %s.", err)
return &Error{message}
}
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(serverCaCert)
tlsConfig.RootCAs = caCertPool
}
// Please avoid using this if possible! Makes using TLS pointless
if common.Configuration.MongoAllowInvalidCertificates {
tlsConfig.InsecureSkipVerify = true
}
store.dialInfo.DialServer = func(addr *mgo.ServerAddr) (net.Conn, error) {
return tls.Dial("tcp", addr.String(), tlsConfig)
}
}
var session *mgo.Session
var err error
if trace.IsLogging(logger.INFO) {
trace.Info("Connecting to mongo...")
}
for connectTime := 0; connectTime < common.Configuration.DatabaseConnectTimeout; connectTime += 10 {
session, err = mgo.DialWithInfo(store.dialInfo)
if err == nil {
break
}
if connectTime == 0 && trace.IsLogging(logger.ERROR) {
trace.Error("Failed to dial mgo. Error: " + err.Error())
}
if strings.HasPrefix(err.Error(), "unauthorized") ||
strings.HasPrefix(err.Error(), "not authorized") ||
strings.HasPrefix(err.Error(), "auth fail") ||
strings.HasPrefix(err.Error(), "Authentication failed") {
break
}
if connectTime == 0 && trace.IsLogging(logger.ERROR) {
trace.Error("Retrying to connect to mongo")
}
}
if session == nil {
message := fmt.Sprintf("Failed to dial mgo. Error: %s.", err)
return &Error{message}
}
store.connected = true
common.HealthStatus.ReconnectedToDatabase()
if trace.IsLogging(logger.INFO) {
trace.Info("Connected to the database")
}
if log.IsLogging(logger.INFO) {
log.Info("Connected to the database")
}
session.SetSafe(&mgo.Safe{})
//session.SetMode(mgo.Monotonic, true)
db := session.DB(common.Configuration.MongoDbName)
db.C(destinations).EnsureIndexKey("destination.destination-org-id")
notificationsCollection := db.C(notifications)
notificationsCollection.EnsureIndexKey("notification.destination-org-id", "notification.destination-id", "notification.destination-type")
notificationsCollection.EnsureIndexKey("notification.resend-time", "notification.status")
objectsCollection := db.C(objects)
objectsCollection.EnsureIndexKey("metadata.destination-org-id")
err = objectsCollection.EnsureIndex(
mgo.Index{
Key: []string{
"metadata.destination-org-id",
"metadata.destination-policy.services.org-id",
"metadata.destination-policy.services.service-name",
},
Name: "syncObjects-destination-policy.services.service-id",
Unique: false,
DropDups: false,
Background: false,
Sparse: true,
})
if err != nil {
log.Error("Failed to create an index on %s. Error: %s", objects, err)
}
err = objectsCollection.EnsureIndex(
mgo.Index{
Key: []string{
"metadata.destination-org-id",
"metadata.destination-policy.timestamp",
},
Unique: false,
DropDups: false,
Background: false,
Sparse: true,
})
if err != nil {
log.Error("Failed to create an index on %s. Error: %s", objects, err)
}
db.C(acls).EnsureIndexKey("org-id", "acl-type")
store.session = session
store.cacheSize = common.Configuration.MongoSessionCacheSize
if store.cacheSize > 1 {
store.sessionCache = make([]*mgo.Session, store.cacheSize)
for i := 0; i < store.cacheSize; i++ {
store.sessionCache[i] = store.session.Copy()
}
}
store.openFiles = make(map[string]*fileHandle)
sleepInMS = common.Configuration.MongoSleepTimeBetweenRetry
if trace.IsLogging(logger.TRACE) {
trace.Trace("Successfully initialized mongo driver")
}
return nil
}
// Stop stops the MongoStorage store
func (store *MongoStorage) Stop() {
if store.cacheSize > 1 {
for i := 0; i < store.cacheSize; i++ {
store.sessionCache[i].Close()
}
}
store.session.Close()
}
// PerformMaintenance performs store's maintenance
func (store *MongoStorage) PerformMaintenance() {
store.checkObjects()
}
// Cleanup erase the on disk Bolt database only for ESS and test
func (store *MongoStorage) Cleanup(isTest bool) common.SyncServiceError {
return nil
}
// GetObjectsToActivate returns inactive objects that are ready to be activated
func (store *MongoStorage) GetObjectsToActivate() ([]common.MetaData, common.SyncServiceError) {
currentTime := time.Now().UTC().Format(time.RFC3339)
query := bson.M{"$or": []bson.M{
bson.M{"status": common.NotReadyToSend},
bson.M{"status": common.ReadyToSend}},
"metadata.inactive": true,
"$and": []bson.M{
bson.M{"metadata.activation-time": bson.M{"$ne": ""}},
bson.M{"metadata.activation-time": bson.M{"$lte": currentTime}}}}
selector := bson.M{"metadata": bson.ElementDocument}
result := []object{}
if err := store.fetchAll(objects, query, selector, &result); err != nil {
return nil, err
}
metaDatas := make([]common.MetaData, len(result))
for i, r := range result {
metaDatas[i] = r.MetaData
}
return metaDatas, nil
}
// StoreObject stores an object
// If the object already exists, return the changes in its destinations list (for CSS) - return the list of deleted destinations
func (store *MongoStorage) StoreObject(metaData common.MetaData, data []byte, status string) ([]common.StoreDestinationStatus, common.SyncServiceError) {
id := getObjectCollectionID(metaData)
if !metaData.NoData && data != nil {
if err := store.storeDataInFile(id, data); err != nil {
return nil, err
}
} else if !metaData.MetaOnly {
store.removeFile(id)
}
if metaData.DestinationPolicy != nil {
metaData.DestinationPolicy.Timestamp = time.Now().UTC().UnixNano()
}
var dests []common.StoreDestinationStatus
var deletedDests []common.StoreDestinationStatus
if status == common.NotReadyToSend || status == common.ReadyToSend {
// The object was receieved from a service, i.e. this node is the origin of the object:
// set its instance id and create destinations array
newID := store.getInstanceID()
metaData.InstanceID = newID
if data != nil && !metaData.NoData && !metaData.MetaOnly {
metaData.DataID = newID
}
var err error
dests, deletedDests, err = createDestinationsFromMeta(store, metaData)
if err != nil {
return nil, err
}
}
existingObject := &object{}
if err := store.fetchOne(objects, bson.M{"_id": id}, nil, existingObject); err != nil {
if err != mgo.ErrNotFound {
return nil, &Error{fmt.Sprintf("Failed to retrieve object's status. Error: %s.", err)}
}
existingObject = nil
}
if existingObject != nil {
if (metaData.DestinationPolicy != nil && existingObject.MetaData.DestinationPolicy == nil) ||
(metaData.DestinationPolicy == nil && existingObject.MetaData.DestinationPolicy != nil) {
return nil, &common.InvalidRequest{Message: "Can't update the existence of Destination Policy"}
}
if metaData.MetaOnly {
metaData.DataID = existingObject.MetaData.DataID
metaData.ObjectSize = existingObject.MetaData.ObjectSize
metaData.ChunkSize = existingObject.MetaData.ChunkSize
metaData.PublicKey = existingObject.MetaData.PublicKey
metaData.Signature = existingObject.MetaData.Signature
}
if metaData.DestinationPolicy != nil {
dests = existingObject.Destinations
}
}
newObject := object{ID: id, MetaData: metaData, Status: status, PolicyReceived: false,
RemainingConsumers: metaData.ExpectedConsumers,
RemainingReceivers: metaData.ExpectedConsumers, Destinations: dests}
if err := store.upsert(objects, bson.M{"_id": id, "metadata.destination-org-id": metaData.DestOrgID}, newObject); err != nil {
return nil, &Error{fmt.Sprintf("Failed to store an object. Error: %s.", err)}
}
return deletedDests, nil
}
// GetObjectDestinations gets destinations that the object has to be sent to
func (store *MongoStorage) GetObjectDestinations(metaData common.MetaData) ([]common.Destination, common.SyncServiceError) {
result := object{}
id := getObjectCollectionID(metaData)
if err := store.fetchOne(objects, bson.M{"_id": id}, bson.M{"destinations": bson.ElementArray}, &result); err != nil {
switch err {
case mgo.ErrNotFound:
return nil, nil
default:
return nil, &Error{fmt.Sprintf("Failed to retrieve object's destinations. Error: %s.", err)}
}
}
dests := make([]common.Destination, 0)
for _, d := range result.Destinations {
dests = append(dests, d.Destination)
}
return dests, nil
}
// GetObjectDestinationsList gets destinations that the object has to be sent to and their status
func (store *MongoStorage) GetObjectDestinationsList(orgID string, objectType string,
objectID string) ([]common.StoreDestinationStatus, common.SyncServiceError) {
result := object{}
id := createObjectCollectionID(orgID, objectType, objectID)
if err := store.fetchOne(objects, bson.M{"_id": id}, bson.M{"destinations": bson.ElementArray}, &result); err != nil {
switch err {
case mgo.ErrNotFound:
return nil, nil
default:
return nil, &Error{fmt.Sprintf("Failed to retrieve object's destinations. Error: %s.", err)}
}
}
return result.Destinations, nil
}
// UpdateObjectDestinations updates object's destinations
// Returns the meta data, object's status, an array of deleted destinations, and an array of added destinations
func (store *MongoStorage) UpdateObjectDestinations(orgID string, objectType string, objectID string, destinationsList []string) (*common.MetaData, string,
[]common.StoreDestinationStatus, []common.StoreDestinationStatus, common.SyncServiceError) {
result := object{}
id := createObjectCollectionID(orgID, objectType, objectID)
selector := bson.M{"metadata": bson.ElementDocument, "destinations": bson.ElementArray, "last-update": bson.ElementTimestamp, "status": bson.ElementString}
for i := 0; i < maxUpdateTries; i++ {
if err := store.fetchOne(objects, bson.M{"_id": id}, selector, &result); err != nil {
return nil, "", nil, nil, &Error{fmt.Sprintf("Failed to retrieve object's destinations. Error: %s.", err)}
}
dests, deletedDests, addedDests, err := createDestinations(orgID, store, result.Destinations, destinationsList)
if err != nil {
return nil, "", nil, nil, err
}
query := bson.M{
"$set": bson.M{"destinations": dests},
"$currentDate": bson.M{"last-update": bson.M{"$type": "timestamp"}},
}
if err := store.update(objects, bson.M{"_id": id, "last-update": result.LastUpdate}, query); err != nil {
if err == mgo.ErrNotFound {
time.Sleep(time.Duration(sleepInMS) * time.Millisecond)
continue
}
return nil, "", nil, nil, &Error{fmt.Sprintf("Failed to update object's destinations. Error: %s.", err)}
}
return &result.MetaData, result.Status, deletedDests, addedDests, nil
}
return nil, "", nil, nil, &Error{"Failed to update object's destinations."}
}
// AddObjectdestinations adds the destinations to object's destination list
// Returns the metadata, object's status, an array of added destinations after removing the overlapped destinations
func (store *MongoStorage) AddObjectDestinations(orgID string, objectType string, objectID string, destinationsList []string) (*common.MetaData, string, []common.StoreDestinationStatus, common.SyncServiceError) {
result := object{}
id := createObjectCollectionID(orgID, objectType, objectID)
selector := bson.M{"metadata": bson.ElementDocument, "destinations": bson.ElementArray, "last-update": bson.ElementTimestamp, "status": bson.ElementString}
for i := 0; i < maxUpdateTries; i++ {
if err := store.fetchOne(objects, bson.M{"_id": id}, selector, &result); err != nil {
return nil, "", nil, &Error{fmt.Sprintf("Failed to retrieve object's destinations. Error: %s.", err)}
}
updatedDests, addedDests, err := getDestinationsForAdd(orgID, store, result.Destinations, destinationsList)
if err != nil {
return nil, "", nil, err
}
query := bson.M{
"$set": bson.M{"destinations": updatedDests},
"$currentDate": bson.M{"last-update": bson.M{"$type": "timestamp"}},
}
if err := store.update(objects, bson.M{"_id": id, "last-update": result.LastUpdate}, query); err != nil {
if err == mgo.ErrNotFound {
time.Sleep(time.Duration(sleepInMS) * time.Millisecond)
continue
}
return nil, "", nil, &Error{fmt.Sprintf("Failed to add destinations to object's destinations list. Error: %s.", err)}
}
return &result.MetaData, result.Status, addedDests, nil
}
return nil, "", nil, &Error{"Failed to add destinations to object's destination list."}
}
// DeleteObjectdestinations deletes the destinations from object's destination list
// Returns the metadata, objects' status, an array of destinations that removed from the current destination list
func (store *MongoStorage) DeleteObjectDestinations(orgID string, objectType string, objectID string, destinationsList []string) (*common.MetaData, string, []common.StoreDestinationStatus, common.SyncServiceError) {
result := object{}
id := createObjectCollectionID(orgID, objectType, objectID)
selector := bson.M{"metadata": bson.ElementDocument, "destinations": bson.ElementArray, "last-update": bson.ElementTimestamp, "status": bson.ElementString}
for i := 0; i < maxUpdateTries; i++ {
if err := store.fetchOne(objects, bson.M{"_id": id}, selector, &result); err != nil {
return nil, "", nil, &Error{fmt.Sprintf("Failed to retrieve object's destinations. Error: %s.", err)}
}
updatedDests, deletedDests, err := getDestinationsForDelete(orgID, store, result.Destinations, destinationsList)
if err != nil {
return nil, "", nil, err
}
query := bson.M{
"$set": bson.M{"destinations": updatedDests},
"$currentDate": bson.M{"last-update": bson.M{"$type": "timestamp"}},
}
if err := store.update(objects, bson.M{"_id": id, "last-update": result.LastUpdate}, query); err != nil {
if err == mgo.ErrNotFound {
time.Sleep(time.Duration(sleepInMS) * time.Millisecond)
continue
}
return nil, "", nil, &Error{fmt.Sprintf("Failed to delete destinations from object's destinations list. Error: %s.", err)}
}
return &result.MetaData, result.Status, deletedDests, nil
}
return nil, "", nil, &Error{"Failed to delete destinations from object's destination list."}
}
// UpdateObjectDeliveryStatus changes the object's delivery status and message for the destination
// Returns true if the status is Deleted and all the destinations are in status Deleted
func (store *MongoStorage) UpdateObjectDeliveryStatus(status string, message string, orgID string, objectType string, objectID string,
destType string, destID string) (bool, common.SyncServiceError) {
if status == "" && message == "" {
return false, nil
}
result := object{}
id := createObjectCollectionID(orgID, objectType, objectID)
allDeleted := true
for i := 0; i < maxUpdateTries; i++ {
if err := store.fetchOne(objects, bson.M{"_id": id},
bson.M{"metadata": bson.ElementDocument, "destinations": bson.ElementArray, "last-update": bson.ElementTimestamp},
&result); err != nil {
return false, &Error{fmt.Sprintf("Failed to retrieve object. Error: %s.", err)}
}
found := false
allConsumed := true
allDeleted = true
for i, d := range result.Destinations {
if !found && d.Destination.DestType == destType && d.Destination.DestID == destID {
d.Message = message
if status != "" {
d.Status = status
}
found = true
result.Destinations[i] = d
} else {
if d.Status != common.Consumed {
allConsumed = false
}
if d.Status != common.Deleted {
allDeleted = false
}
}
}
if !found {
return false, &Error{"Failed to find destination."}
}
query := bson.M{
"$set": bson.M{"destinations": result.Destinations},
"$currentDate": bson.M{"last-update": bson.M{"$type": "timestamp"}},
}
if result.MetaData.AutoDelete && status == common.Consumed && allConsumed && result.MetaData.Expiration == "" {
// Delete the object by setting its expiration time to one hour
expirationTime := time.Now().Add(time.Hour * time.Duration(1)).UTC().Format(time.RFC3339)
query = bson.M{
"$set": bson.M{"destinations": result.Destinations, "metadata.expiration": expirationTime},
"$currentDate": bson.M{"last-update": bson.M{"$type": "timestamp"}},
}
}
if err := store.update(objects, bson.M{"_id": id, "last-update": result.LastUpdate}, query); err != nil {
if err == mgo.ErrNotFound {
time.Sleep(time.Duration(sleepInMS) * time.Millisecond)
continue
}
return false, &Error{fmt.Sprintf("Failed to update object's destinations. Error: %s.", err)}
}
return (allDeleted && status == common.Deleted), nil
}
return false, &Error{"Failed to update object's destinations."}
}
// UpdateObjectDelivering marks the object as being delivered to all its destinations
func (store *MongoStorage) UpdateObjectDelivering(orgID string, objectType string, objectID string) common.SyncServiceError {
result := object{}
id := createObjectCollectionID(orgID, objectType, objectID)
for i := 0; i < maxUpdateTries; i++ {
if err := store.fetchOne(objects, bson.M{"_id": id},
bson.M{"destinations": bson.ElementArray, "last-update": bson.ElementTimestamp},
&result); err != nil {
return &Error{fmt.Sprintf("Failed to retrieve object. Error: %s.", err)}
}
for i, d := range result.Destinations {
d.Status = common.Delivering
result.Destinations[i] = d
}
if err := store.update(objects, bson.M{"_id": id, "last-update": result.LastUpdate},
bson.M{
"$set": bson.M{"destinations": result.Destinations},
"$currentDate": bson.M{"last-update": bson.M{"$type": "timestamp"}},
}); err != nil {
if err == mgo.ErrNotFound {
time.Sleep(time.Duration(sleepInMS) * time.Millisecond)
continue
}
return &Error{fmt.Sprintf("Failed to update object's destinations. Error: %s.", err)}
}
return nil
}
return &Error{fmt.Sprintf("Failed to update object's destinations.")}
}
// RetrieveObjectStatus finds the object and return its status
func (store *MongoStorage) RetrieveObjectStatus(orgID string, objectType string, objectID string) (string, common.SyncServiceError) {
result := object{}
id := createObjectCollectionID(orgID, objectType, objectID)
if err := store.fetchOne(objects, bson.M{"_id": id}, bson.M{"status": bson.ElementString}, &result); err != nil {
switch err {
case mgo.ErrNotFound:
return "", nil
default:
return "", &Error{fmt.Sprintf("Failed to retrieve object's status. Error: %s.", err)}
}
}
return result.Status, nil
}
// RetrieveObjectRemainingConsumers finds the object and returns the number remaining consumers that
// haven't consumed the object yet
func (store *MongoStorage) RetrieveObjectRemainingConsumers(orgID string, objectType string, objectID string) (int, common.SyncServiceError) {
result := object{}
id := createObjectCollectionID(orgID, objectType, objectID)
if err := store.fetchOne(objects, bson.M{"_id": id}, bson.M{"remaining-consumers": bson.ElementInt32}, &result); err != nil {
return 0, &Error{fmt.Sprintf("Failed to retrieve object's remaining comsumers. Error: %s.", err)}
}
return result.RemainingConsumers, nil
}
// DecrementAndReturnRemainingConsumers decrements the number of remaining consumers of the object
func (store *MongoStorage) DecrementAndReturnRemainingConsumers(orgID string, objectType string, objectID string) (int,
common.SyncServiceError) {
id := createObjectCollectionID(orgID, objectType, objectID)
if err := store.update(objects, bson.M{"_id": id},
bson.M{
"$inc": bson.M{"remaining-consumers": -1},
"$currentDate": bson.M{"last-update": bson.M{"$type": "timestamp"}},
}); err != nil {
return 0, &Error{fmt.Sprintf("Failed to decrement object's remaining consumers. Error: %s.", err)}
}
result := object{}
if err := store.fetchOne(objects, bson.M{"_id": id}, bson.M{"remaining-consumers": bson.ElementInt32}, &result); err != nil {
return 0, &Error{fmt.Sprintf("Failed to retrieve object's remaining consumers. Error: %s.", err)}
}
return result.RemainingConsumers, nil
}
// DecrementAndReturnRemainingReceivers decrements the number of remaining receivers of the object
func (store *MongoStorage) DecrementAndReturnRemainingReceivers(orgID string, objectType string, objectID string) (int,
common.SyncServiceError) {
id := createObjectCollectionID(orgID, objectType, objectID)
if err := store.update(objects, bson.M{"_id": id},
bson.M{
"$inc": bson.M{"remaining-receivers": -1},
"$currentDate": bson.M{"last-update": bson.M{"$type": "timestamp"}},
}); err != nil {
return 0, &Error{fmt.Sprintf("Failed to decrement object's remaining receivers. Error: %s.", err)}
}
result := object{}
if err := store.fetchOne(objects, bson.M{"_id": id}, bson.M{"remaining-receivers": bson.ElementInt32}, &result); err != nil {
return 0, &Error{fmt.Sprintf("Failed to retrieve object's remaining receivers. Error: %s.", err)}
}
return result.RemainingReceivers, nil
}
// ResetObjectRemainingConsumers sets the remaining consumers count to the original ExpectedConsumers value
func (store *MongoStorage) ResetObjectRemainingConsumers(orgID string, objectType string, objectID string) common.SyncServiceError {
id := createObjectCollectionID(orgID, objectType, objectID)
result := object{}
if err := store.fetchOne(objects, bson.M{"_id": id}, bson.M{"metadata": bson.ElementDocument}, &result); err != nil {
return &Error{fmt.Sprintf("Failed to retrieve object. Error: %s.", err)}
}
if err := store.update(objects, bson.M{"_id": id},
bson.M{
"$set": bson.M{"remaining-consumers": result.MetaData.ExpectedConsumers},
"$currentDate": bson.M{"last-update": bson.M{"$type": "timestamp"}},
}); err != nil {
return &Error{fmt.Sprintf("Failed to reset object's remaining comsumers. Error: %s.", err)}
}
return nil
}
// RetrieveUpdatedObjects returns the list of all the edge updated objects that are not marked as consumed or received
// If received is true, return objects marked as received
func (store *MongoStorage) RetrieveUpdatedObjects(orgID string, objectType string, received bool) ([]common.MetaData, common.SyncServiceError) {
result := []object{}
var query interface{}
if received {
query = bson.M{"$or": []bson.M{
bson.M{"status": common.CompletelyReceived},
bson.M{"status": common.ObjReceived},
bson.M{"status": common.ObjDeleted}},
"metadata.destination-org-id": orgID, "metadata.object-type": objectType}
} else {
query = bson.M{"$or": []bson.M{
bson.M{"status": common.CompletelyReceived},
bson.M{"status": common.ObjDeleted}},
"metadata.destination-org-id": orgID, "metadata.object-type": objectType}
}
if err := store.fetchAll(objects, query, nil, &result); err != nil {
switch err {
case mgo.ErrNotFound:
return nil, nil
default:
return nil, &Error{fmt.Sprintf("Failed to fetch the objects. Error: %s.", err)}
}
}
metaDatas := make([]common.MetaData, len(result))
for i, r := range result {
metaDatas[i] = r.MetaData
}
return metaDatas, nil
}
// RetrieveObjectsWithDestinationPolicy returns the list of all the objects that have a Destination Policy
// If received is true, return objects marked as policy received
func (store *MongoStorage) RetrieveObjectsWithDestinationPolicy(orgID string, received bool) ([]common.ObjectDestinationPolicy, common.SyncServiceError) {
var query interface{}
if received {
query = bson.M{
"metadata.destination-org-id": orgID,
"$and": []bson.M{
bson.M{"status": bson.M{"$ne": common.ObjDeleted}},
bson.M{"metadata.destination-policy": bson.M{"$ne": nil}},
},
}
} else {
query = bson.M{
"metadata.destination-org-id": orgID,
"policy-received": false,
"$and": []bson.M{
bson.M{"status": bson.M{"$ne": common.ObjDeleted}},
bson.M{"metadata.destination-policy": bson.M{"$ne": nil}},
},
}
}
return store.retrievePolicies(query)
}
// RetrieveObjectsWithDestinationPolicyByService returns the list of all the object Policies for a particular service
func (store *MongoStorage) RetrieveObjectsWithDestinationPolicyByService(orgID, serviceOrgID, serviceName string) ([]common.ObjectDestinationPolicy, common.SyncServiceError) {
subquery := bson.M{
"$elemMatch": bson.M{
"org-id": serviceOrgID,
"service-name": serviceName,
},
}
query := bson.M{
"metadata.destination-org-id": orgID,
"metadata.destination-policy.services": subquery,
}
return store.retrievePolicies(query)
}
// RetrieveObjectsWithDestinationPolicyUpdatedSince returns the list of all the objects that have a Destination Policy updated since the specified time
func (store *MongoStorage) RetrieveObjectsWithDestinationPolicyUpdatedSince(orgID string, since int64) ([]common.ObjectDestinationPolicy, common.SyncServiceError) {
query := bson.M{
"metadata.destination-org-id": orgID,
"metadata.destination-policy.timestamp": bson.M{"$gte": since},
}
return store.retrievePolicies(query)
}
// RetrieveObjectsWithFilters returns the list of all the objects that meet the given conditions
func (store *MongoStorage) RetrieveObjectsWithFilters(orgID string, destinationPolicy *bool, dpServiceOrgID string, dpServiceName string, dpPropertyName string, since int64, objectType string, objectID string, destinationType string, destinationID string, noData *bool, expirationTimeBefore string, deleted *bool) ([]common.MetaData, common.SyncServiceError) {
result := []object{}
query := bson.M{
"metadata.destination-org-id": orgID,
}
if destinationPolicy != nil {
if *destinationPolicy {
query["metadata.destination-policy"] = bson.M{"$ne": nil}
query["metadata.destination-policy.timestamp"] = bson.M{"$gte": since}
if dpServiceOrgID != "" && dpServiceName != "" {
subquery := bson.M{
"$elemMatch": bson.M{
"org-id": dpServiceOrgID,
"service-name": dpServiceName,
},
}
query["metadata.destination-policy.services"] = subquery
}
if dpPropertyName != "" {
query["metadata.destination-policy.properties.name"] = dpPropertyName
}
} else {
query["metadata.destination-policy"] = nil
}
}
if objectType != "" {
query["metadata.object-type"] = objectType
if objectID != "" {
query["metadata.object-id"] = objectID
}
}
if destinationType != "" {
var subquery []bson.M
if destinationID == "" {
subquery = []bson.M{
bson.M{"metadata.destination-type": destinationType},
bson.M{"metadata.destinations-list": bson.M{"$regex": destinationType + ":*"}},
}
} else {
subquery = []bson.M{
bson.M{"metadata.destination-type": destinationType, "metadata.destination-id": destinationID},
bson.M{"metadata.destinations-list": destinationType + ":" + destinationID},
}
}
query["$or"] = subquery
}
if noData != nil {
query["metadata.no-data"] = *noData
}
if expirationTimeBefore != "" {
subquery := bson.M{
"$ne": "",
"$lte": expirationTimeBefore,
}
query["metadata.expiration"] = subquery
}
if deleted != nil {
query["metadata.deleted"] = *deleted
}
if err := store.fetchAll(objects, query, nil, &result); err != nil {
switch err {
case mgo.ErrNotFound:
return nil, nil
default:
return nil, &Error{fmt.Sprintf("Failed to fetch the objects. Error: %s.", err)}
}
}
metaDatas := make([]common.MetaData, len(result))
for i, r := range result {
metaDatas[i] = r.MetaData
}
return metaDatas, nil
}
// RetrieveAllObjects returns the list of all the objects of the specified type
func (store *MongoStorage) RetrieveAllObjects(orgID string, objectType string) ([]common.ObjectDestinationPolicy, common.SyncServiceError) {
query := bson.M{
"metadata.destination-org-id": orgID,
"metadata.object-type": objectType,
}
return store.retrievePolicies(query)
}
// RetrieveObjects returns the list of all the objects that need to be sent to the destination.
// Adds the new destination to the destinations lists of the relevant objects.
func (store *MongoStorage) RetrieveObjects(orgID string, destType string, destID string, resend int) ([]common.MetaData, common.SyncServiceError) {
result := []object{}
query := bson.M{"metadata.destination-org-id": orgID,
"$or": []bson.M{
bson.M{"status": common.ReadyToSend},
bson.M{"status": common.NotReadyToSend},
}}
OUTER:
for i := 0; i < maxUpdateTries; i++ {
if err := store.fetchAll(objects, query, nil, &result); err != nil {
switch err {
case mgo.ErrNotFound:
return nil, nil
default:
return nil, &Error{fmt.Sprintf("Failed to fetch the objects. Error: %s.", err)}
}
}
metaDatas := make([]common.MetaData, 0)
for _, r := range result {
if r.MetaData.DestinationPolicy != nil {
continue
}
if (r.MetaData.DestType == "" || r.MetaData.DestType == destType) &&
(r.MetaData.DestID == "" || r.MetaData.DestID == destID) {
status := common.Pending
if r.Status == common.ReadyToSend && !r.MetaData.Inactive {
status = common.Delivering
}
needToUpdate := false
// Add destination if it doesn't exist
if dest, err := store.RetrieveDestination(orgID, destType, destID); err == nil {
existingDestIndex := -1
for i, d := range r.Destinations {
if d.Destination == *dest {
existingDestIndex = i
break
}
}
if existingDestIndex != -1 {
d := r.Destinations[existingDestIndex]
if status == common.Delivering &&
(resend == common.ResendAll || (resend == common.ResendDelivered && d.Status != common.Consumed) ||
(resend == common.ResendUndelivered && d.Status != common.Consumed && d.Status != common.Delivered)) {
metaDatas = append(metaDatas, r.MetaData)
r.Destinations[existingDestIndex].Status = common.Delivering
needToUpdate = true
}
} else {
if status == common.Delivering {
metaDatas = append(metaDatas, r.MetaData)
}
needToUpdate = true
r.Destinations = append(r.Destinations, common.StoreDestinationStatus{Destination: *dest, Status: status})
}
if needToUpdate {
id := createObjectCollectionID(orgID, r.MetaData.ObjectType, r.MetaData.ObjectID)
if err := store.update(objects, bson.M{"_id": id, "last-update": r.LastUpdate},
bson.M{
"$set": bson.M{"destinations": r.Destinations},
"$currentDate": bson.M{"last-update": bson.M{"$type": "timestamp"}},
}); err != nil {
if err == mgo.ErrNotFound {
time.Sleep(time.Duration(sleepInMS) * time.Millisecond)
continue OUTER
}
return nil, &Error{fmt.Sprintf("Failed to update object's destinations. Error: %s.", err)}
}
}
}
}
}
return metaDatas, nil
}
return nil, &Error{fmt.Sprintf("Failed to update object's destinations.")}
}
// RetrieveConsumedObjects returns all the consumed objects originated from this node
// ESS only API
func (store *MongoStorage) RetrieveConsumedObjects() ([]common.ConsumedObject, common.SyncServiceError) {
return nil, nil
}
// RetrieveObject returns the object meta data with the specified parameters
func (store *MongoStorage) RetrieveObject(orgID string, objectType string, objectID string) (*common.MetaData, common.SyncServiceError) {
result := object{}
id := createObjectCollectionID(orgID, objectType, objectID)
if err := store.fetchOne(objects, bson.M{"_id": id}, bson.M{"metadata": bson.ElementDocument}, &result); err != nil {
switch err {
case mgo.ErrNotFound:
return nil, nil
default:
return nil, &Error{fmt.Sprintf("Failed to fetch the object. Error: %s.", err)}
}
}
return &result.MetaData, nil
}
// RetrieveObjectAndStatus returns the object meta data and status with the specified parameters
func (store *MongoStorage) RetrieveObjectAndStatus(orgID string, objectType string, objectID string) (*common.MetaData, string, common.SyncServiceError) {
result := object{}
id := createObjectCollectionID(orgID, objectType, objectID)
if err := store.fetchOne(objects, bson.M{"_id": id}, nil, &result); err != nil {
switch err {
case mgo.ErrNotFound:
return nil, "", nil
default:
return nil, "", &Error{fmt.Sprintf("Failed to fetch the object. Error: %s.", err)}
}
}
return &result.MetaData, result.Status, nil
}
// RetrieveObjectData returns the object data with the specified parameters
func (store *MongoStorage) RetrieveObjectData(orgID string, objectType string, objectID string) (io.Reader, common.SyncServiceError) {
id := createObjectCollectionID(orgID, objectType, objectID)
fileHandle, err := store.openFile(id)
if err != nil {
switch err {
case mgo.ErrNotFound:
return nil, nil
default:
return nil, &Error{fmt.Sprintf("Failed to open file to read the data. Error: %s.", err)}
}
}
store.putFileHandle(id, fileHandle)
return fileHandle.file, nil
}
// CloseDataReader closes the data reader if necessary
func (store *MongoStorage) CloseDataReader(dataReader io.Reader) common.SyncServiceError {
switch v := dataReader.(type) {