// doPartialSync iterates through the paths, deep-syncing them and
// also syncing their parent directories up to the root node.
434657
func (fbo *folderBranchOps) doPartialSync(
	ctx context.Context, syncConfig keybase1.FolderSyncConfig,
	latestMerged ImmutableRootMetadata) (err error) {
	startTime, timer := fbo.startOp(
		ctx, "Starting partial sync at revision %d", latestMerged.Revision())
	defer func() {
		fbo.endOp(
			ctx, startTime, timer, "Partial sync at revision %d done: %+v",
			latestMerged.Revision(), err)
	}()

	var parentSyncAction, pathSyncAction BlockRequestAction
	var priority int
	switch syncConfig.Mode {
	case keybase1.FolderSyncMode_ENABLED:
		return errors.Errorf("Enabled mode passed to partial sync")
	case keybase1.FolderSyncMode_PARTIAL:
		// Use `PrefetchTail` for directories, to make sure that any child
		// blocks in the directory itself get prefetched.
		parentSyncAction = BlockRequestPrefetchTailWithSync
		pathSyncAction = BlockRequestWithDeepSync
		priority = defaultOnDemandRequestPriority - 1
	default:
		// For TLFs that aren't explicitly configured to be synced in
		// some way, use the working set cache.
		parentSyncAction = BlockRequestPrefetchTail
		// If we run out of space while prefetching the paths, just stop.
		pathSyncAction = BlockRequestPrefetchUntilFull
		// Don't flood outselves with prefetch requests when we're not
		// explicitly trying to sync the folder, just throttle them in
		// the background.
		priority = throttleRequestPriority
	}

	rootNode, _, _, err := fbo.getRootNode(ctx)
	if err != nil {
		return err
	}
	_, err = fbo.syncOneNode(
		ctx, rootNode, latestMerged, priority, parentSyncAction)
	if err != nil {
		return err
	}

	chs := make(map[string]<-chan struct{}, len(syncConfig.Paths))
	lState := makeFBOLockState()
	// Look up and solo-sync each lead-up component of the path.
pathLoop:
	for _, p := range syncConfig.Paths {
		select {
		case <-ctx.Done():
			return ctx.Err()
		default:
		}
		fbo.vlog.CLogf(ctx, libkb.VLog1, "Partially-syncing %s", p)

		parentPath, syncedElem := stdpath.Split(p)
		parents := strings.Split(strings.TrimSuffix(parentPath, "/"), "/")
		currNode := rootNode
		for _, parent := range parents {
			if len(parent) == 0 {
				continue
			}
			// TODO: parallelize the parent fetches and lookups.
			currNode, _, err = fbo.blocks.Lookup(
				ctx, lState, latestMerged.ReadOnly(), currNode, parent)
			switch errors.Cause(err).(type) {
			case idutil.NoSuchNameError:
				fbo.vlog.CLogf(
					ctx, libkb.VLog1, "Synced path %s doesn't exist yet", p)
				continue pathLoop
			case nil:
			default:
				return err
			}

			// Use `PrefetchTail` for directories, to make sure that
			// any child blocks in the directory itself get
			// prefetched.
			_, err = fbo.syncOneNode(
				ctx, currNode, latestMerged, priority, parentSyncAction)
			if err != nil {
				return err
			}
		}

		// Kick off a full deep sync of `syncedElem`.
		elemNode, _, err := fbo.blocks.Lookup(
			ctx, lState, latestMerged.ReadOnly(), currNode, syncedElem)
		switch errors.Cause(err).(type) {
		case idutil.NoSuchNameError:
			fbo.vlog.CLogf(
				ctx, libkb.VLog1, "Synced element %s doesn't exist yet", p)
			continue pathLoop
		case nil:
		default:
			return err
		}

		ptr, err := fbo.syncOneNode(
			ctx, elemNode, latestMerged, priority, pathSyncAction)
		if err != nil {
			return err
		}
		ch, err := fbo.config.BlockOps().Prefetcher().
			WaitChannelForBlockPrefetch(ctx, ptr)
		if err != nil {
			return err
		}
		chs[p] = ch
	}

	for p, ch := range chs {
		select {
		case <-ch:
			fbo.vlog.CLogf(ctx, libkb.VLog1, "Prefetch for %s complete", p)
		case <-ctx.Done():
			return ctx.Err()
		}
	}
	return nil
}
386804
func (d *DirtyBlockCacheStandard) ShouldForceSync(_ tlf.ID) bool {
	d.lock.RLock()
	defer d.lock.RUnlock()
	// TODO: Fill up to likely block boundaries?
	return d.waitBufBytes >= d.syncBufferCap
}
439924
func (c *OpenChannel) FullSync() error {
	c.Lock()
	defer c.Unlock()

	return c.Db.Update(c.fullSync)
}
1261036
func (nr *NodeRegistrar) UpdateLocalKeySync(n *node.Node) error {
	return nr.SharedStore.UpdateLocalKeySync(n)
}
1126164
func (sc *syncContext) doApplySync(syncTasks []syncTask, dryRun, force, update bool) bool {
	syncSuccessful := true

	var createTasks []syncTask
	var pruneTasks []syncTask
	for _, syncTask := range syncTasks {
		if syncTask.targetObj == nil {
			pruneTasks = append(pruneTasks, syncTask)
		} else {
			createTasks = append(createTasks, syncTask)
		}
	}

	var wg sync.WaitGroup
	for _, task := range pruneTasks {
		wg.Add(1)
		go func(t syncTask) {
			defer wg.Done()
			resDetails := sc.pruneObject(t.liveObj, sc.syncOp.Prune, dryRun)
			if !resDetails.Status.Successful() {
				syncSuccessful = false
			}
			if update || !resDetails.Status.Successful() {
				sc.setResourceDetails(&resDetails)
			}
		}(task)
	}
	wg.Wait()

	processCreateTasks := func(tasks []syncTask) {
		var createWg sync.WaitGroup
		for i := range tasks {
			if dryRun && tasks[i].skipDryRun {
				continue
			}
			createWg.Add(1)
			go func(t syncTask) {
				defer createWg.Done()
				if hookutil.IsHook(t.targetObj) {
					return
				}
				resDetails := sc.applyObject(t.targetObj, dryRun, force)
				if !resDetails.Status.Successful() {
					syncSuccessful = false
				}
				if update || !resDetails.Status.Successful() {
					sc.setResourceDetails(&resDetails)
				}
			}(tasks[i])
		}
		createWg.Wait()
	}

	var tasksGroup []syncTask
	for _, task := range createTasks {
		//Only wait if the type of the next task is different than the previous type
		if len(tasksGroup) > 0 && tasksGroup[0].targetObj.GetKind() != task.targetObj.GetKind() {
			processCreateTasks(tasksGroup)
			tasksGroup = []syncTask{task}
		} else {
			tasksGroup = append(tasksGroup, task)
		}
	}
	if len(tasksGroup) > 0 {
		processCreateTasks(tasksGroup)
	}
	return syncSuccessful
}
299028
func syncParentHooks(pipe io.ReadWriter) error {
	// Tell parent.
	if err := writeSync(pipe, procHooks); err != nil {
		return err
	}

	// Wait for parent to give the all-clear.
	return readSync(pipe, procResume)
}
1070328
func (a *Allocator) WaitForInitialSync(ctx context.Context) error {
	select {
	case <-a.initialListDone:
	case <-ctx.Done():
		return fmt.Errorf("identity sync with kvstore was cancelled: %s", ctx.Err())
	}

	return nil
}
653116
func (u *uidProcessor) Resync(ctx context.Context, e *common.EventInfo) error {

	uids := u.netcls.ListAllCgroups("")
	for _, uid := range uids {

		if _, ok := ignoreNames[uid]; ok {
			continue
		}

		processesOfUID := u.netcls.ListAllCgroups(uid)
		activePids := []int32{}

		for _, pid := range processesOfUID {
			if _, ok := ignoreNames[pid]; ok {
				continue
			}

			cgroupPath := uid + "/" + pid
			pidlist, _ := u.netcls.ListCgroupProcesses(cgroupPath)
			if len(pidlist) == 0 {
				if err := u.netcls.DeleteCgroup(cgroupPath); err != nil {
					zap.L().Warn("Unable to delete cgroup",
						zap.String("cgroup", cgroupPath),
						zap.Error(err),
					)
				}
				continue
			}

			iPid, _ := strconv.Atoi(pid)
			activePids = append(activePids, int32(iPid))
		}

		if len(activePids) == 0 {
			if err := u.netcls.DeleteCgroup(uid); err != nil {
				zap.L().Warn("Unable to delete cgroup",
					zap.String("cgroup", uid),
					zap.Error(err),
				)
			}
			continue
		}

		event := &common.EventInfo{
			PID:    activePids[0],
			PUID:   uid,
			PUType: common.UIDLoginPU,
		}

		if err := u.createAndStart(ctx, event, true); err != nil {
			zap.L().Error("Can not synchronize user", zap.String("user", uid))
		}

		for i := 1; i < len(activePids); i++ {
			event := &common.EventInfo{
				PID:    activePids[i],
				PUID:   uid,
				PUType: common.UIDLoginPU,
			}
			if err := u.createAndStart(ctx, event, true); err != nil {
				zap.L().Error("Can not synchronize user", zap.String("user", uid))
			}
		}
	}

	return nil
}
902265
func (o *Container) CreateContainerResync(child *ContainerResync) *bambou.Error {

	return bambou.CurrentSession().CreateChild(o, child)
}
792729
func (bc *BlockChain) FastSyncCommitHead(hash common.Hash) error {
	// Make sure that both the block as well at its state trie exists
	block := bc.GetBlockByHash(hash)
	if block == nil {
		return fmt.Errorf("non existent block [%x…]", hash[:4])
	}
	if _, err := trie.NewSecure(block.Root(), bc.stateCache.TrieDB()); err != nil {
		return err
	}
	// If all checks out, manually set the head block
	bc.chainmu.Lock()
	bc.currentBlock.Store(block)
	bc.chainmu.Unlock()

	log.Info("Committed new head block", "number", block.Number(), "hash", hash)
	return nil
}
1215847
func (db *GoLevelDB) DeleteSync(key []byte) {
	key = nonNilBytes(key)
	err := db.db.Delete(key, &opt.WriteOptions{Sync: true})
	if err != nil {
		cmn.PanicCrisis(err)
	}
}
32401
func (p *peer) initGossipSync() {
	switch {

	// If the remote peer knows of the new gossip queries feature, then
	// we'll create a new gossipSyncer in the AuthenticatedGossiper for it.
	case p.remoteLocalFeatures.HasFeature(lnwire.GossipQueriesOptional):
		srvrLog.Infof("Negotiated chan series queries with %x",
			p.pubKeyBytes[:])

		// Register the this peer's for gossip syncer with the gossiper.
		// This is blocks synchronously to ensure the gossip syncer is
		// registered with the gossiper before attempting to read
		// messages from the remote peer.
		//
		// TODO(wilmer): Only sync updates from non-channel peers. This
		// requires an improved version of the current network
		// bootstrapper to ensure we can find and connect to non-channel
		// peers.
		p.server.authGossiper.InitSyncState(p)

	// If the remote peer has the initial sync feature bit set, then we'll
	// being the synchronization protocol to exchange authenticated channel
	// graph edges/vertexes, but only if they don't know of the new gossip
	// queries.
	case p.remoteLocalFeatures.HasFeature(lnwire.InitialRoutingSync):
		srvrLog.Infof("Requesting full table sync with %x",
			p.pubKeyBytes[:])

		go p.server.authGossiper.SynchronizeNode(p)
	}
}
306845
func (d *Downloader) processFastSyncContent(latest *types.Header) error {
	// Start syncing state of the reported head block. This should get us most of
	// the state of the pivot block.
	stateSync := d.syncState(latest.Root)
	defer stateSync.Cancel()
	go func() {
		if err := stateSync.Wait(); err != nil && err != errCancelStateFetch {
			d.queue.Close() // wake up Results
		}
	}()
	// Figure out the ideal pivot block. Note, that this goalpost may move if the
	// sync takes long enough for the chain head to move significantly.
	pivot := uint64(0)
	if height := latest.Number.Uint64(); height > uint64(fsMinFullBlocks) {
		pivot = height - uint64(fsMinFullBlocks)
	}
	// To cater for moving pivot points, track the pivot block and subsequently
	// accumulated download results separately.
	var (
		oldPivot *fetchResult   // Locked in pivot block, might change eventually
		oldTail  []*fetchResult // Downloaded content after the pivot
	)
	for {
		// Wait for the next batch of downloaded data to be available, and if the pivot
		// block became stale, move the goalpost
		results := d.queue.Results(oldPivot == nil) // Block if we're not monitoring pivot staleness
		if len(results) == 0 {
			// If pivot sync is done, stop
			if oldPivot == nil {
				return stateSync.Cancel()
			}
			// If sync failed, stop
			select {
			case <-d.cancelCh:
				return stateSync.Cancel()
			default:
			}
		}
		if d.chainInsertHook != nil {
			d.chainInsertHook(results)
		}
		if oldPivot != nil {
			results = append(append([]*fetchResult{oldPivot}, oldTail...), results...)
		}
		// Split around the pivot block and process the two sides via fast/full sync
		if atomic.LoadInt32(&d.committed) == 0 {
			latest = results[len(results)-1].Header
			if height := latest.Number.Uint64(); height > pivot+2*uint64(fsMinFullBlocks) {
				log.Warn("Pivot became stale, moving", "old", pivot, "new", height-uint64(fsMinFullBlocks))
				pivot = height - uint64(fsMinFullBlocks)
			}
		}
		P, beforeP, afterP := splitAroundPivot(pivot, results)
		if err := d.commitFastSyncData(beforeP, stateSync); err != nil {
			return err
		}
		if P != nil {
			// If new pivot block found, cancel old state retrieval and restart
			if oldPivot != P {
				stateSync.Cancel()

				stateSync = d.syncState(P.Header.Root)
				defer stateSync.Cancel()
				go func() {
					if err := stateSync.Wait(); err != nil && err != errCancelStateFetch {
						d.queue.Close() // wake up Results
					}
				}()
				oldPivot = P
			}
			// Wait for completion, occasionally checking for pivot staleness
			select {
			case <-stateSync.done:
				if stateSync.err != nil {
					return stateSync.err
				}
				if err := d.commitPivotBlock(P); err != nil {
					return err
				}
				oldPivot = nil

			case <-time.After(time.Second):
				oldTail = afterP
				continue
			}
		}
		// Fast sync done, pivot commit done, full import
		if err := d.importBlockResults(afterP); err != nil {
			return err
		}
	}
}
1159636
func (df *DirtyFile) FinishSync() error {
	// Mark any remaining blocks as finished syncing.  For now, only
	// the top-level indirect block needs this because they are added
	// to the blockPutState by folderBranchOps, not folderBlockOps.
	df.lock.Lock()
	defer df.lock.Unlock()

	// Reset all syncing blocks to just be dirty again (there should
	// only be one, equal to the original top block).
	found := false
	for ptr, state := range df.fileBlockStates {
		if state.orphaned {
			continue
		}
		if state.sync == blockSyncing {
			if found {
				return fmt.Errorf("Unexpected syncing block %v", ptr)
			}
			if ptr != df.Path.TailPointer() {
				return fmt.Errorf("Unexpected syncing block %v; expected %v",
					ptr, df.Path.TailPointer())
			}
			found = true
			err := df.setBlockSyncedLocked(ptr)
			if err != nil {
				return err
			}
		}
	}
	df.dirtyBcache.SyncFinished(df.Path.Tlf, df.totalSyncBytes)
	df.totalSyncBytes = 0
	df.deferredNewBytes = 0
	if df.notYetSyncingBytes > 0 {
		// The sync will never happen (probably because the underlying
		// file was removed).
		df.dirtyBcache.UpdateUnsyncedBytes(df.Path.Tlf,
			-df.notYetSyncingBytes, false)
		df.notYetSyncingBytes = 0
	}
	return nil
}
1241157
func (mysqld *Mysqld) SemiSyncEnabled() (master, slave bool) {
	vars, err := mysqld.fetchVariables(context.TODO(), "rpl_semi_sync_%_enabled")
	if err != nil {
		return false, false
	}
	master = (vars["rpl_semi_sync_master_enabled"] == "ON")
	slave = (vars["rpl_semi_sync_slave_enabled"] == "ON")
	return master, slave
}
371629
func (sm *SyncManager) SyncPeerID() int32 {
	reply := make(chan int32)
	sm.msgChan <- getSyncPeerMsg{reply: reply}
	return <-reply
}
440686
func (a *btcAddress) SyncStatus() SyncStatus {
	switch {
	case a.flags.unsynced && !a.flags.partialSync:
		return Unsynced(a.firstBlock)
	case a.flags.unsynced && a.flags.partialSync:
		return PartialSync(a.partialSyncHeight)
	default:
		return FullSync{}
	}
}