// Sync synchronizes the number of running service states and returns the delta
// of added (>0) or deleted (<0) instances.
967998
func (l *ServiceListener) Sync(isLocked bool, sn *ServiceNode, reqs []StateRequest) (int, bool) {
	ok := true
	count := len(reqs)

	if servicedefinition.ChangeOptions(sn.ChangeOptions).Contains(servicedefinition.RestartAllOnInstanceZeroDown) {
		// If restartAllOnInstanceZeroDown is set on the service ChangeOptions and
		// instance 0 goes down, we want to stop all instances and wait for the
		// nodes to stop, then bring the services back up to get a new instance 0.
		if count != 0 {
			// Look for instance 0.  If we don't have one, shut down all instances so that they'll
			// restart on the next loop.
			found := false
			for _, req := range reqs {
				if req.InstanceID == 0 {
					found = true
					break
				}
			}
			if !found {
				sn.Instances = 0 // NOTE: this will not update the node in zk or elastic
			}
		}
	} else if servicedefinition.ChangeOptions(sn.ChangeOptions).Contains(servicedefinition.RestartAllOnInstanceChanged) {
		// If the service has a change option for restart all on changed, stop all
		// instances and wait for the nodes to stop.  Once all service instances
		// have been stopped (deleted), then go ahead and start the instances.
		if count != 0 && count != sn.Instances {
			sn.Instances = 0 // NOTE: this will not update the node in zk or elastic
		}
	}

	// Do not create instances if service is locked
	if isLocked && count < sn.Instances {
		return 0, ok
	}

	// sort all of the requests by instance id
	SortStateRequests(reqs)

	// Start instances if there is a deficit
	delta := 0
	i := -1
	for ; count < sn.Instances; count++ {
		// Assuming that instanceIDs are gte 0 and that all instance IDs are
		// unique for a service, find the first index that does not match the
		// instanceID value.
		// Example: {0,1,4,5}, [0]=>0, [1]=>1, --> [2]=>4 <--
		for i = i + 1; i < count; i++ {
			if i < reqs[i].InstanceID {
				break
			}
		}

		// Create the instance if the service is not locked
		if !l.Start(sn, i) {
			return delta, false
		}
		delta++

		// Prepend a request object to the array. You could insert it in order,
		// but that is more expensive and doesn't matter.  What is important
		// is that the index of the mismatched value increases by one.
		// Example: Before: {0, 1, 4, 5}, [2]=>4 After: {2, 0, 1, 4, 5}, [3]=>4
		reqs = append(make([]StateRequest, 1), reqs...)

		// See https://play.golang.org/p/t8rd97z8nK if you need more proof
	}

	// Stop instances if there is a surplus
	if count > sn.Instances {
		delta, pass := l.Stop(reqs[sn.Instances:])
		return -delta, ok && pass
	}

	return delta, ok
}
1326286
func (comments *Comments) Sync() {
	endpoint := fmt.Sprintf(urlCommentSync, comments.item.ID)
	comments.endpoint = endpoint
	return
}
603978
func (s *schedule) Sync(timestamp uint32) {
	atomic.StoreInt64(&s.offset, time.Now().UnixNano()-int64(timestamp)*1000)
}
172369
func (l *WAL) sync() {
	err := l.currentSegmentWriter.sync()
	for len(l.syncWaiters) > 0 {
		errC := <-l.syncWaiters
		errC <- err
	}
}
1249900
func (l *LinkNode) Sync() error {

	// Finally update the database by storing the link node and updating
	// any relevant indexes.
	return l.db.Update(func(tx *bbolt.Tx) error {
		nodeMetaBucket := tx.Bucket(nodeInfoBucket)
		if nodeMetaBucket == nil {
			return ErrLinkNodesNotFound
		}

		return putLinkNode(nodeMetaBucket, l)
	})
}
1335163
func (proxier *Proxier) SyncLoop() {
	// Update healthz timestamp at beginning in case Sync() never succeeds.
	if proxier.healthzServer != nil {
		proxier.healthzServer.UpdateTimestamp()
	}
	proxier.syncRunner.Loop(wait.NeverStop)
}
573823
func (c *Counts) Add(c2 Delta) {
	c.CPUUserTime += c2.CPUUserTime
	c.CPUSystemTime += c2.CPUSystemTime
	c.ReadBytes += c2.ReadBytes
	c.WriteBytes += c2.WriteBytes
	c.MajorPageFaults += c2.MajorPageFaults
	c.MinorPageFaults += c2.MinorPageFaults
	c.CtxSwitchVoluntary += c2.CtxSwitchVoluntary
	c.CtxSwitchNonvoluntary += c2.CtxSwitchNonvoluntary
}
901748
func (cache *Cache) Sync(state Writer) error {
	cache.Lock()
	defer cache.Unlock()
	// Determine order for names
	// note names may be of any length less than some limit
	var hashes ProposalHashArray
	for hash := range cache.proposals {
		hashes = append(hashes, hash)
	}
	sort.Stable(hashes)

	// Update or delete names.
	for _, hash := range hashes {
		proposalInfo := cache.proposals[hash]
		proposalInfo.RLock()
		if proposalInfo.removed {
			err := state.RemoveProposal(hash[:])
			if err != nil {
				proposalInfo.RUnlock()
				return err
			}
		} else if proposalInfo.updated {
			err := state.UpdateProposal(hash[:], proposalInfo.ballot)
			if err != nil {
				proposalInfo.RUnlock()
				return err
			}
		}
		proposalInfo.RUnlock()
	}
	return nil
}
1321835
func (f *Facade) syncService(ctx datastore.Context, tenantID, serviceID string, setLockOnCreate, setLockOnUpdate bool) error {
	defer ctx.Metrics().Stop(ctx.Metrics().Start("Facade.syncService"))
	svc, err := f.GetService(ctx, serviceID)
	if err != nil {
		glog.Errorf("Could not get service %s to sync: %s", serviceID, err)
		return err
	}
	if err := f.zzk.UpdateService(ctx, tenantID, svc, setLockOnCreate, setLockOnUpdate); err != nil {
		glog.Errorf("Could not sync service %s to the coordinator: %s", serviceID, err)
		return err
	}
	return nil
}
124058
func (w *Watcher) sync() error {
	w.needSync = false
	// Iterate through log events in reverse insertion order (newest first).
	iter := w.iteratorFunc()
	seen := make(map[watchKey]bool)
	first := true
	lastId := w.lastId
	var entry bson.D
	for iter.Next(&entry) {
		if len(entry) == 0 {
			logger.Tracef("got empty changelog document")
		}
		id := entry[0]
		if id.Name != "_id" {
			panic("watcher: _id field isn't first entry")
		}
		if first {
			w.lastId = id.Value
			first = false
		}
		if id.Value == lastId {
			break
		}
		logger.Tracef("got changelog document: %#v", entry)
		for _, c := range entry[1:] {
			// See txn's Runner.ChangeLog for the structure of log entries.
			var d, r []interface{}
			dr, _ := c.Value.(bson.D)
			for _, item := range dr {
				switch item.Name {
				case "d":
					d, _ = item.Value.([]interface{})
				case "r":
					r, _ = item.Value.([]interface{})
				}
			}
			if len(d) == 0 || len(d) != len(r) {
				logger.Warningf("changelog has invalid collection document: %#v", c)
				continue
			}
			for i := len(d) - 1; i >= 0; i-- {
				key := watchKey{c.Name, d[i]}
				if seen[key] {
					continue
				}
				seen[key] = true
				revno, ok := r[i].(int64)
				if !ok {
					logger.Warningf("changelog has revno with type %T: %#v", r[i], r[i])
					continue
				}
				if revno < 0 {
					revno = -1
				}
				// Queue notifications for per-collection watches.
				for _, info := range w.watches[watchKey{c.Name, nil}] {
					if info.filter != nil && !info.filter(d[i]) {
						continue
					}
					evt := event{
						ch:        info.ch,
						key:       key,
						isDeleted: revno == -1,
						revno:     revno,
					}
					w.syncEvents = append(w.syncEvents, evt)
				}
				// Queue notifications for per-document watches.
				infos := w.watches[key]
				for i, info := range infos {
					if revno > info.revno || revno < 0 && info.revno >= 0 {
						infos[i].revno = revno
						evt := event{
							ch:        info.ch,
							key:       key,
							isDeleted: revno == -1,
							revno:     revno,
						}
						w.syncEvents = append(w.syncEvents, evt)
					}
				}
			}
		}
	}
	if err := iter.Close(); err != nil {
		if qerr, ok := err.(*mgo.QueryError); ok {
			// CappedPositionLost is code 136.
			// Just in case that changes for some reason, we'll also check the error message.
			if qerr.Code == 136 || strings.Contains(qerr.Message, "CappedPositionLost") {
				logger.Warningf("watcher iterator failed due to txn log collection overflow")
				err = cappedPositionLostError
			}
		}
		return errors.Annotate(err, "watcher iteration error")
	}
	return nil
}
1152284
func sync(c context.Context, cfg *Config) error {
	if err := syncVMs(c, cfg.VMs.GetVms()); err != nil {
		return errors.Annotate(err, "failed to sync VMs configs").Err()
	}
	if err := syncPrjs(c, cfg.Projects.GetProject()); err != nil {
		return errors.Annotate(err, "failed to sync project configs").Err()
	}
	return nil
}
1235924
func (cache *Cache) Sync(state Writer) error {
	cache.Lock()
	defer cache.Unlock()
	// Determine order for names
	// note names may be of any length less than some limit
	var names sort.StringSlice
	for nameStr := range cache.names {
		names = append(names, nameStr)
	}
	sort.Stable(names)

	// Update or delete names.
	for _, name := range names {
		nameInfo := cache.names[name]
		nameInfo.RLock()
		if nameInfo.removed {
			err := state.RemoveName(name)
			if err != nil {
				nameInfo.RUnlock()
				return err
			}
		} else if nameInfo.updated {
			err := state.UpdateName(nameInfo.entry)
			if err != nil {
				nameInfo.RUnlock()
				return err
			}
		}
		nameInfo.RUnlock()
	}
	return nil
}
1243524
func (s *LDAPGroupSyncer) Sync() ([]*userv1.Group, []error) {
	openshiftGroups := []*userv1.Group{}
	var errors []error

	// determine what to sync
	klog.V(1).Infof("Listing with %v", s.GroupLister)
	ldapGroupUIDs, err := s.GroupLister.ListGroups()
	if err != nil {
		errors = append(errors, err)
		return nil, errors
	}
	klog.V(1).Infof("Sync ldapGroupUIDs %v", ldapGroupUIDs)

	for _, ldapGroupUID := range ldapGroupUIDs {
		klog.V(1).Infof("Checking LDAP group %v", ldapGroupUID)

		// get membership data
		memberEntries, err := s.GroupMemberExtractor.ExtractMembers(ldapGroupUID)
		if err != nil {
			fmt.Fprintf(s.Err, "Error determining LDAP group membership for %q: %v.\n", ldapGroupUID, err)
			errors = append(errors, err)
			continue
		}

		// determine OpenShift Users' usernames for LDAP group members
		usernames, err := s.determineUsernames(memberEntries)
		if err != nil {
			fmt.Fprintf(s.Err, "Error determining usernames for LDAP group %q: %v.\n", ldapGroupUID, err)
			errors = append(errors, err)
			continue
		}
		klog.V(1).Infof("Has OpenShift users %v", usernames)

		// update the OpenShift Group corresponding to this record
		openshiftGroup, err := s.makeOpenShiftGroup(ldapGroupUID, usernames)
		if err != nil {
			fmt.Fprintf(s.Err, "Error building OpenShift group for LDAP group %q: %v.\n", ldapGroupUID, err)
			errors = append(errors, err)
			continue
		}
		openshiftGroups = append(openshiftGroups, openshiftGroup)

		if !s.DryRun {
			fmt.Fprintf(s.Out, "group/%s\n", openshiftGroup.Name)
			if err := s.updateOpenShiftGroup(openshiftGroup); err != nil {
				fmt.Fprintf(s.Err, "Error updating OpenShift group %q for LDAP group %q: %v.\n", openshiftGroup.Name, ldapGroupUID, err)
				errors = append(errors, err)
				continue
			}
		}
	}

	return openshiftGroups, errors
}
1252627
func (m *memory) Sync() error {
	var sets []*source.ChangeSet

	m.Lock()

	// read the source
	var gerr []string

	for _, source := range m.sources {
		ch, err := source.Read()
		if err != nil {
			gerr = append(gerr, err.Error())
			continue
		}
		sets = append(sets, ch)
	}

	// merge sets
	set, err := m.opts.Reader.Merge(sets...)
	if err != nil {
		m.Unlock()
		return err
	}

	// set values
	vals, err := m.opts.Reader.Values(set)
	if err != nil {
		m.Unlock()
		return err
	}
	m.vals = vals
	m.snap = &loader.Snapshot{
		ChangeSet: set,
		Version:   fmt.Sprintf("%d", time.Now().Unix()),
	}

	m.Unlock()

	// update watchers
	m.update()

	if len(gerr) > 0 {
		return fmt.Errorf("source loading errors: %s", strings.Join(gerr, "\n"))
	}

	return nil
}
986602
func (rpc *EthRPC) EthSyncing() (*Syncing, error) {
	result, err := rpc.RawCall("eth_syncing")
	if err != nil {
		return nil, err
	}
	syncing := new(Syncing)
	if bytes.Equal(result, []byte("false")) {
		return syncing, nil
	}
	err = json.Unmarshal(result, syncing)
	return syncing, err
}
119530
func (ac *AuthorizationCache) synchronize() {
	// if none of our internal reflectors changed, then we can skip reviewing the cache
	skip, currentState := ac.skip.SkipSynchronize(ac.lastState, ac.lastSyncResourceVersioner, ac.roleLastSyncResourceVersioner)
	if skip {
		return
	}

	// by default, we update our current caches and do an incremental change
	userSubjectRecordStore := ac.userSubjectRecordStore
	groupSubjectRecordStore := ac.groupSubjectRecordStore
	reviewRecordStore := ac.reviewRecordStore

	// if there was a global change that forced complete invalidation, we rebuild our cache and do a fast swap at end
	invalidateCache := ac.invalidateCache()
	if invalidateCache {
		userSubjectRecordStore = cache.NewStore(subjectRecordKeyFn)
		groupSubjectRecordStore = cache.NewStore(subjectRecordKeyFn)
		reviewRecordStore = cache.NewStore(reviewRecordKeyFn)
	}

	// iterate over caches and synchronize our three caches
	newKnownNamespaces := ac.synchronizeNamespaces(userSubjectRecordStore, groupSubjectRecordStore, reviewRecordStore)
	ac.synchronizePolicies(userSubjectRecordStore, groupSubjectRecordStore, reviewRecordStore)
	ac.synchronizeRoleBindings(userSubjectRecordStore, groupSubjectRecordStore, reviewRecordStore)
	ac.purgeDeletedNamespaces(ac.allKnownNamespaces, newKnownNamespaces, userSubjectRecordStore, groupSubjectRecordStore, reviewRecordStore)

	// if we did a full rebuild, now we swap the fully rebuilt cache
	if invalidateCache {
		ac.userSubjectRecordStore = userSubjectRecordStore
		ac.groupSubjectRecordStore = groupSubjectRecordStore
		ac.reviewRecordStore = reviewRecordStore
	}
	ac.allKnownNamespaces = newKnownNamespaces

	// we were able to update our cache since this last observation period
	ac.lastState = currentState
}
851708
func (m *monitor) sync() error {
	names, _, err := m.harvest("")
	if len(names) > 0 {
		m.tip = names
	} else {
		m.tip = defaultTip
	}
	return err
}