// UpdateSrvKeyspace saves a new SrvKeyspace. It is a blind write.
487972
func (ts *Server) UpdateSrvKeyspace(ctx context.Context, cell, keyspace string, srvKeyspace *topodatapb.SrvKeyspace) error {
	conn, err := ts.ConnForCell(ctx, cell)
	if err != nil {
		return err
	}

	nodePath := srvKeyspaceFileName(keyspace)
	data, err := proto.Marshal(srvKeyspace)
	if err != nil {
		return err
	}
	_, err = conn.Update(ctx, nodePath, data, nil)
	return err
}
184025
func (ts *Server) GetSrvKeyspaceAllCells(ctx context.Context, keyspace string) ([]*topodatapb.SrvKeyspace, error) {
	cells, err := ts.GetCellInfoNames(ctx)
	if err != nil {
		return nil, err
	}

	srvKeyspaces := make([]*topodatapb.SrvKeyspace, len(cells))
	for _, cell := range cells {
		srvKeyspace, err := ts.GetSrvKeyspace(ctx, cell, keyspace)
		switch {
		case err == nil:
			srvKeyspaces = append(srvKeyspaces, srvKeyspace)
		case IsErrType(err, NoNode):
			// NOOP
		default:
			return srvKeyspaces, err
		}
	}
	return srvKeyspaces, nil
}
1159769
func (client *Client) UpdateSpaceManagerByUsername(spaceGUID string, username string) (Warnings, error) {
	requestBody := updateRoleRequestBody{
		Username: username,
	}

	bodyBytes, err := json.Marshal(requestBody)
	if err != nil {
		return Warnings{}, err
	}
	request, err := client.newHTTPRequest(requestOptions{
		RequestName: internal.PutSpaceManagerByUsernameRequest,
		URIParams:   map[string]string{"space_guid": spaceGUID},
		Body:        bytes.NewReader(bodyBytes),
	})

	if err != nil {
		return nil, err
	}

	response := cloudcontroller.Response{}

	err = client.connection.Make(request, &response)

	return response.Warnings, err
}
538691
func (d *driver) updateKeys(newKey, primary, pruneKey *key) error {
	logrus.Debugf("Updating Keys. New: %v, Primary: %v, Pruned: %v", newKey, primary, pruneKey)

	logrus.Debugf("Current: %v", d.keys)

	var (
		newIdx = -1
		priIdx = -1
		delIdx = -1
		lIP    = net.ParseIP(d.bindAddress)
		aIP    = net.ParseIP(d.advertiseAddress)
	)

	d.Lock()
	defer d.Unlock()

	// add new
	if newKey != nil {
		d.keys = append(d.keys, newKey)
		newIdx += len(d.keys)
	}
	for i, k := range d.keys {
		if primary != nil && k.tag == primary.tag {
			priIdx = i
		}
		if pruneKey != nil && k.tag == pruneKey.tag {
			delIdx = i
		}
	}

	if (newKey != nil && newIdx == -1) ||
		(primary != nil && priIdx == -1) ||
		(pruneKey != nil && delIdx == -1) {
		return types.BadRequestErrorf("cannot find proper key indices while processing key update:"+
			"(newIdx,priIdx,delIdx):(%d, %d, %d)", newIdx, priIdx, delIdx)
	}

	if priIdx != -1 && priIdx == delIdx {
		return types.BadRequestErrorf("attempting to both make a key (index %d) primary and delete it", priIdx)
	}

	d.secMapWalk(func(rIPs string, spis []*spi) ([]*spi, bool) {
		rIP := net.ParseIP(rIPs)
		return updateNodeKey(lIP, aIP, rIP, spis, d.keys, newIdx, priIdx, delIdx), false
	})

	// swap primary
	if priIdx != -1 {
		d.keys[0], d.keys[priIdx] = d.keys[priIdx], d.keys[0]
	}
	// prune
	if delIdx != -1 {
		if delIdx == 0 {
			delIdx = priIdx
		}
		d.keys = append(d.keys[:delIdx], d.keys[delIdx+1:]...)
	}

	logrus.Debugf("Updated: %v", d.keys)

	return nil
}
829747
func (vc *vcursorImpl) DefaultKeyspace() (*vindexes.Keyspace, error) {
	if vc.keyspace == "" {
		return nil, errNoKeyspace
	}
	ks, ok := vc.executor.VSchema().Keyspaces[vc.keyspace]
	if !ok {
		return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "keyspace %s not found in vschema", vc.keyspace)
	}
	return ks.Keyspace, nil
}
28925
func (d *Databases) UpdateRP(ctx context.Context, rpX string, rpY string, rp *chronograf.RetentionPolicy) (*chronograf.RetentionPolicy, error) {
	return d.UpdateRPF(ctx, rpX, rpY, rp)
}
425844
func updateWrrSeq(fe ServiceKey, weights []uint16) error {
	sum := uint16(0)
	for _, v := range weights {
		sum += v
	}
	if sum == 0 {
		return nil
	}
	svcRRSeq, err := generateWrrSeq(weights)
	if err != nil {
		return fmt.Errorf("unable to generate weighted round robin seq for %s with value %+v: %s", fe.String(), weights, err)
	}
	return updateServiceWeights(fe, svcRRSeq)
}
509354
func (conn *FakeVTGateConn) UpdateStream(ctx context.Context, keyspace string, shard string, keyRange *topodatapb.KeyRange, tabletType topodatapb.TabletType, timestamp int64, event *querypb.EventToken) (vtgateconn.UpdateStreamReader, error) {
	return nil, fmt.Errorf("NYI")
}
598053
func (s *storeImpl) updateServiceFromVolatileService(svc *Service, cacheEntry volatileService) {
	svc.DesiredState = cacheEntry.DesiredState
	svc.CurrentState = cacheEntry.CurrentState
}
956779
func (resizeMap *volumeResizeMap) UpdatePVSize(pvcr *PVCWithResizeRequest, newSize resource.Quantity) error {
	oldPv := pvcr.PersistentVolume
	pvClone := oldPv.DeepCopy()

	oldData, err := json.Marshal(pvClone)

	if err != nil {
		return fmt.Errorf("Unexpected error marshaling old PV %q with error : %v", pvClone.Name, err)
	}

	pvClone.Spec.Capacity[v1.ResourceStorage] = newSize

	newData, err := json.Marshal(pvClone)

	if err != nil {
		return fmt.Errorf("Unexpected error marshaling new PV %q with error : %v", pvClone.Name, err)
	}

	patchBytes, err := strategicpatch.CreateTwoWayMergePatch(oldData, newData, pvClone)

	if err != nil {
		return fmt.Errorf("Error Creating two way merge patch for PV %q with error : %v", pvClone.Name, err)
	}

	_, updateErr := resizeMap.kubeClient.CoreV1().PersistentVolumes().Patch(pvClone.Name, commontypes.StrategicMergePatchType, patchBytes)

	if updateErr != nil {
		klog.V(4).Infof("Error updating pv %q with error : %v", pvClone.Name, updateErr)
		return updateErr
	}
	return nil
}
889267
func (c *Core) RekeyUpdate(ctx context.Context, key []byte, nonce string, recovery bool) (*RekeyResult, logical.HTTPCodedError) {
	if recovery {
		return c.RecoveryRekeyUpdate(ctx, key, nonce)
	}
	return c.BarrierRekeyUpdate(ctx, key, nonce)
}
868818
func (c *FakeEvents) UpdateWithEventNamespace(event *v1.Event) (*v1.Event, error) {
	action := core.NewRootUpdateAction(eventsResource, event)
	if c.ns != "" {
		action = core.NewUpdateAction(eventsResource, c.ns, event)
	}
	obj, err := c.Fake.Invokes(action, event)
	if obj == nil {
		return nil, err
	}

	return obj.(*v1.Event), err
}
33185
func (ts *Server) AddSrvKeyspacePartitions(ctx context.Context, keyspace string, shards []*ShardInfo, tabletType topodatapb.TabletType, cells []string) (err error) {
	if err = CheckKeyspaceLocked(ctx, keyspace); err != nil {
		return err
	}

	// The caller intents to update all cells in this case
	if len(cells) == 0 {
		cells, err = ts.GetCellInfoNames(ctx)
		if err != nil {
			return err
		}
	}

	wg := sync.WaitGroup{}
	rec := concurrency.AllErrorRecorder{}
	for _, cell := range cells {
		wg.Add(1)
		go func(cell string) {
			defer wg.Done()
			srvKeyspace, err := ts.GetSrvKeyspace(ctx, cell, keyspace)
			switch {
			case err == nil:
				partitionFound := false

				for _, partition := range srvKeyspace.GetPartitions() {
					if partition.GetServedType() != tabletType {
						continue
					}
					partitionFound = true

					for _, si := range shards {
						found := false
						for _, shardReference := range partition.GetShardReferences() {
							if key.KeyRangeEqual(shardReference.GetKeyRange(), si.GetKeyRange()) {
								found = true
							}
						}

						if !found {
							shardReference := &topodatapb.ShardReference{
								Name:     si.ShardName(),
								KeyRange: si.KeyRange,
							}
							partition.ShardReferences = append(partition.GetShardReferences(), shardReference)
						}
					}
				}

				// Partition does not exist at all, we need to create it
				if !partitionFound {

					partition := &topodatapb.SrvKeyspace_KeyspacePartition{
						ServedType: tabletType,
					}

					shardReferences := make([]*topodatapb.ShardReference, 0)
					for _, si := range shards {
						shardReference := &topodatapb.ShardReference{
							Name:     si.ShardName(),
							KeyRange: si.KeyRange,
						}
						shardReferences = append(shardReferences, shardReference)
					}

					partition.ShardReferences = shardReferences

					srvKeyspace.Partitions = append(srvKeyspace.GetPartitions(), partition)
				}

				err = ts.UpdateSrvKeyspace(ctx, cell, keyspace, srvKeyspace)
				if err != nil {
					rec.RecordError(err)
					return
				}
			case IsErrType(err, NoNode):
				// NOOP
			default:
				rec.RecordError(err)
				return
			}
		}(cell)
	}
	wg.Wait()
	if rec.HasErrors() {
		return NewError(PartialResult, rec.Error().Error())
	}
	return nil
}
1350929
func (server *ResilientServer) GetSrvKeyspaceNames(ctx context.Context, cell string) ([]string, error) {
	server.counts.Add(queryCategory, 1)

	// find the entry in the cache, add it if not there
	key := cell
	server.mutex.Lock()
	entry, ok := server.srvKeyspaceNamesCache[key]
	if !ok {
		entry = &srvKeyspaceNamesEntry{
			cell: cell,
		}
		server.srvKeyspaceNamesCache[key] = entry
	}
	server.mutex.Unlock()

	// Lock the entry, and do everything holding the lock except
	// querying the underlying topo server.
	//
	// This means that even if the topo server is very slow, two concurrent
	// requests will only issue one underlying query.
	entry.mutex.Lock()
	defer entry.mutex.Unlock()

	cacheValid := entry.value != nil && time.Since(entry.insertionTime) < server.cacheTTL
	shouldRefresh := time.Since(entry.lastQueryTime) > server.cacheRefresh

	// If it is not time to check again, then return either the cached
	// value or the cached error but don't ask consul again.
	if !shouldRefresh {
		if cacheValid {
			return entry.value, nil
		}
		return nil, entry.lastError
	}

	// Refresh the state in a background goroutine if no refresh is already
	// in progress none is already running. This way queries are not blocked
	// while the cache is still valid but past the refresh time, and avoids
	// calling out to the topo service while the lock is held.
	if entry.refreshingChan == nil {
		entry.refreshingChan = make(chan struct{})
		entry.lastQueryTime = time.Now()
		go func() {
			result, err := server.topoServer.GetSrvKeyspaceNames(ctx, cell)

			entry.mutex.Lock()
			defer func() {
				close(entry.refreshingChan)
				entry.refreshingChan = nil
				entry.mutex.Unlock()
			}()

			if err == nil {
				// save the value we got and the current time in the cache
				entry.insertionTime = time.Now()
				entry.value = result
			} else {
				server.counts.Add(errorCategory, 1)
				if entry.insertionTime.IsZero() {
					log.Errorf("GetSrvKeyspaceNames(%v, %v) failed: %v (no cached value, caching and returning error)", ctx, cell, err)

				} else if entry.value != nil && time.Since(entry.insertionTime) < server.cacheTTL {
					server.counts.Add(cachedCategory, 1)
					log.Warningf("GetSrvKeyspaceNames(%v, %v) failed: %v (keeping cached value: %v)", ctx, cell, err, entry.value)
				} else {
					log.Errorf("GetSrvKeyspaceNames(%v, %v) failed: %v (cached value expired)", ctx, cell, err)
					entry.insertionTime = time.Time{}
					entry.value = nil
				}
			}

			entry.lastError = err
			entry.lastErrorCtx = ctx
		}()
	}

	// If the cached entry is still valid then use it, otherwise wait
	// for the refresh attempt to complete to get a more up to date
	// response.
	//
	// In the event that the topo service is slow or unresponsive either
	// on the initial fetch or if the cache TTL expires, then several
	// requests could be blocked on refreshingCond waiting for the response
	// to come back.
	if cacheValid {
		return entry.value, nil
	}

	refreshingChan := entry.refreshingChan
	entry.mutex.Unlock()
	select {
	case <-refreshingChan:
	case <-ctx.Done():
		entry.mutex.Lock()
		return nil, fmt.Errorf("timed out waiting for keyspace names")
	}
	entry.mutex.Lock()

	if entry.value != nil {
		return entry.value, nil
	}

	return nil, entry.lastError
}
356822
func (s *RRSetsService) Update(k RRSetKey, val RRSet) (*http.Response, error) {
	var ignored interface{}
	return s.client.put(k.URI(), val, &ignored)
}
678289
func UpdaterServiceStatus(context Context, label string) keybase1.ServiceStatus {
	if label == "" {
		return keybase1.ServiceStatus{Status: keybase1.StatusFromCode(keybase1.StatusCode_SCServiceStatusError, "No service label")}
	}
	serviceStatus := keybase1.ServiceStatus{Label: label}
	updaterService := launchd.NewService(label)
	status, err := updaterService.WaitForStatus(defaultLaunchdWait, 500*time.Millisecond)
	if err != nil {
		serviceStatus.Status = keybase1.StatusFromCode(keybase1.StatusCode_SCServiceStatusError, err.Error())
		return serviceStatus
	}
	if status != nil {
		serviceStatus.Pid = status.Pid()
		serviceStatus.LastExitStatus = status.LastExitStatus()
	}
	if serviceStatus.Pid != "" {
		serviceStatus.InstallStatus = keybase1.InstallStatus_INSTALLED
		serviceStatus.InstallAction = keybase1.InstallAction_NONE
	} else {
		serviceStatus.InstallStatus = keybase1.InstallStatus_NOT_INSTALLED
		serviceStatus.InstallAction = keybase1.InstallAction_INSTALL
	}
	serviceStatus.Status = keybase1.StatusOK("")
	return serviceStatus
}
585565
func (ar *ActionRepository) ApplyKeyspaceAction(ctx context.Context, actionName, keyspace string, r *http.Request) *ActionResult {
	result := &ActionResult{Name: actionName, Parameters: keyspace}

	action, ok := ar.keyspaceActions[actionName]
	if !ok {
		result.error("Unknown keyspace action")
		return result
	}

	ctx, cancel := context.WithTimeout(ctx, *actionTimeout)
	wr := wrangler.New(logutil.NewConsoleLogger(), ar.ts, tmclient.NewTabletManagerClient())
	output, err := action(ctx, wr, keyspace, r)
	cancel()
	if err != nil {
		result.error(err.Error())
		return result
	}
	result.Output = output
	return result
}