// DeleteNIC handles a request to delete an existing network interface.
550856
func (*Service) DeleteNIC(c context.Context, req *crimson.DeleteNICRequest) (*empty.Empty, error) {
	if err := deleteNIC(c, req.Name, req.Machine); err != nil {
		return nil, err
	}
	return &empty.Empty{}, nil
}
241406
func DeleteNetwork(key string) error {
	collections.networkMutex.Lock()
	obj := collections.networks[key]
	collections.networkMutex.Unlock()
	if obj == nil {
		log.Errorf("network %s not found", key)
		return errors.New("network not found")
	}

	// Check if we handle this object
	if objCallbackHandler.NetworkCb == nil {
		log.Errorf("No callback registered for network object")
		return errors.New("Invalid object type")
	}

	// Perform callback
	err := objCallbackHandler.NetworkCb.NetworkDelete(obj)
	if err != nil {
		log.Errorf("NetworkDelete retruned error for: %+v. Err: %v", obj, err)
		return err
	}

	// delete it from modeldb
	collections.networkMutex.Lock()
	err = obj.Delete()
	collections.networkMutex.Unlock()
	if err != nil {
		log.Errorf("Error deleting network %s. Err: %v", obj.Key, err)
	}

	// delete it from cache
	collections.networkMutex.Lock()
	delete(collections.networks, key)
	collections.networkMutex.Unlock()

	return nil
}
813486
func (s *Store) deleteNodeCASTxn(tx *memdb.Txn, idx, cidx uint64, nodeName string) (bool, error) {
	// Look up the node.
	node, err := getNodeTxn(tx, nodeName)
	if err != nil {
		return false, err
	}
	if node == nil {
		return false, nil
	}

	// If the existing index does not match the provided CAS
	// index arg, then we shouldn't update anything and can safely
	// return early here.
	if node.ModifyIndex != cidx {
		return false, nil
	}

	// Call the actual deletion if the above passed.
	if err := s.deleteNodeTxn(tx, idx, nodeName); err != nil {
		return false, err
	}

	return true, nil
}
1294499
func (s *NetworkDeviceService) NewDeleteNetworkDeviceParams(id string) *DeleteNetworkDeviceParams {
	p := &DeleteNetworkDeviceParams{}
	p.p = make(map[string]interface{})
	p.p["id"] = id
	return p
}
533931
func (d *FakeNetEpDriver) DeleteNetwork(id, subnet, nwType, encap string, pktTag, extPktTag int, gateway string, tenant string) error {
	return core.Errorf("Not implemented")
}
1094718
func (p *NetPlugin) DeleteNetwork(id, subnet, nwType, encap string, pktTag, extPktTag int, Gw string, tenant string) error {
	p.Lock()
	defer p.Unlock()
	return p.NetworkDriver.DeleteNetwork(id, subnet, nwType, encap, pktTag, extPktTag, Gw, tenant)
}
989676
func (s *Server) RemoveNetwork(ctx context.Context, request *api.RemoveNetworkRequest) (*api.RemoveNetworkResponse, error) {
	if request.NetworkID == "" {
		return nil, status.Errorf(codes.InvalidArgument, errInvalidArgument.Error())
	}

	var (
		n  *api.Network
		rm = s.removeNetwork
	)

	s.store.View(func(tx store.ReadTx) {
		n = store.GetNetwork(tx, request.NetworkID)
	})
	if n == nil {
		return nil, status.Errorf(codes.NotFound, "network %s not found", request.NetworkID)
	}

	if allocator.IsIngressNetwork(n) {
		rm = s.removeIngressNetwork
	}

	if v, ok := n.Spec.Annotations.Labels[networkallocator.PredefinedLabel]; ok && v == "true" {
		return nil, status.Errorf(codes.FailedPrecondition, "network %s (%s) is a swarm predefined network and cannot be removed",
			request.NetworkID, n.Spec.Annotations.Name)
	}

	if err := rm(n.ID); err != nil {
		if err == store.ErrNotExist {
			return nil, status.Errorf(codes.NotFound, "network %s not found", request.NetworkID)
		}
		return nil, err
	}
	return &api.RemoveNetworkResponse{}, nil
}
669726
func DeleteNetworkID(stateDriver core.StateDriver, netID string) error {
	nwCfg := &mastercfg.CfgNetworkState{}
	nwCfg.StateDriver = stateDriver
	err := nwCfg.Read(netID)
	if err != nil {
		log.Errorf("network %s is not operational", netID)
		return err
	}

	// Will Skip docker network deletion for ACI fabric mode.
	aci, _ := IsAciConfigured()

	if nwCfg.NwType != "infra" {
		// For Infra nw, endpoint delete initiated by netplugin
		// Check if there are any active endpoints
		if hasActiveEndpoints(nwCfg) {
			return core.Errorf("Error: Network has active endpoints")
		}

		if GetClusterMode() == core.Docker && aci == false {
			// Delete the docker network
			err = docknet.DeleteDockNet(nwCfg.Tenant, nwCfg.NetworkName, "")
			if err != nil {
				log.Errorf("Error deleting network %s. Err: %v", netID, err)
				// DeleteDockNet will fail when network has active endpoints.
				// No damage is done yet. It is safe to fail.
				return err
			}
		}
	}

	gstate.GlobalMutex.Lock()
	defer gstate.GlobalMutex.Unlock()
	gCfg := &gstate.Cfg{}
	gCfg.StateDriver = stateDriver
	err = gCfg.Read("")
	if err != nil {
		log.Errorf("error reading tenant info for %q. Error: %s", nwCfg.Tenant, err)
		return err
	}

	// Free resource associated with the network
	err = freeNetworkResources(stateDriver, nwCfg, gCfg)
	if err != nil {
		// Error while freeing up vlan/vxlan/subnet/gateway resources
		// This can only happen because of defects in code
		// No need of any corrective handling here
		return err
	}

	err = nwCfg.Clear()
	if err != nil {
		log.Errorf("error writing nw config. Error: %s", err)
		return err
	}

	return err
}
769278
func updateNIC(c context.Context, n *crimson.NIC, mask *field_mask.FieldMask) (*crimson.NIC, error) {
	if err := validateNICForUpdate(n, mask); err != nil {
		return nil, err
	}
	stmt := squirrel.Update("nics")
	for _, path := range mask.Paths {
		switch path {
		case "mac_address":
			mac, _ := common.ParseMAC48(n.MacAddress)
			stmt = stmt.Set("mac_address", mac)
		case "switch":
			stmt = stmt.Set("switch_id", squirrel.Expr("(SELECT id FROM switches WHERE name = ?)", n.Switch))
		case "switchport":
			stmt = stmt.Set("switchport", n.Switchport)
		}
	}
	stmt = stmt.Where("name = ?", n.Name).Where("machine_id = (SELECT id FROM machines WHERE name = ?)", n.Machine)
	query, args, err := stmt.ToSql()
	if err != nil {
		return nil, errors.Annotate(err, "failed to generate statement").Err()
	}

	tx, err := database.Begin(c)
	if err != nil {
		return nil, errors.Annotate(err, "failed to begin transaction").Err()
	}
	defer tx.MaybeRollback(c)

	_, err = tx.ExecContext(c, query, args...)
	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, "'mac_address'"):
			// e.g. "Error 1062: Duplicate entry '1234567890' for key 'mac_address'".
			return nil, status.Errorf(codes.AlreadyExists, "duplicate MAC address %q", n.MacAddress)
		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 nil, status.Errorf(codes.NotFound, "switch %q does not exist", n.Switch)
		}
		return nil, errors.Annotate(err, "failed to update NIC").Err()
	}
	// The number of rows affected cannot distinguish between zero because the NIC didn't exist
	// and zero because the row already matched, so skip looking at the number of rows affected.

	nics, err := listNICs(c, tx, &crimson.ListNICsRequest{
		Names:    []string{n.Name},
		Machines: []string{n.Machine},
	})
	switch {
	case err != nil:
		return nil, errors.Annotate(err, "failed to fetch updated NIC").Err()
	case len(nics) == 0:
		return nil, status.Errorf(codes.NotFound, "NIC %q does not exist on machine %q", n.Name, n.Machine)
	}

	if err := tx.Commit(); err != nil {
		return nil, errors.Annotate(err, "failed to commit transaction").Err()
	}
	return nics[0], nil
}
825129
func (s *NetworkACLService) NewDeleteNetworkACLParams(id string) *DeleteNetworkACLParams {
	p := &DeleteNetworkACLParams{}
	p.p = make(map[string]interface{})
	p.p["id"] = id
	return p
}
1181467
func (s *NetworkService) NewDeleteStorageNetworkIpRangeParams(id string) *DeleteStorageNetworkIpRangeParams {
	p := &DeleteStorageNetworkIpRangeParams{}
	p.p = make(map[string]interface{})
	p.p["id"] = id
	return p
}
403841
func (ac *APIController) NetworkDelete(network *contivModel.Network) error {
	log.Infof("Received NetworkDelete: %+v", network)

	// Find the tenant
	tenant := contivModel.FindTenant(network.TenantName)
	if tenant == nil {
		return core.Errorf("Tenant not found")
	}

	// if the network has associated epgs, fail the delete
	epgCount := len(network.LinkSets.EndpointGroups)
	if epgCount != 0 {
		return core.Errorf("cannot delete %s has %d endpoint groups",
			network.NetworkName, epgCount)
	}

	svcCount := len(network.LinkSets.Servicelbs)
	if svcCount != 0 {
		return core.Errorf("cannot delete %s has %d services ",
			network.NetworkName, svcCount)
	}

	// In swarm-mode work-flow, if this is mapped to a docker network, reject delete
	if master.GetClusterMode() == core.SwarmMode {
		docknet, err := docknet.GetDocknetState(network.TenantName, network.NetworkName, "")
		if err == nil {
			return fmt.Errorf("cannot delete network %s mapped to docker network %s",
				network.NetworkName, docknet.DocknetUUID)
		}
		if !strings.Contains(strings.ToLower(err.Error()), "key not found") {
			log.Errorf("Error getting docknet state for %s.%s. (retval = %s)",
				network.TenantName, network.NetworkName, err.Error())
			return err
		}
		log.Infof("No docknet state for %s.%s. (retval = %s)",
			network.TenantName, network.NetworkName, err.Error())
	}

	// Remove link
	modeldb.RemoveLinkSet(&tenant.LinkSets.Networks, network)

	// Get the state driver
	stateDriver, err := utils.GetStateDriver()
	if err != nil {
		return err
	}

	// Delete the network
	networkID := network.NetworkName + "." + network.TenantName
	err = master.DeleteNetworkID(stateDriver, networkID)
	if err != nil {
		log.Errorf("Error deleting network %s. Err: %v", network.NetworkName, err)
		return err
	}

	// Save the tenant too since we removed the links
	return tenant.Write()
}
1349715
func (nDB *NetworkDB) deleteNetworkNode(nid string, nodeName string) {
	nodes, ok := nDB.networkNodes[nid]
	if !ok || len(nodes) == 0 {
		return
	}
	newNodes := make([]string, 0, len(nodes)-1)
	for _, name := range nodes {
		if name == nodeName {
			continue
		}
		newNodes = append(newNodes, name)
	}
	nDB.networkNodes[nid] = newNodes
}
565827
func (*Service) CreateNIC(c context.Context, req *crimson.CreateNICRequest) (*crimson.NIC, error) {
	if err := createNIC(c, req.Nic); err != nil {
		return nil, err
	}
	return req.Nic, nil
}
1176663
func (s *NicService) RemoveIpFromNic(p *RemoveIpFromNicParams) (*RemoveIpFromNicResponse, error) {
	resp, err := s.cs.newRequest("removeIpFromNic", p.toURLValues())
	if err != nil {
		return nil, err
	}

	var r RemoveIpFromNicResponse
	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
		}

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

	return &r, nil
}
105932
func (api *NetworksAPI) Delete(networkID string) (task *Task, err error) {
	res, err := api.client.restClient.Delete(api.client.Endpoint+networkUrl+networkID, api.client.options.TokenOptions)
	if err != nil {
		return
	}

	defer res.Body.Close()
	task, err = getTask(getError(res))
	return
}
550327
func (d *Daemon) RevNATDelete(id loadbalancer.ServiceID) error {
	d.loadBalancer.BPFMapMU.Lock()
	defer d.loadBalancer.BPFMapMU.Unlock()

	revNAT, ok := d.loadBalancer.RevNATMap[id]
	if !ok {
		return nil
	}

	err := lbmap.DeleteRevNATBPF(id, revNAT.IsIPv6())

	// TODO should we delete even if err is != nil?
	if err == nil {
		delete(d.loadBalancer.RevNATMap, id)
	}
	return err
}