// createCNPCRD creates and updates the CiliumNetworkPolicies CRD. It should be called
// on agent startup but is idempotent and safe to call again.
519786
func createCNPCRD(clientset apiextensionsclient.Interface) error {
	var (
		// CustomResourceDefinitionSingularName is the singular name of custom resource definition
		CustomResourceDefinitionSingularName = "ciliumnetworkpolicy"

		// CustomResourceDefinitionPluralName is the plural name of custom resource definition
		CustomResourceDefinitionPluralName = "ciliumnetworkpolicies"

		// CustomResourceDefinitionShortNames are the abbreviated names to refer to this CRD's instances
		CustomResourceDefinitionShortNames = []string{"cnp", "ciliumnp"}

		// CustomResourceDefinitionKind is the Kind name of custom resource definition
		CustomResourceDefinitionKind = CNPKindDefinition

		CRDName = CustomResourceDefinitionPluralName + "." + SchemeGroupVersion.Group
	)

	res := &apiextensionsv1beta1.CustomResourceDefinition{
		ObjectMeta: metav1.ObjectMeta{
			Name: CRDName,
			Labels: map[string]string{
				CustomResourceDefinitionSchemaVersionKey: CustomResourceDefinitionSchemaVersion,
			},
		},
		Spec: apiextensionsv1beta1.CustomResourceDefinitionSpec{
			Group:   SchemeGroupVersion.Group,
			Version: SchemeGroupVersion.Version,
			Names: apiextensionsv1beta1.CustomResourceDefinitionNames{
				Plural:     CustomResourceDefinitionPluralName,
				Singular:   CustomResourceDefinitionSingularName,
				ShortNames: CustomResourceDefinitionShortNames,
				Kind:       CustomResourceDefinitionKind,
			},
			Subresources: &apiextensionsv1beta1.CustomResourceSubresources{
				Status: &apiextensionsv1beta1.CustomResourceSubresourceStatus{},
			},
			Scope:      apiextensionsv1beta1.NamespaceScoped,
			Validation: &cnpCRV,
		},
	}

	return createUpdateCRD(clientset, "CiliumNetworkPolicy/v2", res)
}
1287974
func (api *API) CreatePublicIp(ip_type string, reverse_dns string, datacenter_id string) (string, *PublicIp, error) {
	res := new(PublicIp)
	url := createUrl(api, publicIpPathSegment)
	req := struct {
		DatacenterId string `json:"datacenter_id,omitempty"`
		ReverseDns   string `json:"reverse_dns,omitempty"`
		Type         string `json:"type,omitempty"`
	}{DatacenterId: datacenter_id, ReverseDns: reverse_dns, Type: ip_type}
	err := api.Client.Post(url, &req, &res, http.StatusCreated)
	if err != nil {
		return "", nil, err
	}
	res.api = api
	return res.Id, res, nil
}
1283480
func NewCRLFromDB(certs []certdb.CertificateRecord, issuerCert *x509.Certificate, key crypto.Signer, expiryTime time.Duration) ([]byte, error) {
	var revokedCerts []pkix.RevokedCertificate

	newExpiryTime := time.Now().Add(expiryTime)

	// For every record, create a new revokedCertificate and add it to slice
	for _, certRecord := range certs {
		serialInt := new(big.Int)
		serialInt.SetString(certRecord.Serial, 10)
		tempCert := pkix.RevokedCertificate{
			SerialNumber:   serialInt,
			RevocationTime: certRecord.RevokedAt,
		}
		revokedCerts = append(revokedCerts, tempCert)
	}

	return CreateGenericCRL(revokedCerts, key, issuerCert, newExpiryTime)
}
749755
func (c *Client) NodeBalancerConfigCreate(nbID int,
	conf NodeBalancerConfigCreateOpts) (confID int, err error) {

	args, err := c.argMarshal(conf)
	if err != nil {
		return 0, err
	}
	args["NodeBalancerID"] = nbID

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

	var cID int
	err = unmarshalSingle(data, "ConfigID", &cID)
	if err != nil {
		return 0, err
	}

	return cID, nil
}
829694
func newCCPolicyProvider(ctx context.Client, discovery fab.DiscoveryService, channelID string) (CCPolicyProvider, error) {
	if channelID == "" {
		return nil, errors.New("Must provide channel ID for cc policy provider")
	}

	cpp := ccPolicyProvider{
		context:   ctx,
		channelID: channelID,
		discovery: discovery,
		ccDataMap: make(map[string]*ccprovider.ChaincodeData),
	}

	return &cpp, nil
}
459370
func (c *Cluster) CreateSecret(s types.SecretSpec) (string, error) {
	var resp *swarmapi.CreateSecretResponse
	if err := c.lockedManagerAction(func(ctx context.Context, state nodeState) error {
		secretSpec := convert.SecretSpecToGRPC(s)

		r, err := state.controlClient.CreateSecret(ctx,
			&swarmapi.CreateSecretRequest{Spec: &secretSpec})
		if err != nil {
			return err
		}
		resp = r
		return nil
	}); err != nil {
		return "", err
	}
	return resp.Secret.ID, nil
}
1241823
func (document *XmlDocument) CreateCDataNode(data string) (cdata *CDataNode) {
	dataLen := len(data)
	dataBytes := GetCString([]byte(data))
	dataPtr := unsafe.Pointer(&dataBytes[0])
	nodePtr := C.xmlNewCDataBlock(document.Ptr, (*C.xmlChar)(dataPtr), C.int(dataLen))
	if nodePtr != nil {
		cdata = NewNode(unsafe.Pointer(nodePtr), document).(*CDataNode)
	}
	return
}
820701
func (o *Enterprise) CreateNetconfProfile(child *NetconfProfile) *bambou.Error {

	return bambou.CurrentSession().CreateChild(o, child)
}
456944
func createNIC(c context.Context, n *crimson.NIC) error {
	if err := validateNICForCreation(n); err != nil {
		return err
	}
	mac, _ := common.ParseMAC48(n.MacAddress)
	tx, err := database.Begin(c)
	if err != nil {
		return errors.Annotate(err, "failed to begin transaction").Err()
	}
	defer tx.MaybeRollback(c)

	var hostnameId sql.NullInt64
	if n.Hostname != "" {
		ip, _ := common.ParseIPv4(n.Ipv4)
		id, err := model.AssignHostnameAndIP(c, tx, n.Hostname, ip)
		if err != nil {
			return err
		}
		hostnameId.Int64 = id
		hostnameId.Valid = true
	}

	// By setting nics.machine_id NOT NULL when setting up the database, we can avoid checking if the given machine is
	// valid. MySQL will turn up NULL for its column values which will be rejected as an error.
	_, err = tx.ExecContext(c, `
		INSERT INTO nics (name, machine_id, mac_address, switch_id, switchport, hostname_id)
		VALUES (?, (SELECT id FROM machines WHERE name = ?), ?, (SELECT id FROM switches WHERE name = ?), ?, ?)
	`, n.Name, n.Machine, mac, n.Switch, n.Switchport, hostnameId)
	if err != nil {
		switch e, ok := err.(*mysql.MySQLError); {
		case !ok:
			// Type assertion failed.
		case e.Number == mysqlerr.ER_DUP_ENTRY && strings.Contains(e.Message, "'name'"):
			// e.g. "Error 1062: Duplicate entry 'eth0-machineId' for key 'name'".
			return status.Errorf(codes.AlreadyExists, "duplicate NIC %q for machine %q", n.Name, n.Machine)
		case e.Number == mysqlerr.ER_DUP_ENTRY && strings.Contains(e.Message, "'mac_address'"):
			// e.g. "Error 1062: Duplicate entry '1234567890' for key 'mac_address'".
			return status.Errorf(codes.AlreadyExists, "duplicate MAC address %q", n.MacAddress)
		case e.Number == mysqlerr.ER_BAD_NULL_ERROR && strings.Contains(e.Message, "'machine_id'"):
			// e.g. "Error 1048: Column 'machine_id' cannot be null".
			return status.Errorf(codes.NotFound, "machine %q does not exist", n.Machine)
		case e.Number == mysqlerr.ER_BAD_NULL_ERROR && strings.Contains(e.Message, "'switch_id'"):
			// e.g. "Error 1048: Column 'switch_id' cannot be null".
			return status.Errorf(codes.NotFound, "switch %q does not exist", n.Switch)
		}
		return errors.Annotate(err, "failed to create NIC").Err()
	}

	if err := tx.Commit(); err != nil {
		return errors.Annotate(err, "failed to commit transaction").Err()
	}
	return nil
}
578691
func (b *BigIP) CreateTcpProfile(name string, parent string) error {
	config := &TcpProfile{
		Name:         name,
		DefaultsFrom: parent,
	}

	return b.post(config, uriLtm, uriProfile, uriTcp)
}
861597
func (d *Driver) createNetwork() error {
	conn, err := getConnection()
	if err != nil {
		return errors.Wrap(err, "getting libvirt connection")
	}
	defer conn.Close()

	// network: default
	// It is assumed that the libvirt/kvm installation has already created this network

	// network: private

	// Only create the private network if it does not already exist
	if _, err := conn.LookupNetworkByName(d.PrivateNetwork); err != nil {
		// create the XML for the private network from our networkTmpl
		tmpl := template.Must(template.New("network").Parse(networkTmpl))
		var networkXML bytes.Buffer
		if err := tmpl.Execute(&networkXML, d); err != nil {
			return errors.Wrap(err, "executing network template")
		}

		// define the network using our template
		network, err := conn.NetworkDefineXML(networkXML.String())
		if err != nil {
			return errors.Wrapf(err, "defining network from xml: %s", networkXML.String())
		}

		// and finally create it
		if err := network.Create(); err != nil {
			return errors.Wrapf(err, "creating network %s", d.PrivateNetwork)
		}
	}

	return nil
}
1364168
func (o *Enterprise) CreatePublicNetworkMacro(child *PublicNetworkMacro) *bambou.Error {

	return bambou.CurrentSession().CreateChild(o, child)
}
417965
func (d *driver) CreateNetwork(id string, option map[string]interface{}, nInfo driverapi.NetworkInfo, ipV4Data, ipV6Data []driverapi.IPAMData) error {
	if _, err := d.getNetwork(id); err == nil {
		return types.ForbiddenErrorf("network %s exists", id)
	}

	genData, ok := option[netlabel.GenericData].(map[string]string)
	if !ok {
		return fmt.Errorf("Unknown generic data option")
	}

	// Parse and validate the config. It should not conflict with existing networks' config
	config, err := d.parseNetworkOptions(id, genData)
	if err != nil {
		return err
	}

	err = config.processIPAM(id, ipV4Data, ipV6Data)
	if err != nil {
		return err
	}

	err = d.createNetwork(config)

	if err != nil {
		return err
	}

	// A non blank hnsid indicates that the network was discovered
	// from HNS. No need to call HNS if this network was discovered
	// from HNS
	if config.HnsID == "" {
		subnets := []hcsshim.Subnet{}

		for _, ipData := range ipV4Data {
			subnet := hcsshim.Subnet{
				AddressPrefix: ipData.Pool.String(),
			}

			if ipData.Gateway != nil {
				subnet.GatewayAddress = ipData.Gateway.IP.String()
			}

			subnets = append(subnets, subnet)
		}

		network := &hcsshim.HNSNetwork{
			Name:               config.Name,
			Type:               d.name,
			Subnets:            subnets,
			DNSServerList:      config.DNSServers,
			DNSSuffix:          config.DNSSuffix,
			MacPools:           config.MacPools,
			SourceMac:          config.SourceMac,
			NetworkAdapterName: config.NetworkAdapterName,
		}

		if config.VLAN != 0 {
			vlanPolicy, err := json.Marshal(hcsshim.VlanPolicy{
				Type: "VLAN",
				VLAN: config.VLAN,
			})

			if err != nil {
				return err
			}
			network.Policies = append(network.Policies, vlanPolicy)
		}

		if config.VSID != 0 {
			vsidPolicy, err := json.Marshal(hcsshim.VsidPolicy{
				Type: "VSID",
				VSID: config.VSID,
			})

			if err != nil {
				return err
			}
			network.Policies = append(network.Policies, vsidPolicy)
		}

		if network.Name == "" {
			network.Name = id
		}

		configurationb, err := json.Marshal(network)
		if err != nil {
			return err
		}

		configuration := string(configurationb)
		logrus.Debugf("HNSNetwork Request =%v Address Space=%v", configuration, subnets)

		hnsresponse, err := hcsshim.HNSNetworkRequest("POST", "", configuration)
		if err != nil {
			return err
		}

		config.HnsID = hnsresponse.Id
		genData[HNSID] = config.HnsID

	} else {
		// Delete any stale HNS endpoints for this network.
		if endpoints, err := hcsshim.HNSListEndpointRequest(); err == nil {
			for _, ep := range endpoints {
				if ep.VirtualNetwork == config.HnsID {
					logrus.Infof("Removing stale HNS endpoint %s", ep.Id)
					_, err = hcsshim.HNSEndpointRequest("DELETE", ep.Id, "")
					if err != nil {
						logrus.Warnf("Error removing HNS endpoint %s", ep.Id)
					}
				}
			}
		} else {
			logrus.Warnf("Error listing HNS endpoints for network %s", config.HnsID)
		}
	}

	n, err := d.getNetwork(id)
	if err != nil {
		return err
	}
	n.created = true
	return d.storeUpdate(config)
}
562265
func (api *API) CreatePrivateNetwork(request *PrivateNetworkRequest) (string, *PrivateNetwork, error) {
	result := new(PrivateNetwork)
	url := createUrl(api, privateNetworkPathSegment)
	err := api.Client.Post(url, &request, &result, http.StatusAccepted)
	if err != nil {
		return "", nil, err
	}
	result.api = api
	return result.Id, result, nil
}
338587
func (d *driver) CreateNetwork(id string, option map[string]interface{}, nInfo driverapi.NetworkInfo, ipV4Data, ipV6Data []driverapi.IPAMData) error {
	if len(ipV4Data) == 0 || ipV4Data[0].Pool.String() == "0.0.0.0/0" {
		return types.BadRequestErrorf("ipv4 pool is empty")
	}
	// Sanity checks
	d.Lock()
	if _, ok := d.networks[id]; ok {
		d.Unlock()
		return types.ForbiddenErrorf("network %s exists", id)
	}
	d.Unlock()

	// Parse and validate the config. It should not be conflict with existing networks' config
	config, err := parseNetworkOptions(id, option)
	if err != nil {
		return err
	}

	if err = config.processIPAM(id, ipV4Data, ipV6Data); err != nil {
		return err
	}

	// start the critical section, from this point onward we are dealing with the list of networks
	// so to be consistent we cannot allow that the list changes
	d.configNetwork.Lock()
	defer d.configNetwork.Unlock()

	// check network conflicts
	if err = d.checkConflict(config); err != nil {
		nerr, ok := err.(defaultBridgeNetworkConflict)
		if !ok {
			return err
		}
		// Got a conflict with a stale default network, clean that up and continue
		logrus.Warn(nerr)
		d.deleteNetwork(nerr.ID)
	}

	// there is no conflict, now create the network
	if err = d.createNetwork(config); err != nil {
		return err
	}

	return d.storeUpdate(config)
}
677231
func (_class NetworkClass) Create(sessionID SessionRef, args NetworkRecord) (_retval NetworkRef, _err error) {
	_method := "network.create"
	_sessionIDArg, _err := convertSessionRefToXen(fmt.Sprintf("%s(%s)", _method, "session_id"), sessionID)
	if _err != nil {
		return
	}
	_argsArg, _err := convertNetworkRecordToXen(fmt.Sprintf("%s(%s)", _method, "args"), args)
	if _err != nil {
		return
	}
	_result, _err := _class.client.APICall(_method, _sessionIDArg, _argsArg)
	if _err != nil {
		return
	}
	_retval, _err = convertNetworkRefToGo(_method + " -> ", _result.Value)
	return
}
282241
func (ctx *VmContext) createContainer(id string) error {
	ctx.lock.Lock()
	defer ctx.lock.Unlock()

	if ctx.current != StateRunning {
		ctx.Log(DEBUG, "create container %s during %v", id, ctx.current)
		return NewNotReadyError(id)
	}

	c, ok := ctx.containers[id]
	if ok {
		ctx.Log(TRACE, "start sending create container")
		var err error
		err = c.agentCreate()
		ctx.Log(TRACE, "sent create container")
		return err
	} else {
		return fmt.Errorf("container %s not exist", id)
	}
}