INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Determine the current usage for each limit of this service and update corresponding Limit via: py: meth: ~. AwsLimit. _add_current_usage. | def find_usage(self):
"""
Determine the current usage for each limit of this service,
and update corresponding Limit via
:py:meth:`~.AwsLimit._add_current_usage`.
"""
logger.debug("Checking usage for service %s", self.service_name)
for lim in self.limits.values():... |
Find usage for ELBv1/ Classic ELB and update the appropriate limits. | def _find_usage_elbv1(self):
"""
Find usage for ELBv1 / Classic ELB and update the appropriate limits.
:returns: number of Classic ELBs in use
:rtype: int
"""
logger.debug("Checking usage for ELBv1")
self.connect()
lbs = paginate_dict(
self.co... |
Find usage for ELBv2/ Application LB and update the appropriate limits. | def _find_usage_elbv2(self):
"""
Find usage for ELBv2 / Application LB and update the appropriate limits.
:returns: number of Application LBs in use
:rtype: int
"""
logger.debug('Checking usage for ELBv2')
conn2 = client(
'elbv2',
config=C... |
Update usage for a single ALB. | def _update_usage_for_alb(self, conn, alb_arn, alb_name):
"""
Update usage for a single ALB.
:param conn: elbv2 API connection
:type conn: :py:class:`ElasticLoadBalancing.Client`
:param alb_arn: Load Balancer ARN
:type alb_arn: str
:param alb_name: Load Balancer ... |
Update usage for a single NLB. | def _update_usage_for_nlb(self, conn, nlb_arn, nlb_name):
"""
Update usage for a single NLB.
:param conn: elbv2 API connection
:type conn: :py:class:`ElasticLoadBalancing.Client`
:param nlb_arn: Load Balancer ARN
:type nlb_arn: str
:param nlb_name: Load Balancer ... |
Query ELB s DescribeAccountLimits API action and update limits with the quotas returned. Updates self. limits. | def _update_limits_from_api(self):
"""
Query ELB's DescribeAccountLimits API action, and update limits
with the quotas returned. Updates ``self.limits``.
"""
self.connect()
logger.debug("Querying ELB DescribeAccountLimits for limits")
attribs = self.conn.describe_... |
Take a dict of string keys and string values and return a string with them formatted as two columns separated by at least spaces number of separator characters. | def dict2cols(d, spaces=2, separator=' '):
"""
Take a dict of string keys and string values, and return a string with
them formatted as two columns separated by at least ``spaces`` number of
``separator`` characters.
:param d: dict of string keys, string values
:type d: dict
:param spaces: ... |
Paginate through a query that returns a dict result and return the combined result. | def paginate_dict(function_ref, *argv, **kwargs):
"""
Paginate through a query that returns a dict result, and return the
combined result.
Note that this function requires some special kwargs to be passed in:
* __alc_marker_path__ - The dictionary path to the Marker for the next
result set. ... |
Given a dict ( d ) and a list specifying the hierarchical path to a key in that dict ( path ) return the value at that path or None if it does not exist. | def _get_dict_value_by_path(d, path):
"""
Given a dict (``d``) and a list specifying the hierarchical path to a key
in that dict (``path``), return the value at that path or None if it does
not exist.
:param d: the dict to search in
:type d: dict
:param path: the path to the key in the dict... |
Given a dict ( d ) a value ( val ) and a list specifying the hierarchical path to a key in that dict ( path ) set the value in d at path to val. | def _set_dict_value_by_path(d, val, path):
"""
Given a dict (``d``), a value (``val``), and a list specifying the
hierarchical path to a key in that dict (``path``), set the value in ``d``
at ``path`` to ``val``.
:param d: the dict to search in
:type d: dict
:param path: the path to the ke... |
Generate keyword arguments for boto3 connection functions. | def _boto_conn_kwargs(self):
"""
Generate keyword arguments for boto3 connection functions.
If ``self.account_id`` is defined, this will call
:py:meth:`~._get_sts_token` to get STS token credentials using
`boto3.STS.Client.assume_role <https://boto3.readthedocs.org/en/
l... |
Remove all service names specified in services_to_remove from self. services. This allows explicitly removing certain services from ever being checked or otherwise handled. | def remove_services(self, services_to_remove=[]):
"""
Remove all service names specified in ``services_to_remove`` from
``self.services``. This allows explicitly removing certain services from
ever being checked or otherwise handled.
By default, the various methods that work on ... |
Assume a role via STS and return the credentials. | def _get_sts_token(self):
"""
Assume a role via STS and return the credentials.
First connect to STS via :py:func:`boto3.client`, then
assume a role using `boto3.STS.Client.assume_role <https://boto3.readthe
docs.org/en/latest/reference/services/sts.html#STS.Client.assume_role>`... |
For each limit in the specified service ( or all services if service is None ) query the AWS API via boto3 and find the current usage amounts for that limit. | def find_usage(self, service=None, use_ta=True):
"""
For each limit in the specified service (or all services if
``service`` is ``None``), query the AWS API via ``boto3``
and find the current usage amounts for that limit.
This method updates the ``current_usage`` attribute of th... |
Set manual overrides on AWS service limits i. e. if you had limits increased by AWS support. This takes a dict in the same form as that returned by: py: meth: ~. get_limits i. e. service_name ( str ) keys to nested dict of limit_name ( str ) to limit value ( int ) like::: | def set_limit_overrides(self, override_dict, override_ta=True):
"""
Set manual overrides on AWS service limits, i.e. if you
had limits increased by AWS support. This takes a dict in
the same form as that returned by :py:meth:`~.get_limits`,
i.e. service_name (str) keys to nested ... |
Set a manual override on an AWS service limits i. e. if you had limits increased by AWS support. | def set_limit_override(self, service_name, limit_name,
value, override_ta=True):
"""
Set a manual override on an AWS service limits, i.e. if you
had limits increased by AWS support.
This method calls :py:meth:`._AwsService.set_limit_override`
on the co... |
Set manual overrides on the threshold ( used for determining warning/ critical status ) a dict of limits. See: py: class: ~. AwsLimitChecker for information on Warning and Critical thresholds. | def set_threshold_overrides(self, override_dict):
"""
Set manual overrides on the threshold (used for determining
warning/critical status) a dict of limits. See
:py:class:`~.AwsLimitChecker` for information on Warning and
Critical thresholds.
Dict is composed of service ... |
Set a manual override on the threshold ( used for determining warning/ critical status ) for a specific limit. See: py: class: ~. AwsLimitChecker for information on Warning and Critical thresholds. | def set_threshold_override(self, service_name, limit_name,
warn_percent=None, warn_count=None,
crit_percent=None, crit_count=None):
"""
Set a manual override on the threshold (used for determining
warning/critical status) for a specif... |
Check all limits and current usage against their specified thresholds ; return all: py: class: ~. AwsLimit instances that have crossed one or more of their thresholds. | def check_thresholds(self, service=None, use_ta=True):
"""
Check all limits and current usage against their specified thresholds;
return all :py:class:`~.AwsLimit` instances that have crossed
one or more of their thresholds.
If ``service`` is specified, the returned dict has one... |
Return an IAM policy granting all of the permissions needed for awslimitchecker to fully function. This returns a dict suitable for json serialization to a valid IAM policy. | def get_required_iam_policy(self):
"""
Return an IAM policy granting all of the permissions needed for
awslimitchecker to fully function. This returns a dict suitable
for json serialization to a valid IAM policy.
Internally, this calls :py:meth:`~._AwsService.required_iam_permis... |
Query Route53 s GetHostedZoneLimit API action and update limits with the quotas returned. Updates self. limits. | def _update_limits_from_api(self):
"""
Query Route53's GetHostedZoneLimit API action, and update limits
with the quotas returned. Updates ``self.limits``.
"""
logger.info("Querying Route53 GetHostedZoneLimits for limits")
self.connect()
self._find_limit_hosted_zon... |
Return all known limits for this service as a dict of their names to: py: class: ~. AwsLimit objects. | def get_limits(self):
"""
Return all known limits for this service, as a dict of their names
to :py:class:`~.AwsLimit` objects.
Limits from:
docs.aws.amazon.com/Route53/latest/DeveloperGuide/DNSLimitations.html
:returns: dict of limit names to :py:class:`~.AwsLimit` obj... |
Return all available hosted zones | def _get_hosted_zones(self):
"""
Return all available hosted zones
:returns: dict of hosted zones
:rtype: dict
"""
results = paginate_dict(
self.conn.list_hosted_zones,
alc_marker_path=['NextMarker'],
alc_data_path=['HostedZones'],
... |
Return a hosted zone limit [ recordsets|vpc_associations ] | def _get_hosted_zone_limit(self, limit_type, hosted_zone_id):
"""
Return a hosted zone limit [recordsets|vpc_associations]
:rtype: dict
"""
result = self.conn.get_hosted_zone_limit(
Type=limit_type,
HostedZoneId=hosted_zone_id
)
return r... |
Calculate the max recordsets and vpc associations and the current values per hosted zone | def _find_limit_hosted_zone(self):
"""
Calculate the max recordsets and vpc associations and the current values
per hosted zone
"""
for limit_type in [self.MAX_RRSETS_BY_ZONE,
self.MAX_VPCS_ASSOCIATED_BY_ZONE]:
self.limits[limit_type["name"]... |
Return the current IAM policy as a json - serialized string | def get_iam_policy(self):
"""Return the current IAM policy as a json-serialized string"""
checker = AwsLimitChecker()
policy = checker.get_required_iam_policy()
return json.dumps(policy, sort_keys=True, indent=2) |
Determine the current usage for each limit of this service and update corresponding Limit via: py: meth: ~. AwsLimit. _add_current_usage. | def find_usage(self):
"""
Determine the current usage for each limit of this service,
and update corresponding Limit via
:py:meth:`~.AwsLimit._add_current_usage`.
"""
logger.debug("Checking usage for service %s", self.service_name)
self.connect_resource()
... |
Check GitHub for a release with the specified tag name. If present return a 2 - tuple of the release name and release HTML URL. Otherwise return a 2 - tuple of None None ( tag not present ). | def get_tag(self, version):
"""
Check GitHub for a release with the specified tag name. If present,
return a 2-tuple of the release name and release HTML URL. Otherwise,
return a 2-tuple of None, None (tag not present).
:param version: the tag name to check for
:type ver... |
Determine the current usage for each limit of this service and update corresponding Limit via: py: meth: ~. AwsLimit. _add_current_usage. | def find_usage(self):
"""
Determine the current usage for each limit of this service,
and update corresponding Limit via
:py:meth:`~.AwsLimit._add_current_usage`.
"""
logger.debug("Checking usage for service %s", self.service_name)
for lim in self.limits.values():... |
Call the service s API action to retrieve limit/ quota information and update AwsLimit objects in self. limits with this information. | def _update_limits_from_api(self):
"""
Call the service's API action to retrieve limit/quota information, and
update AwsLimit objects in ``self.limits`` with this information.
"""
try:
self.connect()
resp = self.conn.get_send_quota()
except Endpoin... |
Connect to an AWS API via boto3 low - level client and set self. conn to the boto3. client <https:// boto3. readthed ocs. org/ en/ latest/ reference/ core/ boto3. html#boto3. client > _ object ( a botocore. client. * instance ). If self. conn is not None do nothing. This connects to the API name given by self. api_name... | def connect(self):
"""
Connect to an AWS API via boto3 low-level client and set ``self.conn``
to the `boto3.client <https://boto3.readthed
ocs.org/en/latest/reference/core/boto3.html#boto3.client>`_ object
(a ``botocore.client.*`` instance). If ``self.conn`` is not None,
... |
Connect to an AWS API via boto3 high - level resource connection and set self. resource_conn to the boto3. resource <https:// boto3. readthed ocs. org/ en/ latest/ reference/ core/ boto3. html#boto3. resource > _ object ( a boto3. resources. factory. *. ServiceResource instance ). If self. resource_conn is not None do ... | def connect_resource(self):
"""
Connect to an AWS API via boto3 high-level resource connection and set
``self.resource_conn`` to the `boto3.resource <https://boto3.readthed
ocs.org/en/latest/reference/core/boto3.html#boto3.resource>`_ object
(a ``boto3.resources.factory.*.Service... |
Determine the current usage for each limit of this service and update corresponding Limit via: py: meth: ~. AwsLimit. _add_current_usage. | def find_usage(self):
"""
Determine the current usage for each limit of this service,
and update corresponding Limit via
:py:meth:`~.AwsLimit._add_current_usage`.
"""
logger.debug("Checking usage for service %s", self.service_name)
self.connect_resource()
... |
calculates current usage for all DynamoDB limits | def _find_usage_dynamodb(self):
"""calculates current usage for all DynamoDB limits"""
table_count = 0
region_read_capacity = 0
region_write_capacity = 0
logger.debug("Getting usage for DynamoDB tables")
for table in self.resource_conn.tables.all():
table_cou... |
Return all known limits for this service as a dict of their names to: py: class: ~. AwsLimit objects. | def get_limits(self):
"""
Return all known limits for this service, as a dict of their names
to :py:class:`~.AwsLimit` objects.
:returns: dict of limit names to :py:class:`~.AwsLimit` objects
:rtype: dict
"""
self.connect()
region_name = self.conn._client... |
Query DynamoDB s DescribeLimits API action and update limits with the quotas returned. Updates self. limits. | def _update_limits_from_api(self):
"""
Query DynamoDB's DescribeLimits API action, and update limits
with the quotas returned. Updates ``self.limits``.
"""
self.connect()
logger.info("Querying DynamoDB DescribeLimits for limits")
# no need to paginate
lims... |
Returns the currently - installed awslimitchecker version and a best - effort attempt at finding the origin URL and commit/ tag if installed from an editable git clone. | def _get_version_info():
"""
Returns the currently-installed awslimitchecker version, and a best-effort
attempt at finding the origin URL and commit/tag if installed from an
editable git clone.
:returns: awslimitchecker version
:rtype: str
"""
if os.environ.get('VERSIONCHECK_DEBUG', '')... |
The version string for the currently - running awslimitchecker ; includes git branch and tag information. | def version_str(self):
"""
The version string for the currently-running awslimitchecker;
includes git branch and tag information.
:rtype: str
"""
vs = str(self.release)
if self.tag is not None:
vs += '@{t}'.format(t=self.tag)
elif self.commit ... |
load configuration from config/ | def _load_config(self):
"""load configuration from config/"""
logger.debug(
'Listing per-account config subdirectories in %s', self._conf_dir
)
for acct_id in os.listdir(self._conf_dir):
path = os.path.join(self._conf_dir, acct_id)
# skip if not a dire... |
load configuration from one per - account subdirectory | def _load_account(self, acct_id, acct_dir_path):
"""load configuration from one per-account subdirectory"""
# setup a default config dict for the account
self._config[acct_id] = {
'name': None,
'role_name': DEFAULT_ROLE_NAME,
'regions': {}
}
# ... |
load config from a single per - region subdirectory of an account | def _load_region(self, acct_id, region_name, path):
"""load config from a single per-region subdirectory of an account"""
lim_path = os.path.join(path, 'limit_overrides.json')
thresh_path = os.path.join(path, 'threshold_overrides.json')
res = {'limit_overrides': {}, 'threshold_overrides'... |
Return a dictionary of account configuration for the account with the specified ID or name. | def get_account_config(self, id_or_name):
"""
Return a dictionary of account configuration for the account with the
specified ID or name.
:param id_or_name: ID or name of account
:type id_or_name: str
:return: configuration for specified account
:rtype: dict
... |
Run the actual usage and limit check with overrides against a specific account in a specific region optionally assuming a role in the account and optionally setting limit and/ or threshold overrides. | def check_limits(self, acct_id, region_name, role_name=None,
limit_overrides={}, threshold_overrides={}):
"""
Run the actual usage and limit check, with overrides, against a specific
account in a specific region, optionally assuming a role in the account
and optional... |
Main entry point. | def run(self, error_on_warning=False, region=None, accounts=[]):
"""
Main entry point.
"""
all_warnings = []
all_criticals = []
if len(accounts) == 0:
# if no accounts specified, run all of them
accounts = self._conf.list_account_ids
for ac... |
calculate usage for all EBS limits and update Limits | def _find_usage_ebs(self):
"""calculate usage for all EBS limits and update Limits"""
vols = 0
piops = 0
piops_gb = 0
gp_gb = 0
mag_gb = 0
st_gb = 0
sc_gb = 0
logger.debug("Getting usage for EBS volumes")
results = paginate_dict(
... |
find snapshot usage | def _find_usage_snapshots(self):
"""find snapshot usage"""
logger.debug("Getting usage for EBS snapshots")
snaps = paginate_dict(
self.conn.describe_snapshots,
OwnerIds=['self'],
alc_marker_path=['NextToken'],
alc_data_path=['Snapshots'],
... |
Return all known limits for this service as a dict of their names to: py: class: ~. AwsLimit objects. | def get_limits(self):
"""
Return all known limits for this service, as a dict of their names
to :py:class:`~.AwsLimit` objects.
:returns: dict of limit names to :py:class:`~.AwsLimit` objects
:rtype: dict
"""
if self.limits != {}:
return self.limits
... |
Return a dict of EBS - related limits only. This method should only be used internally by: py: meth: ~. get_limits. | def _get_limits_ebs(self):
"""
Return a dict of EBS-related limits only.
This method should only be used internally by
:py:meth:~.get_limits`.
:rtype: dict
"""
limits = {}
limits['Provisioned IOPS'] = AwsLimit(
'Provisioned IOPS',
... |
Run the actual usage and limit check with overrides. | def check_limits(self, verbose=False):
"""
Run the actual usage and limit check, with overrides.
see: http://awslimitchecker.readthedocs.org/en/latest/python_usage.html#ci-deployment-checks
"""
# instantiate the class
checker = AwsLimitChecker()
# set your overri... |
Main entry point. | def run(self, error_on_warning=False, verbose=False):
"""
Main entry point.
"""
warnings, criticals = self.check_limits(verbose=verbose)
# output
if len(warnings) > 0:
print("\nWARNING:\n")
for w in warnings:
print(w)
if len... |
Set a new limit value for the specified limit overriding the default. If override_ta is True also use this value instead of any found by Trusted Advisor. This method simply passes the data through to the: py: meth: ~awslimitchecker. limit. AwsLimit. set_limit_override method of the underlying: py: class: ~. AwsLimit in... | def set_limit_override(self, limit_name, value, override_ta=True):
"""
Set a new limit ``value`` for the specified limit, overriding
the default. If ``override_ta`` is True, also use this value
instead of any found by Trusted Advisor. This method simply
passes the data through to... |
Set the value for the limit as reported by Trusted Advisor for the specified limit. | def _set_ta_limit(self, limit_name, value):
"""
Set the value for the limit as reported by Trusted Advisor,
for the specified limit.
This method should only be called by :py:class:`~.TrustedAdvisor`.
:param limit_name: the name of the limit to override the value for
:ty... |
Override the default warning and critical thresholds used to evaluate the specified limit s usage. Theresholds can be specified as a percentage of the limit or as a usage count or both. | def set_threshold_override(self, limit_name, warn_percent=None,
warn_count=None, crit_percent=None,
crit_count=None):
"""
Override the default warning and critical thresholds used to evaluate
the specified limit's usage. Theresholds c... |
Checks current usage against configured thresholds for all limits for this service. | def check_thresholds(self):
"""
Checks current usage against configured thresholds for all limits
for this service.
:returns: a dict of limit name to :py:class:`~.AwsLimit` instance
for all limits that crossed one or more of their thresholds.
:rtype: :py:obj:`dict` of ... |
Determine the current usage for each limit of this service and update corresponding Limit via: py: meth: ~. AwsLimit. _add_current_usage. | def find_usage(self):
"""
Determine the current usage for each limit of this service,
and update corresponding Limit via
:py:meth:`~.AwsLimit._add_current_usage`.
"""
logger.debug("Checking usage for service %s", self.service_name)
self.connect()
for lim i... |
Generate a node that references a label | def label_ref_node(docname, ref_to, title):
"""Generate a node that references a label"""
txt = Text(title, rawsource=title)
newchild = inline(
':ref:`%s`' % ref_to,
'',
txt,
classes=['xref', 'std', 'std-ref']
)
newnode = pending_xref(
':ref:`%s`' % ref_to,
... |
When the doctree has been read in and include directives have been executed and replaced with the included file walk the tree via LinkToRefVisitor. | def on_doctree_read(_, doctree):
"""
When the doctree has been read in, and ``include`` directives have been
executed and replaced with the included file, walk the tree via
LinkToRefVisitor.
"""
docname = os.path.splitext(
os.path.basename(doctree.attributes['source']))[0]
if docname... |
When we find a target node first make sure it matches the last reference node we saw. Assuming it does see if its refuri ( link URI ) is in our replacement list. If so replace the link with an internal reference. | def visit_target(self, node):
"""
When we find a target node, first make sure it matches the last
reference node we saw. Assuming it does, see if its refuri (link URI)
is in our replacement list. If so, replace the link with an internal
reference.
"""
if self.last... |
Determine the current usage for each limit of this service and update corresponding Limit via: py: meth: ~. AwsLimit. _add_current_usage. | def find_usage(self):
"""
Determine the current usage for each limit of this service,
and update corresponding Limit via
:py:meth:`~.AwsLimit._add_current_usage`.
"""
logger.debug("Checking usage for service %s", self.service_name)
self.connect()
self.conn... |
calculate On - Demand instance usage for all types and update Limits | def _find_usage_instances(self):
"""calculate On-Demand instance usage for all types and update Limits"""
# update our limits with usage
inst_usage = self._instance_usage()
res_usage = self._get_reserved_instance_count()
logger.debug('Reserved instance count: %s', res_usage)
... |
calculate spot instance request usage and update Limits | def _find_usage_spot_instances(self):
"""calculate spot instance request usage and update Limits"""
logger.debug('Getting spot instance request usage')
try:
res = self.conn.describe_spot_instance_requests()
except botocore.exceptions.ClientError as e:
if e.respons... |
calculate spot fleet request usage and update Limits | def _find_usage_spot_fleets(self):
"""calculate spot fleet request usage and update Limits"""
logger.debug('Getting spot fleet request usage')
try:
res = self.conn.describe_spot_fleet_requests()
except botocore.exceptions.ClientError as e:
if e.response['Error']['... |
For each availability zone get the count of current instance reservations of each instance type. Return as a nested dict of AZ name to dict of instance type to reservation count. | def _get_reserved_instance_count(self):
"""
For each availability zone, get the count of current instance
reservations of each instance type. Return as a nested
dict of AZ name to dict of instance type to reservation count.
:rtype: dict
"""
reservations = default... |
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. | def _instance_usage(self):
"""
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
"""
# On-De... |
Return all known limits for this service as a dict of their names to: py: class: ~. AwsLimit objects. | def get_limits(self):
"""
Return all known limits for this service, as a dict of their names
to :py:class:`~.AwsLimit` objects.
:returns: dict of limit names to :py:class:`~.AwsLimit` objects
:rtype: dict
"""
if self.limits != {}:
return self.limits
... |
Query EC2 s DescribeAccountAttributes API action and update limits with the quotas returned. Updates self. limits. | def _update_limits_from_api(self):
"""
Query EC2's DescribeAccountAttributes API action, and update limits
with the quotas returned. Updates ``self.limits``.
"""
self.connect()
self.connect_resource()
logger.info("Querying EC2 DescribeAccountAttributes for limits"... |
Return a dict of limits for EC2 instances only. This method should only be used internally by: py: meth: ~. get_limits. | def _get_limits_instances(self):
"""
Return a dict of limits for EC2 instances only.
This method should only be used internally by
:py:meth:~.get_limits`.
:rtype: dict
"""
# from: http://aws.amazon.com/ec2/faqs/
# (On-Demand, Reserved, Spot)
defau... |
Return a dict of limits for spot requests only. This method should only be used internally by: py: meth: ~. get_limits. | def _get_limits_spot(self):
"""
Return a dict of limits for spot requests only.
This method should only be used internally by
:py:meth:~.get_limits`.
:rtype: dict
"""
limits = {}
limits['Max spot instance requests per region'] = AwsLimit(
'Max... |
calculate usage for VPC - related things | def _find_usage_networking_sgs(self):
"""calculate usage for VPC-related things"""
logger.debug("Getting usage for EC2 VPC resources")
sgs_per_vpc = defaultdict(int)
rules_per_sg = defaultdict(int)
for sg in self.resource_conn.security_groups.all():
if sg.vpc_id is no... |
Return a dict of VPC - related limits only. This method should only be used internally by: py: meth: ~. get_limits. | def _get_limits_networking(self):
"""
Return a dict of VPC-related limits only.
This method should only be used internally by
:py:meth:~.get_limits`.
:rtype: dict
"""
limits = {}
limits['Security groups per VPC'] = AwsLimit(
'Security groups p... |
Return a list of all known EC2 instance types | def _instance_types(self):
"""
Return a list of all known EC2 instance types
:returns: list of all valid known EC2 instance types
:rtype: list
"""
GENERAL_TYPES = [
'a1.2xlarge',
'a1.4xlarge',
'a1.large',
'a1.medium',
... |
Determine the current usage for each limit of this service and update corresponding Limit via: py: meth: ~. AwsLimit. _add_current_usage. | def find_usage(self):
"""
Determine the current usage for each limit of this service,
and update corresponding Limit via
:py:meth:`~.AwsLimit._add_current_usage`.
"""
logger.debug("Checking usage for service %s", self.service_name)
self.connect()
for lim i... |
find usage for DB Instances and related limits | def _find_usage_instances(self):
"""find usage for DB Instances and related limits"""
paginator = self.conn.get_paginator('describe_db_instances')
for page in paginator.paginate():
for instance in page['DBInstances']:
self.limits['Read replicas per master']._add_curre... |
find usage for subnet groups | def _find_usage_subnet_groups(self):
"""find usage for subnet groups"""
paginator = self.conn.get_paginator('describe_db_subnet_groups')
for page in paginator.paginate():
for group in page['DBSubnetGroups']:
self.limits['Subnets per Subnet Group']._add_current_usage(
... |
find usage for security groups | def _find_usage_security_groups(self):
"""find usage for security groups"""
vpc_count = 0
paginator = self.conn.get_paginator('describe_db_security_groups')
for page in paginator.paginate():
for group in page['DBSecurityGroups']:
if 'VpcId' in group and group... |
Return all known limits for this service as a dict of their names to: py: class: ~. AwsLimit objects. | def get_limits(self):
"""
Return all known limits for this service, as a dict of their names
to :py:class:`~.AwsLimit` objects.
:returns: dict of limit names to :py:class:`~.AwsLimit` objects
:rtype: dict
"""
if self.limits != {}:
return self.limits
... |
Query RDS s DescribeAccountAttributes API action and update limits with the quotas returned. Updates self. limits. | def _update_limits_from_api(self):
"""
Query RDS's DescribeAccountAttributes API action, and update limits
with the quotas returned. Updates ``self.limits``.
We ignore the usage information from the API,
"""
self.connect()
logger.info("Querying RDS DescribeAccoun... |
Determine the current usage for each limit of this service and update corresponding Limit via: py: meth: ~. AwsLimit. _add_current_usage. | def find_usage(self):
"""
Determine the current usage for each limit of this service,
and update corresponding Limit via
:py:meth:`~.AwsLimit._add_current_usage`.
"""
logger.debug("Checking usage for service %s", self.service_name)
self.connect()
for lim i... |
Calculate current usage for CloudTrail related metrics | def _find_usage_cloudtrail(self):
"""Calculate current usage for CloudTrail related metrics"""
trail_list = self.conn.describe_trails()['trailList']
trail_count = len(trail_list) if trail_list else 0
for trail in trail_list:
data_resource_count = 0
if self.conn.... |
Return all known limits for this service as a dict of their names to: py: class: ~. AwsLimit objects. | def get_limits(self):
"""
Return all known limits for this service, as a dict of their names
to :py:class:`~.AwsLimit` objects.
:returns: dict of limit names to :py:class:`~.AwsLimit` objects
:rtype: dict
"""
logger.debug("Gathering %s's limits from AWS", self.se... |
Initializes a new plot object with the last available frame. | def initialize_plot(self, ranges=None):
"""
Initializes a new plot object with the last available frame.
"""
# Get element key and ranges for frame
fig = self.generate_plot(self.keys[-1], ranges)
self.drawn = True
return fig |
Returns the dimensions corresponding to each axis. | def _get_axis_dims(self, element):
"""Returns the dimensions corresponding to each axis.
Should return a list of dimensions or list of lists of
dimensions, which will be formatted to label the axis
and to link axes.
"""
dims = element.dimensions()[:3]
pad = [None... |
Updates an existing plot with data corresponding to the key. | def update_frame(self, key, ranges=None, element=None):
"""
Updates an existing plot with data corresponding
to the key.
"""
self.generate_plot(key, ranges, element) |
Initializes a new plot object with the last available frame. | def initialize_plot(self, ranges=None):
"""
Initializes a new plot object with the last available frame.
"""
# Get element key and ranges for frame
return self.generate_plot(list(self.hmap.data.keys())[0], ranges) |
Find the name the user is using to access holoviews. | def get_namespace(self):
"""
Find the name the user is using to access holoviews.
"""
if 'holoviews' not in sys.modules:
raise ImportError('HoloViews does not seem to be imported')
matches = [k for k,v in get_ipython().user_ns.items() # noqa (get_ipython)
i... |
Helper to show the status of the last call to the export method. | def last_export_status(self):
"Helper to show the status of the last call to the export method."
if self.export_success is True:
print("The last call to holoviews.archive.export was successful.")
return
elif self.export_success is None:
print("Status of the la... |
Method to enable or disable automatic capture allowing you to simultaneously set the instance parameters. | def auto(self, enabled=True, **kwargs):
"""
Method to enable or disable automatic capture, allowing you to
simultaneously set the instance parameters.
"""
self.namespace = self.get_namespace()
self.notebook_name = "{notebook}"
self._timestamp = tuple(time.localtim... |
Get the current notebook data and export. | def export(self, timestamp=None):
"""
Get the current notebook data and export.
"""
if self._timestamp is None:
raise Exception("No timestamp set. Has the archive been initialized?")
if self.skip_notebook_export:
super(NotebookArchive, self).export(timesta... |
Similar to FileArchive. add but accepts html strings for substitution | def add(self, obj=None, filename=None, data=None, info={}, html=None):
"Similar to FileArchive.add but accepts html strings for substitution"
initial_last_key = list(self._files.keys())[-1] if len(self) else None
if self._auto:
exporters = self.exporters[:]
# Can only ass... |
Computes substitutions before using nbconvert with preprocessors | def _export_with_html(self): # pragma: no cover
"Computes substitutions before using nbconvert with preprocessors"
self.export_success = False
try:
tstamp = time.strftime(self.timestamp_format, self._timestamp)
substitutions = {}
for (basena... |
Load captured notebook node | def _get_notebook_node(self): # pragma: no cover
"Load captured notebook node"
size = len(self._notebook_data)
if size == 0:
raise Exception("Captured buffer size for notebook node is zero.")
node = reader.reads(self._notebook_data)
self.nbversion = ... |
Utility to process style properties converting any matplotlib specific options to their nearest bokeh equivalent. | def mpl_to_bokeh(properties):
"""
Utility to process style properties converting any
matplotlib specific options to their nearest bokeh
equivalent.
"""
new_properties = {}
for k, v in properties.items():
if isinstance(v, dict):
new_properties[k] = v
elif k == 's':... |
Validates a style and associated value. | def validate(style, value, scalar=False):
"""
Validates a style and associated value.
Arguments
---------
style: str
The style to validate (e.g. 'color', 'size' or 'marker')
value:
The style value to validate
scalar: bool
Returns
-------
valid: boolean or None
... |
Ensures RGB ( A ) tuples in the range 0 - 1 are scaled to 0 - 255. | def rgba_tuple(rgba):
"""
Ensures RGB(A) tuples in the range 0-1 are scaled to 0-255.
"""
if isinstance(rgba, tuple):
return tuple(int(c*255) if i<3 else c for i, c in enumerate(rgba))
else:
return COLOR_ALIASES.get(rgba, rgba) |
Computes styles applied to a batched plot by iterating over the supplied list of style options and expanding any options found in the supplied style dictionary returning a data and mapping defining the data that should be added to the ColumnDataSource. | def expand_batched_style(style, opts, mapping, nvals):
"""
Computes styles applied to a batched plot by iterating over the
supplied list of style options and expanding any options found in
the supplied style dictionary returning a data and mapping defining
the data that should be added to the Column... |
Classmethod equivalent to unittest. TestCase method ( longMessage = False. ) | def simple_equality(cls, first, second, msg=None):
"""
Classmethod equivalent to unittest.TestCase method (longMessage = False.)
"""
if not first==second:
standardMsg = '%s != %s' % (safe_repr(first), safe_repr(second))
raise cls.failureException(msg or standardMs... |
Classmethod equivalent to unittest. TestCase method | def assertEqual(cls, first, second, msg=None):
"""
Classmethod equivalent to unittest.TestCase method
"""
asserter = None
if type(first) is type(second):
asserter = cls.equality_type_funcs.get(type(first))
try: basestring = basestring # Pytho... |
Returns a Bokeh glyph object. | def _init_glyph(self, plot, mapping, properties):
"""
Returns a Bokeh glyph object.
"""
properties = mpl_to_bokeh(properties)
properties = dict(properties, **mapping)
if 'xs' in mapping:
renderer = plot.patches(**properties)
else:
renderer ... |
Returns true if the given point is contained within the bounding box where all boundaries of the box are considered to be inclusive. | def contains(self, x, y):
"""
Returns true if the given point is contained within the
bounding box, where all boundaries of the box are
considered to be inclusive.
"""
left, bottom, right, top = self.aarect().lbrt()
return (left <= x <= right) and (bottom <= y <= ... |
Return True if the given point is contained within the bounding box where the bottom and right boundaries are considered exclusive. | def contains_exclusive(self, x, y):
"""
Return True if the given point is contained within the
bounding box, where the bottom and right boundaries are
considered exclusive.
"""
left, bottom, right, top = self._aarect.lbrt()
return (left <= x < right) and (bottom <... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.