// SyncStatusError makes a best effort attempt to replace the GroupResource
// info in err with the data from the request info of ctx.
971061
func SyncStatusError(ctx context.Context, err error) error {
	if err == nil {
		return nil
	}
	statusErr, isStatusErr := err.(apierrors.APIStatus)
	if !isStatusErr {
		return err
	}
	info, hasInfo := apirequest.RequestInfoFrom(ctx)
	if !hasInfo {
		return err
	}
	status := statusErr.Status()
	if status.Details == nil {
		return err
	}
	oldGR := (&schema.GroupResource{Group: status.Details.Group, Resource: status.Details.Kind}).String()
	newGR := (&schema.GroupResource{Group: info.APIGroup, Resource: info.Resource}).String()
	status.Message = strings.Replace(status.Message, oldGR, newGR, 1)
	status.Details.Group = info.APIGroup
	status.Details.Kind = info.Resource // Yes we set Kind field to resource.
	return &apierrors.StatusError{ErrStatus: status}
}
854923
func (rq *ResourceQuotaController) syncResourceQuota(resourceQuota *v1.ResourceQuota) (err error) {
	// quota is dirty if any part of spec hard limits differs from the status hard limits
	statusLimitsDirty := !apiequality.Semantic.DeepEqual(resourceQuota.Spec.Hard, resourceQuota.Status.Hard)

	// dirty tracks if the usage status differs from the previous sync,
	// if so, we send a new usage with latest status
	// if this is our first sync, it will be dirty by default, since we need track usage
	dirty := statusLimitsDirty || resourceQuota.Status.Hard == nil || resourceQuota.Status.Used == nil

	used := v1.ResourceList{}
	if resourceQuota.Status.Used != nil {
		used = quota.Add(v1.ResourceList{}, resourceQuota.Status.Used)
	}
	hardLimits := quota.Add(v1.ResourceList{}, resourceQuota.Spec.Hard)

	errors := []error{}

	newUsage, err := quota.CalculateUsage(resourceQuota.Namespace, resourceQuota.Spec.Scopes, hardLimits, rq.registry, resourceQuota.Spec.ScopeSelector)
	if err != nil {
		// if err is non-nil, remember it to return, but continue updating status with any resources in newUsage
		errors = append(errors, err)
	}
	for key, value := range newUsage {
		used[key] = value
	}

	// ensure set of used values match those that have hard constraints
	hardResources := quota.ResourceNames(hardLimits)
	used = quota.Mask(used, hardResources)

	// Create a usage object that is based on the quota resource version that will handle updates
	// by default, we preserve the past usage observation, and set hard to the current spec
	usage := resourceQuota.DeepCopy()
	usage.Status = v1.ResourceQuotaStatus{
		Hard: hardLimits,
		Used: used,
	}

	dirty = dirty || !quota.Equals(usage.Status.Used, resourceQuota.Status.Used)

	// there was a change observed by this controller that requires we update quota
	if dirty {
		_, err = rq.rqClient.ResourceQuotas(usage.Namespace).UpdateStatus(usage)
		if err != nil {
			errors = append(errors, err)
		}
	}
	return utilerrors.NewAggregate(errors)
}
794613
func (c *InstanceCache) syncState(ctx context.Context, state *messages.InstanceCache, now time.Time) error {
	root, err := os.Open(c.fs.Root())
	switch {

	case os.IsNotExist(err):
		state.Entries = nil

	case err != nil:
		return err

	default:
		instanceIDs, err := root.Readdirnames(0)
		if err != nil {
			return err
		}
		existingIDs := stringset.New(len(instanceIDs))
		for _, id := range instanceIDs {
			if common.ValidateInstanceID(id, common.AnyHash) != nil {
				continue
			}
			existingIDs.Add(id)

			if _, ok := state.Entries[id]; !ok {
				if state.Entries == nil {
					state.Entries = map[string]*messages.InstanceCache_Entry{}
				}
				state.Entries[id] = &messages.InstanceCache_Entry{
					LastAccess: google.NewTimestamp(now),
				}
			}
		}

		for id := range state.Entries {
			if !existingIDs.Has(id) {
				delete(state.Entries, id)
			}
		}
	}

	state.LastSynced = google.NewTimestamp(now)
	logging.Infof(ctx, "cipd: synchronized instance cache with instance files")
	return nil
}
1222099
func (chs *ChartChangeSync) SyncMirrors() {
	chs.logger.Log("info", "starting mirror sync")
	for _, err := range chs.mirrors.RefreshAll(chs.config.GitTimeout) {
		chs.logger.Log("error", fmt.Sprintf("failure while syncing mirror: %s", err))
	}
	chs.logger.Log("info", "finished syncing mirrors")
}
703497
func (e BadSessionError) ToStatus() (s keybase1.Status) {
	s.Code = SCBadSession
	s.Name = "BAD_SESSION"
	s.Desc = e.Desc
	return s
}
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
}
1312336
func (t *ThirdPartyController) SyncResources() error {
	list, err := t.thirdPartyResourceRegistry.List(api.NewDefaultContext(), nil)
	if err != nil {
		return err
	}
	return t.syncResourceList(list)
}
1087178
func (rq *ResourceQuotaController) resyncMonitors(resources map[schema.GroupVersionResource]struct{}) error {
	if rq.quotaMonitor == nil {
		return nil
	}

	if err := rq.quotaMonitor.SyncMonitors(resources); err != nil {
		return err
	}
	rq.quotaMonitor.StartMonitors()
	return nil
}
516460
func (e ServerErrorBadRequest) ToStatus() (s keybase1.Status) {
	s.Code = StatusCodeServerErrorBadRequest
	s.Name = "BAD_REQUEST"
	s.Desc = e.Reason
	return
}
39859
func SyncResourcePools(conn client.Connection, pools []pool.ResourcePool) error {
	pth := path.Join("/pools")

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

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

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

	// set the resource pools
	for _, p := range pools {
		if err := UpdateResourcePool(conn, p); err != nil {
			return err
		}

		// delete matching records
		if _, ok := chmap[p.ID]; ok {
			delete(chmap, p.ID)
		}
	}

	// remove any leftovers
	for poolid := range chmap {
		if err := RemoveResourcePool(conn, poolid); err != nil {
			return err
		}
	}
	return nil
}
1369776
func (e ServerErrorConflictRevision) ToStatus() (s keybase1.Status) {
	s.Code = StatusCodeServerErrorConflictRevision
	s.Name = "CONFLICT_REVISION"
	s.Desc = e.Error()
	return
}
14722
func ValidateStatefulSetStatus(status *apps.StatefulSetStatus, fieldPath *field.Path) field.ErrorList {
	allErrs := field.ErrorList{}

	allErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(status.Replicas), fieldPath.Child("replicas"))...)
	allErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(status.ReadyReplicas), fieldPath.Child("readyReplicas"))...)
	allErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(status.CurrentReplicas), fieldPath.Child("currentReplicas"))...)
	allErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(status.UpdatedReplicas), fieldPath.Child("updatedReplicas"))...)
	if status.ObservedGeneration != nil {
		allErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(*status.ObservedGeneration), fieldPath.Child("observedGeneration"))...)
	}
	if status.CollisionCount != nil {
		allErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(*status.CollisionCount), fieldPath.Child("collisionCount"))...)
	}

	msg := "cannot be greater than status.replicas"
	if status.ReadyReplicas > status.Replicas {
		allErrs = append(allErrs, field.Invalid(fieldPath.Child("readyReplicas"), status.ReadyReplicas, msg))
	}
	if status.CurrentReplicas > status.Replicas {
		allErrs = append(allErrs, field.Invalid(fieldPath.Child("currentReplicas"), status.CurrentReplicas, msg))
	}
	if status.UpdatedReplicas > status.Replicas {
		allErrs = append(allErrs, field.Invalid(fieldPath.Child("updatedReplicas"), status.UpdatedReplicas, msg))
	}

	return allErrs
}
1297891
func GetWithStatusError(address string) (resp *http.Response, err error) {
	if resp, err = http.Get(address); err != nil {
		if uerr, ok := err.(*url.Error); ok {
			if derr, ok := uerr.Err.(*net.DNSError); ok && !derr.IsTimeout {
				return nil, errdefs.NotFound(err)
			}
		}
		return nil, errdefs.System(err)
	}
	if resp.StatusCode < 400 {
		return resp, nil
	}
	msg := fmt.Sprintf("failed to GET %s with status %s", address, resp.Status)
	body, err := ioutil.ReadAll(resp.Body)
	resp.Body.Close()
	if err != nil {
		return nil, errdefs.System(errors.New(msg + ": error reading body"))
	}

	msg += ": " + string(bytes.TrimSpace(body))
	switch resp.StatusCode {
	case http.StatusNotFound:
		return nil, errdefs.NotFound(errors.New(msg))
	case http.StatusBadRequest:
		return nil, errdefs.InvalidParameter(errors.New(msg))
	case http.StatusUnauthorized:
		return nil, errdefs.Unauthorized(errors.New(msg))
	case http.StatusForbidden:
		return nil, errdefs.Forbidden(errors.New(msg))
	}
	return nil, errdefs.Unknown(errors.New(msg))
}
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
}
517637
func (sc *syncContext) updateHookStatus(hookStatus appv1.ResourceResult) bool {
	sc.lock.Lock()
	defer sc.lock.Unlock()
	for i, prev := range sc.syncRes.Resources {
		if !prev.IsHook() {
			continue
		}
		if hookEqual(prev, hookStatus.Group, hookStatus.Kind, hookStatus.Namespace, hookStatus.Name, hookStatus.HookType) {
			if reflect.DeepEqual(prev, hookStatus) {
				return false
			}
			if prev.HookPhase != hookStatus.HookPhase {
				sc.log.Infof("Hook %s %s/%s hookPhase: %s -> %s", hookStatus.HookType, prev.Kind, prev.Name, prev.HookPhase, hookStatus.HookPhase)
			}
			if prev.Status != hookStatus.Status {
				sc.log.Infof("Hook %s %s/%s status: %s -> %s", hookStatus.HookType, prev.Kind, prev.Name, prev.Status, hookStatus.Status)
			}
			if prev.Message != hookStatus.Message {
				sc.log.Infof("Hook %s %s/%s message: '%s' -> '%s'", hookStatus.HookType, prev.Kind, prev.Name, prev.Message, hookStatus.Message)
			}
			sc.syncRes.Resources[i] = &hookStatus
			return true
		}
	}
	sc.syncRes.Resources = append(sc.syncRes.Resources, &hookStatus)
	sc.log.Infof("Set new hook %s %s/%s. phase: %s, message: %s", hookStatus.HookType, hookStatus.Kind, hookStatus.Name, hookStatus.HookPhase, hookStatus.Message)
	return true
}
1122111
func (e ServerErrorConflictPrevRoot) ToStatus() (s keybase1.Status) {
	s.Code = StatusCodeServerErrorConflictPrevRoot
	s.Name = "CONFLICT_PREV_ROOT"
	s.Desc = e.Error()
	return
}
1218772
func (msdw *MultiSplitDiffWorker) synchronizeSrcAndDestTxState(ctx context.Context) error {
	msdw.SetState(WorkerStateSyncReplication)
	var err error

	// 1. Find all the tablets we will need to work with
	masterInfos := make([]*topo.TabletInfo, len(msdw.destinationAliases))
	for i, shardInfo := range msdw.destinationShards {
		masterInfos[i], err = msdw.getMasterTabletInfoForShard(ctx, shardInfo)
		if err != nil {
			return err
		}
	}

	shortCtx, cancel := context.WithTimeout(ctx, *remoteActionsTimeout)
	source, _ := msdw.wr.TopoServer().GetTablet(shortCtx, msdw.sourceAlias)
	cancel()

	var sourcePosition string

	// 2. Stop replication on destination
	destVreplicationPos, err := msdw.stopVreplicationOnAll(ctx, masterInfos)
	if err != nil {
		return err
	}

	// 3. Pause updates on the source and create consistent snapshot connections
	var scanners []TableScanner
	if msdw.useConsistentSnapshot {
		sourcePosition, scanners, err = msdw.useTransactionScanners(ctx, source)
	} else {
		sourcePosition, scanners, err = msdw.useNonTransactionalScanners(ctx, source, destVreplicationPos)
	}
	if err != nil {
		return err
	}

	msdw.scanners = make([]Scanners, msdw.parallelDiffsCount)
	for i := 0; i < msdw.parallelDiffsCount; i++ {
		// We'll create one of these Scanners struct per thread we want to run in parallel
		scanner := scanners[i]
		i2 := Scanners{
			sourceScanner:      scanner,
			destinationScanner: make([]TableScanner, len(msdw.destinationShards)),
		}
		msdw.scanners[i] = i2
	}

	// 4. Make sure all replicas have caught up with the master
	for i, shardInfo := range msdw.destinationShards {
		masterInfo := masterInfos[i]
		destinationAlias := msdw.destinationAliases[i]

		destinationPosition, err := msdw.stopVreplicationAt(ctx, shardInfo, sourcePosition, masterInfo)
		if err != nil {
			return err
		}

		shortCtx, cancel := context.WithTimeout(ctx, *remoteActionsTimeout)
		destTabletInfo, err := msdw.wr.TopoServer().GetTablet(shortCtx, destinationAlias)
		cancel()
		if err != nil {
			return vterrors.Wrapf(err, "waitForDestinationTabletToReach: cannot get Tablet record for master %v", msdw.shardInfo.MasterAlias)
		}

		queryService, _ := tabletconn.GetDialer()(source.Tablet, true)
		var destScanners []TableScanner

		if msdw.useConsistentSnapshot {
			// loop to wait for the destinationAlias tablet in shardInfo to have reached destinationPosition
			err = msdw.waitForDestinationTabletToReach(ctx, destTabletInfo.Tablet, destinationPosition)
			if err != nil {
				return err
			}

			destScanners, _, err = CreateConsistentTableScanners(ctx, destTabletInfo, msdw.wr, msdw.cleaner, msdw.parallelDiffsCount)
			if err != nil {
				return err
			}
		} else {
			err = msdw.stopReplicationAt(ctx, destinationAlias, destinationPosition)
			if err != nil {
				return vterrors.Wrapf(err, "failed to stop replication on %v at position %v", destinationAlias, destinationPosition)
			}
			destScanners, err = msdw.createNonTransactionalTableScanners(ctx, queryService, destTabletInfo)
			if err != nil {
				return vterrors.Wrapf(err, "failed to stop create table scanners for %v using %v", destTabletInfo, queryService)
			}
		}

		// 5. Spread out destination scanners between the goroutines
		for j := 0; j < msdw.parallelDiffsCount; j++ {
			msdw.scanners[j].destinationScanner[i] = destScanners[j]
		}

		err = msdw.startVreplication(ctx, shardInfo, masterInfo)
		if err != nil {
			return vterrors.Wrapf(err, "failed to restart vreplication for shard %v on tablet %v", shardInfo, masterInfo)
		}

	}
	return nil
}