Query an instance upon creation from the Joyent API
199981
def query_instance(vm_=None, call=None):
    '''
    
    '''
    if isinstance(vm_, six.string_types) and call == 'action':
        vm_ = {'name': vm_, 'provider': 'joyent'}

    if call == 'function':
        # Technically this function may be called other ways too, but it
        # definitely cannot be called with --function.
        raise SaltCloudSystemExit(
            'The query_instance action must be called with -a or --action.'
        )

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

    def _query_ip_address():
        data = show_instance(vm_['name'], call='action')
        if not data:
            log.error(
                'There was an error while querying Joyent. Empty response'
            )
            # Trigger a failure in the wait for IP function
            return False

        if isinstance(data, dict) and 'error' in data:
            log.warning('There was an error in the query %s', data.get('error'))
            # Trigger a failure in the wait for IP function
            return False

        log.debug('Returned query data: %s', data)

        if 'primaryIp' in data[1]:
            # Wait for SSH to be fully configured on the remote side
            if data[1]['state'] == 'running':
                return data[1]['primaryIp']
        return None

    try:
        data = salt.utils.cloud.wait_for_ip(
            _query_ip_address,
            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),
            interval_multiplier=config.get_cloud_config_value(
                'wait_for_ip_interval_multiplier', vm_, __opts__, default=1),
        )
    except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
        try:
            # destroy(vm_['name'])
            pass
        except SaltCloudSystemExit:
            pass
        finally:
            raise SaltCloudSystemExit(six.text_type(exc))

    return data
1292775
def _get_instances(cls, path, context=None, site=None, language=None):
        
        backend_context = {'view_context': context }

        for model in cls._meta.models.values():
            for instance in model.objects.get_instances(path, site, language, backend_context) or []:
                if hasattr(instance, '_process_context'):
                    instance._process_context(backend_context)
                yield instance
904078
def query_one(cls, *args, **kwargs):
        
        doc = cls._coll.find_one(*args, **kwargs)
        if doc:
            return cls.from_storage(doc)
596641
def _fake_openqueryinstances(self, namespace, **params):
        # pylint: disable=invalid-name
        
        self._validate_namespace(namespace)
        self._validate_open_params(**params)

        # pylint: disable=assignment-from-no-return
        # TODO: Not implemented
        result = self._fake_execquery(namespace, **params)

        objects = [] if result is None else [x[2] for x in result[0][2]]

        return self._open_response(objects, namespace,
                                   'PullInstancesWithPath', **params)
1331338
def get_or_create(cls, **kwargs):
        '''
        
        '''
        q = cls._get_instance(**kwargs)
        if q:
            return q
        q = cls(**kwargs)
        _action_and_commit(q, session.add)
        return q
1001651
def instance_contains(container, item):
    """"""
    return item in (member for _, member in inspect.getmembers(container))
924068
def get_instance(self, payload):
        
        return DocumentInstance(self._version, payload, service_sid=self._solution['service_sid'], )
814822
def query_instance(vm_=None, 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 query_instance action must be called with -a or --action.'
        )

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

    log.debug('The new VM instance_id is %s', instance_id)

    params = {'Action': 'DescribeInstances',
              'InstanceId.1': instance_id}

    provider = get_provider(vm_)

    attempts = 0
    while attempts < aws.AWS_MAX_RETRIES:
        data, requesturl = aws.query(params,                # pylint: disable=unbalanced-tuple-unpacking
                                     location=location,
                                     provider=provider,
                                     opts=__opts__,
                                     return_url=True,
                                     sigver='4')
        log.debug('The query returned: %s', data)

        if isinstance(data, dict) and 'error' in data:
            log.warning(
                'There was an error in the query. %s attempts '
                'remaining: %s', attempts, data['error']
            )
        elif isinstance(data, list) and not data:
            log.warning(
                'Query returned an empty list. %s attempts '
                'remaining.', attempts
            )
        else:
            break

        aws.sleep_exponential_backoff(attempts)
        attempts += 1
        continue
    else:
        raise SaltCloudSystemExit(
            'An error occurred while creating VM: {0}'.format(data['error'])
        )

    def __query_ip_address(params, url):  # pylint: disable=W0613
        data = aws.query(params,
                         location=location,
                         provider=provider,
                         opts=__opts__,
                         sigver='4')
        if not data:
            log.error(
                'There was an error while querying EC2. Empty response'
            )
            # Trigger a failure in the wait for IP function
            return False

        if isinstance(data, dict) and 'error' in data:
            log.warning('There was an error in the query. %s', data['error'])
            # Trigger a failure in the wait for IP function
            return False

        log.debug('Returned query data: %s', data)

        if ssh_interface(vm_) == 'public_ips':
            if 'ipAddress' in data[0]['instancesSet']['item']:
                return data
            else:
                log.error(
                    'Public IP not detected.'
                )

        if ssh_interface(vm_) == 'private_ips':
            if 'privateIpAddress' in data[0]['instancesSet']['item']:
                return data
            else:
                log.error(
                    'Private IP not detected.'
                )

    try:
        data = salt.utils.cloud.wait_for_ip(
            __query_ip_address,
            update_args=(params, requesturl),
            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),
            interval_multiplier=config.get_cloud_config_value(
                'wait_for_ip_interval_multiplier', vm_, __opts__, default=1),
        )
    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))

    if 'reactor' in vm_ and vm_['reactor'] is True:
        __utils__['cloud.fire_event'](
            'event',
            'instance queried',
            'salt/cloud/{0}/query_reactor'.format(vm_['name']),
            args={'data': data},
            sock_dir=__opts__['sock_dir'],
            transport=__opts__['transport']
        )

    return data
86442
function(instance) {
      var loadData = function(data) {
        return _.extend(instance, data);
      };

      if (instance.id) {
        // do PUT save
        return api
          .one(config.entity, instance.id)
          .put(instance)
          .then(loadData, console.error);
      } else {
        // no id is set, do a POST
        var endpoint = api;
        if (config.parent) {
          endpoint.one(config.parent.entity, instance[config.parent.key]);
        }
        endpoint.all(config.entity);

        return endpoint
          .post(instance)
          .then(loadData, console.error);
      }
    }
974178
def build_collection_query_object(name, additional_parameters, *args)
    root = "/#{name.to_s}"
    if args.empty?
      #nothing to add
    elsif args.size == 1
      if args.first.to_s =~ /\d+/
        id_metadata = find_id_metadata(name.to_s)
        root << build_id_path(args.first, id_metadata)
      else
        root << "(#{args.first})"
      end
    else
      root << "(#{args.join(',')})"
    end
    QueryBuilder.new(root, additional_parameters)
  end
691908
def query?(name_sym, rpc_desc)
      name_sym.to_s.start_with?('get') ||
        rpc_desc.rpc_desc.input == Google::Protobuf::Empty
    end
1005268
def aws_get_instances_by_id(region, instance_id, raw=True):
    """"""
    client = boto3.session.Session().client('ec2', region)
    try:
        matching_reservations = client.describe_instances(InstanceIds=[instance_id]).get('Reservations', [])
    except ClientError as exc:
        if exc.response.get('Error', {}).get('Code') != 'InvalidInstanceID.NotFound':
            raise
        return []
    instances = []
    [[instances.append(_aws_instance_from_dict(region, instance, raw))  # pylint: disable=expression-not-assigned
      for instance in reservation.get('Instances')] for reservation in matching_reservations if reservation]
    return instances
1087149
static TokenLifeCycleManager getInstance(final String iamEndpoint,
            final String apiKey) {
        if (iamEndpoint == null || iamEndpoint.isEmpty()) {
            throw new IllegalArgumentException(
                    "Cannot initialize with null or empty IAM endpoint.");
        }
        if (apiKey == null || apiKey.isEmpty()) {
            throw new IllegalArgumentException(
                    "Cannot initialize with null or empty IAM apiKey.");
        }
        return getInstanceUnchecked(iamEndpoint, apiKey);
    }
148136
def get_instance(self, payload):
        
        return FeedbackInstance(
            self._version,
            payload,
            account_sid=self._solution['account_sid'],
            call_sid=self._solution['call_sid'],
        )
1047309
def GetInstanceInfo(r, instance, static=None):
    

    if static is None:
        return r.request("get", "/2/instances/%s/info" % instance)
    else:
        return r.request("get", "/2/instances/%s/info" % instance,
                         query={"static": static})
1083106
@Override
    public ServiceInstance<T> queryForInstance(String name, String id) throws Exception
    {
        String path = pathForInstance(name, id);
        try
        {
            byte[] bytes = client.getData().forPath(path);
            return serializer.deserialize(bytes);
        }
        catch ( KeeperException.NoNodeException ignore )
        {
            // ignore
        }
        return null;
    }
592444
function findInstance(state, stateKey, instanceKey, payload) {
    return state[stateKey].find(obj => obj[instanceKey] === payload[instanceKey]);
}