forked from hashicorp/vault
-
Notifications
You must be signed in to change notification settings - Fork 0
/
identity_store_util.go
2415 lines (1920 loc) · 55.9 KB
/
identity_store_util.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 vault
import (
"context"
"fmt"
"strings"
"sync"
"github.com/golang/protobuf/ptypes"
"github.com/hashicorp/errwrap"
memdb "github.com/hashicorp/go-memdb"
uuid "github.com/hashicorp/go-uuid"
"github.com/hashicorp/vault/helper/consts"
"github.com/hashicorp/vault/helper/identity"
"github.com/hashicorp/vault/helper/locksutil"
"github.com/hashicorp/vault/helper/storagepacker"
"github.com/hashicorp/vault/helper/strutil"
"github.com/hashicorp/vault/logical"
)
func (c *Core) loadIdentityStoreArtifacts(ctx context.Context) error {
var err error
if c.identityStore == nil {
c.logger.Warn("identity store is not setup, skipping loading")
return nil
}
err = c.identityStore.loadEntities(ctx)
if err != nil {
return err
}
err = c.identityStore.loadGroups(ctx)
if err != nil {
return err
}
return nil
}
func (i *IdentityStore) loadGroups(ctx context.Context) error {
i.logger.Debug("identity loading groups")
existing, err := i.groupPacker.View().List(ctx, groupBucketsPrefix)
if err != nil {
return errwrap.Wrapf("failed to scan for groups: {{err}}", err)
}
i.logger.Debug("groups collected", "num_existing", len(existing))
i.groupLock.Lock()
defer i.groupLock.Unlock()
for _, key := range existing {
bucket, err := i.groupPacker.GetBucket(i.groupPacker.BucketPath(key))
if err != nil {
return err
}
if bucket == nil {
continue
}
for _, item := range bucket.Items {
group, err := i.parseGroupFromBucketItem(item)
if err != nil {
return err
}
if group == nil {
continue
}
if i.logger.IsDebug() {
i.logger.Debug("loading group", "name", group.Name, "id", group.ID)
}
txn := i.db.Txn(true)
err = i.upsertGroupInTxn(txn, group, false)
if err != nil {
txn.Abort()
return errwrap.Wrapf("failed to update group in memdb: {{err}}", err)
}
txn.Commit()
}
}
if i.logger.IsInfo() {
i.logger.Info("groups restored")
}
return nil
}
func (i *IdentityStore) loadEntities(ctx context.Context) error {
// Accumulate existing entities
i.logger.Debug("loading entities")
existing, err := i.entityPacker.View().List(ctx, storagepacker.StoragePackerBucketsPrefix)
if err != nil {
return errwrap.Wrapf("failed to scan for entities: {{err}}", err)
}
i.logger.Debug("entities collected", "num_existing", len(existing))
// Make the channels used for the worker pool
broker := make(chan string)
quit := make(chan bool)
// Buffer these channels to prevent deadlocks
errs := make(chan error, len(existing))
result := make(chan *storagepacker.Bucket, len(existing))
// Use a wait group
wg := &sync.WaitGroup{}
// Create 64 workers to distribute work to
for j := 0; j < consts.ExpirationRestoreWorkerCount; j++ {
wg.Add(1)
go func() {
defer wg.Done()
for {
select {
case bucketKey, ok := <-broker:
// broker has been closed, we are done
if !ok {
return
}
bucket, err := i.entityPacker.GetBucket(i.entityPacker.BucketPath(bucketKey))
if err != nil {
errs <- err
continue
}
// Write results out to the result channel
result <- bucket
// quit early
case <-quit:
return
}
}
}()
}
// Distribute the collected keys to the workers in a go routine
wg.Add(1)
go func() {
defer wg.Done()
for j, bucketKey := range existing {
if j%500 == 0 {
i.logger.Debug("entities loading", "progress", j)
}
select {
case <-quit:
return
default:
broker <- bucketKey
}
}
// Close the broker, causing worker routines to exit
close(broker)
}()
// Restore each key by pulling from the result chan
for j := 0; j < len(existing); j++ {
select {
case err := <-errs:
// Close all go routines
close(quit)
return err
case bucket := <-result:
// If there is no entry, nothing to restore
if bucket == nil {
continue
}
for _, item := range bucket.Items {
entity, err := i.parseEntityFromBucketItem(ctx, item)
if err != nil {
return err
}
if entity == nil {
continue
}
// Only update MemDB and don't hit the storage again
err = i.upsertEntity(entity, nil, false)
if err != nil {
return errwrap.Wrapf("failed to update entity in MemDB: {{err}}", err)
}
}
}
}
// Let all go routines finish
wg.Wait()
if i.logger.IsInfo() {
i.logger.Info("entities restored")
}
return nil
}
// LockForEntityID returns the lock used to modify the entity.
func (i *IdentityStore) LockForEntityID(entityID string) *locksutil.LockEntry {
return locksutil.LockForKey(i.entityLocks, entityID)
}
// upsertEntityInTxn either creates or updates an existing entity. The
// operations will be updated in both MemDB and storage. If 'persist' is set to
// false, then storage will not be updated. When an alias is transferred from
// one entity to another, both the source and destination entities should get
// updated, in which case, callers should send in both entity and
// previousEntity.
func (i *IdentityStore) upsertEntityInTxn(txn *memdb.Txn, entity *identity.Entity, previousEntity *identity.Entity, persist, lockHeld bool) error {
var err error
if txn == nil {
return fmt.Errorf("txn is nil")
}
if entity == nil {
return fmt.Errorf("entity is nil")
}
// Acquire the lock to modify the entity storage entry
if !lockHeld {
lock := locksutil.LockForKey(i.entityLocks, entity.ID)
lock.Lock()
defer lock.Unlock()
}
for _, alias := range entity.Aliases {
// Verify that alias is not associated to a different one already
aliasByFactors, err := i.MemDBAliasByFactors(alias.MountAccessor, alias.Name, false, false)
if err != nil {
return err
}
if aliasByFactors != nil && aliasByFactors.CanonicalID != entity.ID {
return fmt.Errorf("alias %q in already tied to a different entity %q", alias.ID, aliasByFactors.CanonicalID)
}
// Insert or update alias in MemDB using the transaction created above
err = i.MemDBUpsertAliasInTxn(txn, alias, false)
if err != nil {
return err
}
}
// If previous entity is set, update it in MemDB and persist it
if previousEntity != nil && persist {
err = i.MemDBUpsertEntityInTxn(txn, previousEntity)
if err != nil {
return err
}
// Persist the previous entity object
marshaledPreviousEntity, err := ptypes.MarshalAny(previousEntity)
if err != nil {
return err
}
err = i.entityPacker.PutItem(&storagepacker.Item{
ID: previousEntity.ID,
Message: marshaledPreviousEntity,
})
if err != nil {
return err
}
}
// Insert or update entity in MemDB using the transaction created above
err = i.MemDBUpsertEntityInTxn(txn, entity)
if err != nil {
return err
}
if persist {
entityAsAny, err := ptypes.MarshalAny(entity)
if err != nil {
return err
}
item := &storagepacker.Item{
ID: entity.ID,
Message: entityAsAny,
}
// Persist the entity object
err = i.entityPacker.PutItem(item)
if err != nil {
return err
}
}
return nil
}
// upsertEntity either creates or updates an existing entity. The operations
// will be updated in both MemDB and storage. If 'persist' is set to false,
// then storage will not be updated. When an alias is transferred from one
// entity to another, both the source and destination entities should get
// updated, in which case, callers should send in both entity and
// previousEntity.
func (i *IdentityStore) upsertEntity(entity *identity.Entity, previousEntity *identity.Entity, persist bool) error {
// Create a MemDB transaction to update both alias and entity
txn := i.db.Txn(true)
defer txn.Abort()
err := i.upsertEntityInTxn(txn, entity, previousEntity, persist, false)
if err != nil {
return err
}
txn.Commit()
return nil
}
// upsertEntityNonLocked creates or updates an entity. The lock to modify the
// entity should be held before calling this function.
func (i *IdentityStore) upsertEntityNonLocked(entity *identity.Entity, previousEntity *identity.Entity, persist bool) error {
// Create a MemDB transaction to update both alias and entity
txn := i.db.Txn(true)
defer txn.Abort()
err := i.upsertEntityInTxn(txn, entity, previousEntity, persist, true)
if err != nil {
return err
}
txn.Commit()
return nil
}
func (i *IdentityStore) deleteEntity(entityID string) error {
var err error
var entity *identity.Entity
if entityID == "" {
return fmt.Errorf("missing entity id")
}
// Since an entity ID is required to acquire the lock to modify the
// storage, fetch the entity without acquiring the lock
lockEntity, err := i.MemDBEntityByID(entityID, false)
if err != nil {
return err
}
if lockEntity == nil {
return nil
}
// Acquire the lock to modify the entity storage entry
lock := locksutil.LockForKey(i.entityLocks, lockEntity.ID)
lock.Lock()
defer lock.Unlock()
// Create a MemDB transaction to delete entity
txn := i.db.Txn(true)
defer txn.Abort()
// Fetch the entity using its ID
entity, err = i.MemDBEntityByIDInTxn(txn, entityID, true)
if err != nil {
return err
}
// If there is no entity for the ID, do nothing
if entity == nil {
return nil
}
// Delete all the aliases in the entity. This function will also remove
// the corresponding alias indexes too.
err = i.deleteAliasesInEntityInTxn(txn, entity, entity.Aliases)
if err != nil {
return err
}
// Delete the entity using the same transaction
err = i.MemDBDeleteEntityByIDInTxn(txn, entity.ID)
if err != nil {
return err
}
// Delete the entity from storage
err = i.entityPacker.DeleteItem(entity.ID)
if err != nil {
return err
}
// Committing the transaction *after* successfully deleting entity
txn.Commit()
return nil
}
func (i *IdentityStore) deleteAlias(aliasID string) error {
var err error
var alias *identity.Alias
var entity *identity.Entity
if aliasID == "" {
return fmt.Errorf("missing alias ID")
}
// Since an entity ID is required to acquire the lock to modify the
// storage, fetch the entity without acquiring the lock
// Fetch the alias using its ID
alias, err = i.MemDBAliasByID(aliasID, false, false)
if err != nil {
return err
}
// If there is no alias for the ID, do nothing
if alias == nil {
return nil
}
// Find the entity to which the alias is tied to
lockEntity, err := i.MemDBEntityByAliasID(alias.ID, false)
if err != nil {
return err
}
// If there is no entity tied to a valid alias, something is wrong
if lockEntity == nil {
return fmt.Errorf("alias not associated to an entity")
}
// Acquire the lock to modify the entity storage entry
lock := locksutil.LockForKey(i.entityLocks, lockEntity.ID)
lock.Lock()
defer lock.Unlock()
// Create a MemDB transaction to delete entity
txn := i.db.Txn(true)
defer txn.Abort()
// Fetch the alias again after acquiring the lock using the transaction
// created above
alias, err = i.MemDBAliasByIDInTxn(txn, aliasID, false, false)
if err != nil {
return err
}
// If there is no alias for the ID, do nothing
if alias == nil {
return nil
}
// Fetch the entity again after acquiring the lock using the transaction
// created above
entity, err = i.MemDBEntityByAliasIDInTxn(txn, alias.ID, true)
if err != nil {
return err
}
// If there is no entity tied to a valid alias, something is wrong
if entity == nil {
return fmt.Errorf("alias not associated to an entity")
}
// Lock switching should not end up in this code pointing to different
// entities
if entity.ID != entity.ID {
return fmt.Errorf("operating on an entity to which the lock doesn't belong to")
}
aliases := []*identity.Alias{
alias,
}
// Delete alias from the entity object
err = i.deleteAliasesInEntityInTxn(txn, entity, aliases)
if err != nil {
return err
}
// Update the entity index in the entities table
err = i.MemDBUpsertEntityInTxn(txn, entity)
if err != nil {
return err
}
// Persist the entity object
entityAsAny, err := ptypes.MarshalAny(entity)
if err != nil {
return err
}
item := &storagepacker.Item{
ID: entity.ID,
Message: entityAsAny,
}
err = i.entityPacker.PutItem(item)
if err != nil {
return err
}
// Committing the transaction *after* successfully updating entity in
// storage
txn.Commit()
return nil
}
func (i *IdentityStore) MemDBUpsertAliasInTxn(txn *memdb.Txn, alias *identity.Alias, groupAlias bool) error {
if txn == nil {
return fmt.Errorf("nil txn")
}
if alias == nil {
return fmt.Errorf("alias is nil")
}
tableName := entityAliasesTable
if groupAlias {
tableName = groupAliasesTable
}
aliasRaw, err := txn.First(tableName, "id", alias.ID)
if err != nil {
return errwrap.Wrapf("failed to lookup alias from memdb using alias ID: {{err}}", err)
}
if aliasRaw != nil {
err = txn.Delete(tableName, aliasRaw)
if err != nil {
return errwrap.Wrapf("failed to delete alias from memdb: {{err}}", err)
}
}
if err := txn.Insert(tableName, alias); err != nil {
return errwrap.Wrapf("failed to update alias into memdb: {{err}}", err)
}
return nil
}
func (i *IdentityStore) MemDBUpsertAlias(alias *identity.Alias, groupAlias bool) error {
if alias == nil {
return fmt.Errorf("alias is nil")
}
txn := i.db.Txn(true)
defer txn.Abort()
err := i.MemDBUpsertAliasInTxn(txn, alias, groupAlias)
if err != nil {
return err
}
txn.Commit()
return nil
}
func (i *IdentityStore) MemDBAliasByCanonicalIDInTxn(txn *memdb.Txn, canonicalID string, clone bool, groupAlias bool) (*identity.Alias, error) {
if canonicalID == "" {
return nil, fmt.Errorf("missing canonical ID")
}
if txn == nil {
return nil, fmt.Errorf("txn is nil")
}
tableName := entityAliasesTable
if groupAlias {
tableName = groupAliasesTable
}
aliasRaw, err := txn.First(tableName, "canonical_id", canonicalID)
if err != nil {
return nil, errwrap.Wrapf("failed to fetch alias from memdb using canonical ID: {{err}}", err)
}
if aliasRaw == nil {
return nil, nil
}
alias, ok := aliasRaw.(*identity.Alias)
if !ok {
return nil, fmt.Errorf("failed to declare the type of fetched alias")
}
if clone {
return alias.Clone()
}
return alias, nil
}
func (i *IdentityStore) MemDBAliasByCanonicalID(canonicalID string, clone bool, groupAlias bool) (*identity.Alias, error) {
if canonicalID == "" {
return nil, fmt.Errorf("missing canonical ID")
}
txn := i.db.Txn(false)
return i.MemDBAliasByCanonicalIDInTxn(txn, canonicalID, clone, groupAlias)
}
func (i *IdentityStore) MemDBAliasByIDInTxn(txn *memdb.Txn, aliasID string, clone bool, groupAlias bool) (*identity.Alias, error) {
if aliasID == "" {
return nil, fmt.Errorf("missing alias ID")
}
if txn == nil {
return nil, fmt.Errorf("txn is nil")
}
tableName := entityAliasesTable
if groupAlias {
tableName = groupAliasesTable
}
aliasRaw, err := txn.First(tableName, "id", aliasID)
if err != nil {
return nil, errwrap.Wrapf("failed to fetch alias from memdb using alias ID: {{err}}", err)
}
if aliasRaw == nil {
return nil, nil
}
alias, ok := aliasRaw.(*identity.Alias)
if !ok {
return nil, fmt.Errorf("failed to declare the type of fetched alias")
}
if clone {
return alias.Clone()
}
return alias, nil
}
func (i *IdentityStore) MemDBAliasByID(aliasID string, clone bool, groupAlias bool) (*identity.Alias, error) {
if aliasID == "" {
return nil, fmt.Errorf("missing alias ID")
}
txn := i.db.Txn(false)
return i.MemDBAliasByIDInTxn(txn, aliasID, clone, groupAlias)
}
func (i *IdentityStore) MemDBAliasByFactors(mountAccessor, aliasName string, clone bool, groupAlias bool) (*identity.Alias, error) {
if aliasName == "" {
return nil, fmt.Errorf("missing alias name")
}
if mountAccessor == "" {
return nil, fmt.Errorf("missing mount accessor")
}
txn := i.db.Txn(false)
return i.MemDBAliasByFactorsInTxn(txn, mountAccessor, aliasName, clone, groupAlias)
}
func (i *IdentityStore) MemDBAliasByFactorsInTxn(txn *memdb.Txn, mountAccessor, aliasName string, clone bool, groupAlias bool) (*identity.Alias, error) {
if txn == nil {
return nil, fmt.Errorf("nil txn")
}
if aliasName == "" {
return nil, fmt.Errorf("missing alias name")
}
if mountAccessor == "" {
return nil, fmt.Errorf("missing mount accessor")
}
tableName := entityAliasesTable
if groupAlias {
tableName = groupAliasesTable
}
aliasRaw, err := txn.First(tableName, "factors", mountAccessor, aliasName)
if err != nil {
return nil, errwrap.Wrapf("failed to fetch alias from memdb using factors: {{err}}", err)
}
if aliasRaw == nil {
return nil, nil
}
alias, ok := aliasRaw.(*identity.Alias)
if !ok {
return nil, fmt.Errorf("failed to declare the type of fetched alias")
}
if clone {
return alias.Clone()
}
return alias, nil
}
func (i *IdentityStore) MemDBAliasesByMetadata(filters map[string]string, clone bool, groupAlias bool) ([]*identity.Alias, error) {
if filters == nil {
return nil, fmt.Errorf("map filter is nil")
}
txn := i.db.Txn(false)
defer txn.Abort()
var args []interface{}
for key, value := range filters {
args = append(args, key, value)
break
}
tableName := entityAliasesTable
if groupAlias {
tableName = groupAliasesTable
}
aliasesIter, err := txn.Get(tableName, "metadata", args...)
if err != nil {
return nil, errwrap.Wrapf("failed to lookup aliases using metadata: {{err}}", err)
}
var aliases []*identity.Alias
for alias := aliasesIter.Next(); alias != nil; alias = aliasesIter.Next() {
entry := alias.(*identity.Alias)
if len(filters) <= 1 || satisfiesMetadataFilters(entry.Metadata, filters) {
if clone {
entry, err = entry.Clone()
if err != nil {
return nil, err
}
}
aliases = append(aliases, entry)
}
}
return aliases, nil
}
func (i *IdentityStore) MemDBDeleteAliasByID(aliasID string, groupAlias bool) error {
if aliasID == "" {
return nil
}
txn := i.db.Txn(true)
defer txn.Abort()
err := i.MemDBDeleteAliasByIDInTxn(txn, aliasID, groupAlias)
if err != nil {
return err
}
txn.Commit()
return nil
}
func (i *IdentityStore) MemDBDeleteAliasByIDInTxn(txn *memdb.Txn, aliasID string, groupAlias bool) error {
if aliasID == "" {
return nil
}
if txn == nil {
return fmt.Errorf("txn is nil")
}
alias, err := i.MemDBAliasByIDInTxn(txn, aliasID, false, groupAlias)
if err != nil {
return err
}
if alias == nil {
return nil
}
tableName := entityAliasesTable
if groupAlias {
tableName = groupAliasesTable
}
err = txn.Delete(tableName, alias)
if err != nil {
return errwrap.Wrapf("failed to delete alias from memdb: {{err}}", err)
}
return nil
}
func (i *IdentityStore) MemDBAliases(ws memdb.WatchSet, groupAlias bool) (memdb.ResultIterator, error) {
txn := i.db.Txn(false)
tableName := entityAliasesTable
if groupAlias {
tableName = groupAliasesTable
}
iter, err := txn.Get(tableName, "id")
if err != nil {
return nil, err
}
ws.Add(iter.WatchCh())
return iter, nil
}
func (i *IdentityStore) MemDBUpsertEntityInTxn(txn *memdb.Txn, entity *identity.Entity) error {
if txn == nil {
return fmt.Errorf("nil txn")
}
if entity == nil {
return fmt.Errorf("entity is nil")
}
entityRaw, err := txn.First(entitiesTable, "id", entity.ID)
if err != nil {
return errwrap.Wrapf("failed to lookup entity from memdb using entity id: {{err}}", err)
}
if entityRaw != nil {
err = txn.Delete(entitiesTable, entityRaw)
if err != nil {
return errwrap.Wrapf("failed to delete entity from memdb: {{err}}", err)
}
}
if err := txn.Insert(entitiesTable, entity); err != nil {
return errwrap.Wrapf("failed to update entity into memdb: {{err}}", err)
}
return nil
}
func (i *IdentityStore) MemDBUpsertEntity(entity *identity.Entity) error {
if entity == nil {
return fmt.Errorf("entity to upsert is nil")
}
txn := i.db.Txn(true)
defer txn.Abort()
err := i.MemDBUpsertEntityInTxn(txn, entity)
if err != nil {
return err
}
txn.Commit()
return nil
}
func (i *IdentityStore) MemDBEntityByIDInTxn(txn *memdb.Txn, entityID string, clone bool) (*identity.Entity, error) {
if entityID == "" {
return nil, fmt.Errorf("missing entity id")
}
if txn == nil {
return nil, fmt.Errorf("txn is nil")
}
entityRaw, err := txn.First(entitiesTable, "id", entityID)
if err != nil {
return nil, errwrap.Wrapf("failed to fetch entity from memdb using entity id: {{err}}", err)
}
if entityRaw == nil {
return nil, nil
}
entity, ok := entityRaw.(*identity.Entity)
if !ok {
return nil, fmt.Errorf("failed to declare the type of fetched entity")
}
if clone {
return entity.Clone()
}
return entity, nil
}
func (i *IdentityStore) MemDBEntityByID(entityID string, clone bool) (*identity.Entity, error) {
if entityID == "" {
return nil, fmt.Errorf("missing entity id")
}
txn := i.db.Txn(false)
return i.MemDBEntityByIDInTxn(txn, entityID, clone)
}
func (i *IdentityStore) MemDBEntityByNameInTxn(txn *memdb.Txn, entityName string, clone bool) (*identity.Entity, error) {
if entityName == "" {
return nil, fmt.Errorf("missing entity name")
}
if txn == nil {
return nil, fmt.Errorf("txn is nil")
}
entityRaw, err := txn.First(entitiesTable, "name", entityName)
if err != nil {
return nil, errwrap.Wrapf("failed to fetch entity from memdb using entity name: {{err}}", err)
}
if entityRaw == nil {
return nil, nil
}
entity, ok := entityRaw.(*identity.Entity)
if !ok {
return nil, fmt.Errorf("failed to declare the type of fetched entity")
}
if clone {
return entity.Clone()
}
return entity, nil
}
func (i *IdentityStore) MemDBEntityByName(entityName string, clone bool) (*identity.Entity, error) {
if entityName == "" {
return nil, fmt.Errorf("missing entity name")
}
txn := i.db.Txn(false)
return i.MemDBEntityByNameInTxn(txn, entityName, clone)
}
func (i *IdentityStore) MemDBEntitiesByMetadata(filters map[string]string, clone bool) ([]*identity.Entity, error) {
if filters == nil {
return nil, fmt.Errorf("map filter is nil")
}
txn := i.db.Txn(false)
defer txn.Abort()
var args []interface{}
for key, value := range filters {
args = append(args, key, value)
break
}
entitiesIter, err := txn.Get(entitiesTable, "metadata", args...)
if err != nil {
return nil, errwrap.Wrapf("failed to lookup entities using metadata: {{err}}", err)
}
var entities []*identity.Entity
for entity := entitiesIter.Next(); entity != nil; entity = entitiesIter.Next() {
entry := entity.(*identity.Entity)
if clone {
entry, err = entry.Clone()
if err != nil {
return nil, err
}
}
if len(filters) <= 1 || satisfiesMetadataFilters(entry.Metadata, filters) {
entities = append(entities, entry)
}
}
return entities, nil
}
func (i *IdentityStore) MemDBEntitiesByBucketEntryKeyHash(hashValue string) ([]*identity.Entity, error) {
if hashValue == "" {
return nil, fmt.Errorf("empty hash value")
}
txn := i.db.Txn(false)
defer txn.Abort()
return i.MemDBEntitiesByBucketEntryKeyHashInTxn(txn, hashValue)
}
func (i *IdentityStore) MemDBEntitiesByBucketEntryKeyHashInTxn(txn *memdb.Txn, hashValue string) ([]*identity.Entity, error) {
if txn == nil {
return nil, fmt.Errorf("nil txn")
}
if hashValue == "" {
return nil, fmt.Errorf("empty hash value")