Shutdown and destroy virtual machines in the Google Compute Engine,
 including their associated disks and firewall rules
977647
def cleanup()
      attempts = @options[:timeout].to_i / SLEEPWAIT
      start = Time.now

      @gce_helper.delete_firewall(@firewall, start, attempts)

      @hosts.each do |host|
        @gce_helper.delete_instance(host['vmhostname'], start, attempts)
        @logger.debug("Deleted Google Compute instance #{host['vmhostname']} for #{host.name}")
        @gce_helper.delete_disk(host['diskname'], start, attempts)
        @logger.debug("Deleted Google Compute disk #{host['diskname']} for #{host.name}")
      end

    end
266671
function destroyServer(server, topology, callback) {
  LOCAL_SERVER_EVENTS.forEach(event => server.removeAllListeners(event));

  server.destroy(() => {
    topology.emit(
      'serverClosed',
      new monitoring.ServerClosedEvent(topology.s.id, server.description.address)
    );

    if (typeof callback === 'function') callback(null, null);
  });
}
105072
def destroy(name, call=None):
    '''
    
    '''
    if call == 'function':
        raise SaltCloudSystemExit(
            'The destroy action must be called with -d, --destroy, '
            '-a or --action.'
        )

    __utils__['cloud.fire_event'](
        'event',
        'destroying instance',
        'salt/cloud/{0}/destroying'.format(name),
        args={'name': name},
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    vmobj = _get_vm_by_name(name)
    if vmobj is not None:
        # stop the vm
        if get_vm_status(vmid=vmobj['vmid'])['status'] != 'stopped':
            stop(name, vmobj['vmid'], 'action')

        # wait until stopped
        if not wait_for_state(vmobj['vmid'], 'stopped'):
            return {'Error': 'Unable to stop {0}, command timed out'.format(name)}

        # required to wait a bit here, otherwise the VM is sometimes
        # still locked and destroy fails.
        time.sleep(3)

        query('delete', 'nodes/{0}/{1}'.format(
            vmobj['node'], vmobj['id']
        ))
        __utils__['cloud.fire_event'](
            'event',
            'destroyed instance',
            'salt/cloud/{0}/destroyed'.format(name),
            args={'name': name},
            sock_dir=__opts__['sock_dir'],
            transport=__opts__['transport']
        )
        if __opts__.get('update_cachedir', False) is True:
            __utils__['cloud.delete_minion_cachedir'](
                name, __active_provider_name__.split(':')[0], __opts__)

        return {'Destroyed': '{0} was destroyed.'.format(name)}
159452
def purge(name, delete_key=True):
    '''
    
    '''
    ret = {}
    client = salt.client.get_local_client(__opts__['conf_file'])
    data = vm_info(name, quiet=True)
    if not data:
        __jid_event__.fire_event({'error': 'Failed to find VM {0} to purge'.format(name)}, 'progress')
        return 'fail'
    host = next(six.iterkeys(data))
    try:
        cmd_ret = client.cmd_iter(
                host,
                'virt.purge',
                [name, True],
                timeout=600)
    except SaltClientError as client_error:
        return 'Virtual machine {0} could not be purged: {1}'.format(name, client_error)

    for comp in cmd_ret:
        ret.update(comp)

    if delete_key:
        log.debug('Deleting key %s', name)
        skey = salt.key.Key(__opts__)
        skey.delete_key(name)
    __jid_event__.fire_event({'message': 'Purged VM {0}'.format(name)}, 'progress')
    return 'good'
201061
def destroy_multiprocessing(parallel_data, queue=None):
    '''
    
    '''
    salt.utils.crypt.reinit_crypto()

    parallel_data['opts']['output'] = 'json'
    clouds = salt.loader.clouds(parallel_data['opts'])

    try:
        fun = clouds['{0}.destroy'.format(parallel_data['driver'])]
        with salt.utils.context.func_globals_inject(
            fun,
            __active_provider_name__=':'.join([
                parallel_data['alias'],
                parallel_data['driver']
            ])
        ):
            output = fun(parallel_data['name'])

    except SaltCloudException as exc:
        log.error(
            'Failed to destroy %s. Error: %s',
            parallel_data['name'], exc, exc_info_on_loglevel=logging.DEBUG
        )
        return {parallel_data['name']: {'Error': str(exc)}}

    return {
        parallel_data['name']: salt.utils.data.simple_types_filter(output)
    }
219112
def stop(self):
        

        yield from self._stop_ubridge()
        with (yield from self._execute_lock):
            # stop the QEMU process
            self._hw_virtualization = False
            if self.is_running():
                log.info('Stopping QEMU VM "{}" PID={}'.format(self._name, self._process.pid))
                try:
                    if self.acpi_shutdown:
                        yield from self._control_vm("system_powerdown")
                        yield from gns3server.utils.asyncio.wait_for_process_termination(self._process, timeout=30)
                    else:
                        self._process.terminate()
                        yield from gns3server.utils.asyncio.wait_for_process_termination(self._process, timeout=3)
                except ProcessLookupError:
                    pass
                except asyncio.TimeoutError:
                    if self._process:
                        try:
                            self._process.kill()
                        except ProcessLookupError:
                            pass
                        if self._process.returncode is None:
                            log.warn('QEMU VM "{}" PID={} is still running'.format(self._name, self._process.pid))
            self._process = None
            self._stop_cpulimit()
            yield from super().stop()
15384
def _stop_instance(self):
        
        try:
            vm_stop = self.compute.virtual_machines.power_off(
                self.running_instance_id, self.running_instance_id
            )
        except Exception as error:
            raise AzureCloudException(
                'Unable to stop instance: {0}.'.format(error)
            )

        vm_stop.wait()
1351183
def vm_configured(name, vm_name, cpu, memory, image, version, interfaces,
                  disks, scsi_devices, serial_ports, datacenter, datastore,
                  placement, cd_dvd_drives=None, sata_controllers=None,
                  advanced_configs=None, template=None, tools=True,
                  power_on=False, deploy=False):
    '''
    
    '''
    result = {'name': name,
              'result': None,
              'changes': {},
              'comment': ''}

    log.trace('Validating virtual machine configuration')
    schema = ESXVirtualMachineConfigSchema.serialize()
    log.trace('schema = %s', schema)
    try:
        jsonschema.validate({'vm_name': vm_name,
                             'cpu': cpu,
                             'memory': memory,
                             'image': image,
                             'version': version,
                             'interfaces': interfaces,
                             'disks': disks,
                             'scsi_devices': scsi_devices,
                             'serial_ports': serial_ports,
                             'cd_dvd_drives': cd_dvd_drives,
                             'sata_controllers': sata_controllers,
                             'datacenter': datacenter,
                             'datastore': datastore,
                             'placement': placement,
                             'template': template,
                             'tools': tools,
                             'power_on': power_on,
                             'deploy': deploy}, schema)
    except jsonschema.exceptions.ValidationError as exc:
        raise salt.exceptions.InvalidConfigError(exc)

    service_instance = __salt__['vsphere.get_service_instance_via_proxy']()
    try:
        __salt__['vsphere.get_vm'](vm_name, vm_properties=['name'],
                                   service_instance=service_instance)
    except salt.exceptions.VMwareObjectRetrievalError:
        vm_file = __salt__['vsphere.get_vm_config_file'](
            vm_name, datacenter,
            placement, datastore,
            service_instance=service_instance)
        if vm_file:
            if __opts__['test']:
                result.update({'comment': 'The virtual machine {0}'
                                          ' will be registered.'.format(vm_name)})
                __salt__['vsphere.disconnect'](service_instance)
                return result
            result = vm_registered(vm_name, datacenter, placement,
                                   vm_file, power_on=power_on)
            return result
        else:
            if __opts__['test']:
                result.update({'comment': 'The virtual machine {0}'
                                          ' will be created.'.format(vm_name)})
                __salt__['vsphere.disconnect'](service_instance)
                return result
            if template:
                result = vm_cloned(name)
            else:
                result = vm_created(name, vm_name, cpu, memory, image, version,
                                    interfaces, disks, scsi_devices,
                                    serial_ports, datacenter, datastore,
                                    placement, cd_dvd_drives=cd_dvd_drives,
                                    advanced_configs=advanced_configs,
                                    power_on=power_on)
            return result

    result = vm_updated(name, vm_name, cpu, memory, image, version,
                        interfaces, disks, scsi_devices,
                        serial_ports, datacenter, datastore,
                        cd_dvd_drives=cd_dvd_drives,
                        sata_controllers=sata_controllers,
                        advanced_configs=advanced_configs,
                        power_on=power_on)
    __salt__['vsphere.disconnect'](service_instance)

    log.trace(result)
    return result
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
611671
def destroy_ec2(connection, region, instance_id, log=False):
    

    data = get_ec2_info(connection=connection,
                        instance_id=instance_id,
                        region=region)

    instance = connection.terminate_instances(instance_ids=[data['id']])[0]
    if log:
        log_yellow('destroying instance ...')
    while instance.state != "terminated":
        if log:
            log_yellow("Instance state: %s" % instance.state)
        sleep(10)
        instance.update()
    volume_id = data['volume']
    if volume_id:
        destroy_ebs_volume(connection, region, volume_id)
952151
async def manage(self):
        
        self._vms = await self.iaas.list_vms(self.name)

        vms_stat = Counter([vm.get_state() for vm in self._vms])
        missing = self.count - len(self._vms) if len(self._vms) < self.count else 0
        logging.info(
            'VMs Status: %s expected, %s in iaas, %s running, %s nearby shutdown, %s pending, %s after time shutdown, '
            '%s terminated, %s error, %s unknown, %s missing',
            self.count, len(self._vms), vms_stat[VmState.RUNNING.value], vms_stat[VmState.NEARBY_SHUTDOWN.value],
            vms_stat[VmState.PENDING.value], vms_stat[VmState.AFTER_TIME_SHUTDOWN.value],
            vms_stat[VmState.TERMINATED.value], vms_stat[VmState.ERROR.value], vms_stat[VmState.UNKNOWN.value], missing, extra=self._extra
        )
        for vm in self._vms:
            if vm.is_dead():
                logging.info("Terminate %s", vm, extra=self._extra)
                await vm.terminate()
                self.terminated += 1
        to_create = self.count - (len(self._vms) - self.terminated - vms_stat[VmState.NEARBY_SHUTDOWN.value])
        to_create = to_create if to_create > 0 else 0
        logging.debug("Create %s Vm", to_create, extra=self._extra)
        await self._create_vms(to_create)
        await self._healthcheck(self._vms)
        logging.info(
            'VMs Status update: %s terminated, %s terminated by healthcheck, %s created, %s failed healthcheck',
            self.terminated, self.healthcheck_terminated, to_create, len(self.runtime.failed_checks),
            extra=self._extra
        )
660009
def server_shutdown(server_state):
    
    set_running( False )

    # stop API servers
    rpc_stop(server_state)
    api_stop(server_state)

    # stop atlas node
    server_atlas_shutdown(server_state)

    # stopping GC
    gc_stop()

    # clear PID file
    try:
        if os.path.exists(server_state['pid_file']):
            os.unlink(server_state['pid_file'])
    except:
        pass

    return True
355964
def destroy_vm_vdis(name=None, session=None, call=None):
    '''
    

    '''
    if session is None:
        session = _get_session()
    ret = {}
    # get vm object
    vms = session.xenapi.VM.get_by_name_label(name)
    if len(vms) == 1:
        # read virtual block device (vdb)
        vbds = session.xenapi.VM.get_VBDs(vms[0])
        if vbds is not None:
            x = 0
            for vbd in vbds:
                vbd_record = session.xenapi.VBD.get_record(vbd)
                if vbd_record['VDI'] != 'OpaqueRef:NULL':
                    # read vdi on vdb
                    vdi_record = session.xenapi.VDI.get_record(
                        vbd_record['VDI'])
                    if 'iso' not in vdi_record['name_label']:
                        session.xenapi.VDI.destroy(vbd_record['VDI'])
                        ret['vdi-{}'.format(x)] = vdi_record['name_label']
                x += 1
    return ret
513501
def destroy(vm_, call=None):
    ''''''
    destroy_opt = __opts__.get('destroy', False)
    profiles = __opts__.get('profiles', {})
    profile = __opts__.get('profile',
                           __opts__.get('internal_lxc_profile', []))
    path = None
    if profile and profile in profiles:
        path = profiles[profile].get('path', None)
    action = __opts__.get('action', '')
    if action != 'destroy' and not destroy_opt:
        raise SaltCloudSystemExit(
            'The destroy action must be called with -d, --destroy, '
            '-a or --action.'
        )
    if not get_configured_provider():
        return
    ret = {'comment': '{0} was not found'.format(vm_),
           'result': False}
    if _salt('lxc.info', vm_, path=path):
        __utils__['cloud.fire_event'](
            'event',
            'destroying instance',
            'salt/cloud/{0}/destroying'.format(vm_),
            args={'name': vm_, 'instance_id': vm_},
            sock_dir=__opts__['sock_dir'],
            transport=__opts__['transport']
        )
        cret = _salt('lxc.destroy', vm_, stop=True, path=path)
        ret['result'] = cret['result']
        if ret['result']:
            ret['comment'] = '{0} was destroyed'.format(vm_)
            __utils__['cloud.fire_event'](
                'event',
                'destroyed instance',
                'salt/cloud/{0}/destroyed'.format(vm_),
                args={'name': vm_, 'instance_id': vm_},
                sock_dir=__opts__['sock_dir'],
                transport=__opts__['transport']
            )
            if __opts__.get('update_cachedir', False) is True:
                __utils__['cloud.delete_minion_cachedir'](vm_, __active_provider_name__.split(':')[0], __opts__)
    return ret
478565
@Override
    public void shutdown() {
        try {
            DefaultMonitorRegistry.getInstance().unregister(Monitors.newObjectMonitor(this));
        } catch (Throwable t) {
            logger.error("Cannot shutdown monitor registry", t);
        }
        try {
            peerEurekaNodes.shutdown();
        } catch (Throwable t) {
            logger.error("Cannot shutdown ReplicaAwareInstanceRegistry", t);
        }
        numberOfReplicationsLastMin.stop();

        super.shutdown();
    }
767258
function shutdown(){
    // trigger stop on all workers
    // catch errors thrown by killed workers
    return Promise.all(Object.values(_cluster.workers).map(worker => stopWorker(worker).catch(err => _logger.error(err))));
}
77524
@Override
  public void stopScheduling() {
    LOG.debug("Stopping compute engine");
    // Requesting all workers to stop
    for (ChainingCallback chainingCallback : chainingCallbacks) {
      chainingCallback.stop(false);
    }

    // Workers have 40s to gracefully stop processing tasks
    long until = System.currentTimeMillis() + gracefulStopTimeoutInMs;
    LOG.info("Waiting for workers to finish in-progress tasks");
    while (System.currentTimeMillis() < until && ceWorkerController.hasAtLeastOneProcessingWorker()) {
      try {
        Thread.sleep(200L);
      } catch (InterruptedException e) {
        LOG.debug("Graceful stop period has been interrupted: {}", e);
        Thread.currentThread().interrupt();
        break;
      }
    }

    if (ceWorkerController.hasAtLeastOneProcessingWorker()) {
      LOG.info("Some in-progress tasks did not finish in due time. Tasks will be stopped.");
    }

    // Interrupting the tasks
    for (ChainingCallback chainingCallback : chainingCallbacks) {
      chainingCallback.stop(true);
    }
  }