Suspend an instance

    instance_id
        ID of the instance to be suspended

    CLI Example:

    .. code-block:: bash

        salt '*' nova.suspend 1138
436199
def suspend(instance_id, profile=None, **kwargs):
    '''
    

    '''
    conn = _auth(profile, **kwargs)
    return conn.suspend(instance_id)
1166881
def suspend(name, call=None):
    '''
    
    '''
    if call != 'action':
        raise SaltCloudSystemExit(
            'The suspend action must be called with '
            '-a or --action.'
        )

    vm_properties = [
        "name",
        "summary.runtime.powerState"
    ]

    vm_list = salt.utils.vmware.get_mors_with_properties(_get_si(), vim.VirtualMachine, vm_properties)

    for vm in vm_list:
        if vm["name"] == name:
            if vm["summary.runtime.powerState"] == "poweredOff":
                ret = 'cannot suspend in powered off state'
                log.info('VM %s %s', name, ret)
                return ret
            elif vm["summary.runtime.powerState"] == "suspended":
                ret = 'already suspended'
                log.info('VM %s %s', name, ret)
                return ret
            try:
                log.info('Suspending VM %s', name)
                task = vm["object"].Suspend()
                salt.utils.vmware.wait_for_task(task, name, 'suspend')
            except Exception as exc:
                log.error(
                    'Error while suspending VM %s: %s',
                    name, exc,
                    # Show the traceback if the debug logging level is enabled
                    exc_info_on_loglevel=logging.DEBUG
                )
                return 'failed to suspend'

    return 'suspended'
220046
def show_instance(name, call=None):
    '''
    
    '''
    response = _query('grid', 'server/get', args={'name': name})
    ret = {}
    for item in response['list']:
        name = item['name']
        ret[name] = item

        ret[name]['image_info'] = item['image']
        ret[name]['image'] = item['image']['friendlyName']
        ret[name]['size'] = item['ram']['name']
        ret[name]['public_ips'] = [item['ip']['ip']]
        ret[name]['private_ips'] = []
        ret[name]['state_info'] = item['state']
        if 'active' in item['state']['description']:
            ret[name]['state'] = 'RUNNING'
    return ret
412460
def bind(self, instance_id: str, binding_id: str, details: BindDetails) -> Binding:
        
        
        # Find the instance
        instance = self._backend.find(instance_id)
        
        # Find or create the binding
        binding = self._backend.find(binding_id, instance)
        
        # Create the binding if needed
        return self._backend.bind(binding, details.parameters)
1247729
def stop(self, wait=False):
        
        if self.instance_id is not None:
            log.info("Shutting down node `%s` (VM instance `%s`) ...",
                     self.name, self.instance_id)

            self._cloud_provider.stop_instance(self.instance_id)
            if wait:
                while self.is_alive():
                    time.sleep(1)
            # When an instance is terminated, the EC2 cloud provider will
            # basically return it as "running" state. Setting the
            # `instance_id` attribute to None will force `is_alive()`
            # method not to check with the cloud provider, and forever
            # forgetting about the instance id.
            self.instance_id = None
1170693
def get_instance_id(self, instance):
        "  "
        if type(instance) in [list, tuple]:
            core_signals.request_finished.connect(receiver=RichTextField.reset_instance_counter_listener)
            if RichTextField.__inst_counter >= len(instance):
                return None
            else:
                obj_id = self.instance[ RichTextField.__inst_counter ].pk
            RichTextField.__inst_counter += 1
        else:
            obj_id = instance.pk
        return obj_id
597831
def terminate(self, instances, count=0):
        
        if not instances:
            return
        if count > 0:
            instances = self._scale_down(instances, count)
        self.ec2.terminate_instances([i.id for i in instances])
886085
def cmd_stop(self, argv, help):
        """"""
        parser = argparse.ArgumentParser(
            prog="%s stop" % self.progname,
            description=help,
        )
        instances = self.get_instances(command='stop')
        parser.add_argument("instance", nargs=1,
                            metavar="instance",
                            help="Name of the instance from the config.",
                            choices=sorted(instances))
        args = parser.parse_args(argv)
        instance = instances[args.instance[0]]
        instance.stop()
1265050
def check_instance_status(self, instance_id, wait=True):

        '''
            
        '''

        title = '%s.check_instance_status' % self.__class__.__name__

    # validate inputs
        input_fields = {
            'instance_id': instance_id
        }
        for key, value in input_fields.items():
            object_title = '%s(%s=%s)' % (title, key, str(value))
            self.fields.validate(value, '.%s' % key, object_title)

    # notify status check
        self.iam.printer('Querying AWS region %s for status of instance %s.' % (self.iam.region_name, instance_id))
        
    # check state of instance
        self.iam.printer_on = False
        self.check_instance_state(instance_id)
        self.iam.printer_on = True

    # check instance status
        response = self.connection.describe_instance_status(
            InstanceIds=[ instance_id ]
        )
        if not response['InstanceStatuses']:
            from time import sleep
            from timeit import timeit as timer
            sleep(1)
            response = self.connection.describe_instance_status(
                InstanceIds=[ instance_id ]
            )
            self.iam.printer(response)
        instance_status = response['InstanceStatuses'][0]['InstanceStatus']['Status']

    # wait for instance status to be ok
        if instance_status != 'ok' and wait:
            from time import sleep
            from timeit import timeit as timer
            self.iam.printer('Waiting for initialization of instance %s to stop' % instance_id, flush=True)
            delay = 3
            status_timeout = 0
            while instance_status != 'ok':
                self.iam.printer('.', flush=True)
                sleep(delay)
                t3 = timer()
                response = self.connection.describe_instance_status(
                    InstanceIds=[ instance_id ]
                )
                t4 = timer()
                response_time = t4 - t3
                if 3 - response_time > 0:
                    delay = 3 - response_time
                else:
                    delay = 0
                status_timeout += 1
                if status_timeout > 300:
                    raise Exception('\nTimeout. Failure initializing instance %s on AWS in less than 15min' % instance_id)
                instance_status = response['InstanceStatuses'][0]['InstanceStatus']['Status']
            print(' done.')
        
    # report outcome
        self.iam.printer('Instance %s is %s.' % (instance_id, instance_status))
        
        return instance_status
1323350
def cancel_spot_instance_requests(self, request_ids):
        
        params = {}
        if request_ids:
            self.build_list_params(params, request_ids, 'SpotInstanceRequestId')
        return self.get_list('CancelSpotInstanceRequests', params,
                             [('item', Instance)], verb='POST')
1015002
def is_instance_running(self, instance_id):
        
        self._restore_from_storage(instance_id)
        if self._start_failed:
            raise Exception('is_instance_running for node %s: failing due to'
                            ' previous errors.' % instance_id)
        try:
            v_m = self._qualified_name_to_vm(instance_id)
            if not v_m:
                raise Exception("Can't find instance_id %s" % instance_id)
        except Exception:
            log.error(traceback.format_exc())
            raise
        return v_m._power_state == 'Started'
23735
def get_id(name=None, tags=None, region=None, key=None,
           keyid=None, profile=None, in_states=None, filters=None):

    '''
    

    '''
    instance_ids = find_instances(name=name, tags=tags, region=region, key=key,
                                  keyid=keyid, profile=profile, in_states=in_states,
                                  filters=filters)
    if instance_ids:
        log.info("Instance ids: %s", " ".join(instance_ids))
        if len(instance_ids) == 1:
            return instance_ids[0]
        else:
            raise CommandExecutionError('Found more than one instance '
                                        'matching the criteria.')
    else:
        log.warning('Could not find instance.')
        return None
625406
def _set_client_id(self, client_id):
        
        with self.lock:
            if self.client_id is None:
                self.client_id = client_id
822654
def stop_instance(self, instance_id):
        
        if not instance_id:
            log.info("Instance to stop has no instance id")
            return

        gce = self._connect()

        try:
            request = gce.instances().delete(project=self._project_id,
                                        instance=instance_id, zone=self._zone)
            response = self._execute_request(request)
            self._check_response(response)
        except HttpError as e:
            # If the instance does not exist, we get a 404
            if e.resp.status == 404:
                raise InstanceNotFoundError(
                    "Instance `{instance_id}` was not found"
                    .format(instance_id=instance_id))
            else:
                raise InstanceError(
                    "Could not stop instance `{instance_id}`: `{e}`"
                    .format(instance_id=instance_id, e=e))
        except CloudProviderError as e:
            raise InstanceError(
                "Could not stop instance `{instance_id}`: `{e}`"
                .format(instance_id=instance_id, e=e))
989943
def stop_service(self, instance, service):
        
        req = rest_pb2.EditServiceRequest()
        req.state = 'stopped'
        url = '/services/{}/{}'.format(instance, service)
        self.patch_proto(url, data=req.SerializeToString())
222202
def lock(self, instance_id):
        '''
        
        '''
        nt_ks = self.compute_conn
        response = nt_ks.servers.lock(instance_id)
        return True
709438
def stop(self, instances, count=0):
        
        if not instances:
            return
        if count > 0:
            instances = self._scale_down(instances, count)
        self.ec2.stop_instances([i.id for i in instances])