-
Notifications
You must be signed in to change notification settings - Fork 158
/
Copy pathcontroller.go
1476 lines (1345 loc) · 50.5 KB
/
controller.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 synchronization
import (
"context"
"errors"
"fmt"
"math"
"os"
"sync"
"time"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/timestamppb"
"github.com/mutagen-io/mutagen/pkg/encoding"
"github.com/mutagen-io/mutagen/pkg/logging"
"github.com/mutagen-io/mutagen/pkg/mutagen"
"github.com/mutagen-io/mutagen/pkg/prompting"
"github.com/mutagen-io/mutagen/pkg/state"
"github.com/mutagen-io/mutagen/pkg/synchronization/core"
"github.com/mutagen-io/mutagen/pkg/synchronization/core/ignore"
"github.com/mutagen-io/mutagen/pkg/synchronization/rsync"
"github.com/mutagen-io/mutagen/pkg/url"
)
const (
// autoReconnectInterval is the period of time to wait before attempting an
// automatic reconnect after disconnection or a failed reconnect.
autoReconnectInterval = 15 * time.Second
// rescanWaitDuration is the period of time to wait before attempting to
// rescan after an ephemeral scan failure.
rescanWaitDuration = 5 * time.Second
// synchronizationLongLivedThreshold is the duration that a synchronization
// loop must run in order to be considered long-lived.
synchronizationLongLivedThreshold = 10 * time.Second
// backoffFactorBase is the base to use when calculating the backoff factor.
backoffFactorBase = 2
// backoffFactorMaximumExponent is the the maximum backoff factor exponent.
// The exponent is calculated using the number of sequential short-lived
// synchronization loops.
backoffFactorMaximumExponent = 4
)
// controller manages and executes a single session.
type controller struct {
// logger is the controller logger.
logger *logging.Logger
// sessionPath is the path to the serialized session.
sessionPath string
// archivePath is the path to the serialized archive.
archivePath string
// stateLock guards and tracks changes to session's Paused field, state, and
// synchronizing. Previous holders may continue to poll on synchronizing if
// they store it in a separate variable before releasing the lock.
stateLock *state.TrackingLock
// session encodes the associated session metadata. It is considered static
// and safe for concurrent access except for its Paused field, for which
// stateLock should be held. It should be saved to disk any time it is
// modified.
session *Session
// mergedAlphaConfiguration is the alpha-specific configuration object
// (computed from the core configuration and alpha-specific overrides). It
// is considered static and safe for concurrent access. It is a derived
// field and not saved to disk.
mergedAlphaConfiguration *Configuration
// mergedBetaConfiguration is the beta-specific configuration object
// (computed from the core configuration and beta-specific overrides). It is
// considered static and safe for concurrent access. It is a derived field
// and not saved to disk.
mergedBetaConfiguration *Configuration
// state represents the current synchronization state.
state *State
// synchronizing is used to track whether or not the synchronization loop is
// currently in a state where it is capable of performing synchronization.
// It is non-nil if and only if the synchronization loop is connected and in
// a state where it can perform synchronization. It is closed when
// synchronization fails due to an error.
synchronizing chan struct{}
// lifecycleLock guards access to disabled, cancel, flushRequests, and done.
// Only the current holder of the lifecycle lock may set any of these fields
// or invoke cancel. The synchronization loop may close close done or
// receive from flushRequests without holding the lifecycle lock. Moreover,
// previous lifecycle lock holders may continue to send to flushRequests and
// poll on done after storing them in separate variables and releasing the
// lifecycle lock. Any code wishing to set these fields must first acquire
// the lock, then cancel the synchronization loop and wait for it to
// complete before making any changes.
lifecycleLock sync.Mutex
// disabled indicates that no more changes to the synchronization loop
// lifecycle are allowed (i.e. no more synchronization loops can be started
// for this controller). This is used by terminate and shutdown. It should
// only be set to true once any existing synchronization loop has been
// stopped.
disabled bool
// cancel cancels the synchronization loop execution context. It is nil if
// and only if there is no synchronization loop running.
cancel context.CancelFunc
// flushRequests is used pass flush requests to the synchronization loop. It
// is buffered, allowing a single request to be queued. All requests passed
// via this channel must be buffered and contain room for one error.
flushRequests chan chan error
// done will be closed by the current synchronization loop when it exits.
done chan struct{}
}
// newSession creates a new session and corresponding controller.
func newSession(
ctx context.Context,
logger *logging.Logger,
tracker *state.Tracker,
identifier string,
alpha, beta *url.URL,
configuration, configurationAlpha, configurationBeta *Configuration,
name string,
labels map[string]string,
paused bool,
prompter string,
) (*controller, error) {
// Update status.
prompting.Message(prompter, "Creating session...")
// Set the session version.
version := DefaultVersion
// Compute the creation time and check that it's valid for Protocol Buffers.
creationTime := timestamppb.Now()
if err := creationTime.CheckValid(); err != nil {
return nil, fmt.Errorf("unable to record creation time: %w", err)
}
// Compute merged endpoint configurations.
mergedAlphaConfiguration := MergeConfigurations(configuration, configurationAlpha)
mergedBetaConfiguration := MergeConfigurations(configuration, configurationBeta)
// If the session isn't being created paused, then try to connect to the
// endpoints. Before doing so, set up a deferred handler that will shut down
// any endpoints that aren't handed off to the run loop due to errors.
var alphaEndpoint, betaEndpoint Endpoint
var err error
defer func() {
if alphaEndpoint != nil {
alphaEndpoint.Shutdown()
alphaEndpoint = nil
}
if betaEndpoint != nil {
betaEndpoint.Shutdown()
betaEndpoint = nil
}
}()
if !paused {
logger.Info("Connecting to alpha endpoint")
alphaEndpoint, err = connect(
ctx,
logger.Sublogger("alpha"),
alpha,
prompter,
identifier,
version,
mergedAlphaConfiguration,
true,
)
if err != nil {
logger.Info("Alpha connection failure:", err)
return nil, fmt.Errorf("unable to connect to alpha: %w", err)
}
logger.Info("Connecting to beta endpoint")
betaEndpoint, err = connect(
ctx,
logger.Sublogger("beta"),
beta,
prompter,
identifier,
version,
mergedBetaConfiguration,
false,
)
if err != nil {
logger.Info("Beta connection failure:", err)
return nil, fmt.Errorf("unable to connect to beta: %w", err)
}
}
// Create the session and initial archive.
session := &Session{
Identifier: identifier,
Version: version,
CreationTime: creationTime,
CreatingVersionMajor: mutagen.VersionMajor,
CreatingVersionMinor: mutagen.VersionMinor,
CreatingVersionPatch: mutagen.VersionPatch,
Alpha: alpha,
Beta: beta,
Configuration: configuration,
ConfigurationAlpha: configurationAlpha,
ConfigurationBeta: configurationBeta,
Name: name,
Labels: labels,
Paused: paused,
}
archive := &core.Archive{}
// Compute the session and archive paths.
sessionPath, err := pathForSession(session.Identifier)
if err != nil {
return nil, fmt.Errorf("unable to compute session path: %w", err)
}
archivePath, err := pathForArchive(session.Identifier)
if err != nil {
return nil, fmt.Errorf("unable to compute archive path: %w", err)
}
// Save components to disk.
if err := encoding.MarshalAndSaveProtobuf(sessionPath, session); err != nil {
return nil, fmt.Errorf("unable to save session: %w", err)
}
if err := encoding.MarshalAndSaveProtobuf(archivePath, archive); err != nil {
os.Remove(sessionPath)
return nil, fmt.Errorf("unable to save archive: %w", err)
}
// Create the controller.
controller := &controller{
logger: logger,
sessionPath: sessionPath,
archivePath: archivePath,
stateLock: state.NewTrackingLock(tracker),
session: session,
mergedAlphaConfiguration: mergedAlphaConfiguration,
mergedBetaConfiguration: mergedBetaConfiguration,
state: &State{
Session: session,
AlphaState: &EndpointState{},
BetaState: &EndpointState{},
},
}
// If the session isn't being created paused, then start a synchronization
// loop and mark the endpoints as handed off to that loop so that we don't
// defer their shutdown.
if !paused {
ctx, cancel := context.WithCancel(context.Background())
controller.cancel = cancel
controller.flushRequests = make(chan chan error, 1)
controller.done = make(chan struct{})
go controller.run(ctx, alphaEndpoint, betaEndpoint)
alphaEndpoint = nil
betaEndpoint = nil
}
// Success.
logger.Info("Session initialized")
return controller, nil
}
// loadSession loads an existing session and creates a corresponding controller.
func loadSession(logger *logging.Logger, tracker *state.Tracker, identifier string) (*controller, error) {
// Compute session and archive paths.
sessionPath, err := pathForSession(identifier)
if err != nil {
return nil, fmt.Errorf("unable to compute session path: %w", err)
}
archivePath, err := pathForArchive(identifier)
if err != nil {
return nil, fmt.Errorf("unable to compute archive path: %w", err)
}
// Load and validate the session. We have to populate a few optional fields
// before validation if they're not set. We can't do this in the Session
// literal because they'll be wiped out during unmarshalling, even if not
// set.
session := &Session{}
if err := encoding.LoadAndUnmarshalProtobuf(sessionPath, session); err != nil {
return nil, fmt.Errorf("unable to load session configuration: %w", err)
}
if session.ConfigurationAlpha == nil {
session.ConfigurationAlpha = &Configuration{}
}
if session.ConfigurationBeta == nil {
session.ConfigurationBeta = &Configuration{}
}
if err := session.EnsureValid(); err != nil {
return nil, fmt.Errorf("invalid session found on disk: %w", err)
}
// Create the controller.
controller := &controller{
logger: logger,
sessionPath: sessionPath,
archivePath: archivePath,
stateLock: state.NewTrackingLock(tracker),
session: session,
mergedAlphaConfiguration: MergeConfigurations(
session.Configuration,
session.ConfigurationAlpha,
),
mergedBetaConfiguration: MergeConfigurations(
session.Configuration,
session.ConfigurationBeta,
),
state: &State{
Session: session,
AlphaState: &EndpointState{},
BetaState: &EndpointState{},
},
}
// If the session isn't marked as paused, start a synchronization loop.
if !session.Paused {
ctx, cancel := context.WithCancel(context.Background())
controller.cancel = cancel
controller.flushRequests = make(chan chan error, 1)
controller.done = make(chan struct{})
go controller.run(ctx, nil, nil)
}
// Success.
logger.Info("Session loaded")
return controller, nil
}
// currentState creates a static snapshot of the current session state.
func (c *controller) currentState() *State {
// Lock the session state and defer its release. It's very important that we
// unlock without a notification here, otherwise we'd trigger an infinite
// cycle of list/notify.
c.stateLock.Lock()
defer c.stateLock.UnlockWithoutNotify()
// Create a static copy of the state.
return proto.Clone(c.state).(*State)
}
// flush attempts to force a synchronization cycle for the session. If wait is
// specified, then the method will wait until a post-flush synchronization cycle
// has completed. The provided context (which must be non-nil) can terminate
// this wait early.
func (c *controller) flush(ctx context.Context, prompter string, skipWait bool) error {
// Update status.
prompting.Message(prompter, fmt.Sprintf("Forcing synchronization cycle for session %s...", c.session.Identifier))
// Lock the controller's lifecycle.
c.lifecycleLock.Lock()
// Don't allow any operations if the controller is disabled.
if c.disabled {
c.lifecycleLock.Unlock()
return errors.New("controller disabled")
}
// Check if the session is paused.
if c.cancel == nil {
c.lifecycleLock.Unlock()
return errors.New("session is paused")
}
// Perform logging.
c.logger.Infof("Forcing synchronization cycle")
// Check if the session is currently synchronizing and store the channel
// that we'll use to track synchronizability.
c.stateLock.Lock()
synchronizing := c.synchronizing
c.stateLock.UnlockWithoutNotify()
if synchronizing == nil {
c.lifecycleLock.Unlock()
return errors.New("session is not currently able to synchronize")
}
// Store the channels that we'll need to submit flush requests and track
// synchronization termination.
flushRequests := c.flushRequests
done := c.done
// Release the lifecycle lock.
c.lifecycleLock.Unlock()
// Create a flush request.
request := make(chan error, 1)
// If we don't want to wait, then we can simply send the request in a
// non-blocking manner, in which case either this request (or one that's
// already queued) will be processed eventually. After that, we're done. In
// this case, we'll still check for an inability to synchronize, since we
// may as well report it if we can.
if skipWait {
select {
case flushRequests <- request:
return nil
case <-synchronizing:
return errors.New("synchronization failed before flush request could be sent")
case <-done:
return errors.New("synchronization terminated before flush request could be sent")
default:
return nil
}
}
// Otherwise we need to send the request in a blocking manner, watching for
// cancellation, failure, or termination.
select {
case flushRequests <- request:
case <-ctx.Done():
return errors.New("flush cancelled before request could be sent")
case <-synchronizing:
return errors.New("synchronization failed before flush request could be sent")
case <-done:
return errors.New("synchronization terminated before flush request could be sent")
}
// Now we need to wait for a response to the request, again watching for
// cancellation, failure, or termination.
select {
case err := <-request:
return err
case <-ctx.Done():
return errors.New("flush cancelled while waiting for response")
case <-synchronizing:
return errors.New("synchronization failed while waiting for flush response")
case <-done:
return errors.New("synchronization terminated while waiting for flush response")
}
}
// resume attempts to reconnect and resume the session if it isn't currently
// connected and synchronizing. If lifecycleLockHeld is true, then halt will
// assume that the lifecycle lock is held by the caller and will not attempt to
// acquire it.
func (c *controller) resume(ctx context.Context, prompter string, lifecycleLockHeld bool) error {
// Update status.
prompting.Message(prompter, fmt.Sprintf("Resuming session %s...", c.session.Identifier))
// If not already held, acquire the lifecycle lock and defer its release.
if !lifecycleLockHeld {
c.lifecycleLock.Lock()
defer c.lifecycleLock.Unlock()
}
// Don't allow any resume operations if the controller is disabled.
if c.disabled {
return errors.New("controller disabled")
}
// Perform logging.
c.logger.Infof("Resuming")
// Check if there's an existing synchronization loop (i.e. if the session is
// unpaused).
if c.cancel != nil {
// If there is an existing synchronization loop, check if it's already
// in a state that's considered "connected".
c.stateLock.Lock()
connected := c.state.Status >= Status_Watching
c.stateLock.UnlockWithoutNotify()
// If we're already connected, then there's nothing we need to do. We
// don't even need to mark the session as unpaused because it can't be
// marked as paused if an existing synchronization loop is running (we
// enforce this invariant as part of the controller's logic).
if connected {
return nil
}
// Otherwise, cancel the existing synchronization loop and wait for it
// to finish.
//
// There's something of an efficiency race condition here, because the
// existing loop might succeed in connecting between the time we check
// and the time we cancel it. That could happen if an auto-reconnect
// succeeds or even if the loop was already passed connections and it's
// just hasn't updated its status yet. But the only danger here is
// basically wasting those connections, and the window is very small.
c.cancel()
<-c.done
// Nil out any lifecycle state.
c.cancel = nil
c.flushRequests = nil
c.done = nil
}
// Mark the session as unpaused and save it to disk.
c.stateLock.Lock()
c.session.Paused = false
saveErr := encoding.MarshalAndSaveProtobuf(c.sessionPath, c.session)
c.stateLock.Unlock()
// Attempt to connect to alpha.
c.stateLock.Lock()
c.state.Status = Status_ConnectingAlpha
c.stateLock.Unlock()
alpha, alphaConnectErr := connect(
ctx,
c.logger.Sublogger("alpha"),
c.session.Alpha,
prompter,
c.session.Identifier,
c.session.Version,
c.mergedAlphaConfiguration,
true,
)
c.stateLock.Lock()
c.state.AlphaState.Connected = (alpha != nil)
c.stateLock.Unlock()
// Attempt to connect to beta.
c.stateLock.Lock()
c.state.Status = Status_ConnectingBeta
c.stateLock.Unlock()
beta, betaConnectErr := connect(
ctx,
c.logger.Sublogger("beta"),
c.session.Beta,
prompter,
c.session.Identifier,
c.session.Version,
c.mergedBetaConfiguration,
false,
)
c.stateLock.Lock()
c.state.BetaState.Connected = (beta != nil)
c.stateLock.Unlock()
// Start the synchronization loop with what we have. Alpha or beta may have
// failed to connect (and be nil), but in any case that'll just make the run
// loop keep trying to connect.
ctx, cancel := context.WithCancel(context.Background())
c.cancel = cancel
c.flushRequests = make(chan chan error, 1)
c.done = make(chan struct{})
go c.run(ctx, alpha, beta)
// Report any errors. Since we always want to start a synchronization loop,
// even on partial or complete failure (since it might be able to
// auto-reconnect on its own), we wait until the end to report errors.
if saveErr != nil {
return fmt.Errorf("unable to save session: %w", saveErr)
} else if alphaConnectErr != nil {
return fmt.Errorf("unable to connect to alpha: %w", alphaConnectErr)
} else if betaConnectErr != nil {
return fmt.Errorf("unable to connect to beta: %w", betaConnectErr)
}
// Success.
return nil
}
// controllerHaltMode represents the behavior to use when halting a session.
type controllerHaltMode uint8
const (
// controllerHaltModePause indicates that a session should be halted and
// marked as paused.
controllerHaltModePause controllerHaltMode = iota
// controllerHaltModeShutdown indicates that a session should be halted.
controllerHaltModeShutdown
// controllerHaltModeShutdown indicates that a session should be halted and
// then deleted.
controllerHaltModeTerminate
)
// description returns a human-readable description of a halt mode.
func (m controllerHaltMode) description() string {
switch m {
case controllerHaltModePause:
return "Pausing"
case controllerHaltModeShutdown:
return "Shutting down"
case controllerHaltModeTerminate:
return "Terminating"
default:
panic("unhandled halt mode")
}
}
// halt halts the session with the specified behavior. If lifecycleLockHeld is
// true, then halt will assume that the lifecycle lock is held by the caller and
// will not attempt to acquire it.
func (c *controller) halt(_ context.Context, mode controllerHaltMode, prompter string, lifecycleLockHeld bool) error {
// Update status.
prompting.Message(prompter, fmt.Sprintf("%s session %s...", mode.description(), c.session.Identifier))
// If not already held, acquire the lifecycle lock and defer its release.
if !lifecycleLockHeld {
c.lifecycleLock.Lock()
defer c.lifecycleLock.Unlock()
}
// Don't allow any additional halt operations if the controller is disabled,
// because either this session is being terminated or the service is
// shutting down, and in either case there is no point in halting.
if c.disabled {
return errors.New("controller disabled")
}
// Perform logging.
c.logger.Infof(mode.description())
// Kill any existing synchronization loop.
if c.cancel != nil {
// Cancel the synchronization loop and wait for it to finish.
c.cancel()
<-c.done
// Nil out any lifecycle state.
c.cancel = nil
c.flushRequests = nil
c.done = nil
}
// Handle based on the halt mode.
if mode == controllerHaltModePause {
// Mark the session as paused and save it.
c.stateLock.Lock()
c.session.Paused = true
saveErr := encoding.MarshalAndSaveProtobuf(c.sessionPath, c.session)
c.stateLock.Unlock()
if saveErr != nil {
return fmt.Errorf("unable to save session: %w", saveErr)
}
} else if mode == controllerHaltModeShutdown {
// Disable the controller.
c.disabled = true
} else if mode == controllerHaltModeTerminate {
// Disable the controller.
c.disabled = true
// Wipe the session information from disk.
sessionRemoveErr := os.Remove(c.sessionPath)
archiveRemoveErr := os.Remove(c.archivePath)
if sessionRemoveErr != nil {
return fmt.Errorf("unable to remove session from disk: %w", sessionRemoveErr)
} else if archiveRemoveErr != nil {
return fmt.Errorf("unable to remove archive from disk: %w", archiveRemoveErr)
}
} else {
panic("invalid halt mode specified")
}
// Success.
return nil
}
// reset resets synchronization session history by pausing the session (if it's
// running), overwriting the ancestor data stored on disk with an empty
// ancestor, and then resuming the session (if it was previously running).
func (c *controller) reset(ctx context.Context, prompter string) error {
// Lock the controller's lifecycle and defer its release.
c.lifecycleLock.Lock()
defer c.lifecycleLock.Unlock()
// Check if the session is currently running.
running := c.cancel != nil
// If the session is running, pause it.
if running {
if err := c.halt(ctx, controllerHaltModePause, prompter, true); err != nil {
return fmt.Errorf("unable to pause session: %w", err)
}
}
// Reset the session archive on disk.
c.logger.Infof("Resetting ancestor")
archive := &core.Archive{}
if err := encoding.MarshalAndSaveProtobuf(c.archivePath, archive); err != nil {
return fmt.Errorf("unable to clear session history: %w", err)
}
// Resume the session if it was previously running.
if running {
if err := c.resume(ctx, prompter, true); err != nil {
return fmt.Errorf("unable to resume session: %w", err)
}
}
// Success.
return nil
}
var (
// errHaltedForSafety is a sentinel error indicating that a safety check
// wants the synchronization loop to be halted until manually resumed.
errHaltedForSafety = errors.New("synchronization halted")
)
// run is the main run loop for the controller, managing connectivity and
// synchronization.
func (c *controller) run(ctx context.Context, alpha, beta Endpoint) {
// Log run loop entry.
c.logger.Debug("Run loop commencing")
// Track the number of short-lived synchronization loops.
var shortLivedSynchronizationLoops uint
// Defer resource and state cleanup.
defer func() {
// Shutdown any endpoints. These might be non-nil if the run loop was
// cancelled while partially connected rather than after sync failure.
if alpha != nil {
alpha.Shutdown()
}
if beta != nil {
beta.Shutdown()
}
// Reset the state.
c.stateLock.Lock()
c.state = &State{
Session: c.session,
AlphaState: &EndpointState{},
BetaState: &EndpointState{},
}
c.stateLock.Unlock()
// Log run loop termination.
c.logger.Debug("Run loop terminated")
// Signal completion.
close(c.done)
}()
// Track the last time that synchronization failed.
var lastSynchronizationFailureTime time.Time
// Loop until cancelled.
for {
// Loop until we're connected to both endpoints. We do a non-blocking
// check for cancellation on each reconnect error so that we don't waste
// resources by trying another connect when the context has been
// cancelled (it'll be wasteful). This is better than sentinel errors.
for {
// Ensure that alpha is connected.
if alpha == nil {
c.stateLock.Lock()
c.state.Status = Status_ConnectingAlpha
c.stateLock.Unlock()
alpha, _ = connect(
ctx,
c.logger.Sublogger("alpha"),
c.session.Alpha,
"",
c.session.Identifier,
c.session.Version,
c.mergedAlphaConfiguration,
true,
)
}
c.stateLock.Lock()
c.state.AlphaState.Connected = (alpha != nil)
c.stateLock.Unlock()
// Check for cancellation to avoid a spurious connection to beta in
// case cancellation occurred while connecting to alpha.
select {
case <-ctx.Done():
return
default:
}
// Ensure that beta is connected.
if beta == nil {
c.stateLock.Lock()
c.state.Status = Status_ConnectingBeta
c.stateLock.Unlock()
beta, _ = connect(
ctx,
c.logger.Sublogger("beta"),
c.session.Beta,
"",
c.session.Identifier,
c.session.Version,
c.mergedBetaConfiguration,
false,
)
}
c.stateLock.Lock()
c.state.BetaState.Connected = (beta != nil)
c.stateLock.Unlock()
// If both endpoints are connected, we're done. We perform this
// check here (rather than in the loop condition) because if we did
// it in the loop condition we'd still need a check here to avoid a
// sleep every time (even if already successfully connected).
if alpha != nil && beta != nil {
break
}
// If we failed to connect, wait and then retry. Watch for
// cancellation in the mean time.
select {
case <-ctx.Done():
return
case <-time.After(autoReconnectInterval):
}
}
// Indicate that the synchronization loop is entering a state where it
// can actually perform synchronization. We don't need to perform any
// notification here since this is not a user-visible state change.
c.stateLock.Lock()
c.synchronizing = make(chan struct{})
c.stateLock.UnlockWithoutNotify()
// Perform synchronization.
c.logger.Debug("Entering synchronization loop")
synchronizationStartTime := time.Now()
err := c.synchronize(ctx, alpha, beta)
synchronizationDuration := time.Since(synchronizationStartTime)
c.logger.Debug("Synchronization loop terminated with error:", err)
// Calculate the number of sequential short-lived synchronization loops.
if synchronizationDuration >= synchronizationLongLivedThreshold {
shortLivedSynchronizationLoops = 0
} else {
shortLivedSynchronizationLoops++
}
// Indicate that the synchronization loop is no longer synchronizing.
// Again, no notification is required here since this is not a
// user-visible state change.
c.stateLock.Lock()
close(c.synchronizing)
c.synchronizing = nil
c.stateLock.UnlockWithoutNotify()
// Shutdown the endpoints.
alpha.Shutdown()
alpha = nil
beta.Shutdown()
beta = nil
// If synchronization failed due a halting error, then wait for the
// synchronization loop to be manually resumed.
if err == errHaltedForSafety {
<-ctx.Done()
return
}
// Otherwise, reset the synchronization state, but propagate the error
// that caused failure.
c.stateLock.Lock()
c.state = &State{
Session: c.session,
LastError: err.Error(),
AlphaState: &EndpointState{},
BetaState: &EndpointState{},
}
c.stateLock.Unlock()
// If we were cancelled, then return immediately.
select {
case <-ctx.Done():
return
default:
}
// Calculate the backoff-adjusted auto-reconnect interval. We calculate
// the backoff factor exponent using the number of sequential,
// short-lived synchronization loops (i.e. the more unstable the
// synchronization operations, the more aggressively we back off).
backoffFactorExponent := float64(shortLivedSynchronizationLoops)
if backoffFactorExponent > backoffFactorMaximumExponent {
backoffFactorExponent = backoffFactorMaximumExponent
}
backoffFactor := int64(math.Pow(backoffFactorBase, backoffFactorExponent))
backedOffAutoReconnectInterval := time.Duration(backoffFactor) * autoReconnectInterval
// If less than one auto-reconnect interval has elapsed since the last
// synchronization failure, then wait before attempting reconnection.
now := time.Now()
if now.Sub(lastSynchronizationFailureTime) < backedOffAutoReconnectInterval {
select {
case <-ctx.Done():
return
case <-time.After(backedOffAutoReconnectInterval):
}
}
lastSynchronizationFailureTime = now
}
}
// synchronize is the main synchronization loop for the controller.
func (c *controller) synchronize(ctx context.Context, alpha, beta Endpoint) error {
// Clear any error state upon restart of this function. If there was a
// terminal error previously caused synchronization to fail, then the user
// will have had time to review it (while the run loop is waiting to
// reconnect), so it's not like we're getting rid of it too quickly.
c.stateLock.Lock()
if c.state.LastError != "" {
c.state.LastError = ""
c.stateLock.Unlock()
} else {
c.stateLock.UnlockWithoutNotify()
}
// Track whether or not a flush request triggered the synchronization loop.
var flushRequest chan error
// Load the archive and extract the ancestor. We enforce that the archive
// contains only synchronizable content.
archive := &core.Archive{}
if err := encoding.LoadAndUnmarshalProtobuf(c.archivePath, archive); err != nil {
return fmt.Errorf("unable to load archive: %w", err)
} else if err = archive.EnsureValid(true); err != nil {
return fmt.Errorf("invalid archive found on disk: %w", err)
}
ancestor := archive.Content
// Compute the effective synchronization mode.
synchronizationMode := c.session.Configuration.SynchronizationMode
if synchronizationMode.IsDefault() {
synchronizationMode = c.session.Version.DefaultSynchronizationMode()
}
// Compute the effective ignore syntax.
ignoreSyntax := c.session.Configuration.IgnoreSyntax
if ignoreSyntax.IsDefault() {
ignoreSyntax = c.session.Version.DefaultIgnoreSyntax()
}
// Compute the effective permissions mode.
permissionsMode := c.session.Configuration.PermissionsMode
if permissionsMode.IsDefault() {
permissionsMode = c.session.Version.DefaultPermissionsMode()
}
// Compute, on a per-endpoint basis, whether or not polling should be
// disabled.
αWatchMode := c.mergedAlphaConfiguration.WatchMode
βWatchMode := c.mergedBetaConfiguration.WatchMode
if αWatchMode.IsDefault() {
αWatchMode = c.session.Version.DefaultWatchMode()
}
if βWatchMode.IsDefault() {
βWatchMode = c.session.Version.DefaultWatchMode()
}
αDisablePolling := (αWatchMode == WatchMode_WatchModeNoWatch)
βDisablePolling := (βWatchMode == WatchMode_WatchModeNoWatch)
// Create a switch that will allow us to skip polling and force a
// synchronization cycle. On startup, we enable this switch and skip polling
// to immediately force a check for changes that may have occurred while the
// synchronization loop wasn't running. The only time we don't force this
// check on startup is when both endpoints have polling disabled, which is
// an indication that the session should operate in a fully manual mode.
skipPolling := (!αDisablePolling || !βDisablePolling)
// Create variables to track our reasons for skipping polling.
var skippingPollingDueToScanError, skippingPollingDueToMissingFiles bool
// Loop until there is a synchronization error.
for {
// Unless we've been requested to skip polling, wait for a dirty state
// while monitoring for cancellation. If we've been requested to skip
// polling, it should only be for one iteration.
if !skipPolling {
// Update status to watching.
c.stateLock.Lock()
c.state.Status = Status_Watching
c.stateLock.Unlock()
// Create a polling context that we can cancel. We don't make it a
// subcontext of our own cancellation context because it's easier to
// just track cancellation there separately.
pollCtx, pollCancel := context.WithCancel(context.Background())
// Start alpha polling. If alpha has been put into a no-watch mode,
// then we still perform polling in order to detect transport errors
// that might occur while the session is sitting idle, but we ignore
// any non-error responses and instead wait for the polling context
// to be cancelled. We perform this ignore operation because we
// don't want a broken or malicious endpoint to be able to force
// synchronization, especially if its watching has been
// intentionally disabled.
//
// It's worth noting that, because a well-behaved endpoint in
// no-watch mode never returns events, we'll always be polling on it
// (and thereby testing the transport) right up until the polling
// context is cancelled. Thus, there's no need to worry about cases
// where the endpoint sends back an event that we ignore and then
// has a transport failure without us noticing while we wait on the
// polling context (at least not for well-behaved endpoints).
αPollResults := make(chan error, 1)
go func() {
if αDisablePolling {
if err := alpha.Poll(pollCtx); err != nil {
αPollResults <- err
} else {
<-pollCtx.Done()
αPollResults <- nil
}
} else {
αPollResults <- alpha.Poll(pollCtx)
}
}()
// Start beta polling. The logic here mirrors that for alpha above.
βPollResults := make(chan error, 1)
go func() {
if βDisablePolling {
if err := beta.Poll(pollCtx); err != nil {