find usage for Internet Gateways
18419
def _find_usage_gateways(self):
        """"""
        # Internet gateways
        gws = self.conn.describe_internet_gateways()
        self.limits['Internet gateways']._add_current_usage(
            len(gws['InternetGateways']),
            aws_type='AWS::EC2::InternetGateway',
        )
287396
def find_usage(self):
        
        logger.debug("Checking usage for service %s", self.service_name)
        self.connect()
        for lim in self.limits.values():
            lim._reset_usage()
        self._find_usage_applications()
        self._find_usage_application_versions()
        self._find_usage_environments()
        self._have_usage = True
        logger.debug("Done checking usage.")
1169424
def _find_usage_environments(self):
        """"""
        environments = self.conn.describe_environments()
        self.limits['Environments']._add_current_usage(
            len(environments['Environments']),
            aws_type='AWS::ElasticBeanstalk::Environment',
        )
995158
def find_usage(self):
        
        ignore_statuses = [
            'DELETE_COMPLETE'
        ]
        logger.debug("Checking usage for service %s", self.service_name)
        self.connect()
        for lim in self.limits.values():
            lim._reset_usage()
        count = 0
        paginator = self.conn.get_paginator('describe_stacks')
        iter = paginator.paginate()
        for page in iter:
            for stk in page['Stacks']:
                if stk['StackStatus'] not in ignore_statuses:
                    count += 1
        self.limits['Stacks']._add_current_usage(
            count, aws_type='AWS::CloudFormation::Stack'
        )
        self._have_usage = True
        logger.debug("Done checking usage.")
510654
def _interfaces_ip(out):
    
    ret = dict()

    def parse_network(value, cols):
        """
        Return a tuple of ip, netmask, broadcast
        based on the current set of cols
        """
        brd = None
        if '/' in value:  # we have a CIDR in this address
            ip, cidr = value.split('/')  # pylint: disable=C0103
        else:
            ip = value  # pylint: disable=C0103
            cidr = 32

        if type_ == 'inet':
            mask = cidr_to_ipv4_netmask(int(cidr))
            if 'brd' in cols:
                brd = cols[cols.index('brd') + 1]
        elif type_ == 'inet6':
            mask = cidr
        return (ip, mask, brd)

    groups = re.compile('\r?\n\\d').split(out)
    for group in groups:
        iface = None
        data = dict()

        for line in group.splitlines():
            if ' ' not in line:
                continue
            match = re.match(r'^\d*:\s+([\w.\-]+)(?:@)?([\w.\-]+)?:\s+<(.+)>', line)
            if match:
                iface, parent, attrs = match.groups()
                if 'UP' in attrs.split(','):
                    data['up'] = True
                else:
                    data['up'] = False
                if parent:
                    data['parent'] = parent
                continue

            cols = line.split()
            if len(cols) >= 2:
                type_, value = tuple(cols[0:2])
                iflabel = cols[-1:][0]
                if type_ in ('inet', 'inet6'):
                    if 'secondary' not in cols:
                        ipaddr, netmask, broadcast = parse_network(value, cols)
                        if type_ == 'inet':
                            if 'inet' not in data:
                                data['inet'] = list()
                            addr_obj = dict()
                            addr_obj['address'] = ipaddr
                            addr_obj['netmask'] = netmask
                            addr_obj['broadcast'] = broadcast
                            addr_obj['label'] = iflabel
                            data['inet'].append(addr_obj)
                        elif type_ == 'inet6':
                            if 'inet6' not in data:
                                data['inet6'] = list()
                            addr_obj = dict()
                            addr_obj['address'] = ipaddr
                            addr_obj['prefixlen'] = netmask
                            data['inet6'].append(addr_obj)
                    else:
                        if 'secondary' not in data:
                            data['secondary'] = list()
                        ip_, mask, brd = parse_network(value, cols)
                        data['secondary'].append({
                            'type': type_,
                            'address': ip_,
                            'netmask': mask,
                            'broadcast': brd,
                            'label': iflabel,
                        })
                        del ip_, mask, brd
                elif type_.startswith('link'):
                    data['hwaddr'] = value
        if iface:
            ret[iface] = data
            del iface, data
    return ret
1279583
def _usage_specific(raw):
    '''
    
    '''
    get_key = lambda val: dict([tuple(val.split(":")), ])
    raw = raw.split("\n")
    section, size, used = raw[0].split(" ")
    section = section.replace(",", "_").replace(":", "").lower()

    data = {}
    data[section] = {}

    for val in [size, used]:
        data[section].update(get_key(val.replace(",", "")))

    for devices in raw[1:]:
        data[section].update(get_key(re.sub(r"\s+", ":", devices.strip())))

    return data
1279087
def computer_application_usage(ident, start_date, end_date = nil)
      JSS::Computer.application_usage ident, start_date, end_date, api: self
    end
1370875
def _find_usage_route_tables(self):
        """"""
        # Route tables per VPC
        tables = defaultdict(int)
        for table in self.conn.describe_route_tables()['RouteTables']:
            tables[table['VpcId']] += 1
            # Entries per route table
            routes = [
                r for r in table['Routes']
                if r['Origin'] != 'EnableVgwRoutePropagation'
            ]
            self.limits['Entries per route table']._add_current_usage(
                len(routes),
                aws_type='AWS::EC2::RouteTable',
                resource_id=table['RouteTableId']
            )
        for vpc_id in tables:
            self.limits['Route tables per VPC']._add_current_usage(
                tables[vpc_id],
                aws_type='AWS::EC2::VPC',
                resource_id=vpc_id,
            )
988936
def _find_usage_clusters(self):
        
        count = 0
        fargate_task_count = 0
        paginator = self.conn.get_paginator('list_clusters')
        for page in paginator.paginate():
            for cluster_arn in page['clusterArns']:
                count += 1
                resp = self.conn.describe_clusters(
                    clusters=[cluster_arn], include=['STATISTICS']
                )
                cluster = resp['clusters'][0]
                self.limits[
                    'Container Instances per Cluster'
                ]._add_current_usage(
                    cluster['registeredContainerInstancesCount'],
                    aws_type='AWS::ECS::ContainerInstance',
                    resource_id=cluster['clusterName']
                )
                self.limits['Services per Cluster']._add_current_usage(
                    cluster['activeServicesCount'],
                    aws_type='AWS::ECS::Service',
                    resource_id=cluster['clusterName']
                )
                # Note: 'statistics' is not always present in API responses,
                # even if requested. As far as I can tell, it's omitted if
                # a cluster has no Fargate tasks.
                for stat in cluster.get('statistics', []):
                    if stat['name'] != 'runningFargateTasksCount':
                        continue
                    logger.debug(
                        'Found %s Fargate tasks in cluster %s',
                        stat['value'], cluster_arn
                    )
                    fargate_task_count += int(stat['value'])
                self._find_usage_one_cluster(cluster['clusterName'])
        self.limits['Fargate Tasks']._add_current_usage(
            fargate_task_count, aws_type='AWS::ECS::Task'
        )
        self.limits['Clusters']._add_current_usage(
            count, aws_type='AWS::ECS::Cluster'
        )
741241
def ip_monitor(self, query, days_back=0, page=1, **kwargs):
        """"""
        return self._results('ip-monitor', '/v1/ip-monitor', query=query, days_back=days_back, page=page,
                            items_path=('alerts', ), **kwargs)
448107
def determine_ip_address():
    """"""
    addrs = [
        x.address for k, v in psutil.net_if_addrs().items() if k[0] == "e"
        for x in v if x.family == AddressFamily.AF_INET
    ]
    return addrs[0]
1162132
def find_usage(self):
        
        logger.debug("Checking usage for service %s", self.service_name)
        self.connect()
        for lim in self.limits.values():
            lim._reset_usage()
        self._find_usage_vpcs()
        subnet_to_az = self._find_usage_subnets()
        self._find_usage_ACLs()
        self._find_usage_route_tables()
        self._find_usage_gateways()
        self._find_usage_nat_gateways(subnet_to_az)
        self._find_usages_vpn_gateways()
        self._find_usage_network_interfaces()
        self._have_usage = True
        logger.debug("Done checking usage.")
479530
def find_usage(self):
        
        logger.debug("Checking usage for service %s", self.service_name)
        self.connect()
        for lim in self.limits.values():
            lim._reset_usage()
        self._find_cluster_manual_snapshots()
        self._find_cluster_subnet_groups()
        self._have_usage = True
        logger.debug("Done checking usage.")
958287
def find_usage(self):
        
        logger.debug("Checking usage for service %s", self.service_name)
        self.connect()
        for lim in self.limits.values():
            lim._reset_usage()
        self._find_usage_nodes()
        self._find_usage_subnet_groups()
        self._find_usage_parameter_groups()
        self._find_usage_security_groups()
        self._have_usage = True
        logger.debug("Done checking usage.")
1034727
def _find_usage_apis(self):
        
        api_ids = []
        logger.debug('Finding usage for APIs')
        regional_count = 0
        private_count = 0
        edge_count = 0
        paginator = self.conn.get_paginator('get_rest_apis')
        for resp in paginator.paginate():
            for api in resp['items']:
                api_ids.append(api['id'])
                epconf = api.get('endpointConfiguration', {}).get('types', [])
                if epconf == ['PRIVATE']:
                    private_count += 1
                elif epconf == ['EDGE']:
                    edge_count += 1
                else:
                    regional_count += 1
        self.limits['Regional APIs per account']._add_current_usage(
            regional_count, aws_type='AWS::ApiGateway::RestApi'
        )
        self.limits['Private APIs per account']._add_current_usage(
            private_count, aws_type='AWS::ApiGateway::RestApi'
        )
        self.limits['Edge APIs per account']._add_current_usage(
            edge_count, aws_type='AWS::ApiGateway::RestApi'
        )
        logger.debug('Found %d APIs', len(api_ids))
        # now the per-API limits...
        warn_stages_paginated = None
        logger.debug('Finding usage for per-API limits')
        for api_id in api_ids:
            res_count = 0
            paginator = self.conn.get_paginator('get_resources')
            for resp in paginator.paginate(restApiId=api_id):
                res_count += len(resp['items'])
            self.limits['Resources per API']._add_current_usage(
                res_count, resource_id=api_id,
                aws_type='AWS::ApiGateway::Resource'
            )
            doc_parts = paginate_dict(
                self.conn.get_documentation_parts,
                restApiId=api_id,
                alc_marker_path=['position'],
                alc_data_path=['items'],
                alc_marker_param='position'
            )
            self.limits['Documentation parts per API']._add_current_usage(
                len(doc_parts), resource_id=api_id,
                aws_type='AWS::ApiGateway::DocumentationPart'
            )
            # note that per the boto3 docs, there's no pagination of this...
            stages = self.conn.get_stages(restApiId=api_id)
            if len(set(stages.keys()) - set(['item', 'ResponseMetadata'])) > 0:
                warn_stages_paginated = stages.keys()
            self.limits['Stages per API']._add_current_usage(
                len(stages['item']), resource_id=api_id,
                aws_type='AWS::ApiGateway::Stage'
            )
            authorizers = paginate_dict(
                self.conn.get_authorizers,
                restApiId=api_id,
                alc_marker_path=['position'],
                alc_data_path=['items'],
                alc_marker_param='position'
            )
            self.limits['Custom authorizers per API']._add_current_usage(
                len(authorizers), resource_id=api_id,
                aws_type='AWS::ApiGateway::Authorizer'
            )
        if warn_stages_paginated is not None:
            logger.warning(
                'APIGateway get_stages returned more keys than present in '
                'boto3 docs: %s', sorted(warn_stages_paginated)
            )
941811
def find_usage(self):
        
        logger.debug("Checking usage for service %s", self.service_name)
        self.connect()
        for lim in self.limits.values():
            lim._reset_usage()
        try:
            self._find_usage_filesystems()
        except (EndpointConnectionError, ClientError, ConnectTimeout) as ex:
            logger.warning(
                'Caught exception when trying to use EFS ('
                'perhaps the EFS service is not available in this '
                'region?): %s', ex
            )
        self._have_usage = True
        logger.debug("Done checking usage.")
515426
def _find_usage_network_interfaces(self):
        """"""
        enis = paginate_dict(
            self.conn.describe_network_interfaces,
            alc_marker_path=['NextToken'],
            alc_data_path=['NetworkInterfaces'],
            alc_marker_param='NextToken'
        )

        self.limits['Network interfaces per Region']._add_current_usage(
            len(enis['NetworkInterfaces']),
            aws_type='AWS::EC2::NetworkInterface'
        )