forked from open-horizon/edge-sync-service
/
boltStorage.go
2076 lines (1848 loc) · 68.1 KB
/
boltStorage.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 (
"bytes"
"encoding/json"
"fmt"
"io"
"os"
"strings"
"time"
"github.com/open-horizon/edge-sync-service/common"
"github.com/open-horizon/edge-sync-service/core/dataURI"
"github.com/open-horizon/edge-utilities/logger"
"github.com/open-horizon/edge-utilities/logger/log"
"github.com/open-horizon/edge-utilities/logger/trace"
bolt "go.etcd.io/bbolt"
)
const timebaseBucketName = "syncTimebase"
// BoltStorage is a Bolt based store
type BoltStorage struct {
db *bolt.DB
timebase int64
lockChannel chan int
localDataPath string
}
type boltObject struct {
Meta common.MetaData `json:"meta"`
Status string `json:"status"`
PolicyReceived bool `json:"policy-received"`
RemainingConsumers int `json:"remaining-consumers"`
RemainingReceivers int `json:"remaining-receivers"`
DataPath string `json:"data-path"`
ConsumedTimestamp time.Time `json:"consumed-timestamp"`
Destinations []common.StoreDestinationStatus `json:"destinations"`
RemovedDestinationPolicyServices []common.ServiceID `json:"removed-destination-policy-services"`
}
type boltDestination struct {
Destination common.Destination `json:"destination"`
LastPingTime time.Time `json:"last-ping-time"`
}
type boltMessagingGroup struct {
OrgID string `json:"orgid"`
GroupName string `json:"group-name"`
LastUpdate time.Time `json:"last-update"`
}
type boltACL struct {
Users []common.ACLentry `json:"users"`
OrgID string `json:"org-id"`
ACLType string `json:"acl-type"`
Key string `json:"key"`
}
var (
objectsBucket []byte
webhooksBucket []byte
notificationsBucket []byte
timebaseBucket []byte
destinationsBucket []byte
messagingGroupsBucket []byte
organizationsBucket []byte
aclBucket []byte
)
// Init initializes the Bolt store
func (store *BoltStorage) Init() common.SyncServiceError {
store.lockChannel = make(chan int, 1)
store.lockChannel <- 1
path := common.Configuration.PersistenceRootPath + "/sync/db/"
err := os.MkdirAll(path, 0750)
if err != nil {
return err
}
name := "css-sync.db"
if common.Configuration.NodeType == common.ESS {
name = "ess-sync.db"
}
store.db, err = bolt.Open(path+name, 0600, nil)
if err != nil {
return err
}
objectsBucket = []byte(objects)
webhooksBucket = []byte(webhooks)
notificationsBucket = []byte(notifications)
timebaseBucket = []byte(timebaseBucketName)
destinationsBucket = []byte(destinations)
messagingGroupsBucket = []byte(messagingGroups)
organizationsBucket = []byte(organizations)
aclBucket = []byte(acls)
err = store.db.Update(func(tx *bolt.Tx) error {
_, err = tx.CreateBucketIfNotExists(objectsBucket)
if err != nil {
return err
}
_, err = tx.CreateBucketIfNotExists(webhooksBucket)
if err != nil {
return err
}
_, err = tx.CreateBucketIfNotExists(notificationsBucket)
if err != nil {
return err
}
_, err = tx.CreateBucketIfNotExists(destinationsBucket)
if err != nil {
return err
}
_, err = tx.CreateBucketIfNotExists(messagingGroupsBucket)
if err != nil {
return err
}
_, err = tx.CreateBucketIfNotExists(organizationsBucket)
if err != nil {
return err
}
_, err = tx.CreateBucketIfNotExists(aclBucket)
if err != nil {
return err
}
b, err := tx.CreateBucketIfNotExists(timebaseBucket)
if err != nil {
return err
}
currentTime := time.Now().UnixNano()
store.timebase = currentTime
currentTimeInSeconds := currentTime / 1e9
persistedTimeBase := currentTimeInSeconds
encoded := b.Get([]byte("timebase"))
if encoded != nil {
if err := json.Unmarshal(encoded, &persistedTimeBase); err == nil &&
currentTimeInSeconds <= persistedTimeBase {
persistedTimeBase++
store.timebase = persistedTimeBase * 1e9
}
}
encoded, err = json.Marshal(persistedTimeBase)
if err != nil {
return err
}
err = tx.Bucket(timebaseBucket).Put([]byte("timebase"), []byte(encoded))
return err
})
if err != nil {
return err
}
if len(common.Configuration.ObjectsDataPath) > 0 {
path = common.Configuration.ObjectsDataPath
} else {
path = common.Configuration.PersistenceRootPath + "/sync/local/"
}
err = os.MkdirAll(path, 0750)
store.localDataPath = "file://" + path
if err == nil {
common.HealthStatus.ReconnectedToDatabase()
}
return err
}
// Stop stops the Bolt store
func (store *BoltStorage) Stop() {
store.db.Close()
}
// PerformMaintenance performs store's maintenance
func (store *BoltStorage) PerformMaintenance() {
if common.Configuration.NodeType == common.CSS {
currentTime := time.Now().UTC().Format(time.RFC3339)
function := func(object boltObject) bool {
if object.Meta.Expiration != "" && object.Meta.Expiration <= currentTime &&
(object.Status == common.ReadyToSend || object.Status == common.NotReadyToSend) {
return true
}
return false
}
err := store.deleteObjectsAndNotificationsHelper(function)
if err != nil {
if log.IsLogging(logger.ERROR) {
log.Error("Error in PerformMaintenance: failed to remove expired objects. Error: %s\n", err)
}
} else if trace.IsLogging(logger.TRACE) {
trace.Trace("Removing expired objects")
}
}
}
// Cleanup erase the on disk Bolt database only for ESS and test
func (store *BoltStorage) Cleanup(isTest bool) common.SyncServiceError {
var essDbPath string
if isTest {
cssDbPath := common.Configuration.PersistenceRootPath + "/sync/db/css-sync.db"
essDbPath = common.Configuration.PersistenceRootPath + "/sync/db/ess-sync.db"
if err := os.Remove(cssDbPath); err != nil {
if log.IsLogging(logger.ERROR) {
log.Error("Failed to remove css Bolt testing database")
}
return err
}
if log.IsLogging(logger.DEBUG) {
log.Debug("CSS bolt db at %s is removed\n", cssDbPath)
}
} else {
essDbPath = common.Configuration.PersistenceRootPath + "/sync/db/ess-sync.db"
}
if err := os.Remove(essDbPath); err != nil {
if log.IsLogging(logger.ERROR) {
log.Error("Failed to remove ess Bolt database")
}
return err
}
if log.IsLogging(logger.DEBUG) {
log.Debug("ESS bolt db at %s is removed\n", essDbPath)
}
return 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 *BoltStorage) StoreObject(metaData common.MetaData, data []byte, status string) ([]common.StoreDestinationStatus, common.SyncServiceError) {
var dests []common.StoreDestinationStatus
var deletedDests []common.StoreDestinationStatus
// If the object was receieved from a service (status NotReadyToSend/ReadyToSend), i.e. this node is the origin of the object,
// set instance id. If the object was received from the other side, this node is the receiver of the object:
// keep the instance id of the meta data.
if status == common.NotReadyToSend || status == common.ReadyToSend {
newID := store.getInstanceID()
metaData.InstanceID = newID
if data != nil && !metaData.NoData && !metaData.MetaOnly {
metaData.DataID = newID
}
if common.Configuration.NodeType == common.CSS {
var err error
dests, deletedDests, err = createDestinationsFromMeta(store, metaData)
if err != nil {
return nil, err
}
}
}
if metaData.DestinationPolicy != nil {
metaData.DestinationPolicy.Timestamp = time.Now().UTC().UnixNano()
}
if metaData.MetaOnly {
function := func(object boltObject) (boltObject, common.SyncServiceError) {
if object.Status == common.ConsumedByDest {
// On ESS we remove the data of consumed objects, therefore we can't accept "meta only" updates
return object, &common.InvalidRequest{"Can't update only the meta data of consumed object"}
}
if (object.Meta.DestinationPolicy == nil && metaData.DestinationPolicy != nil) ||
(object.Meta.DestinationPolicy != nil && metaData.DestinationPolicy == nil) {
return object, &common.InvalidRequest{"Can't update the existence of Destination Policy"}
}
metaData.DataID = object.Meta.DataID // Keep the previous data id
metaData.PublicKey = object.Meta.PublicKey // Keep the previous publicKey and signature
metaData.Signature = object.Meta.Signature
object.Meta = metaData
object.Status = status
object.PolicyReceived = false
object.RemainingConsumers = metaData.ExpectedConsumers
object.RemainingReceivers = metaData.ExpectedConsumers
if metaData.DestinationPolicy == nil {
object.Destinations = dests
}
return object, nil
}
err := store.updateObjectHelper(metaData.DestOrgID, metaData.ObjectType, metaData.ObjectID, function)
if err == nil || err != notFound {
return deletedDests, err
}
// If not found, insert it
}
var dataPath string
if !metaData.NoData && data != nil {
dataPath = createDataPathFromMeta(store.localDataPath, metaData)
if _, err := dataURI.StoreData(dataPath, bytes.NewReader(data), uint32(len(data))); err != nil {
return nil, err
}
} else if !metaData.MetaOnly {
if err := dataURI.DeleteStoredData(createDataPathFromMeta(store.localDataPath, metaData)); err != nil {
return nil, err
}
}
newObject := boltObject{Meta: metaData, Status: status, PolicyReceived: false,
RemainingConsumers: metaData.ExpectedConsumers, RemainingReceivers: metaData.ExpectedConsumers,
DataPath: dataPath, Destinations: dests}
function := func(object boltObject) (boltObject, common.SyncServiceError) {
if (object.Meta.DestinationPolicy == nil && metaData.DestinationPolicy != nil) ||
(object.Meta.DestinationPolicy != nil && metaData.DestinationPolicy == nil) {
return object, &common.InvalidRequest{Message: "Can't update the existence of Destination Policy"}
}
if metaData.DestinationPolicy != nil {
newObject.Destinations = object.Destinations
}
return newObject, nil
}
err := store.updateObjectHelper(metaData.DestOrgID, metaData.ObjectType, metaData.ObjectID, function)
if err == notFound {
// Not found, insert
encoded, err := json.Marshal(newObject)
if err != nil {
return nil, err
}
id := getObjectCollectionID(metaData)
err = store.db.Update(func(tx *bolt.Tx) error {
err = tx.Bucket(objectsBucket).Put([]byte(id), []byte(encoded))
return err
})
return deletedDests, err
}
return deletedDests, err
}
// StoreObjectData stores an object's data
// Return true if the object was found and updated
// Return false and no error, if the object doesn't exist
func (store *BoltStorage) StoreObjectData(orgID string, objectType string, objectID string, dataReader io.Reader) (bool, common.SyncServiceError) {
dataPath := createDataPath(store.localDataPath, orgID, objectType, objectID)
written, err := dataURI.StoreData(dataPath, dataReader, 0)
if err != nil {
return false, err
}
function := func(object boltObject) (boltObject, common.SyncServiceError) {
if object.Status == common.NotReadyToSend {
object.Status = common.ReadyToSend
}
if object.Status == common.NotReadyToSend || object.Status == common.ReadyToSend {
newID := store.getInstanceID()
object.Meta.InstanceID = newID
object.Meta.DataID = newID
}
object.DataPath = dataPath
object.Meta.ObjectSize = written
return object, nil
}
if err := store.updateObjectHelper(orgID, objectType, objectID, function); err != nil {
if err == notFound {
return false, nil
}
return false, err
}
return true, nil
}
func (store *BoltStorage) StoreObjectTempData(orgID string, objectType string, objectID string, dataReader io.Reader) (bool, common.SyncServiceError) {
tmpDataPath := createDataPathForTempData(store.localDataPath, orgID, objectType, objectID)
_, err := dataURI.StoreData(tmpDataPath, dataReader, 0)
if err != nil {
return false, err
}
return true, nil
}
func (store *BoltStorage) RemoveObjectTempData(orgID string, objectType string, objectID string) common.SyncServiceError {
tmpDataPath := createDataPathForTempData(store.localDataPath, orgID, objectType, objectID)
if err := dataURI.DeleteStoredData(tmpDataPath); err != nil {
if common.IsNotFound(err) {
return nil
}
return err
}
return nil
}
func (store *BoltStorage) RetrieveTempObjectData(orgID string, objectType string, objectID string) (io.Reader, common.SyncServiceError) {
var dataReader io.Reader
tmpDataPath := createDataPathForTempData(store.localDataPath, orgID, objectType, objectID)
dataReader, err := dataURI.GetData(tmpDataPath)
if err != nil {
if common.IsNotFound(err) {
return nil, nil
}
return nil, err
}
return dataReader, nil
}
// RetrieveObject returns the object meta data with the specified parameters
func (store *BoltStorage) RetrieveObject(orgID string, objectType string, objectID string) (*common.MetaData, common.SyncServiceError) {
var meta *common.MetaData
function := func(object boltObject) common.SyncServiceError {
meta = &object.Meta
return nil
}
if err := store.viewObjectHelper(orgID, objectType, objectID, function); err != nil {
if common.IsNotFound(err) {
return nil, nil
}
return nil, err
}
return meta, nil
}
// RetrieveObjectData returns the object data with the specified parameters
func (store *BoltStorage) RetrieveObjectData(orgID string, objectType string, objectID string) (io.Reader, common.SyncServiceError) {
var dataReader io.Reader
function := func(object boltObject) common.SyncServiceError {
var err error
if object.DataPath != "" {
dataReader, err = dataURI.GetData(object.DataPath)
return err
}
return nil
}
if err := store.viewObjectHelper(orgID, objectType, objectID, function); err != nil {
if common.IsNotFound(err) {
return nil, nil
}
return nil, err
}
return dataReader, nil
}
// RetrieveObjectAndStatus returns the object meta data and status with the specified parameters
func (store *BoltStorage) RetrieveObjectAndStatus(orgID string, objectType string, objectID string) (*common.MetaData, string, common.SyncServiceError) {
var meta *common.MetaData
var status string
function := func(object boltObject) common.SyncServiceError {
meta = &object.Meta
status = object.Status
return nil
}
if err := store.viewObjectHelper(orgID, objectType, objectID, function); err != nil {
if common.IsNotFound(err) {
err = nil
}
return nil, "", err
}
return meta, status, nil
}
// RetrieveObjectStatus finds the object and returns its status
func (store *BoltStorage) RetrieveObjectStatus(orgID string, objectType string, objectID string) (string, common.SyncServiceError) {
var status string
function := func(object boltObject) common.SyncServiceError {
status = object.Status
return nil
}
if err := store.viewObjectHelper(orgID, objectType, objectID, function); err != nil {
if common.IsNotFound(err) {
err = nil
}
return "", err
}
return status, nil
}
// RetrieveUpdatedObjects returns the list of all the edge updated objects that are not marked as consumed
// If received is true, return objects marked as received
func (store *BoltStorage) RetrieveUpdatedObjects(orgID string, objectType string, received bool) ([]common.MetaData, common.SyncServiceError) {
result := make([]common.MetaData, 0)
function := func(object boltObject) {
if orgID == object.Meta.DestOrgID && objectType == object.Meta.ObjectType &&
(object.Status == common.CompletelyReceived || object.Status == common.ObjDeleted ||
(object.Status == common.ObjReceived && received)) {
result = append(result, object.Meta)
}
}
if err := store.retrieveObjectsHelper(function); err != nil {
return nil, err
}
if len(common.Configuration.ObjectsDataPath) > 0 {
for i := 0; i < len(result); i++ {
result[i].DestinationDataURI = createDataPathFromMeta(store.localDataPath, result[i])
}
}
return result, 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 *BoltStorage) RetrieveObjectsWithDestinationPolicy(orgID string, received bool) ([]common.ObjectDestinationPolicy, common.SyncServiceError) {
result := make([]common.ObjectDestinationPolicy, 0)
function := func(object boltObject) {
if orgID == object.Meta.DestOrgID && object.Meta.DestinationPolicy != nil &&
(received || !object.PolicyReceived) {
result = append(result, createObjectDestinationPolicy(object))
}
}
if err := store.retrieveObjectsHelper(function); err != nil {
return nil, err
}
return result, nil
}
// RetrieveObjectsWithDestinationPolicyByService returns the list of all the object Policies for a particular service
func (store *BoltStorage) RetrieveObjectsWithDestinationPolicyByService(orgID, serviceOrgID, serviceName string) ([]common.ObjectDestinationPolicy, common.SyncServiceError) {
result := make([]common.ObjectDestinationPolicy, 0)
function := func(object boltObject) {
if orgID == object.Meta.DestOrgID && object.Meta.DestinationPolicy != nil {
for _, service := range object.Meta.DestinationPolicy.Services {
if serviceOrgID == service.OrgID && serviceName == service.ServiceName {
result = append(result, createObjectDestinationPolicy(object))
}
}
}
}
if err := store.retrieveObjectsHelper(function); err != nil {
return nil, err
}
return result, nil
}
// RetrieveObjectsWithDestinationPolicyUpdatedSince returns the list of all the objects that have a Destination Policy updated since the specified time
func (store *BoltStorage) RetrieveObjectsWithDestinationPolicyUpdatedSince(orgID string, since int64) ([]common.ObjectDestinationPolicy, common.SyncServiceError) {
result := make([]common.ObjectDestinationPolicy, 0)
function := func(object boltObject) {
if orgID == object.Meta.DestOrgID && object.Meta.DestinationPolicy != nil &&
object.Meta.DestinationPolicy.Timestamp >= since {
result = append(result, createObjectDestinationPolicy(object))
}
}
if err := store.retrieveObjectsHelper(function); err != nil {
return nil, err
}
return result, nil
}
// RetrieveObjectsWithFilters returns the list of all othe objects that meet the given conditions
func (store *BoltStorage) 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) ([]common.MetaData, common.SyncServiceError) {
result := make([]common.MetaData, 0)
function := func(object boltObject) {
if orgID == object.Meta.DestOrgID {
// check destinationPolicy
if destinationPolicy != nil {
if *destinationPolicy {
if object.Meta.DestinationPolicy != nil && object.Meta.DestinationPolicy.Timestamp >= since {
check := false
if dpServiceOrgID != "" && dpServiceName != "" {
for _, service := range object.Meta.DestinationPolicy.Services {
if dpServiceOrgID == service.OrgID && dpServiceName == service.ServiceName {
check = true
break
}
}
if !check {
return
}
}
if dpPropertyName != "" {
check = false
for _, policyProperty := range object.Meta.DestinationPolicy.Properties {
if dpPropertyName == policyProperty.Name {
check = true
break
}
}
if !check {
return
}
}
// if check {
// result = append(result, obj.Meta)
// }
} else {
return
}
} else { //*destinationPolicy = false
if object.Meta.DestinationPolicy != nil {
return
}
}
}
// check objectType and objectID
if objectType != "" {
if objectType != object.Meta.ObjectType {
return
}
if objectID != "" {
if objectID != object.Meta.ObjectID {
return
}
}
}
// check destinationType and destinationID
if destinationType != "" {
if object.Meta.DestType != "" {
if destinationType != object.Meta.DestType {
return
}
if destinationID != "" {
if destinationID != object.Meta.DestID {
return
}
}
} else { // check object.Meta.DestinationsList (destinationType: destinationID)
checkedDestList := false
for _, dest := range object.Meta.DestinationsList {
if destinationID != "" {
if dest == destinationType+":"+destinationID {
checkedDestList = true
break
}
} else {
parts := strings.SplitN(dest, ":", 2)
if len(parts) == 2 && parts[0] == destinationType {
checkedDestList = true
break
}
}
}
if !checkedDestList {
return
}
}
}
if noData != nil {
if *noData != object.Meta.NoData {
return
}
}
if expirationTimeBefore != "" {
boltObjectExpirationTime, err := time.Parse(time.RFC3339, object.Meta.Expiration)
queryExpirationTimeBefore, _ := time.Parse(time.RFC3339, expirationTimeBefore)
if err != nil || boltObjectExpirationTime.After(queryExpirationTimeBefore) {
return
}
}
// if expirationTimeBefore is not satisfy, return
result = append(result, object.Meta)
}
}
if err := store.retrieveObjectsHelper(function); err != nil {
return nil, err
}
return result, nil
}
// RetrieveAllObjects returns the list of all the objects of the specified type
func (store *BoltStorage) RetrieveAllObjects(orgID string, objectType string) ([]common.ObjectDestinationPolicy, common.SyncServiceError) {
result := make([]common.ObjectDestinationPolicy, 0)
function := func(object boltObject) {
if orgID == object.Meta.DestOrgID && object.Meta.ObjectType == objectType {
result = append(result, createObjectDestinationPolicy(object))
}
}
if err := store.retrieveObjectsHelper(function); err != nil {
return nil, err
}
return result, nil
}
// RetrieveObjects returns the list of all the objects that need to be sent to the destination
// For CSS: adds the new destination to the destinations lists of the relevant objects.
func (store *BoltStorage) RetrieveObjects(orgID string, destType string, destID string, resend int) ([]common.MetaData, common.SyncServiceError) {
result := make([]common.MetaData, 0)
if common.Configuration.NodeType == common.ESS {
function := func(object boltObject) {
if (orgID == object.Meta.DestOrgID || orgID == "") && !object.Meta.Inactive &&
object.Status == common.ReadyToSend &&
(object.Meta.DestType == "" || object.Meta.DestType == destType || destType == "") &&
(object.Meta.DestID == "" || object.Meta.DestID == destID || destID == "") {
result = append(result, object.Meta)
}
}
if err := store.retrieveObjectsHelper(function); err != nil {
return nil, err
}
return result, nil
}
function := func(object boltObject) (*boltObject, common.SyncServiceError) {
if object.Meta.DestinationPolicy == nil && orgID == object.Meta.DestOrgID &&
(object.Meta.DestType == "" || object.Meta.DestType == destType) &&
(object.Meta.DestID == "" || object.Meta.DestID == destID) {
status := common.Pending
if object.Status == common.ReadyToSend && !object.Meta.Inactive {
status = common.Delivering
}
needToUpdate := false
// Add destination if it doesn't exist in the destinations list
if dest, err := store.RetrieveDestination(orgID, destType, destID); err == nil && dest != nil {
existingDestIndex := -1
for i, d := range object.Destinations {
if d.Destination == *dest {
existingDestIndex = i
break
}
}
if existingDestIndex != -1 {
d := object.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)) {
result = append(result, object.Meta)
object.Destinations[existingDestIndex].Status = common.Delivering
needToUpdate = true
}
} else {
if status == common.Delivering {
result = append(result, object.Meta)
}
needToUpdate = true
object.Destinations = append(object.Destinations, common.StoreDestinationStatus{Destination: *dest, Status: status})
}
if needToUpdate {
return &object, nil
}
return nil, nil
}
}
return nil, nil
}
if err := store.updateObjectsHelper(function); err != nil {
return nil, err
}
return result, nil
}
// RetrieveConsumedObjects returns all the consumed objects originated from this node
func (store *BoltStorage) RetrieveConsumedObjects() ([]common.ConsumedObject, common.SyncServiceError) {
result := make([]common.ConsumedObject, 0)
function := func(object boltObject) {
if object.Status == common.ConsumedByDest {
result = append(result, common.ConsumedObject{MetaData: object.Meta, Timestamp: object.ConsumedTimestamp})
}
}
if err := store.retrieveObjectsHelper(function); err != nil {
return nil, err
}
return result, nil
}
// GetObjectsToActivate returns inactive objects that are ready to be activated
func (store *BoltStorage) GetObjectsToActivate() ([]common.MetaData, common.SyncServiceError) {
currentTime := time.Now().UTC().Format(time.RFC3339)
result := make([]common.MetaData, 0)
function := func(object boltObject) {
if (object.Status == common.NotReadyToSend || object.Status == common.ReadyToSend) &&
object.Meta.Inactive && object.Meta.ActivationTime != "" && object.Meta.ActivationTime <= currentTime {
result = append(result, object.Meta)
}
}
if err := store.retrieveObjectsHelper(function); err != nil {
return nil, err
}
return result, nil
}
// AppendObjectData appends a chunk of data to the object's data
func (store *BoltStorage) AppendObjectData(orgID string, objectType string, objectID string, dataReader io.Reader, dataLength uint32,
offset int64, total int64, isFirstChunk bool, isLastChunk bool) common.SyncServiceError {
dataPath := ""
function := func(object boltObject) (boltObject, common.SyncServiceError) {
dataPath = object.DataPath
if dataPath == "" {
if !isFirstChunk {
return object, &Error{"No path to store data"}
}
dataPath = createDataPathFromMeta(store.localDataPath, object.Meta)
object.DataPath = dataPath
}
return object, nil
}
if err := store.updateObjectHelper(orgID, objectType, objectID, function); err != nil {
return err
}
return dataURI.AppendData(dataPath, dataReader, dataLength, offset, total, isFirstChunk, isLastChunk)
}
// UpdateObjectStatus updates an object's status
func (store *BoltStorage) UpdateObjectStatus(orgID string, objectType string, objectID string, status string) common.SyncServiceError {
function := func(object boltObject) (boltObject, common.SyncServiceError) {
object.Status = status
if status == common.ConsumedByDest {
object.ConsumedTimestamp = time.Now()
}
return object, nil
}
return store.updateObjectHelper(orgID, objectType, objectID, function)
}
// UpdateObjectSourceDataURI pdates object's source data URI
func (store *BoltStorage) UpdateObjectSourceDataURI(orgID string, objectType string, objectID string, sourceDataURI string) common.SyncServiceError {
function := func(object boltObject) (boltObject, common.SyncServiceError) {
object.Meta.SourceDataURI = sourceDataURI
return object, nil
}
return store.updateObjectHelper(orgID, objectType, objectID, function)
}
// RetrieveObjectRemainingConsumers finds the object and returns the number of remaining consumers
// that haven't consumed the object yet
func (store *BoltStorage) RetrieveObjectRemainingConsumers(orgID string, objectType string, objectID string) (int, common.SyncServiceError) {
var remainingConsumers int
function := func(object boltObject) common.SyncServiceError {
remainingConsumers = object.RemainingConsumers
return nil
}
if err := store.viewObjectHelper(orgID, objectType, objectID, function); err != nil {
return 0, err
}
return remainingConsumers, nil
}
// ResetObjectRemainingConsumers sets the remaining consumers count to the original ExpectedConsumers value
func (store *BoltStorage) ResetObjectRemainingConsumers(orgID string, objectType string, objectID string) common.SyncServiceError {
function := func(object boltObject) (boltObject, common.SyncServiceError) {
object.RemainingConsumers = object.Meta.ExpectedConsumers
return object, nil
}
return store.updateObjectHelper(orgID, objectType, objectID, function)
}
// DecrementAndReturnRemainingConsumers decrements the number of remaining consumers of the object
func (store *BoltStorage) DecrementAndReturnRemainingConsumers(orgID string, objectType string, objectID string) (int,
common.SyncServiceError) {
var remainingConsumers int
function := func(object boltObject) (boltObject, common.SyncServiceError) {
object.RemainingConsumers--
remainingConsumers = object.RemainingConsumers
return object, nil
}
if err := store.updateObjectHelper(orgID, objectType, objectID, function); err != nil {
return 0, err
}
return remainingConsumers, nil
}
// DecrementAndReturnRemainingReceivers decrements the number of remaining receivers of the object
func (store *BoltStorage) DecrementAndReturnRemainingReceivers(orgID string, objectType string, objectID string) (int,
common.SyncServiceError) {
var remainingReceivers int
function := func(object boltObject) (boltObject, common.SyncServiceError) {
object.RemainingReceivers--
remainingReceivers = object.RemainingReceivers
return object, nil
}
if err := store.updateObjectHelper(orgID, objectType, objectID, function); err != nil {
return 0, err
}
return remainingReceivers, nil
}
// CloseDataReader closes the data reader if necessary
func (store *BoltStorage) CloseDataReader(dataReader io.Reader) common.SyncServiceError {
switch v := dataReader.(type) {
case *os.File:
return v.Close()
}
return nil
}
// ReadObjectData returns the object data with the specified parameters
func (store *BoltStorage) ReadObjectData(orgID string, objectType string, objectID string, size int, offset int64) (data []byte,
eof bool, length int, err common.SyncServiceError) {
function := func(object boltObject) common.SyncServiceError {
if object.DataPath != "" {
data, eof, length, err = dataURI.GetDataChunk(object.DataPath, size, offset)
return err
}
eof = true
return nil
}
err = store.viewObjectHelper(orgID, objectType, objectID, function)
return
}
// MarkObjectDeleted marks the object as deleted
func (store *BoltStorage) MarkObjectDeleted(orgID string, objectType string, objectID string) common.SyncServiceError {
function := func(object boltObject) (boltObject, common.SyncServiceError) {
object.Status = common.ObjDeleted
object.Meta.Deleted = true
return object, nil
}
return store.updateObjectHelper(orgID, objectType, objectID, function)
}
// MarkDestinationPolicyReceived marks an object's destination policy as having been received
func (store *BoltStorage) MarkDestinationPolicyReceived(orgID string, objectType string, objectID string) common.SyncServiceError {
function := func(object boltObject) (boltObject, common.SyncServiceError) {
object.PolicyReceived = true
return object, nil
}
return store.updateObjectHelper(orgID, objectType, objectID, function)
}
// ActivateObject marks object as active
func (store *BoltStorage) ActivateObject(orgID string, objectType string, objectID string) common.SyncServiceError {
function := func(object boltObject) (boltObject, common.SyncServiceError) {
object.Meta.Inactive = false
return object, nil
}
return store.updateObjectHelper(orgID, objectType, objectID, function)
}
// DeleteStoredObject deletes the object
func (store *BoltStorage) DeleteStoredObject(orgID string, objectType string, objectID string) common.SyncServiceError {
if err := store.DeleteStoredData(orgID, objectType, objectID); err != nil {
return nil
}
id := createObjectCollectionID(orgID, objectType, objectID)
err := store.db.Update(func(tx *bolt.Tx) error {
err := tx.Bucket(objectsBucket).Delete([]byte(id))
return err
})
return err
}
// DeleteStoredData deletes the object's data
func (store *BoltStorage) DeleteStoredData(orgID string, objectType string, objectID string) common.SyncServiceError {
function := func(object boltObject) (boltObject, common.SyncServiceError) {
if object.DataPath == "" {
return object, nil
}
if err := dataURI.DeleteStoredData(object.DataPath); err != nil {
return object, err
}
object.DataPath = ""
return object, nil
}
return store.updateObjectHelper(orgID, objectType, objectID, function)
}
// CleanObjects removes the objects received from the other side.
// For persistant storage only partially recieved objects are removed.
func (store *BoltStorage) CleanObjects() common.SyncServiceError {
function := func(object boltObject) bool {
if object.Status == common.PartiallyReceived {
return true
}
return false
}
err := store.deleteObjectsHelper(function)
if err != nil {
if log.IsLogging(logger.ERROR) {
log.Error("Error in CleanObjects: failed to remove objects. Error: %s\n", err)
}
}
return nil
}
// GetObjectDestinations gets destinations that the object has to be sent to
func (store *BoltStorage) GetObjectDestinations(metaData common.MetaData) ([]common.Destination, common.SyncServiceError) {
if common.Configuration.NodeType == common.ESS {
return []common.Destination{common.Destination{DestOrgID: metaData.DestOrgID, DestType: common.Configuration.DestinationType,
DestID: common.Configuration.DestinationID, Communication: common.Configuration.CommunicationProtocol}}, nil
}
var dests []common.StoreDestinationStatus
function := func(object boltObject) common.SyncServiceError {
dests = object.Destinations
return nil
}
if err := store.viewObjectHelper(metaData.DestOrgID, metaData.ObjectType, metaData.ObjectID, function); err != nil {
if common.IsNotFound(err) {
return nil, nil