Wait for an instance upon creation from the EC2 API, to become available
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_
165252
def wait_for_start(self):
        
        er = self.exec_rabbitmqctl(
            'wait', ['--pid', '1', '--timeout', str(int(self.wait_timeout))])
        output_lines(er, error_exc=TimeoutError)
163089
def _wait_for_request(self, uuid, connection_adapter=None):
        
        start_time = time.time()
        while not self._response[uuid]:
            connection_adapter.check_for_errors()
            if time.time() - start_time > self._timeout:
                self._raise_rpc_timeout_error(uuid)
            time.sleep(IDLE_WAIT)
42250
def __WaitForCredentialsLive(self, iam_aws_id, iam_aws_secret):
    
    print 'waiting for credentials to go live...'
    for region in core.tested_region_names:
      core.WaitForEc2Connection(iam_aws_id, iam_aws_secret, region)
    core.WaitForS3Connection(iam_aws_id, iam_aws_secret)
    
    print 'done'
    return
547932
def waitPuppetCatalogToBeApplied(self, key, sleepTime=5):
        
        # Wait for puppet catalog to be applied
        loop_stop = False
        while not loop_stop:
            status = self[key].getStatus()
            if status == 'No Changes' or status == 'Active':
                self.__printProgression__(True,
                                          key + ' creation: provisioning OK')
                loop_stop = True
            elif status == 'Error':
                self.__printProgression__(False,
                                          key + ' creation: Error - '
                                          'Error during provisioning')
                loop_stop = True
                return False
            else:
                self.__printProgression__('In progress',
                                          key + ' creation: provisioning ({})'
                                          .format(status),
                                          eol='\r')
            time.sleep(sleepTime)
1352474
def wait(self, timeout=None, raise_error=True):
        
        return self.get(timeout=timeout, raise_error=raise_error)
992384
def wait(self, timeout=None):
        
        timeout = ["--interval=%s" % timeout] if timeout else []
        cmdline = ["podman", "wait"] + timeout + [self._id or self.get_id()]
        return run_cmd(cmdline, return_output=True)
733420
def _get_instance(self):
        """"""
        resource = self._connect()

        try:
            instance = resource.Instance(self.running_instance_id)
        except Exception:
            raise EC2CloudException(
                'Instance with ID: {instance_id} not found.'.format(
                    instance_id=self.running_instance_id
                )
            )
        return instance
1041527
def wait_for_copy_available(self, image_id, region):
        
        waiting = True

        describe_image_cmd = "aws ec2 --profile {} --region {} --output json describe-images --image-id {}"\
            .format(self.aws_project, region, image_id)
        while waiting:
            res = subprocess.check_output(shlex.split(describe_image_cmd))
            print "described image returned: {}".format(res)
            image_json = parse_image_json(res)
            image_state = image_json['State']
            if image_state == 'available':
                print "Copied AMI is renamed and ready to use!"
                return
            elif image_state == 'failed':
                print "Copied AMI failed for some reason..."
                sys.exit(5)
            else:
                print "image state is currently: {}".format(image_state)
                print "Sleeping for 30 seconds..."
                time.sleep(30)
677238
def _maybe_wait_for_initializing_instance(instance):
  """"""

  if not instance:
    return

  if instance.state['Name'] == 'initializing':
    while True:
      print(f"Waiting  for {instance} to leave state 'initializing'.")
      instance.reload()
      if instance.state['Name'] == 'running':
        break
      time.sleep(10)
1362324
public void waitForDeployments(@Observes(precedence = -100) AfterStart event, OpenShiftAdapter client,
        CEEnvironmentProcessor.TemplateDetails details, TestClass testClass, CubeOpenShiftConfiguration configuration, OpenShiftClient openshiftClient)
        throws Exception {
        if (testClass == null) {
            // nothing to do, since we're not in ClassScoped context
            return;
        }
        if (details == null) {
            log.warning(String.format("No environment for %s", testClass.getName()));
            return;
        }
        log.info(String.format("Waiting for environment for %s", testClass.getName()));
        try {
            delay(client, details.getResources());
        } catch (Throwable t) {
            throw new IllegalArgumentException("Error waiting for template resources to deploy: " + testClass.getName(), t);
        }
    }
1016482
def create(vm_):
    '''
    
    '''
    try:
        # Check for required profile parameters before sending any API calls.
        if (vm_['profile'] and
           config.is_profile_configured(__opts__,
                                        (__active_provider_name__ or
                                         'oneandone'),
                                        vm_['profile']) is False):
            return False
    except AttributeError:
        pass

    data = None
    conn = get_conn()
    hdds = []

    # Assemble the composite server object.
    server = _get_server(vm_)

    if not bool(server.specs['hardware']['fixed_instance_size_id'])\
        and not bool(server.specs['server_type'] == 'baremetal'):
        # Assemble the hdds object.
        hdds = _get_hdds(vm_)

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

    try:
        data = conn.create_server(server=server, hdds=hdds)

        _wait_for_completion(conn,
                             get_wait_timeout(vm_),
                             data['id'])
    except Exception as exc:  # pylint: disable=W0703
        log.error(
            'Error creating %s on 1and1\n\n'
            'The following exception was thrown by the 1and1 library '
            'when trying to run the initial deployment: \n%s',
            vm_['name'], exc, exc_info_on_loglevel=logging.DEBUG
        )
        return False

    vm_['server_id'] = data['id']
    password = data['first_password']

    def __query_node_data(vm_, data):
        '''
        Query node data until node becomes available.
        '''
        running = False
        try:
            data = show_instance(vm_['name'], 'action')
            if not data:
                return False
            log.debug(
                'Loaded node data for %s:\nname: %s\nstate: %s',
                vm_['name'],
                pprint.pformat(data['name']),
                data['status']['state']
            )
        except Exception as err:
            log.error(
                'Failed to get nodes list: %s', err,
                # Show the trackback if the debug logging level is enabled
                exc_info_on_loglevel=logging.DEBUG
            )
            # Trigger a failure in the wait for IP function
            return False

        running = data['status']['state'].lower() == 'powered_on'
        if not running:
            # Still not running, trigger another iteration
            return

        vm_['ssh_host'] = data['ips'][0]['ip']

        return data

    try:
        data = salt.utils.cloud.wait_for_ip(
            __query_node_data,
            update_args=(vm_, data),
            timeout=config.get_cloud_config_value(
                'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
            interval=config.get_cloud_config_value(
                'wait_for_ip_interval', vm_, __opts__, default=10),
        )
    except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
        try:
            # It might be already up, let's destroy it!
            destroy(vm_['name'])
        except SaltCloudSystemExit:
            pass
        finally:
            raise SaltCloudSystemExit(six.text_type(exc.message))

    log.debug('VM is now running')
    log.info('Created Cloud VM %s', vm_)
    log.debug('%s VM creation details:\n%s', vm_, pprint.pformat(data))

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

    if 'ssh_host' in vm_:
        vm_['password'] = password
        vm_['key_filename'] = get_key_filename(vm_)
        ret = __utils__['cloud.bootstrap'](vm_, __opts__)
        ret.update(data)
        return ret
    else:
        raise SaltCloudSystemExit('A valid IP address was not found.')
101160
def wait_for_sshd(cls, vm_id):
        """"""
        cls.echo('Waiting for the vm to come online')
        version, ip_addr = cls.vm_ip(vm_id)
        give_up = time.time() + 300
        last_error = None
        while time.time() < give_up:
            try:
                inet = socket.AF_INET
                if version == 6:
                    inet = socket.AF_INET6
                sd = socket.socket(inet, socket.SOCK_STREAM,
                                   socket.IPPROTO_TCP)
                sd.settimeout(5)
                sd.connect((ip_addr, 22))
                sd.recv(1024)
                return
            except socket.error as err:
                if err.errno == errno.EHOSTUNREACH and version == 6:
                    cls.error('%s is not reachable, you may be missing '
                              'IPv6 connectivity' % ip_addr)
                last_error = err
                time.sleep(1)
            except Exception as err:
                last_error = err
                time.sleep(1)
        cls.error('VM did not spin up (last error: %s)' % last_error)
164199
def cli(env, identifier, wait):
    """"""

    compute = SoftLayer.HardwareManager(env.client)
    compute_id = helpers.resolve_id(compute.resolve_ids, identifier,
                                    'hardware')
    ready = compute.wait_for_ready(compute_id, wait)
    if ready:
        env.fout("READY")
    else:
        raise exceptions.CLIAbort("Server %s not ready" % compute_id)
484467
def wait( self, timeout = -1 ):
        """"""

        # we can't use ipyparallel.Client.wait() for this, because that
        # method only works for cases where the Client object is the one that
        # submitted the jobs to the cluster hub -- and therefore has the
        # necessary data structures to perform synchronisation. This isn't the
        # case for us, as one of the main goals of epyc is to support disconnected
        # operation, which implies a different Client object retrieving results
        # than the one that submitted the jobs in the first place. This is
        # unfortunate, but understandable given the typical use cases for
        # Client objects.
        #
        # Instead. we have to code around a little busily. The ClusterLab.WaitingTime
        # global sets the latency for waiting, and we repeatedly wait for this amount
        # of time before updating the results. The latency value essentially controls
        # how busy this process is: given that most simulations are expected to
        # be long, a latency in the tens of seconds feels about right as a default
        if self.numberOfPendingResults() > 0:
            # we've got pending results, wait for them
            timeWaited = 0
            while (timeout < 0) or (timeWaited < timeout):
                if self.numberOfPendingResults() == 0:
                    # no pending jobs left, we're complete
                    return True
                else:
                    # not done yet, calculate the waiting period
                    if timeout == -1:
                        # wait for the default waiting period
                        dt = self.WaitingTime
                    else:
                        # wait for the default waiting period or until the end of the timeout.
                        # whichever comes first
                        if (timeout - timeWaited) < self.WaitingTime:
                            dt = timeout - timeWaited
                        else:
                            dt = self.WaitingTime
                            
                    # sleep for a while
                    time.sleep(dt)
                    timeWaited = timeWaited + dt

            # if we get here, the timeout expired, so do a final check
            # and then exit
            return (self.numberOfPendingResults() == 0)

        else:
            # no results, so we got them all
            return True
178973
def wait_for_instance_death(instance, opts={})
      wait_for_instance_status(:terminated, instance, opts) if instance.exists?
    rescue AWS::EC2::Errors::InvalidInstanceID::NotFound
    end
452269
def launch_instance(instance_name,
                    command,
                    existing_ip=None,
                    cpu=1,
                    mem=4,
                    code_dir=None,
                    setup_command=None):
  """"""
  # Create instance
  ip = existing_ip or create_instance(instance_name, cpu=cpu, mem=mem)
  tf.logging.info("Waiting for SSH %s", instance_name)
  ready = wait_for_ssh(ip)
  if not ready:
    raise ValueError("Instance %s never ready for SSH" % instance_name)

  # Copy code
  if code_dir:
    shell_run_with_retry(COPY_CODE, retries=2,
                         local_dir=code_dir, instance_name=instance_name)

  # Run setup
  if setup_command:
    tf.logging.info("Running setup on %s", instance_name)
    remote_run(setup_command, instance_name)

  # Run command
  tf.logging.info("Running command on %s", instance_name)
  remote_run(command, instance_name, detach=True)