// Update a Storage network IP range, only allowed when no IPs in this range have been allocated.
333066
func (s *NetworkService) UpdateStorageNetworkIpRange(p *UpdateStorageNetworkIpRangeParams) (*UpdateStorageNetworkIpRangeResponse, error) {
	resp, err := s.cs.newRequest("updateStorageNetworkIpRange", p.toURLValues())
	if err != nil {
		return nil, err
	}

	var r UpdateStorageNetworkIpRangeResponse
	if err := json.Unmarshal(resp, &r); err != nil {
		return nil, err
	}

	// If we have a async client, we need to wait for the async result
	if s.cs.async {
		b, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
		if err != nil {
			if err == AsyncTimeoutErr {
				return &r, err
			}
			return nil, err
		}

		b, err = getRawValue(b)
		if err != nil {
			return nil, err
		}

		if err := json.Unmarshal(b, &r); err != nil {
			return nil, err
		}
	}

	return &r, nil
}
235998
func (c *ingresses) Update(ingress *extensions.Ingress) (result *extensions.Ingress, err error) {
	result = &extensions.Ingress{}
	err = c.client.Put().
		Namespace(c.ns).
		Resource("ingresses").
		Name(ingress.Name).
		Body(ingress).
		Do().
		Into(result)
	return
}
817265
func (aSpace *addrSpace) updatePoolDBOnAdd(k SubnetKey, nw *net.IPNet, ipr *AddressRange, pdf bool) (func() error, error) {
	aSpace.Lock()
	defer aSpace.Unlock()

	// Check if already allocated
	if _, ok := aSpace.subnets[k]; ok {
		if pdf {
			return nil, types.InternalMaskableErrorf("predefined pool %s is already reserved", nw)
		}
		// This means the same pool is already allocated. updatePoolDBOnAdd is called when there
		// is request for a pool/subpool. It should ensure there is no overlap with existing pools
		return nil, ipamapi.ErrPoolOverlap
	}

	// If master pool, check for overlap
	if ipr == nil {
		if aSpace.contains(k.AddressSpace, nw) {
			return nil, ipamapi.ErrPoolOverlap
		}
		// This is a new master pool, add it along with corresponding bitmask
		aSpace.subnets[k] = &PoolData{Pool: nw, RefCount: 1}
		return func() error { return aSpace.alloc.insertBitMask(k, nw) }, nil
	}

	// This is a new non-master pool (subPool)
	p := &PoolData{
		ParentKey: SubnetKey{AddressSpace: k.AddressSpace, Subnet: k.Subnet},
		Pool:      nw,
		Range:     ipr,
		RefCount:  1,
	}
	aSpace.subnets[k] = p

	// Look for parent pool
	pp, ok := aSpace.subnets[p.ParentKey]
	if ok {
		aSpace.incRefCount(pp, 1)
		return func() error { return nil }, nil
	}

	// Parent pool does not exist, add it along with corresponding bitmask
	aSpace.subnets[p.ParentKey] = &PoolData{Pool: nw, RefCount: 1}
	return func() error { return aSpace.alloc.insertBitMask(p.ParentKey, nw) }, nil
}
288817
func (c *Client) UpdateStoragePool(p *UpdateStoragePoolParameter) (*StoragePool, error) {
	obj, err := c.Request("updateStoragePool", convertParamToMap(p))
	if err != nil {
		return nil, err
	}
	return obj.(*StoragePool), err
}
309471
func UpdateIP(conn client.Connection, req IPRequest, mutate func(*IP) bool) error {
	logger := plog.WithFields(log.Fields{
		"hostid":    req.HostID,
		"ipaddress": req.IPAddress,
	})

	basepth := "/"
	if req.PoolID != "" {
		basepth = path.Join("/pools", req.PoolID)
	}

	// Get the current pool ip
	ppth := path.Join(basepth, "/ips", req.IPID())
	pdat := &PoolIP{}
	if err := conn.Get(ppth, pdat); err != nil {
		logger.WithError(err).Debug("Could not look up virtual ip on resource pool")
		// TODO: error
		return err
	}

	// Get the current host ip
	hpth := path.Join(basepth, "/hosts", req.HostID, "ips", req.IPID())
	hdat := &HostIP{}
	if err := conn.Get(hpth, hdat); err != nil {
		logger.WithError(err).Debug("Could not look up virtual ip on host")
		// TODO: error
		return err
	}

	// mutate the state
	pver, hver := pdat.Version(), hdat.Version()
	ip := &IP{
		PoolIP:    *pdat,
		HostIP:    *hdat,
		HostID:    req.HostID,
		IPAddress: req.IPAddress,
	}

	// only commit the transaction if mutate returns true
	if !mutate(ip) {
		logger.Debug("Transaction aborted")
		return nil
	}

	// set the version object on the respective ips
	*pdat = ip.PoolIP
	pdat.SetVersion(pver)
	*hdat = ip.HostIP
	hdat.SetVersion(hver)

	if err := conn.NewTransaction().Set(ppth, pdat).Set(hpth, hdat).Commit(); err != nil {
		logger.WithError(err).Debug("Could not commit transaction")
		// TODO: error
		return err
	}
	logger.Debug("Updated ip")
	return nil
}
61538
func (s *ClusterSecurityGroup) SetIPRanges(v []*IPRange) *ClusterSecurityGroup {
	s.IPRanges = v
	return s
}
821307
func (a *IPRangeAllocator) Allocate() net.IP {
	a.mutex.Lock()
	defer a.mutex.Unlock()

	// ensure we have some IPs first
	if a.remaining <= 0 {
		return nil
	}

	// get a random number within the size to start with
	idx := rand.Int63n(a.size)

	// find the next available index after the random number that is available
	idx = a.findNextAvailbleIndex(idx)

	// if idx is now -1, then it couldn't find one, which is very unlikely,
	// however if that is, treat it as no more remaining and ensure remaining is
	// now 0
	if idx == -1 {
		a.remaining = 0
		return nil
	}

	// reserve the idx, get the IP bytes
	a.reserved[idx] = true
	a.remaining--
	newBig := big.NewInt(0).Add(a.startBig, big.NewInt(idx))

	return a.bigIntToIP(newBig)
}
103289
func (s *XDSServer) UpdateNetworkPolicy(ep logger.EndpointUpdater, policy *policy.L4Policy,
	ingressPolicyEnforced, egressPolicyEnforced bool, labelsMap,
	deniedIngressIdentities, deniedEgressIdentities cache.IdentityCache, wg *completion.WaitGroup) (error, func() error) {

	s.mutex.Lock()
	defer s.mutex.Unlock()

	// First, validate all policies
	ips := []string{
		ep.GetIPv6Address(),
		ep.GetIPv4Address(),
	}
	var policies []*cilium.NetworkPolicy
	for _, ip := range ips {
		if ip == "" {
			continue
		}
		networkPolicy := getNetworkPolicy(ip, ep.GetIdentity(), ep.ConntrackName(), policy, ingressPolicyEnforced, egressPolicyEnforced,
			labelsMap, deniedIngressIdentities, deniedEgressIdentities)
		err := networkPolicy.Validate()
		if err != nil {
			return fmt.Errorf("error validating generated NetworkPolicy for %s: %s", ip, err), nil
		}
		policies = append(policies, networkPolicy)
	}

	if ep.HasSidecarProxy() { // Use sidecar proxy.
		// If there are no L7 rules, we expect Envoy to NOT be configured with
		// an L7 filter, in which case we'd never receive an ACK for the policy,
		// and we'd wait forever.
		// TODO: Remove this when we implement and inject an Envoy network filter
		// into every Envoy listener to filter at L3/L4.
		var hasL7Rules bool
	Policies:
		for _, p := range policies {
			for _, pnp := range p.IngressPerPortPolicies {
				for _, r := range pnp.Rules {
					if r.L7 != nil {
						hasL7Rules = true
						break Policies
					}
				}
			}
			for _, pnp := range p.EgressPerPortPolicies {
				for _, r := range pnp.Rules {
					if r.L7 != nil {
						hasL7Rules = true
						break Policies
					}
				}
			}
		}
		if !hasL7Rules {
			wg = nil
		}
	} else { // Use node proxy.
		// If there are no listeners configured, the local node's Envoy proxy won't
		// query for network policies and therefore will never ACK them, and we'd
		// wait forever.
		if len(s.listeners) == 0 {
			wg = nil
		}
	}

	// When successful, push them into the cache.
	revertFuncs := make([]xds.AckingResourceMutatorRevertFunc, 0, len(policies))
	revertUpdatedNetworkPolicyEndpoints := make(map[string]logger.EndpointUpdater, len(policies))
	for _, p := range policies {
		var callback func(error)
		if policy != nil {
			policyRevision := policy.Revision
			callback = func(err error) {
				if err == nil {
					go ep.OnProxyPolicyUpdate(policyRevision)
				}
			}
		}
		var c *completion.Completion
		if wg != nil {
			c = wg.AddCompletionWithCallback(callback)
		}
		nodeIDs := make([]string, 0, 1)
		if ep.HasSidecarProxy() {
			if ep.GetIPv4Address() == "" {
				log.Fatal("Envoy: Sidecar proxy has no IPv4 address")
			}
			nodeIDs = append(nodeIDs, ep.GetIPv4Address())
		} else {
			nodeIDs = append(nodeIDs, "127.0.0.1")
		}
		revertFuncs = append(revertFuncs, s.NetworkPolicyMutator.Upsert(NetworkPolicyTypeURL, p.Name, p, nodeIDs, c))
		revertUpdatedNetworkPolicyEndpoints[p.Name] = s.networkPolicyEndpoints[p.Name]
		s.networkPolicyEndpoints[p.Name] = ep
	}

	return nil, func() error {
		log.Debug("Reverting xDS network policy update")

		s.mutex.Lock()
		defer s.mutex.Unlock()

		for name, ep := range revertUpdatedNetworkPolicyEndpoints {
			if ep == nil {
				delete(s.networkPolicyEndpoints, name)
			} else {
				s.networkPolicyEndpoints[name] = ep
			}
		}

		// Don't wait for an ACK for the reverted xDS updates.
		// This is best-effort.
		for _, revertFunc := range revertFuncs {
			revertFunc(completion.NewCompletion(nil, nil))
		}

		log.Debug("Finished reverting xDS network policy update")

		return nil
	}
}
89216
func NetworkRange(network *net.IPNet) (net.IP, net.IP) {
	var (
		netIP   = network.IP.To4()
		firstIP = netIP.Mask(network.Mask)
		lastIP  = net.IPv4(0, 0, 0, 0).To4()
	)

	for i := 0; i < len(lastIP); i++ {
		lastIP[i] = netIP[i] | ^network.Mask[i]
	}
	return firstIP, lastIP
}
207072
func (c *Client) UpdateNetwork(p *UpdateNetworkParameter) (*Network, error) {
	obj, err := c.Request("updateNetwork", convertParamToMap(p))
	if err != nil {
		return nil, err
	}
	return obj.(*Network), err
}
827541
func (c *FakeNetworkPolicies) Update(networkPolicy *v1beta1.NetworkPolicy) (result *v1beta1.NetworkPolicy, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewUpdateAction(networkpoliciesResource, c.ns, networkPolicy), &v1beta1.NetworkPolicy{})

	if obj == nil {
		return nil, err
	}
	return obj.(*v1beta1.NetworkPolicy), err
}
1278534
func (gen *RuleGen) UpdateDNSIPs(lookupTime time.Time, updatedDNSIPs map[string]*DNSIPRecords) (affectedRules []string, updatedNames map[string][]net.IP) {
	updatedNames = make(map[string][]net.IP, len(updatedDNSIPs))
	affectedRulesSet := make(map[string]struct{}, len(updatedDNSIPs))

	gen.Lock()
	defer gen.Unlock()

perDNSName:
	for dnsName, lookupIPs := range updatedDNSIPs {
		updated := gen.updateIPsForName(lookupTime, dnsName, lookupIPs.IPs, lookupIPs.TTL)

		// The IPs didn't change. No more to be done for this dnsName
		if !updated {
			continue perDNSName
		}

		// record the IPs that were different
		updatedNames[dnsName] = lookupIPs.IPs

		// accumulate the rules affected by new IPs, that we need to update with
		// CIDR rules
		for _, uuid := range gen.sourceRules.LookupValues(dnsName) {
			affectedRulesSet[uuid] = struct{}{}
		}
	}

	// Convert the set to a list
	for uuid := range affectedRulesSet {
		affectedRules = append(affectedRules, uuid)
	}

	return affectedRules, updatedNames
}
472142
func (client *Client) UpdateRecord(ctx context.Context, name string, rec UpdateDNSRecord) (*DNSRecord, error) {
	body, err := json.Marshal(UpdateDNSRecordResponse{
		Record: rec,
	})
	if err != nil {
		return nil, err
	}

	id := strconv.FormatInt(rec.ID, 10)
	resp, err := client.dnsRequest(ctx, "/v1/domains/"+name+"/records/"+id, nil, string(body), "PUT")
	if err != nil {
		return nil, err
	}

	var r DNSRecordResponse
	if err = json.Unmarshal(resp, &r); err != nil {
		return nil, err
	}

	return &(r.Record), nil
}
1046348
func (s *DBSecurityGroup) SetIPRanges(v []*IPRange) *DBSecurityGroup {
	s.IPRanges = v
	return s
}
850918
func (c *limitRanges) Update(limitRange *api.LimitRange) (result *api.LimitRange, err error) {
	result = &api.LimitRange{}
	if len(limitRange.ResourceVersion) == 0 {
		err = fmt.Errorf("invalid update object, missing resource version: %v", limitRange)
		return
	}
	err = c.r.Put().Namespace(c.ns).Resource("limitRanges").Name(limitRange.Name).Body(limitRange).Do().Into(result)
	return
}
637003
func (r *Range) Release(ip net.IP) error {
	ok, offset := r.contains(ip)
	if !ok {
		return nil
	}

	return r.alloc.Release(offset)
}
69121
func (api *NetworksAPI) UpdateNetwork(id string, networkSpec *NetworkUpdateSpec) (task *Task, err error) {
	body, err := json.Marshal(networkSpec)
	if err != nil {
		return
	}

	res, err := api.client.restClient.Patch(
		api.client.Endpoint+networkUrl+id,
		"application/json",
		bytes.NewReader(body),
		api.client.options.TokenOptions)
	if err != nil {
		return
	}

	defer res.Body.Close()
	task, err = getTask(getError(res))
	return
}