/*
http://redis.io/commands/sync
*/
171655
func (c *Client) Sync() (string, error) {
	var ret string

	err := c.command(
		&ret,
		[]byte("SYNC"),
	)

	return ret, err
}
1158044
func (dc *DeploymentController) syncDeploymentStatus(allRSs []*apps.ReplicaSet, newRS *apps.ReplicaSet, d *apps.Deployment) error {
	newStatus := calculateStatus(allRSs, newRS, d)

	if reflect.DeepEqual(d.Status, newStatus) {
		return nil
	}

	newDeployment := d
	newDeployment.Status = newStatus
	_, err := dc.client.AppsV1().Deployments(newDeployment.Namespace).UpdateStatus(newDeployment)
	return err
}
176646
func (c *Client) Sync() error {
	cli, err := clientv3.New(clientv3.Config{
		Endpoints:   c.Endpoints,
		DialTimeout: 20 * time.Second,
		TLS:         c.TLS,
	})
	if err != nil {
		return err
	}
	defer cli.Close()

	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	err = cli.Sync(ctx)
	cancel()
	if err != nil {
		return err
	}
	klog.V(1).Infof("etcd endpoints read from etcd: %s", strings.Join(cli.Endpoints(), ","))

	c.Endpoints = cli.Endpoints()
	return nil
}
552966
func SyncDirAdditive(src, dst string) error {
	srcInfos, err := ioutil.ReadDir(src)
	if err != nil {
		return errors.Wrapf(err, "failed to open %s", src)
	}

	for _, srcInfo := range srcInfos {
		srcPath := path.Join(src, srcInfo.Name())
		dstPath := path.Join(dst, srcInfo.Name())

		if dstInfo, err := os.Stat(dstPath); os.IsNotExist(err) {
			// safe to copy
			if srcInfo.IsDir() {
				err = CopyDir(srcPath, dstPath)
			} else {
				err = CopyFile(srcPath, dstPath)
			}
			if err != nil {
				return errors.Wrapf(err, "failed to copy %s to %s", srcPath, dstPath)
			}
		} else if err != nil {
			return errors.Wrapf(err, "failed to stat %s", dstPath)
		} else if srcInfo.IsDir() && dstInfo.IsDir() {
			// if source and destination are both directories, sync recursively
			if err = SyncDirAdditive(srcPath, dstPath); err != nil {
				return errors.Wrapf(err, "failed to sync %s to %s", srcPath, dstPath)
			}
		}
	}
	return nil
}
485041
func (a *Action) Sync(ms int) <-chan interface{} {
	m := make(chan interface{})

	if a.cache != nil {
		go func() {
			m <- a.cache
			close(m)
		}()
	} else {
		if ms <= 0 {
			ms = 1
		}

		md := time.Duration(ms) * time.Millisecond

		a.When(func(b interface{}, _ ActionInterface) {
			go func() {
				m <- b
				close(m)
			}()
		})

		go func() {
			<-time.After(md)
			<-m
		}()
	}

	return m
}
603978
func (s *schedule) Sync(timestamp uint32) {
	atomic.StoreInt64(&s.offset, time.Now().UnixNano()-int64(timestamp)*1000)
}
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
}
387880
func (c *config) Sync() error {
	if err := c.opts.Loader.Sync(); err != nil {
		return err
	}

	snap, err := c.opts.Loader.Snapshot()
	if err != nil {
		return err
	}

	c.Lock()
	defer c.Unlock()

	c.snap = snap
	vals, err := c.opts.Reader.Values(snap.ChangeSet)
	if err != nil {
		return err
	}
	c.vals = vals

	return nil
}
1225618
func addArgs(r AddRequest) redis.Args {
	args := redis.Args{r.Job.Queue, r.Job.Data, int(r.Timeout / time.Millisecond)}

	if r.Replicate > 0 {
		args = args.Add("REPLICATE", r.Replicate)
	}

	if r.Delay > 0 {
		args = args.Add("DELAY", int64(r.Delay.Seconds()))
	}

	if r.Retry > 0 {
		args = args.Add("RETRY", int64(r.Retry.Seconds()))
	}

	if r.TTL > 0 {
		args = args.Add("TTL", int64(r.TTL.Seconds()))
	}

	if r.Maxlen > 0 {
		args = args.Add("MAXLEN", r.Maxlen)
	}

	if r.Async {
		args = args.Add("ASYNC")
	}
	return args
}
890595
func (s *Logging) Sync() error {
	s.mutex.RLock()
	w := s.writer
	s.mutex.RUnlock()

	return w.Sync()
}
92808
func NewRedis(cf map[string]string, lifeTime int32) *Redis {
	rc := &Redis{key: DefaultKey}
	if _, ok := cf["key"]; !ok {
		cf["key"] = DefaultKey
	}
	rc.key = cf["key"]
	rc.conninfo = cf["conn"]
	rc.LifeTime = lifeTime
	rc.connectInit()
	return rc
}
67313
func (w *Watcher) sync() error {
	session := w.pings.Database.Session.Copy()
	defer session.Close()
	pings, err := w.lookupPings(session)
	if err != nil {
		return err
	}
	dead, err := w.lookForDead(pings)
	if err != nil {
		return err
	}
	alive, unknownSeqs, err := w.handleAlive(pings)
	if err != nil {
		return err
	}
	err = w.lookupUnknownSeqs(unknownSeqs, dead, session)
	if err != nil {
		return err
	}

	// Pingers that were known to be alive and haven't reported
	// in the last two slots are now considered dead. Dispatch
	// the respective events and forget their sequences.
	for seq, key := range w.beingKey {
		if dead[seq] || !alive[seq] {
			logger.Tracef("[%s] removing seq=%d with key %q", w.modelUUID[:6], seq, key)
			delete(w.beingKey, seq)
			delete(w.beingSeq, key)
			for _, ch := range w.watches[key] {
				w.pending = append(w.pending, event{ch, key, false})
			}
		}
	}
	return nil
}
957770
func (c *syncClient) Flushall() (err Error) {
	_, err = c.conn.ServiceRequest(&FLUSHALL, [][]byte{})
	return
}
887780
func (c *ServiceClient) sync() error {
	sreg, creg, sdereg, cdereg := 0, 0, 0, 0

	consulServices, err := c.client.Services()
	if err != nil {
		metrics.IncrCounter([]string{"client", "consul", "sync_failure"}, 1)
		return fmt.Errorf("error querying Consul services: %v", err)
	}

	consulChecks, err := c.client.Checks()
	if err != nil {
		metrics.IncrCounter([]string{"client", "consul", "sync_failure"}, 1)
		return fmt.Errorf("error querying Consul checks: %v", err)
	}

	// Remove Nomad services in Consul but unknown locally
	for id := range consulServices {
		if _, ok := c.services[id]; ok {
			// Known service, skip
			continue
		}

		// Ignore if this is not a Nomad managed service. Also ignore
		// Nomad managed services if this is not a client agent.
		// This is to prevent server agents from removing services
		// registered by client agents
		if !isNomadService(id) || !c.isClientAgent {
			// Not managed by Nomad, skip
			continue
		}

		// Unknown Nomad managed service; kill
		if err := c.client.ServiceDeregister(id); err != nil {
			if isOldNomadService(id) {
				// Don't hard-fail on old entries. See #3620
				continue
			}

			metrics.IncrCounter([]string{"client", "consul", "sync_failure"}, 1)
			return err
		}
		sdereg++
		metrics.IncrCounter([]string{"client", "consul", "service_deregistrations"}, 1)
	}

	// Add Nomad services missing from Consul
	for id, locals := range c.services {
		if _, ok := consulServices[id]; !ok {
			if err = c.client.ServiceRegister(locals); err != nil {
				metrics.IncrCounter([]string{"client", "consul", "sync_failure"}, 1)
				return err
			}
			sreg++
			metrics.IncrCounter([]string{"client", "consul", "service_registrations"}, 1)
		}
	}

	// Remove Nomad checks in Consul but unknown locally
	for id, check := range consulChecks {
		if _, ok := c.checks[id]; ok {
			// Known check, leave it
			continue
		}

		// Ignore if this is not a Nomad managed check. Also ignore
		// Nomad managed checks if this is not a client agent.
		// This is to prevent server agents from removing checks
		// registered by client agents
		if !isNomadService(check.ServiceID) || !c.isClientAgent {
			// Service not managed by Nomad, skip
			continue
		}

		// Unknown Nomad managed check; remove
		if err := c.client.CheckDeregister(id); err != nil {
			if isOldNomadService(check.ServiceID) {
				// Don't hard-fail on old entries.
				continue
			}

			metrics.IncrCounter([]string{"client", "consul", "sync_failure"}, 1)
			return err
		}
		cdereg++
		metrics.IncrCounter([]string{"client", "consul", "check_deregistrations"}, 1)
	}

	// Add Nomad checks missing from Consul
	for id, check := range c.checks {
		if _, ok := consulChecks[id]; ok {
			// Already in Consul; skipping
			continue
		}

		if err := c.client.CheckRegister(check); err != nil {
			metrics.IncrCounter([]string{"client", "consul", "sync_failure"}, 1)
			return err
		}
		creg++
		metrics.IncrCounter([]string{"client", "consul", "check_registrations"}, 1)

		// Handle starting scripts
		if script, ok := c.scripts[id]; ok {
			// If it's already running, cancel and replace
			if oldScript, running := c.runningScripts[id]; running {
				oldScript.cancel()
			}
			// Start and store the handle
			c.runningScripts[id] = script.run()
		}
	}

	// Only log if something was actually synced
	if sreg > 0 || sdereg > 0 || creg > 0 || cdereg > 0 {
		c.logger.Debug("sync complete", "registered_services", sreg, "deregistered_services", sdereg,
			"registered_checks", creg, "deregistered_checks", cdereg)
	}
	return nil
}
188559
func (d *Downloader) syncState(root common.Hash) *stateSync {
	s := newStateSync(d, root)
	select {
	case d.stateSyncStart <- s:
	case <-d.quitCh:
		s.err = errCancelStateFetch
		close(s.done)
	}
	return s
}
717830
func (f *lightFetcher) syncLoop() {
	requesting := false
	defer f.pm.wg.Done()
	for {
		select {
		case <-f.pm.quitSync:
			return
		// when a new announce is received, request loop keeps running until
		// no further requests are necessary or possible
		case newAnnounce := <-f.requestChn:
			f.lock.Lock()
			s := requesting
			requesting = false
			var (
				rq      *distReq
				reqID   uint64
				syncing bool
			)

			if !f.syncing && !(newAnnounce && s) {
				rq, reqID, syncing = f.nextRequest()
			}
			f.lock.Unlock()

			if rq != nil {
				requesting = true
				if _, ok := <-f.pm.reqDist.queue(rq); ok {
					if syncing {
						f.lock.Lock()
						f.syncing = true
						f.lock.Unlock()
					} else {
						go func() {
							time.Sleep(softRequestTimeout)
							f.reqMu.Lock()
							req, ok := f.requested[reqID]
							if ok {
								req.timeout = true
								f.requested[reqID] = req
							}
							f.reqMu.Unlock()
							// keep starting new requests while possible
							f.requestChn <- false
						}()
					}
				} else {
					f.requestChn <- false
				}
			}
		case reqID := <-f.timeoutChn:
			f.reqMu.Lock()
			req, ok := f.requested[reqID]
			if ok {
				delete(f.requested, reqID)
			}
			f.reqMu.Unlock()
			if ok {
				f.pm.serverPool.adjustResponseTime(req.peer.poolEntry, time.Duration(mclock.Now()-req.sent), true)
				req.peer.Log().Debug("Fetching data timed out hard")
				go f.pm.removePeer(req.peer.id)
			}
		case resp := <-f.deliverChn:
			f.reqMu.Lock()
			req, ok := f.requested[resp.reqID]
			if ok && req.peer != resp.peer {
				ok = false
			}
			if ok {
				delete(f.requested, resp.reqID)
			}
			f.reqMu.Unlock()
			if ok {
				f.pm.serverPool.adjustResponseTime(req.peer.poolEntry, time.Duration(mclock.Now()-req.sent), req.timeout)
			}
			f.lock.Lock()
			if !ok || !(f.syncing || f.processResponse(req, resp)) {
				resp.peer.Log().Debug("Failed processing response")
				go f.pm.removePeer(resp.peer.id)
			}
			f.lock.Unlock()
		case p := <-f.syncDone:
			f.lock.Lock()
			p.Log().Debug("Done synchronising with peer")
			f.checkSyncedHeaders(p)
			f.syncing = false
			f.lock.Unlock()
			f.requestChn <- false
		}
	}
}
821023
func (ssc *StatefulSetController) sync(key string) error {
	startTime := time.Now()
	defer func() {
		klog.V(4).Infof("Finished syncing statefulset %q (%v)", key, time.Since(startTime))
	}()

	namespace, name, err := cache.SplitMetaNamespaceKey(key)
	if err != nil {
		return err
	}
	set, err := ssc.setLister.StatefulSets(namespace).Get(name)
	if errors.IsNotFound(err) {
		klog.Infof("StatefulSet has been deleted %v", key)
		return nil
	}
	if err != nil {
		utilruntime.HandleError(fmt.Errorf("unable to retrieve StatefulSet %v from store: %v", key, err))
		return err
	}

	selector, err := metav1.LabelSelectorAsSelector(set.Spec.Selector)
	if err != nil {
		utilruntime.HandleError(fmt.Errorf("error converting StatefulSet %v selector: %v", key, err))
		// This is a non-transient error, so don't retry.
		return nil
	}

	if err := ssc.adoptOrphanRevisions(set); err != nil {
		return err
	}

	pods, err := ssc.getPodsForStatefulSet(set, selector)
	if err != nil {
		return err
	}

	return ssc.syncStatefulSet(set, pods)
}