-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathsyncer.go
More file actions
3064 lines (2642 loc) · 88.1 KB
/
syncer.go
File metadata and controls
3064 lines (2642 loc) · 88.1 KB
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 sync
import (
"bytes"
"context"
"database/sql"
"errors"
"fmt"
"io"
"iter"
"os"
"slices"
"strconv"
"strings"
"time"
"github.com/Masterminds/semver/v3"
"github.com/conductorone/baton-sdk/pkg/bid"
"github.com/conductorone/baton-sdk/pkg/dotc1z"
"github.com/conductorone/baton-sdk/pkg/retry"
"github.com/conductorone/baton-sdk/pkg/sync/expand"
"github.com/conductorone/baton-sdk/pkg/types/entitlement"
batonGrant "github.com/conductorone/baton-sdk/pkg/types/grant"
"github.com/conductorone/baton-sdk/pkg/types/resource"
"github.com/conductorone/baton-sdk/pkg/types/sessions"
mapset "github.com/deckarep/golang-set/v2"
"github.com/grpc-ecosystem/go-grpc-middleware/logging/zap/ctxzap"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.uber.org/zap"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
c1zpb "github.com/conductorone/baton-sdk/pb/c1/c1z/v1"
v2 "github.com/conductorone/baton-sdk/pb/c1/connector/v2"
reader_v2 "github.com/conductorone/baton-sdk/pb/c1/reader/v2"
"github.com/conductorone/baton-sdk/pkg/annotations"
"github.com/conductorone/baton-sdk/pkg/connectorstore"
"github.com/conductorone/baton-sdk/pkg/dotc1z/manager"
"github.com/conductorone/baton-sdk/pkg/types"
)
var tracer = otel.Tracer("baton-sdk/sync")
var dontFixCycles, _ = strconv.ParseBool(os.Getenv("BATON_DONT_FIX_CYCLES"))
var ErrSyncNotComplete = fmt.Errorf("sync exited without finishing")
type Syncer interface {
Sync(context.Context) error
Close(context.Context) error
}
type ProgressCounts struct {
ResourceTypes int
Resources map[string]int
EntitlementsProgress map[string]int
LastEntitlementLog map[string]time.Time
GrantsProgress map[string]int
LastGrantLog map[string]time.Time
LastActionLog time.Time
}
const maxLogFrequency = 10 * time.Second
// TODO: use a mutex or a syncmap for when this code becomes parallel
func NewProgressCounts() *ProgressCounts {
return &ProgressCounts{
Resources: make(map[string]int),
EntitlementsProgress: make(map[string]int),
LastEntitlementLog: make(map[string]time.Time),
GrantsProgress: make(map[string]int),
LastGrantLog: make(map[string]time.Time),
LastActionLog: time.Time{},
}
}
func (p *ProgressCounts) LogResourceTypesProgress(ctx context.Context) {
l := ctxzap.Extract(ctx)
l.Info("Synced resource types", zap.Int("count", p.ResourceTypes))
}
func (p *ProgressCounts) LogResourcesProgress(ctx context.Context, resourceType string) {
l := ctxzap.Extract(ctx)
resources := p.Resources[resourceType]
l.Info("Synced resources", zap.String("resource_type_id", resourceType), zap.Int("count", resources))
}
func (p *ProgressCounts) LogEntitlementsProgress(ctx context.Context, resourceType string) {
entitlementsProgress := p.EntitlementsProgress[resourceType]
resources := p.Resources[resourceType]
l := ctxzap.Extract(ctx)
if resources == 0 {
// if resuming sync, resource counts will be zero, so don't calculate percentage. just log every 10 seconds.
if time.Since(p.LastEntitlementLog[resourceType]) > maxLogFrequency {
l.Info("Syncing entitlements",
zap.String("resource_type_id", resourceType),
zap.Int("synced", entitlementsProgress),
)
p.LastEntitlementLog[resourceType] = time.Now()
}
return
}
percentComplete := (entitlementsProgress * 100) / resources
switch {
case percentComplete == 100:
l.Info("Synced entitlements",
zap.String("resource_type_id", resourceType),
zap.Int("count", entitlementsProgress),
zap.Int("total", resources),
)
p.LastEntitlementLog[resourceType] = time.Time{}
case time.Since(p.LastEntitlementLog[resourceType]) > maxLogFrequency:
if entitlementsProgress > resources {
l.Warn("more entitlement resources than resources",
zap.String("resource_type_id", resourceType),
zap.Int("synced", entitlementsProgress),
zap.Int("total", resources),
)
} else {
l.Info("Syncing entitlements",
zap.String("resource_type_id", resourceType),
zap.Int("synced", entitlementsProgress),
zap.Int("total", resources),
zap.Int("percent_complete", percentComplete),
)
}
p.LastEntitlementLog[resourceType] = time.Now()
}
}
func (p *ProgressCounts) LogGrantsProgress(ctx context.Context, resourceType string) {
grantsProgress := p.GrantsProgress[resourceType]
resources := p.Resources[resourceType]
l := ctxzap.Extract(ctx)
if resources == 0 {
// if resuming sync, resource counts will be zero, so don't calculate percentage. just log every 10 seconds.
if time.Since(p.LastGrantLog[resourceType]) > maxLogFrequency {
l.Info("Syncing grants",
zap.String("resource_type_id", resourceType),
zap.Int("synced", grantsProgress),
)
p.LastGrantLog[resourceType] = time.Now()
}
return
}
percentComplete := (grantsProgress * 100) / resources
switch {
case percentComplete == 100:
l.Info("Synced grants",
zap.String("resource_type_id", resourceType),
zap.Int("count", grantsProgress),
zap.Int("total", resources),
)
p.LastGrantLog[resourceType] = time.Time{}
case time.Since(p.LastGrantLog[resourceType]) > maxLogFrequency:
if grantsProgress > resources {
l.Warn("more grant resources than resources",
zap.String("resource_type_id", resourceType),
zap.Int("synced", grantsProgress),
zap.Int("total", resources),
)
} else {
l.Info("Syncing grants",
zap.String("resource_type_id", resourceType),
zap.Int("synced", grantsProgress),
zap.Int("total", resources),
zap.Int("percent_complete", percentComplete),
)
}
p.LastGrantLog[resourceType] = time.Now()
}
}
func (p *ProgressCounts) LogExpandProgress(ctx context.Context, actions []*expand.EntitlementGraphAction) {
actionsLen := len(actions)
if time.Since(p.LastActionLog) < maxLogFrequency {
return
}
p.LastActionLog = time.Now()
l := ctxzap.Extract(ctx)
l.Info("Expanding grants", zap.Int("actions_remaining", actionsLen))
}
// syncer orchestrates a connector sync and stores the results using the provided datasource.Writer.
type syncer struct {
c1zManager manager.Manager
c1zPath string
externalResourceC1ZPath string
externalResourceEntitlementIdFilter string
store connectorstore.Writer
externalResourceReader connectorstore.Reader
connector types.ConnectorClient
state State
runDuration time.Duration
transitionHandler func(s Action)
progressHandler func(p *Progress)
tmpDir string
skipFullSync bool
lastCheckPointTime time.Time
counts *ProgressCounts
targetedSyncResources []*v2.Resource
onlyExpandGrants bool
dontExpandGrants bool
syncID string
skipEGForResourceType map[string]bool
skipEntitlementsForResourceType map[string]bool
skipEntitlementsAndGrants bool
skipGrants bool
resourceTypeTraits map[string][]v2.ResourceType_Trait
syncType connectorstore.SyncType
injectSyncIDAnnotation bool
setSessionStore sessions.SetSessionStore
syncResourceTypes []string
}
const minCheckpointInterval = 10 * time.Second
// Checkpoint marshals the current state and stores it.
func (s *syncer) Checkpoint(ctx context.Context, force bool) error {
if !force && !s.lastCheckPointTime.IsZero() && time.Since(s.lastCheckPointTime) < minCheckpointInterval {
return nil
}
ctx, span := tracer.Start(ctx, "syncer.Checkpoint")
defer span.End()
s.lastCheckPointTime = time.Now()
checkpoint, err := s.state.Marshal()
if err != nil {
return err
}
err = s.store.CheckpointSync(ctx, checkpoint)
if err != nil {
return err
}
return nil
}
func (s *syncer) handleInitialActionForStep(ctx context.Context, a Action) {
if s.transitionHandler != nil {
s.transitionHandler(a)
}
}
func (s *syncer) handleProgress(ctx context.Context, a *Action, c int) {
if s.progressHandler != nil {
//nolint:gosec // No risk of overflow because `c` is a slice length.
count := uint32(c)
s.progressHandler(NewProgress(a, count))
}
}
func isWarning(ctx context.Context, err error) bool {
if err == nil {
return false
}
if status.Code(err) == codes.NotFound {
return true
}
return false
}
func (s *syncer) startOrResumeSync(ctx context.Context) (string, bool, error) {
// Sync resuming logic:
// If we know our sync ID, set it as the current sync and return (resuming that sync).
// If targetedSyncResources is not set, find the most recent unfinished sync of our desired sync type & resume it (regardless of partial or full).
// If there are no unfinished syncs of our desired sync type, start a new sync.
// If targetedSyncResources is set, start a new partial sync. Use the most recent completed sync as the parent sync ID (if it exists).
if s.syncID != "" {
err := s.store.SetCurrentSync(ctx, s.syncID)
if err != nil {
return "", false, err
}
return s.syncID, false, nil
}
var syncID string
var newSync bool
var err error
if len(s.targetedSyncResources) == 0 {
syncID, newSync, err = s.store.StartOrResumeSync(ctx, s.syncType, "")
if err != nil {
return "", false, err
}
return syncID, newSync, nil
}
// Get most recent completed full sync if it exists
latestFullSyncResponse, err := s.store.GetLatestFinishedSync(ctx, reader_v2.SyncsReaderServiceGetLatestFinishedSyncRequest_builder{
SyncType: string(connectorstore.SyncTypeFull),
}.Build())
if err != nil {
return "", false, err
}
var latestFullSyncId string
latestFullSync := latestFullSyncResponse.GetSync()
if latestFullSync != nil {
latestFullSyncId = latestFullSync.GetId()
}
syncID, err = s.store.StartNewSync(ctx, connectorstore.SyncTypePartial, latestFullSyncId)
if err != nil {
return "", false, err
}
newSync = true
return syncID, newSync, nil
}
func (s *syncer) getActiveSyncID() string {
if s.injectSyncIDAnnotation {
return s.syncID
}
return ""
}
// Sync starts the syncing process. The sync process is driven by the action stack that is part of the state object.
// For each page of data that is required to be fetched from the connector, a new action is pushed on to the stack. Once
// an action is completed, it is popped off of the queue. Before processing each action, we checkpoint the state object
// into the datasource. This allows for graceful resumes if a sync is interrupted.
func (s *syncer) Sync(ctx context.Context) error {
ctx, span := tracer.Start(ctx, "syncer.Sync")
defer span.End()
if s.skipFullSync {
return s.SkipSync(ctx)
}
l := ctxzap.Extract(ctx)
runCtx := ctx
var runCanc context.CancelFunc
if s.runDuration > 0 {
runCtx, runCanc = context.WithTimeout(ctx, s.runDuration)
}
if runCanc != nil {
defer runCanc()
}
err := s.loadStore(ctx)
if err != nil {
return err
}
resp, err := s.connector.Validate(ctx, &v2.ConnectorServiceValidateRequest{})
if err != nil {
return err
}
if resp.GetSdkVersion() != "" {
sdkVersion, err := semver.NewVersion(resp.GetSdkVersion())
if err != nil {
l.Warn("error parsing sdk version", zap.String("sdk_version", resp.GetSdkVersion()), zap.Error(err))
} else {
supportsActiveSyncId, err := semver.NewConstraint(">= 0.4.3")
if err != nil {
return fmt.Errorf("error parsing sdk version %s: %w", resp.GetSdkVersion(), err)
}
s.injectSyncIDAnnotation = supportsActiveSyncId.Check(sdkVersion)
}
}
syncResourceTypeMap := make(map[string]bool)
if len(s.syncResourceTypes) > 0 {
for _, rt := range s.syncResourceTypes {
syncResourceTypeMap[rt] = true
}
}
// Validate any targeted resource IDs before starting a sync.
targetedResources := []*v2.Resource{}
for _, r := range s.targetedSyncResources {
if len(s.syncResourceTypes) > 0 {
if _, ok := syncResourceTypeMap[r.GetId().GetResourceType()]; !ok {
continue
}
}
targetedResources = append(targetedResources, r)
}
syncID, newSync, err := s.startOrResumeSync(ctx)
if err != nil {
return err
}
s.syncID = syncID
// Set the syncID on the wrapper after we have it
if syncID == "" {
err = errors.New("no syncID found after starting or resuming sync")
l.Error("no syncID found after starting or resuming sync", zap.Error(err))
return err
}
span.SetAttributes(attribute.String("sync_id", syncID))
if newSync {
l.Debug("beginning new sync", zap.String("sync_id", syncID))
} else {
l.Debug("resuming previous sync", zap.String("sync_id", syncID))
}
currentStep, err := s.store.CurrentSyncStep(ctx)
if err != nil {
return err
}
state := &state{}
err = state.Unmarshal(currentStep)
if err != nil {
return err
}
s.state = state
if !newSync {
currentAction := s.state.Current()
currentActionOp := ""
currentActionPageToken := ""
currentActionResourceID := ""
currentActionResourceTypeID := ""
if currentAction != nil {
currentActionOp = currentAction.Op.String()
currentActionPageToken = currentAction.PageToken
currentActionResourceID = currentAction.ResourceID
currentActionResourceTypeID = currentAction.ResourceTypeID
}
entitlementGraph := s.state.EntitlementGraph(ctx)
l.Info("resumed previous sync",
zap.String("sync_id", syncID),
zap.String("sync_type", string(s.syncType)),
zap.String("current_action_op", currentActionOp),
zap.String("current_action_resource_id", currentActionResourceID),
zap.String("current_action_resource_type_id", currentActionResourceTypeID),
zap.String("current_action_page_token", currentActionPageToken),
zap.Bool("needs_expansion", s.state.NeedsExpansion()),
zap.Bool("has_external_resources_grants", s.state.HasExternalResourcesGrants()),
zap.Bool("should_fetch_related_resources", s.state.ShouldFetchRelatedResources()),
zap.Bool("should_skip_entitlements_and_grants", s.state.ShouldSkipEntitlementsAndGrants()),
zap.Bool("should_skip_grants", s.state.ShouldSkipGrants()),
zap.Bool("graph_loaded", entitlementGraph.Loaded),
zap.Bool("graph_has_no_cycles", entitlementGraph.HasNoCycles),
zap.Int("graph_depth", entitlementGraph.Depth),
zap.Int("graph_actions", len(entitlementGraph.Actions)),
zap.Int("graph_edges", len(entitlementGraph.Edges)),
zap.Int("graph_nodes", len(entitlementGraph.Nodes)),
)
}
retryer := retry.NewRetryer(ctx, retry.RetryConfig{
MaxAttempts: 0,
InitialDelay: 1 * time.Second,
MaxDelay: 0,
})
var warnings []error
for s.state.Current() != nil {
err = s.Checkpoint(ctx, false)
if err != nil {
return err
}
// If we have more than 10 warnings and more than 10% of actions ended in a warning, exit the sync.
if len(warnings) > 10 {
completedActionsCount := s.state.GetCompletedActionsCount()
if completedActionsCount > 0 && float64(len(warnings))/float64(completedActionsCount) > 0.1 {
return fmt.Errorf("too many warnings, exiting sync. warnings: %v completed actions: %d", warnings, completedActionsCount)
}
}
select {
case <-runCtx.Done():
err = context.Cause(runCtx)
switch {
case errors.Is(err, context.DeadlineExceeded):
l.Info("sync run duration has expired, exiting sync early", zap.String("sync_id", syncID))
// It would be nice to remove this once we're more confident in the checkpointing logic.
checkpointErr := s.Checkpoint(ctx, true)
if checkpointErr != nil {
l.Error("error checkpointing before exiting sync", zap.Error(checkpointErr))
}
return errors.Join(checkpointErr, ErrSyncNotComplete)
default:
l.Error("sync context cancelled", zap.String("sync_id", syncID), zap.Error(err))
return err
}
default:
}
stateAction := s.state.Current()
switch stateAction.Op {
case InitOp:
s.state.FinishAction(ctx)
if s.skipEntitlementsAndGrants {
s.state.SetShouldSkipEntitlementsAndGrants()
}
if s.skipGrants {
s.state.SetShouldSkipGrants()
}
if len(targetedResources) > 0 {
for _, r := range targetedResources {
s.state.PushAction(ctx, Action{
Op: SyncTargetedResourceOp,
ResourceID: r.GetId().GetResource(),
ResourceTypeID: r.GetId().GetResourceType(),
ParentResourceID: r.GetParentResourceId().GetResource(),
ParentResourceTypeID: r.GetParentResourceId().GetResourceType(),
})
}
s.state.SetShouldFetchRelatedResources()
s.state.PushAction(ctx, Action{Op: SyncResourceTypesOp})
err = s.Checkpoint(ctx, true)
if err != nil {
return err
}
// Don't do grant expansion or external resources in partial syncs, as we likely lack related resources/entitlements/grants
continue
}
// FIXME(jirwin): Disabling syncing assets for now
// s.state.PushAction(ctx, Action{Op: SyncAssetsOp})
if !s.state.ShouldSkipEntitlementsAndGrants() {
s.state.PushAction(ctx, Action{Op: SyncGrantExpansionOp})
}
if s.externalResourceReader != nil {
s.state.PushAction(ctx, Action{Op: SyncExternalResourcesOp})
}
if s.onlyExpandGrants {
s.state.SetNeedsExpansion()
err = s.Checkpoint(ctx, true)
if err != nil {
return err
}
continue
}
if !s.state.ShouldSkipEntitlementsAndGrants() {
if !s.state.ShouldSkipGrants() {
s.state.PushAction(ctx, Action{Op: SyncGrantsOp})
}
s.state.PushAction(ctx, Action{Op: SyncEntitlementsOp})
s.state.PushAction(ctx, Action{Op: SyncStaticEntitlementsOp})
}
s.state.PushAction(ctx, Action{Op: SyncResourcesOp})
s.state.PushAction(ctx, Action{Op: SyncResourceTypesOp})
err = s.Checkpoint(ctx, true)
if err != nil {
return err
}
continue
case SyncResourceTypesOp:
err = s.SyncResourceTypes(ctx)
if !retryer.ShouldWaitAndRetry(ctx, err) {
return err
}
continue
case SyncResourcesOp:
err = s.SyncResources(ctx)
if !retryer.ShouldWaitAndRetry(ctx, err) {
return err
}
continue
case SyncTargetedResourceOp:
err = s.SyncTargetedResource(ctx)
if isWarning(ctx, err) {
l.Warn("skipping sync targeted resource action", zap.Any("stateAction", stateAction), zap.Error(err))
warnings = append(warnings, err)
s.state.FinishAction(ctx)
continue
}
if !retryer.ShouldWaitAndRetry(ctx, err) {
return err
}
continue
case SyncStaticEntitlementsOp:
err = s.SyncStaticEntitlements(ctx)
if isWarning(ctx, err) {
l.Warn("skipping sync static entitlements action", zap.Any("stateAction", stateAction), zap.Error(err))
warnings = append(warnings, err)
s.state.FinishAction(ctx)
continue
}
if !retryer.ShouldWaitAndRetry(ctx, err) {
return err
}
continue
case SyncEntitlementsOp:
err = s.SyncEntitlements(ctx)
if isWarning(ctx, err) {
l.Warn("skipping sync entitlement action", zap.Any("stateAction", stateAction), zap.Error(err))
warnings = append(warnings, err)
s.state.FinishAction(ctx)
continue
}
if !retryer.ShouldWaitAndRetry(ctx, err) {
return err
}
continue
case SyncGrantsOp:
err = s.SyncGrants(ctx)
if isWarning(ctx, err) {
l.Warn("skipping sync grant action", zap.Any("stateAction", stateAction), zap.Error(err))
warnings = append(warnings, err)
s.state.FinishAction(ctx)
continue
}
if !retryer.ShouldWaitAndRetry(ctx, err) {
return err
}
continue
case SyncExternalResourcesOp:
err = s.SyncExternalResources(ctx)
if !retryer.ShouldWaitAndRetry(ctx, err) {
return err
}
continue
case SyncAssetsOp:
err = s.SyncAssets(ctx)
if !retryer.ShouldWaitAndRetry(ctx, err) {
return err
}
continue
case SyncGrantExpansionOp:
if s.dontExpandGrants || !s.state.NeedsExpansion() {
l.Debug("skipping grant expansion, no grants to expand")
s.state.FinishAction(ctx)
continue
}
err = s.SyncGrantExpansion(ctx)
if !retryer.ShouldWaitAndRetry(ctx, err) {
return err
}
continue
default:
return fmt.Errorf("unexpected sync step")
}
}
// Force a checkpoint to clear completed actions & entitlement graph in sync_token.
s.state.ClearEntitlementGraph(ctx)
err = s.Checkpoint(ctx, true)
if err != nil {
return err
}
err = s.store.EndSync(ctx)
if err != nil {
return err
}
l.Info("Sync complete.")
err = s.store.Cleanup(ctx)
if err != nil {
return err
}
_, err = s.connector.Cleanup(ctx, v2.ConnectorServiceCleanupRequest_builder{
ActiveSyncId: s.getActiveSyncID(),
}.Build())
if err != nil {
l.Error("error clearing connector caches", zap.Error(err))
}
if len(warnings) > 0 {
l.Warn("sync completed with warnings", zap.Int("warning_count", len(warnings)), zap.Any("warnings", warnings))
}
return nil
}
func (s *syncer) SkipSync(ctx context.Context) error {
ctx, span := tracer.Start(ctx, "syncer.SkipSync")
defer span.End()
l := ctxzap.Extract(ctx)
l.Info("skipping sync")
var runCanc context.CancelFunc
if s.runDuration > 0 {
_, runCanc = context.WithTimeout(ctx, s.runDuration)
}
if runCanc != nil {
defer runCanc()
}
err := s.loadStore(ctx)
if err != nil {
return err
}
_, err = s.connector.Validate(ctx, &v2.ConnectorServiceValidateRequest{})
if err != nil {
return err
}
// TODO: Create a new sync type for empty syncs.
_, err = s.store.StartNewSync(ctx, connectorstore.SyncTypeFull, "")
if err != nil {
return err
}
err = s.store.EndSync(ctx)
if err != nil {
return err
}
err = s.store.Cleanup(ctx)
if err != nil {
return err
}
return nil
}
func (s *syncer) listAllResourceTypes(ctx context.Context) iter.Seq2[[]*v2.ResourceType, error] {
return func(yield func([]*v2.ResourceType, error) bool) {
pageToken := ""
for {
resp, err := s.connector.ListResourceTypes(ctx, v2.ResourceTypesServiceListResourceTypesRequest_builder{PageToken: pageToken}.Build())
if err != nil {
_ = yield(nil, err)
return
}
resourceTypes := resp.GetList()
if len(resourceTypes) > 0 {
if !yield(resourceTypes, err) {
return
}
}
pageToken = resp.GetNextPageToken()
if pageToken == "" {
return
}
}
}
}
// SyncResourceTypes calls the ListResourceType() connector endpoint and persists the results in to the datasource.
func (s *syncer) SyncResourceTypes(ctx context.Context) error {
ctx, span := tracer.Start(ctx, "syncer.SyncResourceTypes")
defer span.End()
pageToken := s.state.PageToken(ctx)
if pageToken == "" {
ctxzap.Extract(ctx).Info("Syncing resource types...")
s.handleInitialActionForStep(ctx, *s.state.Current())
}
err := s.loadStore(ctx)
if err != nil {
return err
}
resp, err := s.connector.ListResourceTypes(ctx, v2.ResourceTypesServiceListResourceTypesRequest_builder{
PageToken: pageToken,
ActiveSyncId: s.getActiveSyncID(),
}.Build())
if err != nil {
return err
}
var resourceTypes []*v2.ResourceType
if len(s.syncResourceTypes) > 0 {
syncResourceTypeMap := make(map[string]bool)
for _, rt := range s.syncResourceTypes {
syncResourceTypeMap[rt] = true
}
for _, rt := range resp.GetList() {
if shouldSync := syncResourceTypeMap[rt.GetId()]; shouldSync {
resourceTypes = append(resourceTypes, rt)
}
}
} else {
resourceTypes = resp.GetList()
}
err = s.store.PutResourceTypes(ctx, resourceTypes...)
if err != nil {
return err
}
s.counts.ResourceTypes += len(resourceTypes)
s.handleProgress(ctx, s.state.Current(), len(resourceTypes))
if resp.GetNextPageToken() == "" {
s.counts.LogResourceTypesProgress(ctx)
if len(s.syncResourceTypes) > 0 {
validResourceTypesResp, err := s.store.ListResourceTypes(ctx, v2.ResourceTypesServiceListResourceTypesRequest_builder{PageToken: pageToken}.Build())
if err != nil {
return err
}
err = validateSyncResourceTypesFilter(s.syncResourceTypes, validResourceTypesResp.GetList())
if err != nil {
return err
}
}
s.state.FinishAction(ctx)
return nil
}
err = s.state.NextPage(ctx, resp.GetNextPageToken())
if err != nil {
return err
}
return nil
}
func validateSyncResourceTypesFilter(resourceTypesFilter []string, validResourceTypes []*v2.ResourceType) error {
validResourceTypesMap := make(map[string]bool)
for _, rt := range validResourceTypes {
validResourceTypesMap[rt.GetId()] = true
}
for _, rt := range resourceTypesFilter {
if _, ok := validResourceTypesMap[rt]; !ok {
return fmt.Errorf("invalid resource type '%s' in filter", rt)
}
}
return nil
}
// getSubResources fetches the sub resource types from a resources' annotations.
func (s *syncer) getSubResources(ctx context.Context, parent *v2.Resource) error {
ctx, span := tracer.Start(ctx, "syncer.getSubResources")
defer span.End()
for _, a := range parent.GetAnnotations() {
if a.MessageIs((*v2.ChildResourceType)(nil)) {
crt := &v2.ChildResourceType{}
err := a.UnmarshalTo(crt)
if err != nil {
return err
}
childAction := Action{
Op: SyncResourcesOp,
ResourceTypeID: crt.GetResourceTypeId(),
ParentResourceID: parent.GetId().GetResource(),
ParentResourceTypeID: parent.GetId().GetResourceType(),
}
s.state.PushAction(ctx, childAction)
}
}
return nil
}
func (s *syncer) getResourceFromConnector(ctx context.Context, resourceID *v2.ResourceId, parentResourceID *v2.ResourceId) (*v2.Resource, error) {
ctx, span := tracer.Start(ctx, "syncer.getResource")
defer span.End()
resourceResp, err := s.connector.GetResource(ctx,
v2.ResourceGetterServiceGetResourceRequest_builder{
ResourceId: resourceID,
ParentResourceId: parentResourceID,
ActiveSyncId: s.getActiveSyncID(),
}.Build(),
)
if err == nil {
return resourceResp.GetResource(), nil
}
l := ctxzap.Extract(ctx)
if status.Code(err) == codes.NotFound {
l.Warn("skipping resource due to not found", zap.String("resource_id", resourceID.GetResource()), zap.String("resource_type_id", resourceID.GetResourceType()))
return nil, nil
}
if status.Code(err) == codes.Unimplemented {
l.Warn("skipping resource due to unimplemented connector", zap.String("resource_id", resourceID.GetResource()), zap.String("resource_type_id", resourceID.GetResourceType()))
return nil, nil
}
return nil, err
}
func (s *syncer) SyncTargetedResource(ctx context.Context) error {
ctx, span := tracer.Start(ctx, "syncer.SyncTargetedResource")
defer span.End()
resourceID := s.state.ResourceID(ctx)
resourceTypeID := s.state.ResourceTypeID(ctx)
if resourceID == "" || resourceTypeID == "" {
return errors.New("cannot get resource without a resource target")
}
parentResourceID := s.state.ParentResourceID(ctx)
parentResourceTypeID := s.state.ParentResourceTypeID(ctx)
var prID *v2.ResourceId
if parentResourceID != "" && parentResourceTypeID != "" {
prID = v2.ResourceId_builder{
ResourceType: parentResourceTypeID,
Resource: parentResourceID,
}.Build()
}
resource, err := s.getResourceFromConnector(ctx, v2.ResourceId_builder{
ResourceType: resourceTypeID,
Resource: resourceID,
}.Build(), prID)
if err != nil {
return err
}
// If getResource encounters not found or unimplemented, it returns a nil resource and nil error.
if resource == nil {
s.state.FinishAction(ctx)
return nil
}
// Save our resource in the DB
if err := s.store.PutResources(ctx, resource); err != nil {
return err
}
s.state.FinishAction(ctx)
// Actions happen in reverse order. We want to sync child resources, then entitlements, then grants
shouldSkipGrants, err := s.shouldSkipGrants(ctx, resource)
if err != nil {
return err
}
if !shouldSkipGrants {
s.state.PushAction(ctx, Action{
Op: SyncGrantsOp,
ResourceTypeID: resourceTypeID,
ResourceID: resourceID,
})
}
shouldSkipEnts, err := s.shouldSkipEntitlements(ctx, resource)
if err != nil {
return err
}
if !shouldSkipEnts {
s.state.PushAction(ctx, Action{
Op: SyncEntitlementsOp,
ResourceTypeID: resourceTypeID,
ResourceID: resourceID,
})
}
err = s.getSubResources(ctx, resource)
if err != nil {
return err
}
return nil
}
// SyncResources handles fetching all of the resources from the connector given the provided resource types. For each
// resource, we gather any child resource types it may emit, and traverse the resource tree.
func (s *syncer) SyncResources(ctx context.Context) error {
ctx, span := tracer.Start(ctx, "syncer.SyncResources")
defer span.End()
if s.state.Current().ResourceTypeID == "" {
pageToken := s.state.PageToken(ctx)
if pageToken == "" {
ctxzap.Extract(ctx).Info("Syncing resources...")
s.handleInitialActionForStep(ctx, *s.state.Current())
}
resp, err := s.store.ListResourceTypes(ctx, v2.ResourceTypesServiceListResourceTypesRequest_builder{PageToken: pageToken}.Build())
if err != nil {
return err
}
if resp.GetNextPageToken() != "" {
err = s.state.NextPage(ctx, resp.GetNextPageToken())
if err != nil {
return err
}
} else {
s.state.FinishAction(ctx)
}