INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Given an arbitrary resource attempt to resolve back to a qualified name. | def get_name(self, r):
"""Given an arbitrary resource attempt to resolve back to a qualified name."""
namer = ResourceNameAdapters[self.manager.resource_type.service]
return namer(r) |
Main. | def update_headers(src_tree):
"""Main."""
print("src tree", src_tree)
for root, dirs, files in os.walk(src_tree):
py_files = fnmatch.filter(files, "*.py")
for f in py_files:
print("checking", f)
p = os.path.join(root, f)
with open(p) as fh:
... |
Show extant locks and unlocks. | def list_locks(account_id, resource_type=None, resource_id=None):
"""Show extant locks and unlocks.
"""
locks = Client(BASE_URL, account_id).list_locks().json()
for r in locks:
if 'LockDate' in r:
r['LockDate'] = datetime.fromtimestamp(r['LockDate'])
if 'RevisionDate' in r:
... |
Show extant locks status | def lock_status(account_id, resource_id, parent_id):
"""Show extant locks' status
"""
return output(
Client(BASE_URL, account_id).lock_status(resource_id, parent_id)) |
Lock a resource | def lock(account_id, resource_id, region):
"""Lock a resource
"""
return output(
Client(BASE_URL, account_id).lock(resource_id, region)) |
Get extant locks for the given account. | def list_locks(self, account_id=None):
"""Get extant locks for the given account.
"""
account_id = self.get_account_id(account_id)
return self.http.get(
"%s/%s/locks" % (self.endpoint, account_id),
auth=self.get_api_auth()) |
Get the lock status for a given resource. | def lock_status(self, resource_id, parent_id=None, account_id=None):
"""Get the lock status for a given resource.
for security groups, parent id is their vpc.
"""
account_id = self.get_account_id(account_id)
params = parent_id and {'parent_id': parent_id} or None
return ... |
Lock a given resource | def lock(self, resource_id, region, account_id=None):
"""Lock a given resource
"""
account_id = self.get_account_id(account_id)
return self.http.post(
"%s/%s/locks/%s/lock" % (self.endpoint, account_id, resource_id),
json={'region': region},
auth=self.... |
report on a cross account policy execution. | def report(config, output, use, output_dir, accounts,
field, no_default_fields, tags, region, debug, verbose,
policy, policy_tags, format, resource, cache_path):
"""report on a cross account policy execution."""
accounts_config, custodian_config, executor = init(
config, use, debug... |
run an aws script across accounts | def run_script(config, output_dir, accounts, tags, region, echo, serial, script_args):
"""run an aws script across accounts"""
# TODO count up on success / error / error list by account
accounts_config, custodian_config, executor = init(
config, None, serial, True, accounts, tags, (), ())
if ec... |
Execute a set of policies on an account. | def run_account(account, region, policies_config, output_path,
cache_period, cache_path, metrics, dryrun, debug):
"""Execute a set of policies on an account.
"""
logging.getLogger('custodian.output').setLevel(logging.ERROR + 1)
CONN_CACHE.session = None
CONN_CACHE.time = None
# ... |
run a custodian policy across accounts | def run(config, use, output_dir, accounts, tags, region,
policy, policy_tags, cache_period, cache_path, metrics,
dryrun, debug, verbose, metrics_uri):
"""run a custodian policy across accounts"""
accounts_config, custodian_config, executor = init(
config, use, debug, verbose, accounts, t... |
Send logs | def emit(self, message):
"""Send logs"""
# We're sending messages asynchronously, bubble to caller when
# we've detected an error on the message. This isn't great,
# but options once we've gone async without a deferred/promise
# aren't great.
if self.transport and self.tr... |
Ensure all logging output has been flushed. | def flush(self):
"""Ensure all logging output has been flushed."""
if self.shutdown:
return
self.flush_buffers(force=True)
self.queue.put(FLUSH_MARKER)
self.queue.join() |
format message. | def format_message(self, msg):
"""format message."""
return {'timestamp': int(msg.created * 1000),
'message': self.format(msg),
'stream': self.log_stream or msg.name,
'group': self.log_group} |
start thread transports. | def start_transports(self):
"""start thread transports."""
self.transport = Transport(
self.queue, self.batch_size, self.batch_interval,
self.session_factory)
thread = threading.Thread(target=self.transport.loop)
self.threads.append(thread)
thread.daemon =... |
Handle various client side errors when describing images | def extract_bad_ami(e):
"""Handle various client side errors when describing images"""
msg = e.response['Error']['Message']
error = e.response['Error']['Code']
e_ami_ids = None
if error == 'InvalidAMIID.NotFound':
e_ami_ids = [
e_ami_id.strip() for e_a... |
format config for lambda exec | def format_json(config):
"""format config for lambda exec
"""
with open(config) as fh:
print(json.dumps(yaml.safe_load(fh.read()), indent=2)) |
Sanity check api deployment | def check():
"""Sanity check api deployment
"""
t = time.time()
results = Client(BASE_URL).version()
print("Endpoint", BASE_URL)
print("Response Time %0.2f" % (time.time() - t))
print("Headers")
for k, v in results.headers.items():
print(" %s: %s" % (k, v))
print("Body")
... |
lambda/ api/ db metrics | def metrics(function, api, start, period):
"""lambda/api/db metrics"""
from c7n.mu import LambdaManager
manager = LambdaManager(boto3.Session)
start = parse_date(start)
period = int(abs(parse_timedelta(period).total_seconds()))
print("Lambda Metrics")
metrics = manager.metrics(
[{'F... |
Fetch locks data | def records(account_id):
"""Fetch locks data
"""
s = boto3.Session()
table = s.resource('dynamodb').Table('Sphere11.Dev.ResourceLocks')
results = table.scan()
for r in results['Items']:
if 'LockDate' in r:
r['LockDate'] = datetime.fromtimestamp(r['LockDate'])
if 'Rev... |
Attempt to acquire any pending locks. | def flush_pending(function):
"""Attempt to acquire any pending locks.
"""
s = boto3.Session()
client = s.client('lambda')
results = client.invoke(
FunctionName=function,
Payload=json.dumps({'detail-type': 'Scheduled Event'})
)
content = results.pop('Payload').read()
pprin... |
Check config status in an account. | def config_status():
""" Check config status in an account.
"""
s = boto3.Session()
client = s.client('config')
channels = client.describe_delivery_channel_status()[
'DeliveryChannelsStatus']
for c in channels:
print(yaml.safe_dump({
c['name']: dict(
s... |
run local app server assumes into the account | def local(reload, port):
"""run local app server, assumes into the account
"""
import logging
from bottle import run
from app import controller, app
from c7n.resources import load_resources
load_resources()
print("Loaded resources definitions")
logging.basicConfig(level=logging.DEBUG... |
Given a class return its docstring. | def _schema_get_docstring(starting_class):
""" Given a class, return its docstring.
If no docstring is present for the class, search base classes in MRO for a
docstring.
"""
for cls in inspect.getmro(starting_class):
if inspect.getdoc(cls):
return inspect.getdoc(cls) |
For tab - completion via argcomplete return completion options. | def schema_completer(prefix):
""" For tab-completion via argcomplete, return completion options.
For the given prefix so far, return the possible options. Note that
filtering via startswith happens after this list is returned.
"""
from c7n import schema
load_resources()
components = prefix... |
Print info about the resources actions and filters available. | def schema_cmd(options):
""" Print info about the resources, actions and filters available. """
from c7n import schema
if options.json:
schema.json_dump(options.resource)
return
load_resources()
resource_mapping = schema.resource_vocabulary()
if options.summary:
schema.... |
Determine the start and end dates based on user - supplied options. | def _metrics_get_endpoints(options):
""" Determine the start and end dates based on user-supplied options. """
if bool(options.start) ^ bool(options.end):
log.error('--start and --end must be specified together')
sys.exit(1)
if options.start and options.end:
start = options.start
... |
Extract an instance id from an error | def extract_instance_id(state_error):
"Extract an instance id from an error"
instance_id = None
match = RE_ERROR_INSTANCE_ID.search(str(state_error))
if match:
instance_id = match.groupdict().get('instance_id')
if match is None or instance_id is None:
raise ValueError("Could not extr... |
EC2 API and AWOL Tags | def augment(self, resources):
"""EC2 API and AWOL Tags
While ec2 api generally returns tags when doing describe_x on for
various resources, it may also silently fail to do so unless a tag
is used as a filter.
See footnote on for official documentation.
https://docs.aws.... |
meta model subscriber on resource registration. | def register_resources(klass, registry, resource_class):
""" meta model subscriber on resource registration.
SecurityHub Findings Filter
"""
for rtype, resource_manager in registry.items():
if not resource_manager.has_arn():
continue
if 'post-find... |
Publish message to a GCP pub/ sub topic | def publish_message(self, message, client):
"""Publish message to a GCP pub/sub topic
"""
return client.execute_command('publish', {
'topic': self.data['transport']['topic'],
'body': {
'messages': {
'data': self.pack(message)
... |
Sets headers on Mimetext message | def set_mimetext_headers(self, message, subject, from_addr, to_addrs, cc_addrs, priority):
"""Sets headers on Mimetext message"""
message['Subject'] = subject
message['From'] = from_addr
message['To'] = ', '.join(to_addrs)
if cc_addrs:
message['Cc'] = ', '.join(cc_ad... |
meta model subscriber on resource registration. | def register_resources(klass, registry, resource_class):
""" meta model subscriber on resource registration.
We watch for PHD event that provides affected entities and register
the health-event filter to the resources.
"""
services = {'acm-certificate', 'directconnect', 'dms-ins... |
Create a lambda code archive for running custodian. | def custodian_archive(packages=None):
"""Create a lambda code archive for running custodian.
Lambda archive currently always includes `c7n` and
`pkg_resources`. Add additional packages in the mode block.
Example policy that includes additional packages
.. code-block:: yaml
policy:
... |
Add the named Python modules to the archive. For consistency s sake we only add *. py files not *. pyc. We also don t add other files including compiled modules. You ll have to add such files manually using: py: meth: add_file. | def add_modules(self, ignore, *modules):
"""Add the named Python modules to the archive. For consistency's sake
we only add ``*.py`` files, not ``*.pyc``. We also don't add other
files, including compiled modules. You'll have to add such files
manually using :py:meth:`add_file`.
... |
Add *. py files under the directory path to the archive. | def add_directory(self, path, ignore=None):
"""Add ``*.py`` files under the directory ``path`` to the archive.
"""
for root, dirs, files in os.walk(path):
arc_prefix = os.path.relpath(root, os.path.dirname(path))
# py3 remove pyc cache dirs.
if '__pycache__' i... |
Add the file at src to the archive. | def add_file(self, src, dest=None):
"""Add the file at ``src`` to the archive.
If ``dest`` is ``None`` then it is added under just the original
filename. So ``add_file('foo/bar.txt')`` ends up at ``bar.txt`` in the
archive, while ``add_file('bar.txt', 'foo/bar.txt')`` ends up at
... |
This is a special case of: py: meth: add_file that helps for adding a py when a pyc may be present as well. So for example if __file__ is foo. pyc and you do: | def add_py_file(self, src, dest=None):
"""This is a special case of :py:meth:`add_file` that helps for adding
a ``py`` when a ``pyc`` may be present as well. So for example, if
``__file__`` is ``foo.pyc`` and you do:
.. code-block:: python
archive.add_py_file(__file__)
... |
Add file contents to the archive under dest. | def add_contents(self, dest, contents):
"""Add file contents to the archive under ``dest``.
If ``dest`` is a path, it will be added compressed and world-readable
(user-writeable). You may also pass a :py:class:`~zipfile.ZipInfo` for
custom behavior.
"""
assert not self.... |
Close the zip file. | def close(self):
"""Close the zip file.
Note underlying tempfile is removed when archive is garbage collected.
"""
self._closed = True
self._zip_file.close()
log.debug(
"Created custodian serverless archive size: %0.2fmb",
(os.path.getsize(self._t... |
Return the b64 encoded sha256 checksum of the archive. | def get_checksum(self, encoder=base64.b64encode, hasher=hashlib.sha256):
"""Return the b64 encoded sha256 checksum of the archive."""
assert self._closed, "Archive not closed"
with open(self._temp_archive_file.name, 'rb') as fh:
return encoder(checksum(fh, hasher())).decode('ascii') |
Return a read - only: py: class: ~zipfile. ZipFile. | def get_reader(self):
"""Return a read-only :py:class:`~zipfile.ZipFile`."""
assert self._closed, "Archive not closed"
buf = io.BytesIO(self.get_bytes())
return zipfile.ZipFile(buf, mode='r') |
Create or update an alias for the given function. | def publish_alias(self, func_data, alias):
"""Create or update an alias for the given function.
"""
if not alias:
return func_data['FunctionArn']
func_name = func_data['FunctionName']
func_version = func_data['Version']
exists = resource_exists(
s... |
Returns a sqlite row factory that returns a dictionary | def row_factory(cursor, row):
"""Returns a sqlite row factory that returns a dictionary"""
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d |
Get the resource s tag value. | def get_tag_value(resource, tag, utf_8=False):
"""Get the resource's tag value."""
tags = {k.lower(): v for k, v in resource.get('tags', {}).items()}
value = tags.get(tag, False)
if value is not False:
if utf_8:
value = value.encode('utf8').decode('u... |
report on guard duty enablement by account | def report(config, tags, accounts, master, debug, region):
"""report on guard duty enablement by account"""
accounts_config, master_info, executor = guardian_init(
config, debug, master, accounts, tags)
session = get_session(
master_info.get('role'), 'c7n-guardian',
master_info.get(... |
suspend guard duty in the given accounts. | def disable(config, tags, accounts, master, debug,
suspend, disable_detector, delete_detector, dissociate, region):
"""suspend guard duty in the given accounts."""
accounts_config, master_info, executor = guardian_init(
config, debug, master, accounts, tags)
if sum(map(int, (suspend, di... |
enable guard duty on a set of accounts | def enable(config, master, tags, accounts, debug, message, region):
"""enable guard duty on a set of accounts"""
accounts_config, master_info, executor = guardian_init(
config, debug, master, accounts, tags)
regions = expand_regions(region)
for r in regions:
log.info("Processing Region:%... |
Return all the security group names configured in this action. | def get_action_group_names(self):
"""Return all the security group names configured in this action."""
return self.get_group_names(
list(itertools.chain(
*[self._get_array('add'),
self._get_array('remove'),
self._get_array('isolation-group'... |
Resolve security names to security groups resources. | def get_groups_by_names(self, names):
"""Resolve security names to security groups resources."""
if not names:
return []
client = utils.local_session(
self.manager.session_factory).client('ec2')
sgs = self.manager.retry(
client.describe_security_groups... |
Resolve any security group names to the corresponding group ids | def resolve_group_names(self, r, target_group_ids, groups):
"""Resolve any security group names to the corresponding group ids
With the context of a given network attached resource.
"""
names = self.get_group_names(target_group_ids)
if not names:
return target_group_... |
Resolve the resources security groups that need be modified. | def resolve_remove_symbols(self, r, target_group_ids, rgroups):
"""Resolve the resources security groups that need be modified.
Specifically handles symbolic names that match annotations from policy filters
for groups being removed.
"""
if 'matched' in target_group_ids:
... |
Return lists of security groups to set on each resource | def get_groups(self, resources):
"""Return lists of security groups to set on each resource
For each input resource, parse the various add/remove/isolation-
group policies for 'modify-security-groups' to find the resulting
set of VPC security groups to attach to that resource.
... |
jsonschema generation helper | def type_schema(
type_name, inherits=None, rinherit=None,
aliases=None, required=None, **props):
"""jsonschema generation helper
params:
- type_name: name of the type
- inherits: list of document fragments that are required via anyOf[$ref]
- rinherit: use another schema as a base... |
Return a mapping of key value to resources with the corresponding value. | def group_by(resources, key):
"""Return a mapping of key value to resources with the corresponding value.
Key may be specified as dotted form for nested dictionary lookup
"""
resource_map = {}
parts = key.split('.')
for r in resources:
v = r
for k in parts:
v = v.get... |
Some sources from apis return lowerCased where as describe calls | def camelResource(obj):
"""Some sources from apis return lowerCased where as describe calls
always return TitleCase, this function turns the former to the later
"""
if not isinstance(obj, dict):
return obj
for k in list(obj.keys()):
v = obj.pop(k)
obj["%s%s" % (k[0].upper(),... |
Return a list of ec2 instances for the query. | def query_instances(session, client=None, **query):
"""Return a list of ec2 instances for the query.
"""
if client is None:
client = session.client('ec2')
p = client.get_paginator('describe_instances')
results = p.paginate(**query)
return list(itertools.chain(
*[r["Instances"] fo... |
Cache a session thread local for up to 45m | def local_session(factory):
"""Cache a session thread local for up to 45m"""
factory_region = getattr(factory, 'region', 'global')
s = getattr(CONN_CACHE, factory_region, {}).get('session')
t = getattr(CONN_CACHE, factory_region, {}).get('time')
n = time.time()
if s is not None and t + (60 * 45... |
>>> x = {} >>> set_annotation ( x marker a ) >>> annotation ( x marker ) [ a ] | def set_annotation(i, k, v):
"""
>>> x = {}
>>> set_annotation(x, 'marker', 'a')
>>> annotation(x, 'marker')
['a']
"""
if not isinstance(i, dict):
raise ValueError("Can only annotate dictionaries")
if not isinstance(v, list):
v = [v]
if k in i:
ev = i.get(k)... |
Generate an Amazon Resource Name. See http:// docs. aws. amazon. com/ general/ latest/ gr/ aws - arns - and - namespaces. html. | def generate_arn(
service, resource, partition='aws',
region=None, account_id=None, resource_type=None, separator='/'):
"""Generate an Amazon Resource Name.
See http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html.
"""
if region and region in REGION_PARTITION_MAP:
... |
Return an identifier for a snapshot of a database or cluster. | def snapshot_identifier(prefix, db_identifier):
"""Return an identifier for a snapshot of a database or cluster.
"""
now = datetime.now()
return '%s-%s-%s' % (prefix, db_identifier, now.strftime('%Y-%m-%d-%H-%M')) |
Decorator for retry boto3 api call on transient errors. | def get_retry(codes=(), max_attempts=8, min_delay=1, log_retries=False):
"""Decorator for retry boto3 api call on transient errors.
https://www.awsarchitectureblog.com/2015/03/backoff.html
https://en.wikipedia.org/wiki/Exponential_backoff
:param codes: A sequence of retryable error codes.
:param m... |
Geometric backoff sequence w/ jitter | def backoff_delays(start, stop, factor=2.0, jitter=False):
"""Geometric backoff sequence w/ jitter
"""
cur = start
while cur <= stop:
if jitter:
yield cur - (cur * random.random())
else:
yield cur
cur = cur * factor |
Process cidr ranges. | def parse_cidr(value):
"""Process cidr ranges."""
klass = IPv4Network
if '/' not in value:
klass = ipaddress.ip_address
try:
v = klass(six.text_type(value))
except (ipaddress.AddressValueError, ValueError):
v = None
return v |
Generic wrapper to log uncaught exceptions in a function. | def worker(f):
"""Generic wrapper to log uncaught exceptions in a function.
When we cross concurrent.futures executor boundaries we lose our
traceback information, and when doing bulk operations we may tolerate
transient failures on a partial subset. However we still want to have
full accounting of... |
Reformat schema to be in a more displayable format. | def reformat_schema(model):
""" Reformat schema to be in a more displayable format. """
if not hasattr(model, 'schema'):
return "Model '{}' does not have a schema".format(model)
if 'properties' not in model.schema:
return "Schema in unexpected format."
ret = copy.deepcopy(model.schema[... |
Format all string values in an object. Return the updated object | def format_string_values(obj, err_fallback=(IndexError, KeyError), *args, **kwargs):
"""
Format all string values in an object.
Return the updated object
"""
if isinstance(obj, dict):
new = {}
for key in obj.keys():
new[key] = format_string_values(obj[key], *args, **kwarg... |
Retrieve dax resources for serverless policies or related resources | def get_resources(self, ids, cache=True):
"""Retrieve dax resources for serverless policies or related resources
"""
client = local_session(self.manager.session_factory).client('dax')
return client.describe_clusters(ClusterNames=ids).get('Clusters') |
Generate a c7n - org gcp projects config file | def main(output):
"""
Generate a c7n-org gcp projects config file
"""
client = Session().client('cloudresourcemanager', 'v1', 'projects')
results = []
for page in client.execute_paged_query('list', {}):
for project in page.get('projects', []):
if project['lifecycleState'] ... |
Query a set of resources. | def filter(self, resource_manager, **params):
"""Query a set of resources."""
m = self.resolve(resource_manager.resource_type)
client = resource_manager.get_client()
enum_op, list_op, extra_args = m.enum_spec
parent_type, annotate_parent = m.parent_spec
parents = self.m... |
Return an iterator resource attribute filters configured. | def get_attr_filters(self):
"""Return an iterator resource attribute filters configured.
"""
for f in self.data.keys():
if f not in self.multi_attrs:
continue
fv = self.data[f]
if isinstance(fv, dict):
fv['key'] = f
... |
add CloudTrail permissions to an S3 policy preserving existing | def cloudtrail_policy(original, bucket_name, account_id, bucket_region):
'''add CloudTrail permissions to an S3 policy, preserving existing'''
ct_actions = [
{
'Action': 's3:GetBucketAcl',
'Effect': 'Allow',
'Principal': {'Service': 'cloudtrail.amazonaws.com'},
... |
Returns all extant rds engine upgrades. | def _get_available_engine_upgrades(client, major=False):
"""Returns all extant rds engine upgrades.
As a nested mapping of engine type to known versions
and their upgrades.
Defaults to minor upgrades, but configurable to major.
Example::
>>> _get_engine_upgrades(client)
{
'o... |
Create a local output directory per execution. | def get_local_output_dir():
"""Create a local output directory per execution.
We've seen occassional (1/100000) perm issues with lambda on temp
directory and changing unix execution users (2015-2018), so use a
per execution temp space. With firecracker lambdas this may be outdated.
"""
output_d... |
Get policy lambda execution configuration. | def init_config(policy_config):
"""Get policy lambda execution configuration.
cli parameters are serialized into the policy lambda config,
we merge those with any policy specific execution options.
--assume role and -s output directory get special handling, as
to disambiguate any cli context.
... |
index policy metrics | def index_metrics(
config, start, end, incremental=False, concurrency=5, accounts=None,
period=3600, tag=None, index='policy-metrics', verbose=False):
"""index policy metrics"""
logging.basicConfig(level=(verbose and logging.DEBUG or logging.INFO))
logging.getLogger('botocore').setLevel(logg... |
make config revision look like describe output. | def transform_revision(self, revision):
"""make config revision look like describe output."""
config = self.manager.get_source('config')
return config.load_resource(revision) |
meta model subscriber on resource registration. | def register_resources(klass, registry, resource_class):
""" meta model subscriber on resource registration.
We watch for new resource types being registered and if they
support aws config, automatically register the jsondiff filter.
"""
config_type = getattr(resource_class.reso... |
Add basic options ot the subparser. | def _default_options(p, blacklist=""):
""" Add basic options ot the subparser.
`blacklist` is a list of options to exclude from the default set.
e.g.: ['region', 'log-group']
"""
provider = p.add_argument_group(
"provider", "AWS account information, defaults per the aws cli")
if 'regio... |
Add options specific to the report subcommand. | def _report_options(p):
""" Add options specific to the report subcommand. """
_default_options(p, blacklist=['cache', 'log-group', 'quiet'])
p.add_argument(
'--days', type=float, default=1,
help="Number of days of history to consider")
p.add_argument(
'--raw', type=argparse.File... |
Add options specific to metrics subcommand. | def _metrics_options(p):
""" Add options specific to metrics subcommand. """
_default_options(p, blacklist=['log-group', 'output-dir', 'cache', 'quiet'])
p.add_argument(
'--start', type=date_parse,
help='Start date (requires --end, overrides --days)')
p.add_argument(
'--end', ty... |
Add options specific to logs subcommand. | def _logs_options(p):
""" Add options specific to logs subcommand. """
_default_options(p, blacklist=['cache', 'quiet'])
# default time range is 0 to "now" (to include all log entries)
p.add_argument(
'--start',
default='the beginning', # invalid, will result in 0
help='Start d... |
Add options specific to schema subcommand. | def _schema_options(p):
""" Add options specific to schema subcommand. """
p.add_argument(
'resource', metavar='selector', nargs='?',
default=None).completer = _schema_tab_completer
p.add_argument(
'--summary', action="store_true",
help="Summarize counts of available resourc... |
Augment rds clusters with their respective tags. | def _rds_cluster_tags(model, dbs, session_factory, generator, retry):
"""Augment rds clusters with their respective tags."""
client = local_session(session_factory).client('rds')
def process_tags(db):
try:
db['Tags'] = retry(
client.list_tags_for_resource,
... |
Type convert the csv record modifies in place. | def process_user_record(cls, info):
"""Type convert the csv record, modifies in place."""
keys = list(info.keys())
# Value conversion
for k in keys:
v = info[k]
if v in ('N/A', 'no_information'):
info[k] = None
elif v == 'false':
... |
Mimic the format returned by LambdaManager. logs () | def normalized_log_entries(raw_entries):
'''Mimic the format returned by LambdaManager.logs()'''
entry_start = r'([0-9:, \-]+) - .* - (\w+) - (.*)$'
entry = None
# process start/end here - avoid parsing log entries twice
for line in raw_entries:
m = re.match(entry_start, line)
if m:
... |
filter out entries before start and after end | def log_entries_in_range(entries, start, end):
'''filter out entries before start and after end'''
start = _timestamp_from_string(start)
end = _timestamp_from_string(end)
for entry in entries:
log_timestamp = entry.get('timestamp', 0)
if log_timestamp >= start and log_timestamp <= end:
... |
Get logs for a specific log group | def log_entries_from_group(session, group_name, start, end):
'''Get logs for a specific log group'''
logs = session.client('logs')
log.info("Fetching logs from group: %s" % group_name)
try:
logs.describe_log_groups(logGroupNamePrefix=group_name)
except ClientError as e:
if e.response... |
Builds and returns a cloud API service object. | def _create_service_api(credentials, service_name, version, developer_key=None,
cache_discovery=False, http=None):
"""Builds and returns a cloud API service object.
Args:
credentials (OAuth2Credentials): Credentials that will be used to
authenticate the API calls.
... |
Construct an http client suitable for googleapiclient usage w/ user agent. | def _build_http(http=None):
"""Construct an http client suitable for googleapiclient usage w/ user agent.
"""
if not http:
http = httplib2.Http(
timeout=HTTP_REQUEST_TIMEOUT, ca_certs=HTTPLIB_CA_BUNDLE)
user_agent = 'Python-httplib2/{} (gzip), {}/{}'.format(
httplib2.__versi... |
Safely initialize a repository class to a property. | def client(self, service_name, version, component, **kw):
"""Safely initialize a repository class to a property.
Args:
repository_class (class): The class to initialize.
version (str): The gcp service version for the repository.
Returns:
object: An instance ... |
A thread local instance of httplib2. Http. | def http(self):
"""A thread local instance of httplib2.Http.
Returns:
httplib2.Http: An Http instance authorized by the credentials.
"""
if self._use_cached_http and hasattr(self._local, 'http'):
return self._local.http
if self._http_replay is not None:
... |
Builds HttpRequest object. | def _build_request(self, verb, verb_arguments):
"""Builds HttpRequest object.
Args:
verb (str): Request verb (ex. insert, update, delete).
verb_arguments (dict): Arguments to be passed with the request.
Returns:
httplib2.HttpRequest: HttpRequest to be sent t... |
Builds pagination - aware request object. | def _build_next_request(self, verb, prior_request, prior_response):
"""Builds pagination-aware request object.
More details:
https://developers.google.com/api-client-library/python/guide/pagination
Args:
verb (str): Request verb (ex. insert, update, delete).
p... |
Executes command ( ex. add ) via a dedicated http object. | def execute_command(self, verb, verb_arguments):
"""Executes command (ex. add) via a dedicated http object.
Async APIs may take minutes to complete. Therefore, callers are
encouraged to leverage concurrent.futures (or similar) to place long
running commands on a separate threads.
... |
Executes query ( ex. list ) via a dedicated http object. | def execute_paged_query(self, verb, verb_arguments):
"""Executes query (ex. list) via a dedicated http object.
Args:
verb (str): Method to execute on the component (ex. get, list).
verb_arguments (dict): key-value pairs to be passed to _BuildRequest.
Yields:
... |
Executes query ( ex. search ) via a dedicated http object. | def execute_search_query(self, verb, verb_arguments):
"""Executes query (ex. search) via a dedicated http object.
Args:
verb (str): Method to execute on the component (ex. search).
verb_arguments (dict): key-value pairs to be passed to _BuildRequest.
Yields:
... |
Executes query ( ex. get ) via a dedicated http object. | def execute_query(self, verb, verb_arguments):
"""Executes query (ex. get) via a dedicated http object.
Args:
verb (str): Method to execute on the component (ex. get, list).
verb_arguments (dict): key-value pairs to be passed to _BuildRequest.
Returns:
dict:... |
Run execute with retries and rate limiting. | def _execute(self, request):
"""Run execute with retries and rate limiting.
Args:
request (object): The HttpRequest object to execute.
Returns:
dict: The response from the API.
"""
if self._rate_limiter:
# Since the ratelimiter library only e... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.