This is bad delete function
        because one vpc can have more than one subnet.
        It is Ok if user only use CAL for manage cloud resource
        We will update ASAP.
171469
def delete(self, subnet_id):
        
        # 1 : show subnet
        subnet = self.client.describe_subnets(
            SubnetIds=[subnet_id]).get('Subnets')[0]
        vpc_id = subnet.get('VpcId')
        # 2 : delete subnet
        self.client.delete_subnet(SubnetId=subnet_id)
        # 3 : delete vpc
        return self.client.delete_vpc(VpcId=vpc_id)
631570
def delete_host(zone, name, keyname, keyfile, nameserver, timeout, port=53,
                keyalgorithm='hmac-md5'):
    '''
    
    '''
    res = []
    if zone in name:
        name = name.replace(zone, '').rstrip('.')
    fqdn = '{0}.{1}'.format(name, zone)
    request = dns.message.make_query(fqdn, 'A')
    answer = dns.query.udp(request, nameserver, timeout, port)

    try:
        ips = [i.address for i in answer.answer[0].items]
    except IndexError:
        ips = []

    ret = delete(zone, name, keyname, keyfile, nameserver, timeout, port=port,
                 keyalgorithm=keyalgorithm)
    res.append("{0} of type \'A\'".format(ret[fqdn]))

    for ip in ips:
        parts = ip.split('.')[::-1]
        i = len(parts)
        popped = []

        # Iterate over possible reverse zones
        while i > 1:
            p = parts.pop(0)
            i -= 1
            popped.append(p)
            zone = '{0}.{1}'.format('.'.join(parts), 'in-addr.arpa.')
            name = '.'.join(popped)
            rev_fqdn = '{0}.{1}'.format(name, zone)
            ret = delete(zone, name, keyname, keyfile, nameserver, timeout,
                         'PTR', "{0}.".format(fqdn), port, keyalgorithm)

            if "Deleted" in ret[rev_fqdn]:
                res.append("{0} of type \'PTR\'".format(ret[rev_fqdn]))
                return {fqdn: res}

        res.append(ret[rev_fqdn])

    return {fqdn: res}
266767
def delete_network_all_subnets(self, net_id):
        
        try:
            body = {'network_id': net_id}
            subnet_list = self.neutronclient.list_subnets(body=body)
            subnet_list = subnet_list.get('subnets')
            for subnet in subnet_list:
                if subnet.get('network_id') == net_id:
                    subnet_id = subnet.get('id')
                    self.neutronclient.delete_subnet(subnet_id)
        except Exception as exc:
            LOG.error("Failed to delete subnet for net %(net)s "
                      "Exc %(exc)s", {'net': net_id, 'exc': str(exc)})
            return False
        try:
            self.neutronclient.delete_network(net_id)
        except Exception as exc:
            LOG.error("Failed to delete network %(net)s Exc %(exc)s",
                      {'net': net_id, 'exc': str(exc)})
            return False
        return True
913214
def destroy(name, call=None, kwargs=None):  # pylint: disable=unused-argument
    '''
    
    '''
    if kwargs is None:
        kwargs = {}

    if call == 'function':
        raise SaltCloudSystemExit(
            'The destroy action must be called with -d, --destroy, '
            '-a or --action.'
        )

    compconn = get_conn(client_type='compute')

    node_data = show_instance(name, call='action')
    if node_data['storage_profile']['os_disk'].get('managed_disk'):
        vhd = node_data['storage_profile']['os_disk']['managed_disk']['id']
    else:
        vhd = node_data['storage_profile']['os_disk']['vhd']['uri']

    ret = {name: {}}
    log.debug('Deleting VM')
    result = compconn.virtual_machines.delete(node_data['resource_group'], name)
    result.wait()

    if __opts__.get('update_cachedir', False) is True:
        __utils__['cloud.delete_minion_cachedir'](
           name,
           __active_provider_name__.split(':')[0],
           __opts__
        )

    cleanup_disks = config.get_cloud_config_value(
        'cleanup_disks',
        get_configured_provider(),
        __opts__,
        search_global=False,
        default=False,
    )

    if cleanup_disks:
        cleanup_vhds = kwargs.get(
            'delete_vhd',
            config.get_cloud_config_value(
                'cleanup_vhds',
                get_configured_provider(),
                __opts__,
                search_global=False,
                default=False
            )
        )

        if cleanup_vhds:
            log.debug('Deleting vhd')

            comps = vhd.split('/')
            container = comps[-2]
            blob = comps[-1]

            ret[name]['delete_disk'] = {
                'delete_disks': cleanup_disks,
                'delete_vhd': cleanup_vhds,
                'container': container,
                'blob': blob,
            }

            if vhd.startswith('http'):
                ret[name]['data'] = delete_blob(
                    kwargs={'container': container, 'blob': blob},
                    call='function'
                )
            else:
                ret[name]['data'] = delete_managed_disk(
                    kwargs={'resource_group': node_data['resource_group'],
                            'container': container,
                            'blob': blob},
                    call='function'
                )

        cleanup_data_disks = kwargs.get(
            'delete_data_disks',
            config.get_cloud_config_value(
                'cleanup_data_disks',
                get_configured_provider(),
                __opts__,
                search_global=False,
                default=False
            )
        )

        if cleanup_data_disks:
            log.debug('Deleting data_disks')
            ret[name]['data_disks'] = {}

            for disk in node_data['storage_profile']['data_disks']:
                datavhd = disk.get('managed_disk', {}).get('id') or disk.get('vhd', {}).get('uri')
                comps = datavhd.split('/')
                container = comps[-2]
                blob = comps[-1]

                ret[name]['data_disks'][disk['name']] = {
                    'delete_disks': cleanup_disks,
                    'delete_vhd': cleanup_vhds,
                    'container': container,
                    'blob': blob,
                }

                if datavhd.startswith('http'):
                    ret[name]['data'] = delete_blob(
                        kwargs={'container': container, 'blob': blob},
                        call='function'
                    )
                else:
                    ret[name]['data'] = delete_managed_disk(
                        kwargs={'resource_group': node_data['resource_group'],
                                'container': container,
                                'blob': blob},
                        call='function'
                    )

    cleanup_interfaces = config.get_cloud_config_value(
        'cleanup_interfaces',
        get_configured_provider(),
        __opts__,
        search_global=False,
        default=False
    )

    if cleanup_interfaces:
        ret[name]['cleanup_network'] = {
            'cleanup_interfaces': cleanup_interfaces,
            'resource_group': node_data['resource_group'],
            'data': [],
        }

        ifaces = node_data['network_profile']['network_interfaces']
        for iface in ifaces:
            resource_group = iface['id'].split('/')[4]
            ret[name]['cleanup_network']['data'].append(
                delete_interface(
                    kwargs={
                        'resource_group': resource_group,
                        'iface_name': iface['name'],
                    },
                    call='function',
                )
            )

    return ret
241267
def DeleteInstance(self, si, logger, session, vcenter_data_model, vm_uuid, vm_name):
        
        # find vm
        vm = self.pv_service.find_by_uuid(si, vm_uuid)
        if vm is not None:
            # destroy vm
            result = self.pv_service.destroy_vm(vm=vm, logger=logger)
        else:
            resource___format = "Could not find the VM {0},will remove the resource.".format(vm_name)
            logger.info(resource___format)
            result = resource___format

        return result
1259185
def delete_network_resource_property_entry(resource, prop):
    

    def delete_func(cmd, resource_group_name, resource_name, item_name, no_wait=False):  # pylint: disable=unused-argument
        client = getattr(network_client_factory(cmd.cli_ctx), resource)
        item = client.get(resource_group_name, resource_name)
        keep_items = \
            [x for x in item.__getattribute__(prop) if x.name.lower() != item_name.lower()]
        _set_param(item, prop, keep_items)
        if no_wait:
            sdk_no_wait(no_wait, client.create_or_update, resource_group_name, resource_name, item)
        else:
            result = sdk_no_wait(no_wait, client.create_or_update, resource_group_name, resource_name, item).result()
            if next((x for x in getattr(result, prop) if x.name.lower() == item_name.lower()), None):
                raise CLIError("Failed to delete '{}' on '{}'".format(item_name, resource_name))

    func_name = 'delete_network_resource_property_entry_{}_{}'.format(resource, prop)
    setattr(sys.modules[__name__], func_name, delete_func)
    return func_name
587776
public static base_response delete(nitro_service client, String profilename) throws Exception {
		vpnclientlessaccessprofile deleteresource = new vpnclientlessaccessprofile();
		deleteresource.profilename = profilename;
		return deleteresource.delete_resource(client);
	}
375796
def delete_network(self, tenant_name, network):
        
        seg_id = network.segmentation_id
        network_info = {
            'organizationName': tenant_name,
            'partitionName': self._part_name,
            'segmentId': seg_id,
        }
        LOG.debug("Deleting %s network in DCNM.", network_info)

        res = self._delete_network(network_info)
        if res and res.status_code in self._resp_ok:
            LOG.debug("Deleted %s network in DCNM.", network_info)
        else:
            LOG.error("Failed to delete %s network in DCNM.",
                      network_info)
            raise dexc.DfaClientRequestFailed(reason=res)
79123
def teardown
      raise "Only Ec2 teardown supported" unless cloud_provider.name.to_s == 'ec2'
      puts "! Tearing down cloud #{name}"
      # load_balancers.each do |name, lb|
      #   puts "! Deleting load_balaner #{lb_name}"
      #   lb.teardown
      # end
      load_balancers.each do |lb|
        puts "-----> Tearing down load balancer: #{lb.name}"
        lb.teardown
      end

      rds_instances.each do |rds|
        puts "-----> Tearing down RDS Instance: #{rds.name}"
        rds.teardown
      end
      # instances belonging to an auto_scaling group must be deleted before the auto_scaling group
      #THIS SCARES ME! nodes.each{|n| n.terminate_instance!}
      # loop {nodes.size>0 ? sleep(4) : break }
      if autoscalers.empty?
        nodes.each do |node|
          node.terminate!
        end
      else
        autoscalers.each do |a|
          puts "-----> Tearing down autoscaler #{a.name}"
          a.teardown
        end
      end
      # autoscalers.keys.each do |as_name|
      #   puts "! Deleting auto_scaling_group #{as_name}"
      #   cloud_provider.as.delete_autoscaling_group('AutoScalingGroupName' => as_name)
      # end
      #TODO: keypair.delete # Do we want to delete the keypair?  probably, but not certain
    end
848677
private DeleteSubnetResponseType deleteSubnet(final String subnetId) {
        DeleteSubnetResponseType ret = new DeleteSubnetResponseType();
        ret.setRequestId(UUID.randomUUID().toString());
        mockSubnetController.deleteSubnet(subnetId);
        return ret;
    }
1216826
public static syslog_aaa delete(nitro_service client, syslog_aaa resource) throws Exception
	{
		resource.validate("delete");
		return ((syslog_aaa[]) resource.delete_resource(client))[0];
	}
658045
def delete(gandi, background, force, resource):
    
    output_keys = ['id', 'type', 'step']

    resource = sorted(tuple(set(resource)))
    possible_resources = gandi.iaas.resource_list()
    for item in resource:
        if item not in possible_resources:
            gandi.echo('Sorry virtual machine %s does not exist' % item)
            gandi.echo('Please use one of the following: %s' %
                       possible_resources)
            return

    if not force:
        instance_info = "'%s'" % ', '.join(resource)
        proceed = click.confirm("Are you sure to delete Virtual Machine %s?" %
                                instance_info)

        if not proceed:
            return

    iaas_list = gandi.iaas.list()
    stop_opers = []
    for item in resource:
        vm = next((vm for (index, vm) in enumerate(iaas_list)
                   if vm['hostname'] == item), gandi.iaas.info(item))
        if vm['state'] == 'running':
            if background:
                gandi.echo('Virtual machine not stopped, background option '
                           'disabled')
                background = False
            oper = gandi.iaas.stop(item, background)
            if not background:
                stop_opers.append(oper)

    opers = gandi.iaas.delete(resource, background)
    if background:
        for oper in stop_opers + opers:
            output_generic(gandi, oper, output_keys)

    return opers
419536
def update_dcnm_partition_static_route(self, tenant_id, arg_dict):
        
        ip_list = self.os_helper.get_subnet_nwk_excl(tenant_id,
                                                     arg_dict.get('excl_list'))
        srvc_node_ip = self.get_out_srvc_node_ip_addr(tenant_id)
        ret = self.dcnm_obj.update_partition_static_route(
            arg_dict.get('tenant_name'), fw_const.SERV_PART_NAME, ip_list,
            vrf_prof=self.cfg.firewall.fw_service_part_vrf_profile,
            service_node_ip=srvc_node_ip)
        if not ret:
            LOG.error("Unable to update DCNM ext profile with static "
                      "route %s", arg_dict.get('router_id'))
            self.delete_intf_router(tenant_id, arg_dict.get('tenant_name'),
                                    arg_dict.get('router_id'))
            return False
        return True
980878
def destroy(name, conn=None, call=None, kwargs=None):
    '''
    
    '''
    if call == 'function':
        raise SaltCloudSystemExit(
            'The destroy action must be called with -d, --destroy, '
            '-a or --action.'
        )

    if not conn:
        conn = get_conn()

    if kwargs is None:
        kwargs = {}

    instance_data = show_instance(name, call='action')
    service_name = instance_data['deployment']['name']
    disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']

    ret = {}
    # TODO: Add the ability to delete or not delete a hosted service when
    # deleting a VM
    try:
        log.debug('Deleting role')
        result = conn.delete_role(service_name, service_name, name)
        delete_type = 'delete_role'
    except AzureException:
        log.debug('Failed to delete role, deleting deployment')
        try:
            result = conn.delete_deployment(service_name, service_name)
        except AzureConflictHttpError as exc:
            log.error(exc.message)
            raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
        delete_type = 'delete_deployment'
    _wait_for_async(conn, result.request_id)
    ret[name] = {
        delete_type: {'request_id': result.request_id},
    }
    if __opts__.get('update_cachedir', False) is True:
        __utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)

    cleanup_disks = config.get_cloud_config_value(
        'cleanup_disks',
        get_configured_provider(), __opts__, search_global=False, default=False,
    )
    if cleanup_disks:
        cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
            'cleanup_vhds',
            get_configured_provider(), __opts__, search_global=False, default=False,
        ))
        log.debug('Deleting disk %s', disk_name)
        if cleanup_vhds:
            log.debug('Deleting vhd')

        def wait_for_destroy():
            '''
            Wait for the VM to be deleted
            '''
            try:
                data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
                return data
            except AzureConflictHttpError:
                log.debug('Waiting for VM to be destroyed...')
            time.sleep(5)
            return False

        data = salt.utils.cloud.wait_for_fun(
            wait_for_destroy,
            timeout=config.get_cloud_config_value(
                'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
        )
        ret[name]['delete_disk'] = {
            'name': disk_name,
            'delete_vhd': cleanup_vhds,
            'data': data
        }

        # Services can't be cleaned up unless disks are too
        cleanup_services = config.get_cloud_config_value(
            'cleanup_services',
            get_configured_provider(), __opts__, search_global=False, default=False
        )
        if cleanup_services:
            log.debug('Deleting service %s', service_name)

            def wait_for_disk_delete():
                '''
                Wait for the disk to be deleted
                '''
                try:
                    data = delete_service(kwargs={'name': service_name}, call='function')
                    return data
                except AzureConflictHttpError:
                    log.debug('Waiting for disk to be deleted...')
                time.sleep(5)
                return False

            data = salt.utils.cloud.wait_for_fun(
                wait_for_disk_delete,
                timeout=config.get_cloud_config_value(
                    'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
            )
            ret[name]['delete_services'] = {
                'name': service_name,
                'data': data
            }

    return ret
716171
def network_delete_event(self, network_info):
        """"""

        net_id = network_info['network_id']
        if net_id not in self.network:
            LOG.error('network_delete_event: net_id %s does not exist.',
                      net_id)
            return

        segid = self.network[net_id].get('segmentation_id')
        tenant_id = self.network[net_id].get('tenant_id')
        tenant_name = self.get_project_name(tenant_id)
        net = utils.Dict2Obj(self.network[net_id])
        if not tenant_name:
            LOG.error('Project %(tenant_id)s does not exist.',
                      {'tenant_id': tenant_id})
            self.update_network_db(net.id, constants.DELETE_FAIL)
            return

        try:
            self.dcnm_client.delete_network(tenant_name, net)
            # Put back the segmentation id into the pool.
            self.seg_drvr.release_segmentation_id(segid)

            # Remove entry from database and cache.
            self.delete_network_db(net_id)
            del self.network[net_id]
            snets = [k for k in self.subnet if (
                self.subnet[k].get('network_id') == net_id)]
            [self.subnet.pop(s) for s in snets]
        except dexc.DfaClientRequestFailed:
            LOG.error('Failed to create network %(net)s.',
                      {'net': net.name})
            self.update_network_db(net_id, constants.DELETE_FAIL)
        # deleting all related VMs
        instances = self.get_vms()
        instances_related = [k for k in instances if k.network_id == net_id]
        for vm in instances_related:
            LOG.debug("deleting vm %s because network is deleted", vm.name)
            self.delete_vm_function(vm.port_id, vm)
        self.network_del_notif(tenant_id, tenant_name, net_id)
216044
def delete(self, req, driver):
        
        response = driver.delete_network(req.params, id)
        data = {
            'action': "delete",
            'controller': "network",
            'id': id,
            'cloud': req.environ['calplus.cloud'],
            'response': response
        }
        return data
1302899
def purge_existing_ovb(nova_api, neutron):
    
    LOG.info('Cleaning up OVB environment from the tenant.')
    for server in nova_api.servers.list():
        if server.name in ('bmc', 'undercloud'):
            server.delete()
        if server.name.startswith('baremetal_'):
            server.delete()
    for router in neutron.list_routers().get('routers'):
        if router['name'] not in ('router', 'bmc_router'):
            continue
        for subnet in neutron.list_subnets().get('subnets'):
            if not (subnet['name'].startswith('bmc_eth') or subnet['name'] == 'rdo-m-subnet'):
                continue
            try:
                neutron.remove_interface_router(router['id'], {'subnet_id': subnet['id']})
            except neutronclient.common.exceptions.NotFound:
                pass
    try:
        bmc_router = neutron.list_routers(name='bmc_router').get('routers')[0]
        for port in neutron.list_ports(device_id=bmc_router['id'])['ports']:
            if port.get('device_owner') == 'network:router_gateway':
                continue
            info = {'id': router['id'],
                    'port_id': port['id'],
                    'tenant_id': bmc_router.get('tenant_id'),
                    }
            neutron.remove_interface_router(bmc_router['id'], info)
        neutron.delete_router(bmc_router['id'])
    except IndexError:  # already doesnt exist
        pass

    for _ in range(0, 5):
        try:
            for port in neutron.list_ports()['ports']:
                if port['name'].endswith('_provision'):
                    neutron.delete_port(port['id'])
            for net in neutron.list_networks().get('networks'):
                if not net['name'].startswith('provision_'):
                    continue
                for port in neutron.list_ports(network_id=net['id'])['ports']:
                    if port.get('device_owner') == 'network:router_interface':
                        continue
                    try:
                        neutron.delete_port(port['id'])
                    except neutronclient.common.exceptions.PortNotFoundClient:
                            pass
                    for subnet in neutron.list_subnets(network_id=net['id'])['subnets']:
                        neutron.delete_subnet(subnet['id'])
                neutron.delete_network(net['id'])
        except neutronclient.common.exceptions.Conflict:
            LOG.debug('waiting for all the ports to be freed...')
            time.sleep(5)
        else:
            return