// transitionPassiveSyncer transitions a passive syncer to an active one.
//
// NOTE: This must be called with the syncersMu lock held.
768826
func (m *SyncManager) transitionPassiveSyncer(s *GossipSyncer) error {
	log.Debugf("Transitioning passive GossipSyncer(%x) to active",
		s.cfg.peerPub)

	if err := s.ProcessSyncTransition(ActiveSync); err != nil {
		return err
	}

	delete(m.inactiveSyncers, s.cfg.peerPub)
	m.activeSyncers[s.cfg.peerPub] = s

	return nil
}
1038514
func (o *RsyncOptions) WatchAndSync() error {

	// these variables must be accessed while holding the changeLock
	// mutex as they are shared between goroutines to communicate
	// sync state/events.
	var (
		changeLock sync.Mutex
		dirty      bool
		lastChange time.Time
		watchError error
	)

	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		return fmt.Errorf("error setting up filesystem watcher: %v", err)
	}
	defer watcher.Close()

	go func() {
		for {
			select {
			case event := <-watcher.Events:
				changeLock.Lock()
				klog.V(5).Infof("filesystem watch event: %s", event)
				lastChange = time.Now()
				dirty = true
				if event.Op&fsnotify.Remove == fsnotify.Remove {
					if e := watcher.Remove(event.Name); e != nil {
						klog.V(5).Infof("error removing watch for %s: %v", event.Name, e)
					}
				} else {
					if e := fsnotification.AddRecursiveWatch(watcher, event.Name); e != nil && watchError == nil {
						watchError = e
					}
				}
				changeLock.Unlock()
			case err := <-watcher.Errors:
				changeLock.Lock()
				watchError = fmt.Errorf("error watching filesystem for changes: %v", err)
				changeLock.Unlock()
			}
		}
	}()

	err = fsnotification.AddRecursiveWatch(watcher, o.Source.Path)
	if err != nil {
		return fmt.Errorf("error watching source path %s: %v", o.Source.Path, err)
	}

	delay := 2 * time.Second
	ticker := time.NewTicker(delay)
	defer ticker.Stop()
	for {
		changeLock.Lock()
		if watchError != nil {
			return watchError
		}
		// if a change happened more than 'delay' seconds ago, sync it now.
		// if a change happened less than 'delay' seconds ago, sleep for 'delay' seconds
		// and see if more changes happen, we don't want to sync when
		// the filesystem is in the middle of changing due to a massive
		// set of changes (such as a local build in progress).
		if dirty && time.Now().After(lastChange.Add(delay)) {
			klog.V(1).Info("Synchronizing filesystem changes...")
			err = o.Strategy.Copy(o.Source, o.Destination, o.Out, o.ErrOut)
			if err != nil {
				return err
			}
			klog.V(1).Info("Done.")
			dirty = false
		}
		changeLock.Unlock()
		<-ticker.C
	}
}
666489
func (cl *CaptureLogger) Passthrough() bool {
	cl.RLock()
	defer cl.RUnlock()
	return cl.passthrough
}
434123
func (l *list) MoveAfter(e, mark *element) {
	if e.list != l || e == mark {
		return
	}
	l.insert(l.remove(e), mark)
}
619518
func (r *UpstreamService) Sync() *UpstreamSyncCall {
	c := &UpstreamSyncCall{s: r.s, urlParams_: make(gensupport.URLParams)}
	return c
}
783979
func (p *Process) waitForSync(downstream *discoverd.Instance) {
	p.Logger.Debug("waiting for downstream sync")

	stopCh := make(chan struct{})
	doneCh := make(chan struct{})

	var once sync.Once
	p.cancelSyncWait = func() {
		once.Do(func() { close(stopCh); <-doneCh })
	}

	go p.waitForSyncInner(downstream, stopCh, doneCh)
}
1103951
func (n *Notifier) NotifyPostTransition(transition *machine.TransitionNotification) (err error) {
	n.logger.Infof("%s transitioned via event %s: from %s into %s", transition.Machine, transition.Transition, transition.FromState, transition.ToState)

	j, err := json.Marshal(transition)
	if err != nil {
		return errors.Wrap(err, "could not JSON encode transition notification")
	}

	err = n.fw.PublishRaw("choria.machine.transition", j)
	if err != nil {
		return errors.Wrap(err, "could not publish notification")
	}

	return nil
}
1298423
func (l *PacketIntervalList) MoveAfter(e, mark *PacketIntervalElement) {
	if e.list != l || e == mark || mark.list != l {
		return
	}
	l.insert(l.remove(e), mark)
}
663420
func (g *gregorHandler) serverSync(ctx context.Context,
	cli gregor1.IncomingInterface, gcli *grclient.Client, syncRes *chat1.SyncAllNotificationRes) (res []gregor.InBandMessage, err error) {
	defer g.chatLog.Trace(ctx, func() error { return err }, "serverSync")()

	// Get time of the last message we synced (unless this is our first time syncing)
	var t time.Time
	if !g.isFirstConnect() {
		pt := gcli.StateMachineLatestCTime(ctx)
		if pt != nil {
			t = *pt
		}
		g.Debug(ctx, "serverSync: starting replay from: %s", t)
	} else {
		g.Debug(ctx, "serverSync: performing a fresh replay")
	}

	// Sync down everything from the server
	consumedMsgs, err := gcli.Sync(ctx, cli, syncRes)
	if err != nil {
		g.Debug(ctx, "serverSync: error syncing from the server, reason: %s", err)
		return nil, err
	}
	g.Debug(ctx, "serverSync: consumed %d messages", len(consumedMsgs))

	// Schedule replay of in-band messages
	g.replayCh <- replayThreadArg{
		cli: cli,
		t:   t,
		ctx: globals.BackgroundChatCtx(ctx, g.G()),
	}

	g.pushState(keybase1.PushReason_RECONNECTED)
	return consumedMsgs, nil
}
390026
func (p *Peer) startTransitionToNormalMode() {
	log := p.log.New("fn", "startTransitionToNormalMode")
	if p.Info().State.Primary.Meta[p.idKey] != p.id || p.Info().Role != RolePrimary {
		panic("startTransitionToNormalMode called when not primary")
	}

	// In the normal takeover case, we'd pick an async. In this case, we take
	// any other peer because we know none of them has anything replicated.
	var newSync *discoverd.Instance
	for _, peer := range p.Info().Peers {
		if peer.Meta[p.idKey] != p.id {
			newSync = peer
		}
	}
	if newSync == nil {
		log.Warn("would takeover but no peers present")
		return
	}
	newAsync := make([]*discoverd.Instance, 0, len(p.Info().Peers))
	for _, a := range p.Info().Peers {
		if a.Meta[p.idKey] != p.id && a.Meta[p.idKey] != newSync.Meta[p.idKey] {
			newAsync = append(newAsync, a)
		}
	}

	log.Debug("transitioning to normal mode")
	p.startTakeoverWithPeer("transitioning to normal mode", p.db.XLog().Zero(), &State{
		Sync:  newSync,
		Async: newAsync,
	})
}
1138460
func NewSyncedEnforcer(params ...interface{}) *SyncedEnforcer {
	e := &SyncedEnforcer{}
	e.Enforcer = NewEnforcer(params...)
	e.autoLoad = false
	return e
}
1253546
func (f *FSM) Transition() error {
	f.eventMu.Lock()
	defer f.eventMu.Unlock()
	return f.doTransition()
}
707874
func (conn *BytesConnectionStr) NewAsyncPublisher(topic string, successClb func(*client.ProducerMessage), errorClb func(err *client.ProducerError)) (BytesPublisher, error) {
	return &bytesAsyncPublisherKafka{conn, topic, successClb, errorClb}, nil
}
659650
func (s *StateSyncer) Pause() {
	s.pauseLock.Lock()
	s.paused++
	s.pauseLock.Unlock()
}
469562
func (pm *ProtocolManager) syncer() {
	// Start and ensure cleanup of sync mechanisms
	pm.fetcher.Start()
	defer pm.fetcher.Stop()
	defer pm.downloader.Terminate()

	// Wait for different events to fire synchronisation operations
	forceSync := time.NewTicker(forceSyncCycle)
	defer forceSync.Stop()

	for {
		select {
		case <-pm.newPeerCh:
			// Make sure we have peers to select from, then sync
			if pm.peers.Len() < minDesiredPeerCount {
				break
			}
			go pm.synchronise(pm.peers.BestPeer())

		case <-forceSync.C:
			// Force a sync even if not enough peers are present
			go pm.synchronise(pm.peers.BestPeer())

		case <-pm.noMorePeers:
			return
		}
	}
}
407670
func (s *Sinc) TransitionFreq() float64 {
	if s == nil {
		return 0
	}
	return s.CutOffFreq / float64(s.SamplingFreq)
}
1013316
func (s *Server) GracefulStop() {
	s.quitOnce.Do(func() {
		close(s.quit)
	})

	defer func() {
		s.doneOnce.Do(func() {
			close(s.done)
		})
	}()

	s.channelzRemoveOnce.Do(func() {
		if channelz.IsOn() {
			channelz.RemoveEntry(s.channelzID)
		}
	})
	s.mu.Lock()
	if s.conns == nil {
		s.mu.Unlock()
		return
	}

	for lis := range s.lis {
		lis.Close()
	}
	s.lis = nil
	if !s.drain {
		for c := range s.conns {
			c.(transport.ServerTransport).Drain()
		}
		s.drain = true
	}

	// Wait for serving threads to be ready to exit.  Only then can we be sure no
	// new conns will be created.
	s.mu.Unlock()
	s.serveWG.Wait()
	s.mu.Lock()

	for len(s.conns) != 0 {
		s.cv.Wait()
	}
	s.conns = nil
	if s.events != nil {
		s.events.Finish()
		s.events = nil
	}
	s.mu.Unlock()
}