// FullSync serializes, and writes to disk the *full* channel state, using
// both the active channel bucket to store the prefixed column fields, and the
// remote node's ID to store the remainder of the channel state.
439924
func (c *OpenChannel) FullSync() error {
	c.Lock()
	defer c.Unlock()

	return c.Db.Update(c.fullSync)
}
1195435
func (u *UIDMonitor) Resync(ctx context.Context) error {
	return u.proc.Resync(ctx, nil)
}
1289167
func (m *activeDeadlineHandler) ShouldSync(pod *v1.Pod) bool {
	return m.pastActiveDeadline(pod)
}
33553
func (l *Listener) resync(cn *ListenerConn, notificationChan <-chan *Notification) error {
	doneChan := make(chan error)
	go func() {
		for channel := range l.channels {
			// If we got a response, return that error to our caller as it's
			// going to be more descriptive than cn.Err().
			gotResponse, err := cn.Listen(channel)
			if gotResponse && err != nil {
				doneChan <- err
				return
			}

			// If we couldn't reach the server, wait for notificationChan to
			// close and then return the error message from the connection, as
			// per ListenerConn's interface.
			if err != nil {
				for _ = range notificationChan {
				}
				doneChan <- cn.Err()
				return
			}
		}
		doneChan <- nil
	}()

	// Ignore notifications while synchronization is going on to avoid
	// deadlocks.  We have to send a nil notification over Notify anyway as
	// we can't possibly know which notifications (if any) were lost while
	// the connection was down, so there's no reason to try and process
	// these messages at all.
	for {
		select {
		case _, ok := <-notificationChan:
			if !ok {
				notificationChan = nil
			}

		case err := <-doneChan:
			return err
		}
	}
}
8782
func (l *LinuxMonitor) Resync(ctx context.Context) error {
	return l.proc.Resync(ctx, nil)
}
219805
func (l *State) updateSyncState() error {
	// Get all checks and services from the master
	req := structs.NodeSpecificRequest{
		Datacenter:   l.config.Datacenter,
		Node:         l.config.NodeName,
		QueryOptions: structs.QueryOptions{Token: l.tokens.AgentToken()},
	}

	var out1 structs.IndexedNodeServices
	if err := l.Delegate.RPC("Catalog.NodeServices", &req, &out1); err != nil {
		return err
	}

	var out2 structs.IndexedHealthChecks
	if err := l.Delegate.RPC("Health.NodeChecks", &req, &out2); err != nil {
		return err
	}

	// Create useful data structures for traversal
	remoteServices := make(map[string]*structs.NodeService)
	if out1.NodeServices != nil {
		remoteServices = out1.NodeServices.Services
	}

	remoteChecks := make(map[types.CheckID]*structs.HealthCheck, len(out2.HealthChecks))
	for _, rc := range out2.HealthChecks {
		remoteChecks[rc.CheckID] = rc
	}

	// Traverse all checks, services and the node info to determine
	// which entries need to be updated on or removed from the server

	l.Lock()
	defer l.Unlock()

	// Check if node info needs syncing
	if out1.NodeServices == nil || out1.NodeServices.Node == nil ||
		out1.NodeServices.Node.ID != l.config.NodeID ||
		!reflect.DeepEqual(out1.NodeServices.Node.TaggedAddresses, l.config.TaggedAddresses) ||
		!reflect.DeepEqual(out1.NodeServices.Node.Meta, l.metadata) {
		l.nodeInfoInSync = false
	}

	// Check which services need syncing

	// Look for local services that do not exist remotely and mark them for
	// syncing so that they will be pushed to the server later
	for id, s := range l.services {
		if remoteServices[id] == nil {
			s.InSync = false
		}
	}

	// Traverse the list of services from the server.
	// Remote services which do not exist locally have been deregistered.
	// Otherwise, check whether the two definitions are still in sync.
	for id, rs := range remoteServices {
		ls := l.services[id]
		if ls == nil {
			// The consul service is managed automatically and does
			// not need to be deregistered
			if id == structs.ConsulServiceID {
				continue
			}

			// Mark a remote service that does not exist locally as deleted so
			// that it will be removed on the server later.
			l.services[id] = &ServiceState{Deleted: true}
			continue
		}

		// If the service is already scheduled for removal skip it
		if ls.Deleted {
			continue
		}

		// If our definition is different, we need to update it. Make a
		// copy so that we don't retain a pointer to any actual state
		// store info for in-memory RPCs.
		if ls.Service.EnableTagOverride {
			ls.Service.Tags = make([]string, len(rs.Tags))
			copy(ls.Service.Tags, rs.Tags)
		}
		ls.InSync = ls.Service.IsSame(rs)
	}

	// Check which checks need syncing

	// Look for local checks that do not exist remotely and mark them for
	// syncing so that they will be pushed to the server later
	for id, c := range l.checks {
		if remoteChecks[id] == nil {
			c.InSync = false
		}
	}

	// Traverse the list of checks from the server.
	// Remote checks which do not exist locally have been deregistered.
	// Otherwise, check whether the two definitions are still in sync.
	for id, rc := range remoteChecks {
		lc := l.checks[id]

		if lc == nil {
			// The Serf check is created automatically and does not
			// need to be deregistered.
			if id == structs.SerfCheckID {
				l.logger.Printf("[DEBUG] agent: Skipping remote check %q since it is managed automatically", id)
				continue
			}

			// Mark a remote check that does not exist locally as deleted so
			// that it will be removed on the server later.
			l.checks[id] = &CheckState{Deleted: true}
			continue
		}

		// If the check is already scheduled for removal skip it.
		if lc.Deleted {
			continue
		}

		// If our definition is different, we need to update it
		if l.config.CheckUpdateInterval == 0 {
			lc.InSync = lc.Check.IsSame(rc)
			continue
		}

		// Copy the existing check before potentially modifying
		// it before the compare operation.
		lcCopy := lc.Check.Clone()

		// Copy the server's check before modifying, otherwise
		// in-memory RPCs will have side effects.
		rcCopy := rc.Clone()

		// If there's a defer timer active then we've got a
		// potentially spammy check so we don't sync the output
		// during this sweep since the timer will mark the check
		// out of sync for us. Otherwise, it is safe to sync the
		// output now. This is especially important for checks
		// that don't change state after they are created, in
		// which case we'd never see their output synced back ever.
		if lc.DeferCheck != nil {
			lcCopy.Output = ""
			rcCopy.Output = ""
		}
		lc.InSync = lcCopy.IsSame(rcCopy)
	}
	return nil
}
848914
func awaitSync(ctx context.Context, client api.Server, revision string) error {
	return backoff(1*time.Second, 2, 10, 1*time.Minute, func() (bool, error) {
		refs, err := client.SyncStatus(ctx, revision)
		return err == nil && len(refs) == 0, err
	})
}
370193
func (p *blockPrefetcher) OverallSyncStatus() PrefetchProgress {
	p.overallSyncStatusLock.RLock()
	defer p.overallSyncStatusLock.RUnlock()
	return p.overallSyncStatus
}
1044811
func (m *monitors) Resync(ctx context.Context) error {

	failure := false
	var errs string

	for _, i := range m.monitors {
		if err := i.Resync(ctx); err != nil {
			errs = errs + err.Error()
			failure = true
		}
	}

	if failure {
		return fmt.Errorf("Monitor resync failed: %s", errs)
	}

	return nil
}
1238037
func (api *PublicDownloaderAPI) SubscribeSyncStatus(status chan interface{}) *SyncStatusSubscription {
	api.installSyncSubscription <- status
	return &SyncStatusSubscription{api: api, c: status}
}
141104
func (tlf *TLF) Fsync(ctx context.Context, req *fuse.FsyncRequest) (err error) {
	dir := tlf.getStoredDir()
	if dir == nil {
		// The directory hasn't been loaded yet, so there's nothing to do.
		return nil
	}

	return dir.Fsync(ctx, req)
}
1322075
func NewCmdSimpleFSSync(
	cl *libcmdline.CommandLine, g *libkb.GlobalContext) cli.Command {
	return cli.Command{
		Name:  "sync",
		Usage: "Manages the per-folder syncing state",
		Subcommands: append([]cli.Command{
			NewCmdSimpleFSSyncEnable(cl, g),
			NewCmdSimpleFSSyncDisable(cl, g),
			NewCmdSimpleFSSyncShow(cl, g),
		}),
	}
}
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)
	}
}
1345075
func (s *Server) ExecSync(ctx context.Context, req *pb.ExecSyncRequest) (resp *pb.ExecSyncResponse, err error) {
	const operation = "exec_sync"
	defer func() {
		recordOperation(operation, time.Now())
		recordError(operation, err)
	}()
	logrus.Debugf("ExecSyncRequest %+v", req)
	c, err := s.GetContainerFromShortID(req.ContainerId)
	if err != nil {
		return nil, err
	}

	if err = s.Runtime().UpdateContainerStatus(c); err != nil {
		return nil, err
	}

	cState := c.State()
	if !(cState.Status == oci.ContainerStateRunning || cState.Status == oci.ContainerStateCreated) {
		return nil, fmt.Errorf("container is not created or running")
	}

	cmd := req.Cmd
	if cmd == nil {
		return nil, fmt.Errorf("exec command cannot be empty")
	}

	execResp, err := s.Runtime().ExecSyncContainer(c, cmd, req.Timeout)
	if err != nil {
		return nil, err
	}
	resp = &pb.ExecSyncResponse{
		Stdout:   execResp.Stdout,
		Stderr:   execResp.Stderr,
		ExitCode: execResp.ExitCode,
	}

	logrus.Infof("Exec'd %s in %s", cmd, c.Description())
	logrus.Debugf("ExecSyncResponse: %+v", resp)
	return resp, nil
}
182079
func (c *Client) FullStatus(args params.StatusParams) (params.FullStatus, error) {
	if err := c.checkCanRead(); err != nil {
		return params.FullStatus{}, err
	}

	var noStatus params.FullStatus
	var context statusContext

	m, err := c.api.stateAccessor.Model()
	if err != nil {
		return noStatus, errors.Annotate(err, "cannot get model")
	}
	context.presence.Presence = c.api.presence.ModelPresence(m.UUID())
	cfg, err := m.Config()
	if err != nil {
		return noStatus, errors.Annotate(err, "cannot obtain current model config")
	}
	context.providerType = cfg.Type()

	if context.model, err = c.api.stateAccessor.Model(); err != nil {
		return noStatus, errors.Annotate(err, "could not fetch model")
	}
	if context.status, err = context.model.LoadModelStatus(); err != nil {
		return noStatus, errors.Annotate(err, "could not load model status values")
	}
	if context.allAppsUnitsCharmBindings, err =
		fetchAllApplicationsAndUnits(c.api.stateAccessor, context.model); err != nil {
		return noStatus, errors.Annotate(err, "could not fetch applications and units")
	}
	if context.consumerRemoteApplications, err =
		fetchConsumerRemoteApplications(c.api.stateAccessor); err != nil {
		return noStatus, errors.Annotate(err, "could not fetch remote applications")
	}
	// Only admins can see offer details.
	if err := c.checkIsAdmin(); err == nil {
		if context.offers, err =
			fetchOffers(c.api.stateAccessor, context.allAppsUnitsCharmBindings.applications); err != nil {
			return noStatus, errors.Annotate(err, "could not fetch application offers")
		}
	}
	if context.machines, err = fetchMachines(c.api.stateAccessor, nil); err != nil {
		return noStatus, errors.Annotate(err, "could not fetch machines")
	}
	// These may be empty when machines have not finished deployment.
	if context.ipAddresses, context.spaces, context.linkLayerDevices, err =
		fetchNetworkInterfaces(c.api.stateAccessor); err != nil {
		return noStatus, errors.Annotate(err, "could not fetch IP addresses and link layer devices")
	}
	if context.relations, context.relationsById, err = fetchRelations(c.api.stateAccessor); err != nil {
		return noStatus, errors.Annotate(err, "could not fetch relations")
	}
	if len(context.allAppsUnitsCharmBindings.applications) > 0 {
		if context.leaders, err = c.api.leadershipReader.Leaders(); err != nil {
			return noStatus, errors.Annotate(err, "could not fetch leaders")
		}
	}
	if context.controllerTimestamp, err = c.api.stateAccessor.ControllerTimestamp(); err != nil {
		return noStatus, errors.Annotate(err, "could not fetch controller timestamp")
	}

	logger.Tracef("Applications: %v", context.allAppsUnitsCharmBindings.applications)
	logger.Tracef("Remote applications: %v", context.consumerRemoteApplications)
	logger.Tracef("Offers: %v", context.offers)
	logger.Tracef("Relations: %v", context.relations)

	if len(args.Patterns) > 0 {
		predicate := BuildPredicateFor(args.Patterns)

		// First, attempt to match machines. Any units on those
		// machines are implicitly matched.
		matchedMachines := make(set.Strings)
		for _, machineList := range context.machines {
			for _, m := range machineList {
				matches, err := predicate(m)
				if err != nil {
					return noStatus, errors.Annotate(
						err, "could not filter machines",
					)
				}
				if matches {
					matchedMachines.Add(m.Id())
				}
			}
		}

		// Filter units
		matchedSvcs := make(set.Strings)
		unitChainPredicate := UnitChainPredicateFn(predicate, context.unitByName)
		// It's possible that we will discover a unit that matches given filter
		// half way through units collection. In that case, it may be that the machine
		// for that unit has other applications' units on it that have already been examined
		// prior. This means that we may miss these other application(s).
		// This behavior has been inconsistent since we get units in a map where
		// the order is not guaranteed.
		// To cater for this scenario, we need to gather all units
		// in a temporary collection keyed on machine to allow for the later
		// pass. This fixes situations similar to inconsistencies
		// observed in lp#1592872.
		machineUnits := map[string][]string{}
		for _, unitMap := range context.allAppsUnitsCharmBindings.units {
			for name, unit := range unitMap {
				machineId, err := unit.AssignedMachineId()
				if err != nil {
					machineId = ""
				} else if matchedMachines.Contains(machineId) {
					// Unit is on a matching machine.
					matchedSvcs.Add(unit.ApplicationName())
					continue
				}
				if machineId != "" {
					machineUnits[machineId] = append(machineUnits[machineId], unit.ApplicationName())
				}

				// Always start examining at the top-level. This
				// prevents a situation where we filter a subordinate
				// before we discover its parent is a match.
				if !unit.IsPrincipal() {
					continue
				} else if matches, err := unitChainPredicate(unit); err != nil {
					return noStatus, errors.Annotate(err, "could not filter units")
				} else if !matches {
					delete(unitMap, name)
					continue
				}
				matchedSvcs.Add(unit.ApplicationName())
				if machineId != "" {
					matchedMachines.Add(machineId)
				}
			}
		}
		for _, m := range matchedMachines.SortedValues() {
			for _, a := range machineUnits[m] {
				if !matchedSvcs.Contains(a) {
					matchedSvcs.Add(a)
				}
			}
		}

		// Filter applications
		for appName, app := range context.allAppsUnitsCharmBindings.applications {
			matches, err := predicate(app)
			if err != nil {
				return noStatus, errors.Annotate(err, "could not filter applications")
			}

			// There are matched units for this application
			// or the application matched the given criteria.
			deleted := false
			if !matchedSvcs.Contains(appName) && !matches {
				delete(context.allAppsUnitsCharmBindings.applications, appName)
				deleted = true
			}

			// Filter relations:
			// Remove relations for applications that were deleted and
			// for the applications that did not match the
			// given criteria.
			if deleted || !matches {
				// delete relations for this app
				if relations, ok := context.relations[appName]; ok {
					for _, r := range relations {
						delete(context.relationsById, r.Id())
					}
					delete(context.relations, appName)
				}
			}
		}
		// TODO(wallyworld) - filter remote applications

		// Filter machines
		for status, machineList := range context.machines {
			matched := make([]*state.Machine, 0, len(machineList))
			for _, m := range machineList {
				machineContainers, err := m.Containers()
				if err != nil {
					return noStatus, err
				}
				machineContainersSet := set.NewStrings(machineContainers...)

				if matchedMachines.Contains(m.Id()) || !matchedMachines.Intersection(machineContainersSet).IsEmpty() {
					// The machine is matched directly, or contains a unit
					// or container that matches.
					logger.Tracef("machine %s is hosting something.", m.Id())
					matched = append(matched, m)
					continue
				}
			}
			context.machines[status] = matched
		}
	}

	modelStatus, err := c.modelStatus()
	if err != nil {
		return noStatus, errors.Annotate(err, "cannot determine model status")
	}
	return params.FullStatus{
		Model:               modelStatus,
		Machines:            context.processMachines(),
		Applications:        context.processApplications(),
		RemoteApplications:  context.processRemoteApplications(),
		Offers:              context.processOffers(),
		Relations:           context.processRelations(),
		ControllerTimestamp: context.controllerTimestamp,
	}, nil
}
1047307
func (s *StateSyncer) retrySyncFullEventFn() event {
	select {
	// trigger a full sync immediately.
	// this is usually called when a consul server was added to the cluster.
	// stagger the delay to avoid a thundering herd.
	case <-s.SyncFull.Notif():
		select {
		case <-time.After(s.stagger(s.serverUpInterval)):
			return syncFullNotifEvent
		case <-s.ShutdownCh:
			return shutdownEvent
		}

	// retry full sync after some time
	// todo(fs): why don't we use s.Interval here?
	case <-time.After(s.retryFailInterval + s.stagger(s.retryFailInterval)):
		return syncFullTimerEvent

	case <-s.ShutdownCh:
		return shutdownEvent
	}
}
434756
func (s *SimpleFSHandler) SimpleFSSyncStatus(ctx context.Context, filter keybase1.ListFilter) (keybase1.FSSyncStatus, error) {
	ctx, cancel := s.wrapContextWithTimeout(ctx)
	defer cancel()
	cli, err := s.client()
	if err != nil {
		return keybase1.FSSyncStatus{}, err
	}
	return cli.SimpleFSSyncStatus(ctx, filter)
}