Find counts of currently-running EC2 Instances
        (On-Demand or Reserved) by placement (Availability
        Zone) and instance type (size). Return as a nested dict
        of AZ name to dict of instance type to count.

        :rtype: dict
182362
def _instance_usage(self):
        
        # On-Demand instances by type
        ondemand = {}
        for t in self._instance_types():
            ondemand[t] = 0
        az_to_inst = {}
        logger.debug("Getting usage for on-demand instances")
        for inst in self.resource_conn.instances.all():
            if inst.spot_instance_request_id:
                logger.info("Spot instance found (%s); skipping from "
                            "Running On-Demand Instances count", inst.id)
                continue
            if inst.state['Name'] in ['stopped', 'terminated']:
                logger.debug("Ignoring instance %s in state %s", inst.id,
                             inst.state['Name'])
                continue
            if inst.placement['AvailabilityZone'] not in az_to_inst:
                az_to_inst[
                    inst.placement['AvailabilityZone']] = deepcopy(ondemand)
            try:
                az_to_inst[
                    inst.placement['AvailabilityZone']][inst.instance_type] += 1
            except KeyError:
                logger.error("ERROR - unknown instance type '%s'; not "
                             "counting", inst.instance_type)
        return az_to_inst
750916
def __GetInstances(self, group_name = None, state_filter=None):
    
    all_instances = self.ec2.get_all_instances()
    instances = []
    for res in all_instances:
      for group in res.groups:
        if group_name and group.name != group_name:
          continue
        for instance in res.instances:
          if state_filter == None or instance.state == state_filter:
            instances.append(instance)
    return instances
455371
def is_instance_running(self, instance_id):
        
        self._init_az_api()
        # Here, it's always better if we update the instance.
        vm = self._get_vm(instance_id, force_reload=True)
        # FIXME: should we rather check `vm.instance_view.statuses`
        # and search for `.code == "PowerState/running"`? or
        # `vm.instance_view.vm_agent.statuses` and search for `.code
        # == 'ProvisioningState/suceeded'`?
        return vm.provisioning_state == u'Succeeded'
803282
def instances(exp=".*"):
    ""
    expression = re.compile(exp)
    instances = []
    for node in ec2_instances():
        if node.tags and ip(node):
            try:
                if expression.match(node.tags.get("Name")):
                    instances.append(node)
            except TypeError:
                pass
    return instances
979988
def show_instance(name, call=None):
    '''
    
    '''
    if call != 'action':
        raise SaltCloudSystemExit(
            'The show_instance action must be called with -a or --action.'
        )

    items = query(action='ve', command=name)

    ret = {}
    for item in items:
        if 'text' in item.__dict__:
            ret[item.tag] = item.text
        else:
            ret[item.tag] = item.attrib

        if item._children:
            ret[item.tag] = {}
            children = item._children
            for child in children:
                ret[item.tag][child.tag] = child.attrib

    __utils__['cloud.cache_node'](ret, __active_provider_name__, __opts__)
    return ret
1037899
def lookup_instance(name: str, instance_type: str = '', image_name: str = '',
                    states: tuple = ('running', 'stopped', 'initializing')):
  

  ec2 = get_ec2_resource()

  instances = ec2.instances.filter(
    Filters=[{'Name': 'instance-state-name', 'Values': states}])

  prefix = get_prefix()
  username = get_username()

  # look for an existing instance matching job, ignore instances launched
  # by different user or under different resource name
  result = []
  for i in instances.all():
    instance_name = get_name(i)
    if instance_name != name:
      continue

    seen_prefix, seen_username = parse_key_name(i.key_name)
    if prefix != seen_prefix:
      print(f"Found {name} launched under {seen_prefix}, ignoring")
      continue
    if username != seen_username:
      print(f"Found {name} launched by {seen_username}, ignoring")
      continue

    if instance_type:
      assert i.instance_type == instance_type, f"Found existing instance for job {name} but different instance type ({i.instance_type}) than requested ({instance_type}), terminate {name} first or use new task name."

    if image_name:
      assert i.image.name == image_name, f"Found existing instance for job {name} but launched with different image ({i.image.name}) than requested ({image_name}), terminate {name} first or use new task name."
    result.append(i)

    assert len(result) < 2, f"Found two instances with name {name}"
    if not result:
      return None
    else:
      return result[0]
1350231
def _find_usage_elbv2(self):
        
        logger.debug('Checking usage for ELBv2')
        conn2 = client(
            'elbv2',
            config=Config(retries={'max_attempts': ELBV2_MAX_RETRY_ATTEMPTS}),
            **self._boto3_connection_kwargs
        )
        logger.debug("Connected to %s in region %s (with max retry attempts "
                     "overridden to %d)", 'elbv2',
                     conn2._client_config.region_name, ELBV2_MAX_RETRY_ATTEMPTS)
        # Target groups
        tgroups = paginate_dict(
            conn2.describe_target_groups,
            alc_marker_path=['NextMarker'],
            alc_data_path=['TargetGroups'],
            alc_marker_param='Marker'
        )
        self.limits['Target groups']._add_current_usage(
            len(tgroups['TargetGroups']),
            aws_type='AWS::ElasticLoadBalancingV2::TargetGroup'
        )
        # ALBs
        lbs = paginate_dict(
            conn2.describe_load_balancers,
            alc_marker_path=['NextMarker'],
            alc_data_path=['LoadBalancers'],
            alc_marker_param='Marker'
        )
        logger.debug(
            'Checking usage for each of %d ALBs', len(lbs['LoadBalancers'])
        )
        alb_count = 0
        nlb_count = 0
        for lb in lbs['LoadBalancers']:
            if lb.get('Type') == 'network':
                nlb_count += 1
            else:
                alb_count += 1
                self._update_usage_for_alb(
                    conn2,
                    lb['LoadBalancerArn'],
                    lb['LoadBalancerName']
                )
        self.limits['Network load balancers']._add_current_usage(
            nlb_count,
            aws_type='AWS::ElasticLoadBalancing::NetworkLoadBalancer'
        )
        logger.debug('Done with ELBv2 usage')
        return alb_count
375456
def _build_instance_common_args(self, ec2_keyname, availability_zone,
                                    keep_alive, hadoop_version):
        
        params = {
            'Instances.KeepJobFlowAliveWhenNoSteps' : str(keep_alive).lower(),
        }

        if hadoop_version:
            params['Instances.HadoopVersion'] = hadoop_version
        if ec2_keyname:
            params['Instances.Ec2KeyName'] = ec2_keyname
        if availability_zone:
            params['Instances.Placement.AvailabilityZone'] = availability_zone

        return params
309534
def _find_usage_subnets(self):
        """"""
        # subnets per VPC
        subnet_to_az = {}
        subnets = defaultdict(int)
        for subnet in self.conn.describe_subnets()['Subnets']:
            subnets[subnet['VpcId']] += 1
            subnet_to_az[subnet['SubnetId']] = subnet['AvailabilityZone']
        for vpc_id in subnets:
            self.limits['Subnets per VPC']._add_current_usage(
                subnets[vpc_id],
                aws_type='AWS::EC2::VPC',
                resource_id=vpc_id
            )
        return subnet_to_az
64385
def _find_usage_spot_instances(self):
        """"""
        logger.debug('Getting spot instance request usage')
        try:
            res = self.conn.describe_spot_instance_requests()
        except botocore.exceptions.ClientError as e:
            if e.response['Error']['Code'] == 'UnsupportedOperation':
                return
            raise
        count = 0
        for req in res['SpotInstanceRequests']:
            if req['State'] in ['open', 'active']:
                count += 1
                logger.debug('Counting spot instance request %s state=%s',
                             req['SpotInstanceRequestId'], req['State'])
            else:
                logger.debug('NOT counting spot instance request %s state=%s',
                             req['SpotInstanceRequestId'], req['State'])
        self.limits['Max spot instance requests per region']._add_current_usage(
            count,
            aws_type='AWS::EC2::SpotInstanceRequest'
        )
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
755212
def list_buckets(self, instance):
        
        # Server does not do pagination on listings of this resource.
        # Return an iterator anyway for similarity with other API methods
        response = self._client.get_proto(path='/buckets/' + instance)
        message = rest_pb2.ListBucketsResponse()
        message.ParseFromString(response.content)
        buckets = getattr(message, 'bucket')
        return iter([
            Bucket(bucket, instance, self) for bucket in buckets])
707772
def _find_usage_vpcs(self):
        """"""
        # overall number of VPCs
        vpcs = self.conn.describe_vpcs()
        self.limits['VPCs']._add_current_usage(
            len(vpcs['Vpcs']),
            aws_type='AWS::EC2::VPC'
        )
688233
def _get_deployment_instance_summary(awsclient, deployment_id, instance_id):
    
    client_codedeploy = awsclient.get_client('codedeploy')
    request = {
        'deploymentId': deployment_id,
        'instanceId': instance_id
    }
    response = client_codedeploy.get_deployment_instance(**request)
    return response['instanceSummary']['status'], \
           response['instanceSummary']['lifecycleEvents'][-1]['lifecycleEventName']
1359149
def show_instance(name, call=None):
    '''
    
    '''
    node = get_node(name)
    ret = query(command='my/machines/{0}'.format(node['id']),
                location=node['location'], method='GET')

    return ret
479719
def _build_instance_count_and_type_args(self, master_instance_type,
                                            slave_instance_type, num_instances):
        
        params = {
            'Instances.MasterInstanceType' : master_instance_type,
            'Instances.SlaveInstanceType' : slave_instance_type,
            'Instances.InstanceCount' : num_instances,
            }
        return params
311133
def _extract_instance_info(instances):
    '''
    
    '''
    ret = {}
    for instance in instances:
        # items could be type dict or list (for stopped EC2 instances)
        if isinstance(instance['instancesSet']['item'], list):
            for item in instance['instancesSet']['item']:
                name = _extract_name_tag(item)
                ret[name] = item
                ret[name]['name'] = name
                ret[name].update(
                    dict(
                        id=item['instanceId'],
                        image=item['imageId'],
                        size=item['instanceType'],
                        state=item['instanceState']['name'],
                        private_ips=item.get('privateIpAddress', []),
                        public_ips=item.get('ipAddress', [])
                    )
                )
        else:
            item = instance['instancesSet']['item']
            name = _extract_name_tag(item)
            ret[name] = item
            ret[name]['name'] = name
            ret[name].update(
                dict(
                    id=item['instanceId'],
                    image=item['imageId'],
                    size=item['instanceType'],
                    state=item['instanceState']['name'],
                    private_ips=item.get('privateIpAddress', []),
                    public_ips=item.get('ipAddress', [])
                )
            )

    return ret