// Sync synchronizes client's endpoints with the known endpoints from the etcd membership.
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
}
56110
func (pm *ProtocolManager) synchronise(peer *peer) {
	// Short circuit if no peers are available
	if peer == nil {
		return
	}

	// Make sure the peer's TD is higher than our own.
	if !pm.needToSync(peer.headBlockInfo()) {
		return
	}

	ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
	defer cancel()
	pm.blockchain.(*light.LightChain).SyncCht(ctx)
	pm.downloader.Synchronise(peer.id, peer.Head(), peer.Td(), downloader.LightSync)
}
18373
func (w *WALSegmentWriter) sync() error {
	if err := w.bw.Flush(); err != nil {
		return err
	}

	if f, ok := w.w.(*os.File); ok {
		return f.Sync()
	}
	return nil
}
88482
func (us *UsersService) Sync() (*http.Response, error) {
	u, err := urlWithOptions("/users/sync", nil)
	if err != nil {
		return nil, err
	}

	req, err := us.client.NewRequest("POST", u, nil, nil)
	if err != nil {
		return nil, err
	}

	resp, err := us.client.Do(req, nil)
	if err != nil {
		return nil, err
	}

	return resp, err
}
1344098
func (sc *syncContext) sync() {
	syncTasks, successful := sc.generateSyncTasks()
	if !successful {
		sc.setOperationPhase(appv1.OperationFailed, "one or more synchronization tasks are not valid")
		return
	}

	// If no sync tasks were generated (e.g., in case all application manifests have been removed),
	// set the sync operation as successful.
	if len(syncTasks) == 0 {
		sc.setOperationPhase(appv1.OperationSucceeded, "successfully synced (no manifests)")
		return
	}

	// Perform a `kubectl apply --dry-run` against all the manifests. This will detect most (but
	// not all) validation issues with the user's manifests (e.g. will detect syntax issues, but
	// will not not detect if they are mutating immutable fields). If anything fails, we will refuse
	// to perform the sync.
	if !sc.startedPreSyncPhase() {
		// Optimization: we only wish to do this once per operation, performing additional dry-runs
		// is harmless, but redundant. The indicator we use to detect if we have already performed
		// the dry-run for this operation, is if the resource or hook list is empty.
		if !sc.doApplySync(syncTasks, true, false, sc.syncOp.DryRun) {
			sc.setOperationPhase(appv1.OperationFailed, "one or more objects failed to apply (dry run)")
			return
		}
		if sc.syncOp.DryRun {
			sc.setOperationPhase(appv1.OperationSucceeded, "successfully synced (dry run)")
			return
		}
	}

	// All objects passed a `kubectl apply --dry-run`, so we are now ready to actually perform the sync.
	if sc.syncOp.SyncStrategy == nil {
		// default sync strategy to hook if no strategy
		sc.syncOp.SyncStrategy = &appv1.SyncStrategy{Hook: &appv1.SyncStrategyHook{}}
	}
	if sc.syncOp.SyncStrategy.Apply != nil {
		if !sc.startedSyncPhase() {
			if !sc.doApplySync(syncTasks, false, sc.syncOp.SyncStrategy.Apply.Force, true) {
				sc.setOperationPhase(appv1.OperationFailed, "one or more objects failed to apply")
				return
			}
			// If apply was successful, return here and force an app refresh. This is so the app
			// will become requeued into the workqueue, to force a new sync/health assessment before
			// marking the operation as completed
			return
		}
		sc.setOperationPhase(appv1.OperationSucceeded, "successfully synced")
	} else if sc.syncOp.SyncStrategy.Hook != nil {
		hooks, err := sc.getHooks()
		if err != nil {
			sc.setOperationPhase(appv1.OperationError, fmt.Sprintf("failed to generate hooks resources: %v", err))
			return
		}
		sc.doHookSync(syncTasks, hooks)
	} else {
		sc.setOperationPhase(appv1.OperationFailed, "Unknown sync strategy")
		return
	}
}
1360040
func (cache *Cache) Sync(st Writer) error {
	if cache.readonly {
		// Sync is (should be) a no-op for read-only - any modifications should have been caught in respective methods
		return nil
	}
	cache.Lock()
	defer cache.Unlock()
	var addresses crypto.Addresses
	for address := range cache.accounts {
		addresses = append(addresses, address)
	}

	sort.Sort(addresses)
	for _, address := range addresses {
		accInfo := cache.accounts[address]
		accInfo.RLock()
		if accInfo.removed {
			err := st.RemoveAccount(address)
			if err != nil {
				return err
			}
		} else if accInfo.updated {
			// First update account in case it needs to be created
			err := st.UpdateAccount(accInfo.account)
			if err != nil {
				return err
			}
			// Sort keys
			var keys binary.Words256
			for key := range accInfo.storage {
				keys = append(keys, key)
			}
			sort.Sort(keys)
			// Update account's storage
			for _, key := range keys {
				value := accInfo.storage[key]
				err := st.SetStorage(address, key, value)
				if err != nil {
					return err
				}
			}

		}
		accInfo.RUnlock()
	}
	return nil
}
1359181
func (d *Downloader) Synchronise(id string, head common.Hash, td *big.Int, mode SyncMode) error {
	err := d.synchronise(id, head, td, mode)
	switch err {
	case nil:
	case errBusy:

	case errTimeout, errBadPeer, errStallingPeer, errUnsyncedPeer,
		errEmptyHeaderSet, errPeersUnavailable, errTooOld,
		errInvalidAncestor, errInvalidChain:
		log.Warn("Synchronisation failed, dropping peer", "peer", id, "err", err)
		if d.dropPeer == nil {
			// The dropPeer method is nil when `--copydb` is used for a local copy.
			// Timeouts can occur if e.g. compaction hits at the wrong time, and can be ignored
			log.Warn("Downloader wants to drop peer, but peerdrop-function is not set", "peer", id)
		} else {
			d.dropPeer(id)
		}
	default:
		log.Warn("Synchronisation failed, retrying", "err", err)
	}
	return err
}
355361
func (ctx *Context) Sync(dryrun bool) (err error) {
	// vcs.ShowCmd = true
	outOfDate, err := ctx.VerifyVendor()
	if err != nil {
		return fmt.Errorf("Failed to verify checksums: %v", err)
	}
	// GOPATH includes the src dir, move up a level.
	cacheRoot := filepath.Join(ctx.RootGopath, "..", ".cache", "govendor")
	err = os.MkdirAll(cacheRoot, 0700)
	if err != nil {
		return err
	}

	// collect errors and proceed where you can.
	rem := remoteFailureList{}

	h := sha1.New()
	updatedVendorFile := false

	for _, vp := range outOfDate {
		// Bundle packages together that have the same revision and share at least one root segment.
		if len(vp.Revision) == 0 {
			continue
		}
		from := vp.Path
		if len(vp.Origin) > 0 {
			from = vp.Origin
		}
		if from != vp.Path {
			fmt.Fprintf(ctx, "fetch %q from %q\n", vp.Path, from)
		} else {
			fmt.Fprintf(ctx, "fetch %q\n", vp.Path)
		}
		if dryrun {
			continue
		}
		pkgDir := filepath.Join(cacheRoot, from)

		// See if repo exists.
		sysVcsCmd, repoRoot, err := vcs.FromDir(pkgDir, cacheRoot)
		var vcsCmd *VCSCmd
		repoRootDir := filepath.Join(cacheRoot, repoRoot)
		if err != nil {
			rr, err := vcs.RepoRootForImportPath(from, false)
			if err != nil {
				rem = append(rem, remoteFailure{Msg: "failed to ping remote repo", Path: vp.Path, Err: err})
				continue
			}
			if !ctx.Insecure && !vcsIsSecure(rr.Repo) {
				rem = append(rem, remoteFailure{Msg: "repo remote not secure", Path: vp.Path, Err: nil})
				continue
			}

			vcsCmd = updateVcsCmd(rr.VCS)

			repoRoot = rr.Root
			repoRootDir = filepath.Join(cacheRoot, repoRoot)
			err = os.MkdirAll(repoRootDir, 0700)
			if err != nil {
				rem = append(rem, remoteFailure{Msg: "failed to make repo root dir", Path: vp.Path, Err: err})
				continue
			}

			err = vcsCmd.CreateAtRev(repoRootDir, rr.Repo, vp.Revision)
			if err != nil {
				rem = append(rem, remoteFailure{Msg: "failed to clone repo", Path: vp.Path, Err: err})
				continue
			}
		} else {
			// Use cache.
			vcsCmd = updateVcsCmd(sysVcsCmd)

			err = vcsCmd.RevisionSync(repoRootDir, vp.Revision)
			// If revision was not found in the cache, download and try again.
			if err != nil {
				err = vcsCmd.Download(repoRootDir)
				if err != nil {
					rem = append(rem, remoteFailure{Msg: "failed to download repo", Path: vp.Path, Err: err})
					continue
				}
				err = vcsCmd.RevisionSync(repoRootDir, vp.Revision)
				if err != nil {
					rem = append(rem, remoteFailure{Msg: "failed to sync repo to " + vp.Revision, Path: vp.Path, Err: err})
					continue
				}
			}
		}
		dest := filepath.Join(ctx.RootDir, ctx.VendorFolder, pathos.SlashToFilepath(vp.Path))
		// Path handling with single sub-packages and differing origins need to be properly handled.
		src := pkgDir

		// Scan go files for files that should be ignored based on tags and filenames.
		ignoreFiles, _, err := ctx.getIgnoreFiles(src)
		if err != nil {
			rem = append(rem, remoteFailure{Msg: "failed to get ignore files", Path: vp.Path, Err: err})
			continue
		}

		root, _ := pathos.TrimCommonSuffix(src, vp.Path)

		// Need to ensure we copy files from "b.Root/<import-path>" for the following command.
		err = ctx.CopyPackage(dest, src, root, vp.Path, ignoreFiles, vp.Tree, h, nil)
		if err != nil {
			fmt.Fprintf(ctx, "failed to copy package from %q to %q: %+v", src, dest, err)
		}
		checksum := h.Sum(nil)
		h.Reset()
		vp.ChecksumSHA1 = base64.StdEncoding.EncodeToString(checksum)
		updatedVendorFile = true
	}

	// Only write a vendor file if something changes.
	if updatedVendorFile {
		err = ctx.WriteVendorFile()
		if err != nil {
			return err
		}
	}

	// Return network errors here.
	if len(rem) > 0 {
		return rem
	}

	return nil
}
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
}
1365371
func (sd *etcdServiceDiscovery) SyncServers() error {
	keys, err := sd.cli.Get(
		context.TODO(),
		"servers/",
		clientv3.WithPrefix(),
		clientv3.WithKeysOnly(),
	)
	if err != nil {
		return err
	}

	// delete invalid servers (local ones that are not in etcd)
	allIds := make([]string, 0)

	// filter servers I need to grab info
	for _, kv := range keys.Kvs {
		svType, svID, err := parseEtcdKey(string(kv.Key))
		if err != nil {
			logger.Log.Warnf("failed to parse etcd key %s, error: %s", kv.Key, err.Error())
		}
		allIds = append(allIds, svID)
		// TODO is this slow? if so we can paralellize
		if _, ok := sd.serverMapByID.Load(svID); !ok {
			logger.Log.Debugf("loading info from missing server: %s/%s", svType, svID)
			sv, err := sd.getServerFromEtcd(svType, svID)
			if err != nil {
				logger.Log.Errorf("error getting server from etcd: %s, error: %s", svID, err.Error())
				continue
			}
			sd.addServer(sv)
		}
	}
	sd.deleteLocalInvalidServers(allIds)

	sd.printServers()
	sd.lastSyncTime = time.Now()
	return nil
}
536816
func (pb *PingBatcher) Sync() error {
	request := make(chan struct{})
	select {
	case pb.syncChan <- request:
		select {
		case <-request:
			return nil
		case <-pb.tomb.Dying():
			break
		}
	case <-pb.tomb.Dying():
		break
	}
	if err := pb.tomb.Err(); err == nil {
		return errors.Errorf("PingBatcher is stopped")
	} else {
		return err
	}
}
1207067
func (o *object) Sync() error {

	if !o.opened {
		return fmt.Errorf("object isn't opened object:%s", o.name)
	}
	if o.readonly {
		return fmt.Errorf("trying to Sync a readonly object:%s", o.name)
	}

	cachedcopy, err := os.OpenFile(o.cachepath, os.O_RDWR, 0664)
	if err != nil {
		return fmt.Errorf("couldn't open localfile for sync'ing. local=%s err=%v", o.cachepath, err)
	}
	defer cachedcopy.Close()

	// Create an uploader with the session and default options
	uploader := s3manager.NewUploader(o.fs.sess)

	if _, err := cachedcopy.Seek(0, os.SEEK_SET); err != nil {
		return fmt.Errorf("error seeking to start of cachedcopy err=%v", err) //don't retry on local filesystem errors
	}

	// Upload the file to S3.
	_, err = uploader.Upload(&s3manager.UploadInput{
		Bucket: aws.String(o.fs.bucket),
		Key:    aws.String(o.name),
		Body:   cachedcopy,
	})
	if err != nil {
		gou.Warnf("could not upload %v", err)
		return fmt.Errorf("failed to upload file, %v", err)
	}
	return nil
}
640556
func (ipvs *Ipvs) Sync(state state.State) error {
	start := time.Now()
	defer func() {
		log.Debugf("[ipvs] Sync took %v", time.Since(start))
	}()

	ipvs.Lock()
	defer ipvs.Unlock()
	log.Debug("[ipvs] Syncing")

	stateSet := ipvs.getStateServicesSet(state)
	currentSet, err := ipvs.getCurrentServicesSet()
	if err != nil {
		return err
	}

	rulesToAdd := stateSet.Difference(currentSet)
	rulesToRemove := currentSet.Difference(stateSet)

	// Adding services and destinations missing
	for r := range rulesToAdd.Iter() {
		service := r.(types.Service)
		dsts := state.GetDestinations(&service)

		if err := ipvs.addServiceAndDestinations(service, dsts); err != nil {
			return err
		}
		log.Debugf("[ipvs] Added service: %#v with destinations: %#v", service, dsts)
	}

	// Cleaning rules
	for r := range rulesToRemove.Iter() {
		service := r.(types.Service)
		err := ipvs.handler.DelService(ToIpvsService(&service))
		if err != nil {
			return err
		}
		log.Debugf("[ipvs] Removed service: %#v", service)
	}

	// Syncing destination rules
	for _, s := range state.GetServices() {
		if err := ipvs.syncDestinations(state, s); err != nil {
			return err
		}
	}

	return nil
}
240518
func (ec *EstablishingController) sync(key string) error {
	cachedCRD, err := ec.crdLister.Get(key)
	if apierrors.IsNotFound(err) {
		return nil
	}
	if err != nil {
		return err
	}

	if !apiextensions.IsCRDConditionTrue(cachedCRD, apiextensions.NamesAccepted) ||
		apiextensions.IsCRDConditionTrue(cachedCRD, apiextensions.Established) {
		return nil
	}

	crd := cachedCRD.DeepCopy()
	establishedCondition := apiextensions.CustomResourceDefinitionCondition{
		Type:    apiextensions.Established,
		Status:  apiextensions.ConditionTrue,
		Reason:  "InitialNamesAccepted",
		Message: "the initial names have been accepted",
	}
	apiextensions.SetCRDCondition(crd, establishedCondition)

	// Update server with new CRD condition.
	_, err = ec.crdClient.CustomResourceDefinitions().UpdateStatus(crd)
	if apierrors.IsNotFound(err) || apierrors.IsConflict(err) {
		// deleted or changed in the meantime, we'll get called again
		return nil
	}
	if err != nil {
		return err
	}

	return nil
}
1238068
func SyncConfig(addr string, localDir string) (bool, error) {
	return local.SyncConfig(addr, localDir)
}
1134319
func (s *HTTPServer) syncChanges() {
	if err := s.agent.State.SyncChanges(); err != nil {
		s.agent.logger.Printf("[ERR] agent: failed to sync changes: %v", err)
	}
}
1145728
func (logger *Logger) Sync(eventId uint64) {
	logger.mutex.RLock()
	for _, eventHandlerSpec := range logger.eventHandlerMap {
		if atomic.LoadUint64(&eventHandlerSpec.lastSentEventId) < eventId {
			// lastSentEventId wasn't incremented, meaning it was dropped. no point waiting for it
			continue
		}

		// wait for the lastProcessedEventId to become >= eventId
		eventHandlerSpec.lastProcessedEventIdCond.L.Lock()
		for eventHandlerSpec.lastProcessedEventId < eventId {
			eventHandlerSpec.lastProcessedEventIdCond.Wait()
		}
		eventHandlerSpec.lastProcessedEventIdCond.L.Unlock()
	}
	logger.mutex.RUnlock()
}