Wait until an instance is deleted.
    
    We require that initially, the specified instance exists.
    TODO: docstring
760853
def wait_for_instance_deletion(credentials, project, zone, instance_name,
                               interval_seconds=5):
    
    
    t0 = time.time()
    access_token = credentials.get_access_token()
    headers = {
        'Authorization': 'Bearer %s' % access_token.access_token
    }

    r = requests.get('https://www.googleapis.com/compute/v1/'
                     'projects/%s/zones/%s/instances/%s'
                     % (project, zone, instance_name),
                     headers=headers)
    
    if r.status_code == 404:
        raise AssertionError('Instance "%s" does not exist!' % instance_name)
        
    r.raise_for_status()
    _LOGGER.debug('Instance "%s" exists.', instance_name)

    while True:
        time.sleep(interval_seconds)

        access_token = credentials.get_access_token()
        headers = {
            'Authorization': 'Bearer %s' % access_token.access_token
        }

        r = requests.get('https://www.googleapis.com/compute/v1/'
                         'projects/%s/zones/%s/instances/%s'
                         % (project, zone, instance_name),
                         headers=headers)
        if r.status_code == 404:
            break
        r.raise_for_status()
        _LOGGER.debug('Instance "%s" still exists.', instance_name)
        
    t1 = time.time()
    t = t1-t0
    t_min = t/60.0
    _LOGGER.info('Instance was deleted after %.1f s (%.1f m).', t, t_min)
177539
def wait_for_instance(
        vm_=None,
        data=None,
        ip_address=None,
        display_ssh_output=True,
        call=None,
    ):
    '''
    
    '''
    if call == 'function':
        # Technically this function may be called other ways too, but it
        # definitely cannot be called with --function.
        raise SaltCloudSystemExit(
            'The wait_for_instance action must be called with -a or --action.'
        )

    if vm_ is None:
        vm_ = {}

    if data is None:
        data = {}

    ssh_gateway_config = vm_.get(
        'gateway', get_ssh_gateway_config(vm_)
    )

    __utils__['cloud.fire_event'](
        'event',
        'waiting for ssh',
        'salt/cloud/{0}/waiting_for_ssh'.format(vm_['name']),
        args={'ip_address': ip_address},
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    ssh_connect_timeout = config.get_cloud_config_value(
        'ssh_connect_timeout', vm_, __opts__, 900   # 15 minutes
    )
    ssh_port = config.get_cloud_config_value(
        'ssh_port', vm_, __opts__, 22
    )

    if config.get_cloud_config_value('win_installer', vm_, __opts__):
        username = config.get_cloud_config_value(
            'win_username', vm_, __opts__, default='Administrator'
        )
        win_passwd = config.get_cloud_config_value(
            'win_password', vm_, __opts__, default=''
        )
        win_deploy_auth_retries = config.get_cloud_config_value(
            'win_deploy_auth_retries', vm_, __opts__, default=10
        )
        win_deploy_auth_retry_delay = config.get_cloud_config_value(
            'win_deploy_auth_retry_delay', vm_, __opts__, default=1
        )
        use_winrm = config.get_cloud_config_value(
            'use_winrm', vm_, __opts__, default=False
        )
        winrm_verify_ssl = config.get_cloud_config_value(
            'winrm_verify_ssl', vm_, __opts__, default=True
        )

        if win_passwd and win_passwd == 'auto':
            log.debug('Waiting for auto-generated Windows EC2 password')
            while True:
                password_data = get_password_data(
                    name=vm_['name'],
                    kwargs={
                        'key_file': vm_['private_key'],
                    },
                    call='action',
                )
                win_passwd = password_data.get('password', None)
                if win_passwd is None:
                    log.debug(password_data)
                    # This wait is so high, because the password is unlikely to
                    # be generated for at least 4 minutes
                    time.sleep(60)
                else:
                    logging_data = password_data

                    logging_data['password'] = 'XXX-REDACTED-XXX'
                    logging_data['passwordData'] = 'XXX-REDACTED-XXX'
                    log.debug(logging_data)

                    vm_['win_password'] = win_passwd
                    break

        # SMB used whether psexec or winrm
        if not salt.utils.cloud.wait_for_port(ip_address,
                                              port=445,
                                              timeout=ssh_connect_timeout):
            raise SaltCloudSystemExit(
                'Failed to connect to remote windows host'
            )

        # If not using winrm keep same psexec behavior
        if not use_winrm:

            log.debug('Trying to authenticate via SMB using psexec')

            if not salt.utils.cloud.validate_windows_cred(ip_address,
                                                          username,
                                                          win_passwd,
                                                          retries=win_deploy_auth_retries,
                                                          retry_delay=win_deploy_auth_retry_delay):
                raise SaltCloudSystemExit(
                    'Failed to authenticate against remote windows host (smb)'
                )

        # If using winrm
        else:

            # Default HTTPS port can be changed in cloud configuration
            winrm_port = config.get_cloud_config_value(
                'winrm_port', vm_, __opts__, default=5986
            )

            # Wait for winrm port to be available
            if not salt.utils.cloud.wait_for_port(ip_address,
                                                  port=winrm_port,
                                                  timeout=ssh_connect_timeout):
                raise SaltCloudSystemExit(
                    'Failed to connect to remote windows host (winrm)'
                )

            log.debug('Trying to authenticate via Winrm using pywinrm')

            if not salt.utils.cloud.wait_for_winrm(ip_address,
                                                          winrm_port,
                                                          username,
                                                          win_passwd,
                                                          timeout=ssh_connect_timeout,
                                                          verify=winrm_verify_ssl):
                raise SaltCloudSystemExit(
                    'Failed to authenticate against remote windows host'
                )

    elif salt.utils.cloud.wait_for_port(ip_address,
                                        port=ssh_port,
                                        timeout=ssh_connect_timeout,
                                        gateway=ssh_gateway_config
                                        ):
        # If a known_hosts_file is configured, this instance will not be
        # accessible until it has a host key. Since this is provided on
        # supported instances by cloud-init, and viewable to us only from the
        # console output (which may take several minutes to become available,
        # we have some more waiting to do here.
        known_hosts_file = config.get_cloud_config_value(
            'known_hosts_file', vm_, __opts__, default=None
        )
        if known_hosts_file:
            console = {}
            while 'output_decoded' not in console:
                console = get_console_output(
                    instance_id=vm_['instance_id'],
                    call='action',
                    location=get_location(vm_)
                )
                pprint.pprint(console)
                time.sleep(5)
            output = salt.utils.stringutils.to_unicode(console['output_decoded'])
            comps = output.split('-----BEGIN SSH HOST KEY KEYS-----')
            if len(comps) < 2:
                # Fail; there are no host keys
                return False

            comps = comps[1].split('-----END SSH HOST KEY KEYS-----')
            keys = ''
            for line in comps[0].splitlines():
                if not line:
                    continue
                keys += '\n{0} {1}'.format(ip_address, line)

            with salt.utils.files.fopen(known_hosts_file, 'a') as fp_:
                fp_.write(salt.utils.stringutils.to_str(keys))
            fp_.close()

        for user in vm_['usernames']:
            if salt.utils.cloud.wait_for_passwd(
                host=ip_address,
                port=ssh_port,
                username=user,
                ssh_timeout=config.get_cloud_config_value(
                    'wait_for_passwd_timeout', vm_, __opts__, default=1 * 60
                ),
                key_filename=vm_['key_filename'],
                display_ssh_output=display_ssh_output,
                gateway=ssh_gateway_config,
                maxtries=config.get_cloud_config_value(
                    'wait_for_passwd_maxtries', vm_, __opts__, default=15
                ),
                known_hosts_file=config.get_cloud_config_value(
                    'known_hosts_file', vm_, __opts__,
                    default='/dev/null'
                ),
            ):
                __opts__['ssh_username'] = user
                vm_['ssh_username'] = user
                break
        else:
            raise SaltCloudSystemExit(
                'Failed to authenticate against remote ssh'
            )
    else:
        raise SaltCloudSystemExit(
            'Failed to connect to remote ssh'
        )

    if 'reactor' in vm_ and vm_['reactor'] is True:
        __utils__['cloud.fire_event'](
            'event',
            'ssh is available',
            'salt/cloud/{0}/ssh_ready_reactor'.format(vm_['name']),
            args={'ip_address': ip_address},
            sock_dir=__opts__['sock_dir'],
            transport=__opts__['transport']
        )

    return vm_
726704
def resume_instance(self, paused_info):
        

        if not paused_info.get("instance_id"):
            log.info("Instance to stop has no instance id.")
            return

        gce = self._connect()

        try:
            request = gce.instances().start(project=self._project_id,
                                            instance=paused_info["instance_id"],
                                            zone=self._zone)
            operation = self._execute_request(request)
            response = self._wait_until_done(operation)
            self._check_response(response)
            return
        except HttpError as e:
            log.error("Error restarting instance: `%s", e)
            raise InstanceError("Error restarting instance `%s`", e)
397738
def wait(self, *args, **kwargs):
        """"""
        if _debug: IOCB._debug("wait(%d) %r %r", self.ioID, args, kwargs)

        # waiting from a non-daemon thread could be trouble
        return self.ioComplete.wait(*args, **kwargs)
1129338
private void waitForInstances(String flowletId, int expectedInstances) throws InterruptedException, TimeoutException {
    int numRunningFlowlets = getNumberOfProvisionedInstances(flowletId);
    int secondsWaited = 0;
    while (numRunningFlowlets != expectedInstances) {
      LOG.debug("waiting for {} instances of {} before suspending flowlets", expectedInstances, flowletId);
      TimeUnit.SECONDS.sleep(SECONDS_PER_WAIT);
      secondsWaited += SECONDS_PER_WAIT;
      if (secondsWaited > MAX_WAIT_SECONDS) {
        String errmsg =
          String.format("waited %d seconds for instances of %s to reach expected count of %d, but %d are running",
                                      secondsWaited, flowletId, expectedInstances, numRunningFlowlets);
        LOG.error(errmsg);
        throw new TimeoutException(errmsg);
      }
      numRunningFlowlets = getNumberOfProvisionedInstances(flowletId);
    }
  }
217988
def wait(self, timeout=None):
        
        if self._thread is None:
            return
        self._thread.join(timeout=timeout)
755240
def check_instance_state(self, instance_id, wait=True):
        
        '''
            
        '''

        title = '%s.check_instance_state' % 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 state check
        self.iam.printer('Querying AWS region %s for state of instance %s.' % (self.iam.region_name, instance_id))

    # check connection to API
        try:
            self.connection.describe_instances()
        except:
            raise AWSConnectionError(title)
                
    # check existence of instance
        try:
            response = self.connection.describe_instances(
                InstanceIds=[ instance_id ]
            )
        except:
            raise ValueError('\nInstance %s does not exist.' % instance_id)
        if not 'Reservations' in response.keys():
            raise ValueError('\nInstance %s does not exist.' % instance_id)
        elif not response['Reservations']:
            raise ValueError('\nInstance %s does not exist.' % instance_id)
        elif not 'Instances' in response['Reservations'][0].keys():
            raise ValueError('\nInstance %s does not exist.' % instance_id)
        elif not response['Reservations'][0]['Instances'][0]:
            raise ValueError('\nInstance %s does not exist.' % instance_id)
                
    # check into state of instance
        elif not 'State' in response['Reservations'][0]['Instances'][0].keys():
            from time import sleep
            from timeit import timeit as timer
            self.iam.printer('Checking into the status of instance %s ... ' % instance_id, flush=True)
            state_timeout = 0
            while not 'State' in response['Reservations'][0]['Instances'][0].keys():
                self.iam.printer('.', flush=True)
                sleep(3)
                state_timeout += 1
                response = self.connection.describe_instances(
                    InstanceIds=[ instance_id ]
                )
                if state_timeout > 3:
                    raise Exception('\nFailure to determine status of instance %s.' % instance_id)
            self.iam.printer('done.')
            
    # return None if instance has already been terminated
        instance_state = response['Reservations'][0]['Instances'][0]['State']['Name']
        if instance_state == 'shutting-down' or instance_state == 'terminated':
            self.iam.printer('Instance %s has already been terminated.' % instance_id)
            return None
            
    # wait while instance is pending
        elif instance_state == 'pending':
            self.iam.printer('Instance %s is %s.' % (instance_id, instance_state), flush=True)
            if not wait:
                return instance_state
            else:
                from time import sleep
                from timeit import timeit as timer
                delay = 3
                while instance_state == 'pending':
                    self.iam.printer('.', flush=True)
                    sleep(delay)
                    t3 = timer()
                    response = self.connection.describe_instances(
                        InstanceIds=[ instance_id ]
                    )
                    t4 = timer()
                    response_time = t4 - t3
                    if 3 - response_time > 0:
                        delay = 3 - response_time
                    else:
                        delay = 0
                    instance_state = response['Reservations'][0]['Instances'][0]['State']['Name']
                self.iam.printer(' done.')

    # report outcome
        self.iam.printer('Instance %s is %s.' % (instance_id, instance_state))

        return instance_state
184919
def wait(self, timeout=None):
        
        self.__stopped.wait(timeout)
        return self.__stopped.is_set()
624719
def wait_for(self, timeout=None):
        
        from broqer.op import OnEmitFuture  # due circular dependency
        return self | OnEmitFuture(timeout=timeout)
925962
def wait(self, state, timeout=-1):
        

        if isinstance(state, str):
            state = state.upper()

        return _lxc.Container.wait(self, state, timeout)
1018542
@Override
    public Object beforeDelete(S storable) throws PersistException {
        S existing = (S) storable.copy();
        try {
            if (!existing.tryLoad()) {
                existing = null;
            }
            return existing;
        } catch (FetchException e) {
            throw e.toPersistException();
        }
    }
909528
def delete_instance(self, instance, using_transactions=True, dry_run=False):
        
        self.before_delete_instance(instance, dry_run)
        if not using_transactions and dry_run:
            # we don't have transactions and we want to do a dry_run
            pass
        else:
            instance.delete()
        self.after_delete_instance(instance, dry_run)
1211615
async def wait_until_ready(
        self, timeout: Optional[float] = None, no_raise: bool = False
    ) -> bool:
        
        if self.node.ready.is_set():
            return True

        try:
            return await self.node.wait_until_ready(timeout=timeout)
        except asyncio.TimeoutError:
            if no_raise:
                return False
            else:
                raise
1366729
def _wait(self):
        
        val = self.wait_change.get()

        if isinstance(val, Exception):
            # Don't other uncharging, because execution is going to stop
            raise val
        else:
            # Uncharge for resources.
            self.member_burden -= len(val)
            self.concurrency_burden -= 1
104775
def exists(self, value=None):
        
        try:
            if not value:
                value = self.get()
        except (AttributeError, DoesNotExist):
            # If the instance is deleted, the _pk attribute doesn't exist
            # anymore. So we catch the AttributeError to return False (this pk
            # field doesn't exist anymore) in this specific case
            return False
        else:
            return self.connection.sismember(self.collection_key, value)
137930
def _wait_until_no_error_exp(self, timeout, wait_func, *args):
		""""""
	
		timeout = robot.utils.timestr_to_secs(timeout) if timeout is not None else self._timeout_in_secs
		maxtime = time.time() + timeout
		
		while True:
		
			try:
				timeout_error = wait_func(*args)
				if not timeout_error: return
				if time.time() > maxtime: raise AssertionError(timeout_error)
				time.sleep(0.2)
				
			except AssertionError:
			
				raise
				
			except:
			
				if time.time() > maxtime: raise
				continue
803508
def pop(self, instance):
        '''
'''
        if isinstance(instance, self.model):
            iid = instance.get_state().iid
        else:
            iid = instance
        instance = None
        for d in (self._new, self._modified, self._deleted):
            if iid in d:
                inst = d.pop(iid)
                if instance is None:
                    instance = inst
                elif inst is not instance:
                    raise ValueError('Critical error: %s is duplicated' % iid)
        return instance