// NodeBalancerCreate maps to the 'nodebalancer.create' call.
//
// https://www.linode.com/api/nodebalancer/nodebalancer.create
508417
func (c *Client) NodeBalancerCreate(datacenterID int, label *string,
	throttle *int) (nbID int, err error) {

	args := make(map[string]interface{})
	args["DatacenterID"] = datacenterID
	args["Label"] = label
	args["ClientConnThrottle"] = throttle

	data, err := c.apiCall("nodebalancer.create", args)
	if err != nil {
		return 0, err
	}

	err = unmarshalSingle(data, "NodeBalancerID", &nbID)
	if err != nil {
		return 0, err
	}

	return nbID, nil
}
840579
func (api *API) CreateLoadBalancerPool(pool LoadBalancerPool) (LoadBalancerPool, error) {
	uri := api.userBaseURL("/user") + "/load_balancers/pools"
	res, err := api.makeRequest("POST", uri, pool)
	if err != nil {
		return LoadBalancerPool{}, errors.Wrap(err, errMakeRequestError)
	}
	var r loadBalancerPoolResponse
	if err := json.Unmarshal(res, &r); err != nil {
		return LoadBalancerPool{}, errors.Wrap(err, errUnmarshalError)
	}
	return r.Result, nil
}
260547
func (c *Client) LinodeDiskCreate(linodeID int, label string, dType string,
	size int) (jobID int, diskID int, err error) {

	args := make(map[string]interface{})
	args["LinodeID"] = linodeID
	args["Label"] = label
	args["Type"] = dType
	args["Size"] = size

	data, err := c.apiCall("linode.disk.create", args)
	if err != nil {
		return 0, 0, err
	}

	out := struct {
		JobID  int `json:"JobID"`
		DiskID int `json:"DiskID"`
	}{}

	err = json.Unmarshal(data, &out)
	if err != nil {
		return 0, 0, err
	}

	return out.JobID, out.DiskID, err
}
122969
func createNode(shift uint32, key1 interface{}, val1 interface{}, key2hash uint32, key2 interface{}, val2 interface{}) hmnode {
	key1hash := Hash(key1)
	if key1hash == key2hash {
		return &hashCollisionHmnode{key1hash, 2, []interface{}{key1, val1, key2, val2}}
	}
	node := emptyBitmapIndexedHmnode.assoc(shift, key1hash, key1, val1).assoc(shift, key2hash, key2, val2)
	return node
}
529940
func (client *Client) CreateLoadBalancerTCPListener(args *CreateLoadBalancerTCPListenerArgs) (err error) {
	response := &CommonLoadBalancerListenerResponse{}
	err = client.Invoke("CreateLoadBalancerTCPListener", args, response)
	return err
}
726756
func (c *Connection) Create(path string, node client.Node) error {
	c.RLock()
	defer c.RUnlock()
	if err := c.isClosed(); err != nil {
		return err
	}
	if err := c.ensurePath(path); err != nil {
		return err
	}
	return c.create(path, node)
}
160931
func (c *Client) NodeBalancerNodeDelete(nodeID int) error {
	args := make(map[string]interface{})
	args["NodeID"] = nodeID

	_, err := c.apiCall("nodebalancer.node.delete", args)
	if err != nil {
		return err
	}

	return nil
}
303073
func (c *client) CreateParentNodes(path string) error {
	if !c.active {
		return ErrClientClosed
	}
	if path[0] != '/' {
		return zk.ErrInvalidPath
	}
	payload := []byte("")
	pathString := ""
	pathNodes := strings.Split(path, "/")
	for i := 1; i < len(pathNodes); i++ {
		if i <= len(c.rootNodePayload) {
			payload = c.rootNodePayload[i-1]
		} else {
			payload = []byte("")
		}
		pathString += "/" + pathNodes[i]
		_, err := c.Create(pathString, payload, 0, c.acl)
		// not being able to create the node because it exists or not having
		// sufficient rights is not an issue. It is ok for the node to already
		// exist and/or us to only have read rights
		if err != nil && err != zk.ErrNodeExists && err != zk.ErrNoAuth {
			return err
		}
	}
	return nil
}
40542
func (p *Pattern) CreateNode(data string, pos int, d parser.DataSource, mo textmate.MatchObject) (ret *parser.Node) {
	ret = &parser.Node{Name: p.Name, Range: text.Region{A: mo[0], B: mo[1]}, P: d}
	defer ret.UpdateRange()

	if !p.Match.Empty() {
		p.CreateCaptureNodes(data, pos, d, mo, ret, p.Captures)
	}
	if p.Begin.Empty() {
		return
	}
	if len(p.BeginCaptures) > 0 {
		p.CreateCaptureNodes(data, pos, d, mo, ret, p.BeginCaptures)
	} else {
		p.CreateCaptureNodes(data, pos, d, mo, ret, p.Captures)
	}

	if p.End.Empty() {
		return
	}
	var (
		found  = false
		i, end int
	)
	for i, end = ret.Range.B, len(data); i < len(data); {
		endmatch := p.End.Find(data, i)
		if endmatch == nil {
			if !found {
				// oops.. no end found at all, set it to the next line
				if e2 := strings.IndexRune(data[i:], '\n'); e2 != -1 {
					end = i + e2
				} else {
					end = len(data)
				}
				break
			}
			end = i
			break
		}
		end = endmatch[1]

		if len(p.cachedPatterns) > 0 {
			// Might be more recursive patterns to apply before the end is reached
			pattern2, match2 := p.FirstMatch(data, i)
			if match2 != nil && (match2[0] < endmatch[0] || (match2[0] == endmatch[0] && ret.Range.A == ret.Range.B)) {
				found = true
				r := pattern2.CreateNode(data, i, d, match2)
				ret.Append(r)
				i = r.Range.B
				continue
			}
		}
		if len(p.EndCaptures) > 0 {
			p.CreateCaptureNodes(data, i, d, endmatch, ret, p.EndCaptures)
		} else {
			p.CreateCaptureNodes(data, i, d, endmatch, ret, p.Captures)
		}
		break
	}
	ret.Range.B = end
	return
}
1083498
func CreateNodeCluster(createRequest NodeCreateRequest) (NodeCluster, error) {

	url := "nodecluster/"
	request := "POST"
	var response NodeCluster

	newCluster, err := json.Marshal(createRequest)
	if err != nil {
		return response, err
	}

	data, err := TutumCall(url, request, newCluster)
	if err != nil {
		return response, err
	}

	err = json.Unmarshal(data, &response)
	if err != nil {
		return response, err
	}

	return response, nil
}
245693
func (c *Client) NodeBalancerUpdate(nbID int, label *string, throttle *int) error {
	args := make(map[string]interface{})
	args["NodeBalancerID"] = nbID
	args["Label"] = label
	args["ClientConnThrottle"] = throttle

	_, err := c.apiCall("nodebalancer.update", args)
	if err != nil {
		return err
	}

	return nil
}
172248
func (t *tree) Create(values ...interface{}) Changer {
	var path []nodeContent
	for _, value := range values {
		path = append(path, justValue{value})
	}
	n, err := t.container.root.create(path...)
	return &changer{n, err}
}
255987
func (cs *CSCloud) EnsureLoadBalancer(ctx context.Context, clusterName string, service *v1.Service, nodes []*v1.Node) (status *v1.LoadBalancerStatus, err error) {
	klog.V(4).Infof("EnsureLoadBalancer(%v, %v, %v, %v, %v, %v)", clusterName, service.Namespace, service.Name, service.Spec.LoadBalancerIP, service.Spec.Ports, nodes)

	if len(service.Spec.Ports) == 0 {
		return nil, fmt.Errorf("requested load balancer with no ports")
	}

	// Get the load balancer details and existing rules.
	lb, err := cs.getLoadBalancer(service)
	if err != nil {
		return nil, err
	}

	// Set the load balancer algorithm.
	switch service.Spec.SessionAffinity {
	case v1.ServiceAffinityNone:
		lb.algorithm = "roundrobin"
	case v1.ServiceAffinityClientIP:
		lb.algorithm = "source"
	default:
		return nil, fmt.Errorf("unsupported load balancer affinity: %v", service.Spec.SessionAffinity)
	}

	// Verify that all the hosts belong to the same network, and retrieve their ID's.
	lb.hostIDs, lb.networkID, err = cs.verifyHosts(nodes)
	if err != nil {
		return nil, err
	}

	if !lb.hasLoadBalancerIP() {
		// Create or retrieve the load balancer IP.
		if err := lb.getLoadBalancerIP(service.Spec.LoadBalancerIP); err != nil {
			return nil, err
		}

		if lb.ipAddr != "" && lb.ipAddr != service.Spec.LoadBalancerIP {
			defer func(lb *loadBalancer) {
				if err != nil {
					if err := lb.releaseLoadBalancerIP(); err != nil {
						klog.Errorf(err.Error())
					}
				}
			}(lb)
		}
	}

	klog.V(4).Infof("Load balancer %v is associated with IP %v", lb.name, lb.ipAddr)

	for _, port := range service.Spec.Ports {
		// All ports have their own load balancer rule, so add the port to lbName to keep the names unique.
		lbRuleName := fmt.Sprintf("%s-%d", lb.name, port.Port)

		// If the load balancer rule exists and is up-to-date, we move on to the next rule.
		exists, needsUpdate, err := lb.checkLoadBalancerRule(lbRuleName, port)
		if err != nil {
			return nil, err
		}
		if exists && !needsUpdate {
			klog.V(4).Infof("Load balancer rule %v is up-to-date", lbRuleName)
			// Delete the rule from the map, to prevent it being deleted.
			delete(lb.rules, lbRuleName)
			continue
		}

		if needsUpdate {
			klog.V(4).Infof("Updating load balancer rule: %v", lbRuleName)
			if err := lb.updateLoadBalancerRule(lbRuleName); err != nil {
				return nil, err
			}
			// Delete the rule from the map, to prevent it being deleted.
			delete(lb.rules, lbRuleName)
			continue
		}

		klog.V(4).Infof("Creating load balancer rule: %v", lbRuleName)
		lbRule, err := lb.createLoadBalancerRule(lbRuleName, port)
		if err != nil {
			return nil, err
		}

		klog.V(4).Infof("Assigning hosts (%v) to load balancer rule: %v", lb.hostIDs, lbRuleName)
		if err = lb.assignHostsToRule(lbRule, lb.hostIDs); err != nil {
			return nil, err
		}

	}

	// Cleanup any rules that are now still in the rules map, as they are no longer needed.
	for _, lbRule := range lb.rules {
		klog.V(4).Infof("Deleting obsolete load balancer rule: %v", lbRule.Name)
		if err := lb.deleteLoadBalancerRule(lbRule); err != nil {
			return nil, err
		}
	}

	status = &v1.LoadBalancerStatus{}
	status.Ingress = []v1.LoadBalancerIngress{{IP: lb.ipAddr}}

	return status, nil
}
599890
func (c *Client) NodeBalancerConfigUpdate(confID int, conf NodeBalancerConfigUpdateOpts) error {
	args, err := c.argMarshal(conf)
	if err != nil {
		return err
	}
	args["ConfigID"] = confID

	_, err = c.apiCall("nodebalancer.config.update", args)
	if err != nil {
		return err
	}

	return nil
}
1017483
func (loadBalancer *HostComputeLoadBalancer) Create() (*HostComputeLoadBalancer, error) {
	logrus.Debugf("hcn::HostComputeLoadBalancer::Create id=%s", loadBalancer.Id)

	jsonString, err := json.Marshal(loadBalancer)
	if err != nil {
		return nil, err
	}

	logrus.Debugf("hcn::HostComputeLoadBalancer::Create JSON: %s", jsonString)
	loadBalancer, hcnErr := createLoadBalancer(string(jsonString))
	if hcnErr != nil {
		return nil, hcnErr
	}
	return loadBalancer, nil
}
165497
func (aws *TestingAWSService) CreateLoadBalancer(lbd *LoadBalancerDefinition) (string, error) {
	aws.Log = append(aws.Log, AWSActionLog{
		Action: "CreateLoadBalancer",
		NotableParams: map[string]string{
			"name":            lbd.Name,
			"security_groups": fmt.Sprintf("%v", lbd.SecurityGroups),
			"scheme":          lbd.Scheme,
			"subnets":         fmt.Sprintf("%v", lbd.Subnets),
			"listeners":       fmt.Sprintf("%v", lbd.Listeners),
		},
	})
	return "", nil
}
923913
func (lb *LbaasV1) UpdateLoadBalancer(clusterName string, service *v1.Service, nodes []*v1.Node) error {
	loadBalancerName := cloudprovider.GetLoadBalancerName(service)
	glog.V(4).Infof("UpdateLoadBalancer(%v, %v, %v)", clusterName, loadBalancerName, nodes)

	vip, err := getVipByName(lb.network, loadBalancerName)
	if err != nil {
		return err
	}

	// Set of member (addresses) that _should_ exist
	addrs := map[string]bool{}
	for _, node := range nodes {
		addr, addrErr := nodeAddressForLB(node)
		if addrErr != nil {
			return addrErr
		}

		addrs[addr] = true
	}

	// Iterate over members that _do_ exist
	pager := members.List(lb.network, members.ListOpts{PoolID: vip.PoolID})
	err = pager.EachPage(func(page pagination.Page) (bool, error) {
		memList, err := members.ExtractMembers(page)
		if err != nil {
			return false, err
		}

		for _, member := range memList {
			if _, found := addrs[member.Address]; found {
				// Member already exists
				delete(addrs, member.Address)
			} else {
				// Member needs to be deleted
				err = members.Delete(lb.network, member.ID).ExtractErr()
				if err != nil {
					return false, err
				}
			}
		}

		return true, nil
	})
	if err != nil {
		return err
	}

	// Anything left in addrs is a new member that needs to be added
	for addr := range addrs {
		_, err := members.Create(lb.network, members.CreateOpts{
			PoolID:       vip.PoolID,
			Address:      addr,
			ProtocolPort: vip.ProtocolPort,
		}).Extract()
		if err != nil {
			return err
		}
	}

	return nil
}