// Sync will synchronize virtual IP assignments for a pool.  It will assign virtual IPs that
// are not assigned to a host.  It will unassign any active assignments if the virtual IP as been
// removed from the pool.
515447
func (s *ZKVirtualIPSynchronizer) Sync(pool p.ResourcePool, assignments map[string]string) error {
	virtualIPMap := s.getVirtualIPMap(pool)

	errorList := SyncError{}
	for _, ip := range s.virtualIPsWithNoAssignment(virtualIPMap, assignments) {
		err := s.handler.Assign(ip.PoolID, ip.IP, ip.Netmask, ip.BindInterface)
		if err != nil {
			errorList = append(errorList, err)
		}
	}

	for _, ip := range s.assignmentsWithNoVirtualIP(virtualIPMap, assignments) {
		err := s.handler.Unassign(pool.ID, ip)
		if err != nil {
			errorList = append(errorList, err)
		}
	}

	if len(errorList) > 0 {
		return errorList
	}

	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
}
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
}
399263
func (l *State) SyncChanges() error {
	l.Lock()
	defer l.Unlock()

	// We will do node-level info syncing at the end, since it will get
	// updated by a service or check sync anyway, given how the register
	// API works.

	// Sync the services
	// (logging happens in the helper methods)
	for id, s := range l.services {
		var err error
		switch {
		case s.Deleted:
			err = l.deleteService(id)
		case !s.InSync:
			err = l.syncService(id)
		default:
			l.logger.Printf("[DEBUG] agent: Service %q in sync", id)
		}
		if err != nil {
			return err
		}
	}

	// Sync the checks
	// (logging happens in the helper methods)
	for id, c := range l.checks {
		var err error
		switch {
		case c.Deleted:
			err = l.deleteCheck(id)
		case !c.InSync:
			if c.DeferCheck != nil {
				c.DeferCheck.Stop()
				c.DeferCheck = nil
			}
			err = l.syncCheck(id)
		default:
			l.logger.Printf("[DEBUG] agent: Check %q in sync", id)
		}
		if err != nil {
			return err
		}
	}

	// Now sync the node level info if we need to, and didn't do any of
	// the other sync operations.
	if l.nodeInfoInSync {
		l.logger.Printf("[DEBUG] agent: Node info in sync")
		return nil
	}
	return l.syncNodeInfo()
}
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
}
371629
func (sm *SyncManager) SyncPeerID() int32 {
	reply := make(chan int32)
	sm.msgChan <- getSyncPeerMsg{reply: reply}
	return <-reply
}
1022075
func (user *User) Sync(params ...interface{}) error {
	insta := user.inst
	body, err := insta.sendSimpleRequest(urlUserInfo, user.ID)
	if err == nil {
		resp := userResp{}
		err = json.Unmarshal(body, &resp)
		if err == nil {
			*user = resp.User
			user.inst = insta
			for _, param := range params {
				switch b := param.(type) {
				case bool:
					if b {
						err = user.FriendShip()
					}
				}
			}
		}
	}
	return err
}
994805
func (b *blockManager) SyncPeer() *ServerPeer {
	b.syncPeerMutex.Lock()
	defer b.syncPeerMutex.Unlock()

	return b.syncPeer
}
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
}
947098
func syncNetwork(d *Daemon) {
	//sync every 5 seconds
	for {
		networks, err := GetNetworks()
		if err != nil {
			log.Println("Error in getNetworks")
			time.Sleep(3 * time.Second)
			continue
		}

		// add interface
		for _, network := range networks {
			_, err := util.GetIfaceAddr(network.Name)

			if err != nil {
				// network not exsit create the interface from net store
				if err = AddInternalPort(ovsClient, bridgeName, network.Name, network.VNI); err != nil {
					log.Println("add internal port err in syncNetwork", network.Name)
					continue
				}
				time.Sleep(1 * time.Second)

				if err = util.SetMtu(network.Name, mtu); err != nil {
					log.Println("set mtu err in syncNetwork", network.Name)
					continue
				}

				_, subnet, _ := net.ParseCIDR(network.Subnet)
				gatewayCIDR := &net.IPNet{net.ParseIP(network.Gateway), subnet.Mask}
				if err = util.SetInterfaceIp(network.Name, gatewayCIDR.String()); err != nil {
					log.Println("set ip err in syncNetwork", network.Name)
					continue
				}

				if err = util.InterfaceUp(network.Name); err != nil {
					log.Println("interface up err in syncNetwork", network.Name)
					continue
				}
				d.Gateways[network.Name] = struct{}{}

				if err = setupIPTables(network.Name, network.Subnet); err != nil {
					log.Println("iptable setup err in syncNetwork", network.Name)
					continue
				}
				log.Println(network.Name + " network created")
			}
		}

		//delete unused interface
		var found bool
		for k, _ := range d.Gateways {
			found = false
			for _, network := range networks {
				if network.Name == k {
					//find network in the datastore
					found = true
					break
				}
			}

			// not found interface named k, delete it
			if !found {
				deletePort(ovsClient, bridgeName, k)
				delete(d.Gateways, k)
				log.Println("delete unused interface", k)
			}
		}
		time.Sleep(5 * time.Second)
	}
}
604264
func SyncHosts(conn client.Connection, hosts []host.Host) error {
	pth := path.Join("/hosts")

	logger := plog.WithField("zkpath", pth)

	// look up children host ids
	ch, err := conn.Children(pth)
	if err != nil && err != client.ErrNoNode {
		logger.WithError(err).Debug("Could not look up hosts")
		return err
	}

	// store the host ids in a hash map
	chmap := make(map[string]struct{})
	for _, hostID := range ch {
		chmap[hostID] = struct{}{}
	}

	// set the hosts
	for _, h := range hosts {
		if _, ok := chmap[h.ID]; ok {
			if err := UpdateHost(conn, h); err != nil {
				return err
			}
			delete(chmap, h.ID)
		} else {
			if err := AddHost(conn, h); err != nil {
				return err
			}
		}
	}

	// remove any leftovers
	for hostID := range chmap {
		if err := removeHost(conn, "", hostID); err != nil {
			logger.WithField("hostid", hostID).WithError(err).Debug("Could not delete host entry from zookeeper")
			return err
		}
	}
	return nil
}
745085
func (i *VCSInstaller) sync(repo vcs.Repo) error {

	if _, err := os.Stat(repo.LocalPath()); os.IsNotExist(err) {
		return repo.Get()
	}
	return repo.Update()
}
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
}
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
}
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
}
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)
}
1102843
func (m *Manager) syncState() {
	m.mu.Lock()
	defer m.mu.Unlock()

	// Traverse the local state and ensure all proxy services are registered
	services := m.State.Services()
	for svcID, svc := range services {
		if svc.Kind != structs.ServiceKindConnectProxy {
			continue
		}
		// TODO(banks): need to work out when to default some stuff. For example
		// Proxy.LocalServicePort is practically necessary for any sidecar and can
		// default to the port of the sidecar service, but only if it's already
		// registered and once we get past here, we don't have enough context to
		// know that so we'd need to set it here if not during registration of the
		// proxy service. Sidecar Service and managed proxies in the interim can
		// do that, but we should validate more generally that that is always
		// true.
		err := m.ensureProxyServiceLocked(svc, m.State.ServiceToken(svcID))
		if err != nil {
			m.Logger.Printf("[ERR] failed to watch proxy service %s: %s", svc.ID,
				err)
		}
	}

	// Now see if any proxies were removed
	for proxyID := range m.proxies {
		if _, ok := services[proxyID]; !ok {
			// Remove them
			m.removeProxyServiceLocked(proxyID)
		}
	}
}