id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
232,100
RiotGames/cloud-inquisitor
plugins/public/cinq-auditor-cloudtrail/cinq_auditor_cloudtrail/__init__.py
CloudTrailAuditor.validate_sqs_policy
def validate_sqs_policy(self, accounts): """Given a list of accounts, ensures that the SQS policy allows all the accounts to write to the queue Args: accounts (`list` of :obj:`Account`): List of accounts Returns: `None` """ sqs_queue_name = self.dbconfig.get('sqs_queue_name', self.ns) sqs_queue_region = self.dbconfig.get('sqs_queue_region', self.ns) sqs_account = AWSAccount.get(self.dbconfig.get('sqs_queue_account', self.ns)) session = get_aws_session(sqs_account) sqs = session.client('sqs', region_name=sqs_queue_region) sqs_queue_url = sqs.get_queue_url(QueueName=sqs_queue_name, QueueOwnerAWSAccountId=sqs_account.account_number) sqs_attribs = sqs.get_queue_attributes(QueueUrl=sqs_queue_url['QueueUrl'], AttributeNames=['Policy']) policy = json.loads(sqs_attribs['Attributes']['Policy']) for account in accounts: arn = 'arn:aws:sns:*:{}:{}'.format(account.account_number, sqs_queue_name) if arn not in policy['Statement'][0]['Condition']['ForAnyValue:ArnEquals']['aws:SourceArn']: self.log.warning('SQS policy is missing condition for ARN {}'.format(arn)) policy['Statement'][0]['Condition']['ForAnyValue:ArnEquals']['aws:SourceArn'].append(arn) sqs.set_queue_attributes(QueueUrl=sqs_queue_url['QueueUrl'], Attributes={'Policy': json.dumps(policy)})
python
def validate_sqs_policy(self, accounts): sqs_queue_name = self.dbconfig.get('sqs_queue_name', self.ns) sqs_queue_region = self.dbconfig.get('sqs_queue_region', self.ns) sqs_account = AWSAccount.get(self.dbconfig.get('sqs_queue_account', self.ns)) session = get_aws_session(sqs_account) sqs = session.client('sqs', region_name=sqs_queue_region) sqs_queue_url = sqs.get_queue_url(QueueName=sqs_queue_name, QueueOwnerAWSAccountId=sqs_account.account_number) sqs_attribs = sqs.get_queue_attributes(QueueUrl=sqs_queue_url['QueueUrl'], AttributeNames=['Policy']) policy = json.loads(sqs_attribs['Attributes']['Policy']) for account in accounts: arn = 'arn:aws:sns:*:{}:{}'.format(account.account_number, sqs_queue_name) if arn not in policy['Statement'][0]['Condition']['ForAnyValue:ArnEquals']['aws:SourceArn']: self.log.warning('SQS policy is missing condition for ARN {}'.format(arn)) policy['Statement'][0]['Condition']['ForAnyValue:ArnEquals']['aws:SourceArn'].append(arn) sqs.set_queue_attributes(QueueUrl=sqs_queue_url['QueueUrl'], Attributes={'Policy': json.dumps(policy)})
[ "def", "validate_sqs_policy", "(", "self", ",", "accounts", ")", ":", "sqs_queue_name", "=", "self", ".", "dbconfig", ".", "get", "(", "'sqs_queue_name'", ",", "self", ".", "ns", ")", "sqs_queue_region", "=", "self", ".", "dbconfig", ".", "get", "(", "'sqs...
Given a list of accounts, ensures that the SQS policy allows all the accounts to write to the queue Args: accounts (`list` of :obj:`Account`): List of accounts Returns: `None`
[ "Given", "a", "list", "of", "accounts", "ensures", "that", "the", "SQS", "policy", "allows", "all", "the", "accounts", "to", "write", "to", "the", "queue" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-auditor-cloudtrail/cinq_auditor_cloudtrail/__init__.py#L75-L101
232,101
RiotGames/cloud-inquisitor
plugins/public/cinq-auditor-cloudtrail/cinq_auditor_cloudtrail/__init__.py
CloudTrail.run
def run(self): """Configures and enables a CloudTrail trail and logging on a single AWS Account. Has the capability to create both single region and multi-region trails. Will automatically create SNS topics, subscribe to SQS queues and turn on logging for the account in question, as well as reverting any manual changes to the trails if applicable. Returns: None """ for aws_region in AWS_REGIONS: self.log.debug('Checking trails for {}/{}'.format( self.account.account_name, aws_region )) ct = self.session.client('cloudtrail', region_name=aws_region) trails = ct.describe_trails() if len(trails['trailList']) == 0: if aws_region == self.global_ct_region: self.create_cloudtrail(aws_region) else: for trail in trails['trailList']: if trail['Name'] in ('Default', self.trail_name): if not trail['IsMultiRegionTrail']: if trail['Name'] == self.trail_name and self.global_ct_region == aws_region: ct.update_trail( Name=trail['Name'], IncludeGlobalServiceEvents=True, IsMultiRegionTrail=True ) auditlog( event='cloudtrail.update_trail', actor=self.ns, data={ 'trailName': trail['Name'], 'account': self.account.account_name, 'region': aws_region, 'changes': [ { 'setting': 'IsMultiRegionTrail', 'oldValue': False, 'newValue': True } ] } ) else: ct.delete_trail(name=trail['Name']) auditlog( event='cloudtrail.delete_trail', actor=self.ns, data={ 'trailName': trail['Name'], 'account': self.account.account_name, 'region': aws_region, 'reason': 'Incorrect region, name or not multi-regional' } ) else: if trail['HomeRegion'] == aws_region: if self.global_ct_region != aws_region or trail['Name'] == 'Default': ct.delete_trail(Name=trail['Name']) auditlog( event='cloudtrail.delete_trail', actor=self.ns, data={ 'trailName': trail['Name'], 'account': self.account.account_name, 'region': aws_region, 'reason': 'Incorrect name or region for multi-region trail' } ) trails = ct.describe_trails() for trail in trails['trailList']: if trail['Name'] == self.trail_name and trail['HomeRegion'] == aws_region: self.validate_trail_settings(ct, aws_region, trail)
python
def run(self): for aws_region in AWS_REGIONS: self.log.debug('Checking trails for {}/{}'.format( self.account.account_name, aws_region )) ct = self.session.client('cloudtrail', region_name=aws_region) trails = ct.describe_trails() if len(trails['trailList']) == 0: if aws_region == self.global_ct_region: self.create_cloudtrail(aws_region) else: for trail in trails['trailList']: if trail['Name'] in ('Default', self.trail_name): if not trail['IsMultiRegionTrail']: if trail['Name'] == self.trail_name and self.global_ct_region == aws_region: ct.update_trail( Name=trail['Name'], IncludeGlobalServiceEvents=True, IsMultiRegionTrail=True ) auditlog( event='cloudtrail.update_trail', actor=self.ns, data={ 'trailName': trail['Name'], 'account': self.account.account_name, 'region': aws_region, 'changes': [ { 'setting': 'IsMultiRegionTrail', 'oldValue': False, 'newValue': True } ] } ) else: ct.delete_trail(name=trail['Name']) auditlog( event='cloudtrail.delete_trail', actor=self.ns, data={ 'trailName': trail['Name'], 'account': self.account.account_name, 'region': aws_region, 'reason': 'Incorrect region, name or not multi-regional' } ) else: if trail['HomeRegion'] == aws_region: if self.global_ct_region != aws_region or trail['Name'] == 'Default': ct.delete_trail(Name=trail['Name']) auditlog( event='cloudtrail.delete_trail', actor=self.ns, data={ 'trailName': trail['Name'], 'account': self.account.account_name, 'region': aws_region, 'reason': 'Incorrect name or region for multi-region trail' } ) trails = ct.describe_trails() for trail in trails['trailList']: if trail['Name'] == self.trail_name and trail['HomeRegion'] == aws_region: self.validate_trail_settings(ct, aws_region, trail)
[ "def", "run", "(", "self", ")", ":", "for", "aws_region", "in", "AWS_REGIONS", ":", "self", ".", "log", ".", "debug", "(", "'Checking trails for {}/{}'", ".", "format", "(", "self", ".", "account", ".", "account_name", ",", "aws_region", ")", ")", "ct", ...
Configures and enables a CloudTrail trail and logging on a single AWS Account. Has the capability to create both single region and multi-region trails. Will automatically create SNS topics, subscribe to SQS queues and turn on logging for the account in question, as well as reverting any manual changes to the trails if applicable. Returns: None
[ "Configures", "and", "enables", "a", "CloudTrail", "trail", "and", "logging", "on", "a", "single", "AWS", "Account", "." ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-auditor-cloudtrail/cinq_auditor_cloudtrail/__init__.py#L132-L210
232,102
RiotGames/cloud-inquisitor
plugins/public/cinq-auditor-cloudtrail/cinq_auditor_cloudtrail/__init__.py
CloudTrail.validate_trail_settings
def validate_trail_settings(self, ct, aws_region, trail): """Validates logging, SNS and S3 settings for the global trail. Has the capability to: - start logging for the trail - create SNS topics & queues - configure or modify a S3 bucket for logging """ self.log.debug('Validating trail {}/{}/{}'.format( self.account.account_name, aws_region, trail['Name'] )) status = ct.get_trail_status(Name=trail['Name']) if not status['IsLogging']: self.log.warning('Logging is disabled for {}/{}/{}'.format( self.account.account_name, aws_region, trail['Name'] )) self.start_logging(aws_region, trail['Name']) if 'SnsTopicName' not in trail or not trail['SnsTopicName']: self.log.warning('SNS Notifications not enabled for {}/{}/{}'.format( self.account.account_name, aws_region, trail['Name'] )) self.create_sns_topic(aws_region) self.enable_sns_notification(aws_region, trail['Name']) if not self.validate_sns_topic_subscription(aws_region): self.log.warning( 'SNS Notification configured but not subscribed for {}/{}/{}'.format( self.account.account_name, aws_region, trail['Name'] ) ) self.subscribe_sns_topic_to_sqs(aws_region) if trail['S3BucketName'] != self.bucket_name: self.log.warning('CloudTrail is logging to an incorrect bucket for {}/{}/{}'.format( self.account.account_name, trail['S3BucketName'], trail['Name'] )) self.set_s3_bucket(aws_region, trail['Name'], self.bucket_name) if not trail.get('S3KeyPrefix') or trail['S3KeyPrefix'] != self.account.account_name: self.log.warning('Missing or incorrect S3KeyPrefix for {}/{}/{}'.format( self.account.account_name, aws_region, trail['Name'] )) self.set_s3_prefix(aws_region, trail['Name'])
python
def validate_trail_settings(self, ct, aws_region, trail): self.log.debug('Validating trail {}/{}/{}'.format( self.account.account_name, aws_region, trail['Name'] )) status = ct.get_trail_status(Name=trail['Name']) if not status['IsLogging']: self.log.warning('Logging is disabled for {}/{}/{}'.format( self.account.account_name, aws_region, trail['Name'] )) self.start_logging(aws_region, trail['Name']) if 'SnsTopicName' not in trail or not trail['SnsTopicName']: self.log.warning('SNS Notifications not enabled for {}/{}/{}'.format( self.account.account_name, aws_region, trail['Name'] )) self.create_sns_topic(aws_region) self.enable_sns_notification(aws_region, trail['Name']) if not self.validate_sns_topic_subscription(aws_region): self.log.warning( 'SNS Notification configured but not subscribed for {}/{}/{}'.format( self.account.account_name, aws_region, trail['Name'] ) ) self.subscribe_sns_topic_to_sqs(aws_region) if trail['S3BucketName'] != self.bucket_name: self.log.warning('CloudTrail is logging to an incorrect bucket for {}/{}/{}'.format( self.account.account_name, trail['S3BucketName'], trail['Name'] )) self.set_s3_bucket(aws_region, trail['Name'], self.bucket_name) if not trail.get('S3KeyPrefix') or trail['S3KeyPrefix'] != self.account.account_name: self.log.warning('Missing or incorrect S3KeyPrefix for {}/{}/{}'.format( self.account.account_name, aws_region, trail['Name'] )) self.set_s3_prefix(aws_region, trail['Name'])
[ "def", "validate_trail_settings", "(", "self", ",", "ct", ",", "aws_region", ",", "trail", ")", ":", "self", ".", "log", ".", "debug", "(", "'Validating trail {}/{}/{}'", ".", "format", "(", "self", ".", "account", ".", "account_name", ",", "aws_region", ","...
Validates logging, SNS and S3 settings for the global trail. Has the capability to: - start logging for the trail - create SNS topics & queues - configure or modify a S3 bucket for logging
[ "Validates", "logging", "SNS", "and", "S3", "settings", "for", "the", "global", "trail", "." ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-auditor-cloudtrail/cinq_auditor_cloudtrail/__init__.py#L212-L269
232,103
RiotGames/cloud-inquisitor
plugins/public/cinq-auditor-cloudtrail/cinq_auditor_cloudtrail/__init__.py
CloudTrail.create_sns_topic
def create_sns_topic(self, region): """Creates an SNS topic if needed. Returns the ARN if the created SNS topic Args: region (str): Region name Returns: `str` """ sns = self.session.client('sns', region_name=region) self.log.info('Creating SNS topic for {}/{}'.format(self.account, region)) # Create the topic res = sns.create_topic(Name=self.topic_name) arn = res['TopicArn'] # Allow CloudTrail to publish messages with a policy update tmpl = get_template('cloudtrail_sns_policy.json') policy = tmpl.render(region=region, account_id=self.account.account_number, topic_name=self.topic_name) sns.set_topic_attributes(TopicArn=arn, AttributeName='Policy', AttributeValue=policy) auditlog( event='cloudtrail.create_sns_topic', actor=self.ns, data={ 'account': self.account.account_name, 'region': region } ) return arn
python
def create_sns_topic(self, region): sns = self.session.client('sns', region_name=region) self.log.info('Creating SNS topic for {}/{}'.format(self.account, region)) # Create the topic res = sns.create_topic(Name=self.topic_name) arn = res['TopicArn'] # Allow CloudTrail to publish messages with a policy update tmpl = get_template('cloudtrail_sns_policy.json') policy = tmpl.render(region=region, account_id=self.account.account_number, topic_name=self.topic_name) sns.set_topic_attributes(TopicArn=arn, AttributeName='Policy', AttributeValue=policy) auditlog( event='cloudtrail.create_sns_topic', actor=self.ns, data={ 'account': self.account.account_name, 'region': region } ) return arn
[ "def", "create_sns_topic", "(", "self", ",", "region", ")", ":", "sns", "=", "self", ".", "session", ".", "client", "(", "'sns'", ",", "region_name", "=", "region", ")", "self", ".", "log", ".", "info", "(", "'Creating SNS topic for {}/{}'", ".", "format",...
Creates an SNS topic if needed. Returns the ARN if the created SNS topic Args: region (str): Region name Returns: `str`
[ "Creates", "an", "SNS", "topic", "if", "needed", ".", "Returns", "the", "ARN", "if", "the", "created", "SNS", "topic" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-auditor-cloudtrail/cinq_auditor_cloudtrail/__init__.py#L272-L302
232,104
RiotGames/cloud-inquisitor
plugins/public/cinq-auditor-cloudtrail/cinq_auditor_cloudtrail/__init__.py
CloudTrail.validate_sns_topic_subscription
def validate_sns_topic_subscription(self, region): """Validates SQS subscription to the SNS topic. Returns `True` if subscribed or `False` if not subscribed or topic is missing Args: region (str): Name of AWS Region Returns: `bool` """ sns = self.session.client('sns', region_name=region) arn = 'arn:aws:sns:{}:{}:{}'.format(region, self.account.account_number, self.topic_name) try: data = sns.list_subscriptions_by_topic(TopicArn=arn) except ClientError as ex: self.log.error('Failed to list subscriptions by topic in {} ({}): {}'.format( self.account.account_name, region, ex )) return False for sub in data['Subscriptions']: if sub['Endpoint'] == self.sqs_queue: if sub['SubscriptionArn'] == 'PendingConfirmation': self.log.warning('Subscription pending confirmation for {} in {}'.format( self.account.account_name, region )) return False return True return False
python
def validate_sns_topic_subscription(self, region): sns = self.session.client('sns', region_name=region) arn = 'arn:aws:sns:{}:{}:{}'.format(region, self.account.account_number, self.topic_name) try: data = sns.list_subscriptions_by_topic(TopicArn=arn) except ClientError as ex: self.log.error('Failed to list subscriptions by topic in {} ({}): {}'.format( self.account.account_name, region, ex )) return False for sub in data['Subscriptions']: if sub['Endpoint'] == self.sqs_queue: if sub['SubscriptionArn'] == 'PendingConfirmation': self.log.warning('Subscription pending confirmation for {} in {}'.format( self.account.account_name, region )) return False return True return False
[ "def", "validate_sns_topic_subscription", "(", "self", ",", "region", ")", ":", "sns", "=", "self", ".", "session", ".", "client", "(", "'sns'", ",", "region_name", "=", "region", ")", "arn", "=", "'arn:aws:sns:{}:{}:{}'", ".", "format", "(", "region", ",", ...
Validates SQS subscription to the SNS topic. Returns `True` if subscribed or `False` if not subscribed or topic is missing Args: region (str): Name of AWS Region Returns: `bool`
[ "Validates", "SQS", "subscription", "to", "the", "SNS", "topic", ".", "Returns", "True", "if", "subscribed", "or", "False", "if", "not", "subscribed", "or", "topic", "is", "missing" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-auditor-cloudtrail/cinq_auditor_cloudtrail/__init__.py#L304-L336
232,105
RiotGames/cloud-inquisitor
plugins/public/cinq-auditor-cloudtrail/cinq_auditor_cloudtrail/__init__.py
CloudTrail.subscribe_sns_topic_to_sqs
def subscribe_sns_topic_to_sqs(self, region): """Subscribe SQS to the SNS topic. Returns the ARN of the SNS Topic subscribed Args: region (`str`): Name of the AWS region Returns: `str` """ sns = self.session.resource('sns', region_name=region) topic = sns.Topic('arn:aws:sns:{}:{}:{}'.format(region, self.account.account_number, self.topic_name)) topic.subscribe(Protocol='sqs', Endpoint=self.sqs_queue) auditlog( event='cloudtrail.subscribe_sns_topic_to_sqs', actor=self.ns, data={ 'account': self.account.account_name, 'region': region } ) return topic.attributes['TopicArn']
python
def subscribe_sns_topic_to_sqs(self, region): sns = self.session.resource('sns', region_name=region) topic = sns.Topic('arn:aws:sns:{}:{}:{}'.format(region, self.account.account_number, self.topic_name)) topic.subscribe(Protocol='sqs', Endpoint=self.sqs_queue) auditlog( event='cloudtrail.subscribe_sns_topic_to_sqs', actor=self.ns, data={ 'account': self.account.account_name, 'region': region } ) return topic.attributes['TopicArn']
[ "def", "subscribe_sns_topic_to_sqs", "(", "self", ",", "region", ")", ":", "sns", "=", "self", ".", "session", ".", "resource", "(", "'sns'", ",", "region_name", "=", "region", ")", "topic", "=", "sns", ".", "Topic", "(", "'arn:aws:sns:{}:{}:{}'", ".", "fo...
Subscribe SQS to the SNS topic. Returns the ARN of the SNS Topic subscribed Args: region (`str`): Name of the AWS region Returns: `str`
[ "Subscribe", "SQS", "to", "the", "SNS", "topic", ".", "Returns", "the", "ARN", "of", "the", "SNS", "Topic", "subscribed" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-auditor-cloudtrail/cinq_auditor_cloudtrail/__init__.py#L338-L361
232,106
RiotGames/cloud-inquisitor
plugins/public/cinq-auditor-cloudtrail/cinq_auditor_cloudtrail/__init__.py
CloudTrail.create_cloudtrail
def create_cloudtrail(self, region): """Creates a new CloudTrail Trail Args: region (str): Name of the AWS region Returns: `None` """ ct = self.session.client('cloudtrail', region_name=region) # Creating the sns topic for the trail prior to creation self.create_sns_topic(region) ct.create_trail( Name=self.trail_name, S3BucketName=self.bucket_name, S3KeyPrefix=self.account.account_name, IsMultiRegionTrail=True, IncludeGlobalServiceEvents=True, SnsTopicName=self.topic_name ) self.subscribe_sns_topic_to_sqs(region) auditlog( event='cloudtrail.create_cloudtrail', actor=self.ns, data={ 'account': self.account.account_name, 'region': region } ) self.log.info('Created CloudTrail for {} in {} ({})'.format(self.account, region, self.bucket_name))
python
def create_cloudtrail(self, region): ct = self.session.client('cloudtrail', region_name=region) # Creating the sns topic for the trail prior to creation self.create_sns_topic(region) ct.create_trail( Name=self.trail_name, S3BucketName=self.bucket_name, S3KeyPrefix=self.account.account_name, IsMultiRegionTrail=True, IncludeGlobalServiceEvents=True, SnsTopicName=self.topic_name ) self.subscribe_sns_topic_to_sqs(region) auditlog( event='cloudtrail.create_cloudtrail', actor=self.ns, data={ 'account': self.account.account_name, 'region': region } ) self.log.info('Created CloudTrail for {} in {} ({})'.format(self.account, region, self.bucket_name))
[ "def", "create_cloudtrail", "(", "self", ",", "region", ")", ":", "ct", "=", "self", ".", "session", ".", "client", "(", "'cloudtrail'", ",", "region_name", "=", "region", ")", "# Creating the sns topic for the trail prior to creation", "self", ".", "create_sns_topi...
Creates a new CloudTrail Trail Args: region (str): Name of the AWS region Returns: `None`
[ "Creates", "a", "new", "CloudTrail", "Trail" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-auditor-cloudtrail/cinq_auditor_cloudtrail/__init__.py#L363-L395
232,107
RiotGames/cloud-inquisitor
plugins/public/cinq-auditor-cloudtrail/cinq_auditor_cloudtrail/__init__.py
CloudTrail.enable_sns_notification
def enable_sns_notification(self, region, trailName): """Enable SNS notifications for a Trail Args: region (`str`): Name of the AWS region trailName (`str`): Name of the CloudTrail Trail Returns: `None` """ ct = self.session.client('cloudtrail', region_name=region) ct.update_trail(Name=trailName, SnsTopicName=self.topic_name) auditlog( event='cloudtrail.enable_sns_notification', actor=self.ns, data={ 'account': self.account.account_name, 'region': region } ) self.log.info('Enabled SNS notifications for trail {} in {}/{}'.format( trailName, self.account.account_name, region ))
python
def enable_sns_notification(self, region, trailName): ct = self.session.client('cloudtrail', region_name=region) ct.update_trail(Name=trailName, SnsTopicName=self.topic_name) auditlog( event='cloudtrail.enable_sns_notification', actor=self.ns, data={ 'account': self.account.account_name, 'region': region } ) self.log.info('Enabled SNS notifications for trail {} in {}/{}'.format( trailName, self.account.account_name, region ))
[ "def", "enable_sns_notification", "(", "self", ",", "region", ",", "trailName", ")", ":", "ct", "=", "self", ".", "session", ".", "client", "(", "'cloudtrail'", ",", "region_name", "=", "region", ")", "ct", ".", "update_trail", "(", "Name", "=", "trailName...
Enable SNS notifications for a Trail Args: region (`str`): Name of the AWS region trailName (`str`): Name of the CloudTrail Trail Returns: `None`
[ "Enable", "SNS", "notifications", "for", "a", "Trail" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-auditor-cloudtrail/cinq_auditor_cloudtrail/__init__.py#L397-L422
232,108
RiotGames/cloud-inquisitor
plugins/public/cinq-auditor-cloudtrail/cinq_auditor_cloudtrail/__init__.py
CloudTrail.start_logging
def start_logging(self, region, name): """Turn on logging for a CloudTrail Trail Args: region (`str`): Name of the AWS region name (`str`): Name of the CloudTrail Trail Returns: `None` """ ct = self.session.client('cloudtrail', region_name=region) ct.start_logging(Name=name) auditlog( event='cloudtrail.start_logging', actor=self.ns, data={ 'account': self.account.account_name, 'region': region } ) self.log.info('Enabled logging for {} ({})'.format(name, region))
python
def start_logging(self, region, name): ct = self.session.client('cloudtrail', region_name=region) ct.start_logging(Name=name) auditlog( event='cloudtrail.start_logging', actor=self.ns, data={ 'account': self.account.account_name, 'region': region } ) self.log.info('Enabled logging for {} ({})'.format(name, region))
[ "def", "start_logging", "(", "self", ",", "region", ",", "name", ")", ":", "ct", "=", "self", ".", "session", ".", "client", "(", "'cloudtrail'", ",", "region_name", "=", "region", ")", "ct", ".", "start_logging", "(", "Name", "=", "name", ")", "auditl...
Turn on logging for a CloudTrail Trail Args: region (`str`): Name of the AWS region name (`str`): Name of the CloudTrail Trail Returns: `None`
[ "Turn", "on", "logging", "for", "a", "CloudTrail", "Trail" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-auditor-cloudtrail/cinq_auditor_cloudtrail/__init__.py#L424-L445
232,109
RiotGames/cloud-inquisitor
plugins/public/cinq-auditor-cloudtrail/cinq_auditor_cloudtrail/__init__.py
CloudTrail.set_s3_prefix
def set_s3_prefix(self, region, name): """Sets the S3 prefix for a CloudTrail Trail Args: region (`str`): Name of the AWS region name (`str`): Name of the CloudTrail Trail Returns: `None` """ ct = self.session.client('cloudtrail', region_name=region) ct.update_trail(Name=name, S3KeyPrefix=self.account.account_name) auditlog( event='cloudtrail.set_s3_prefix', actor=self.ns, data={ 'account': self.account.account_name, 'region': region } ) self.log.info('Updated S3KeyPrefix to {0} for {0}/{1}'.format( self.account.account_name, region ))
python
def set_s3_prefix(self, region, name): ct = self.session.client('cloudtrail', region_name=region) ct.update_trail(Name=name, S3KeyPrefix=self.account.account_name) auditlog( event='cloudtrail.set_s3_prefix', actor=self.ns, data={ 'account': self.account.account_name, 'region': region } ) self.log.info('Updated S3KeyPrefix to {0} for {0}/{1}'.format( self.account.account_name, region ))
[ "def", "set_s3_prefix", "(", "self", ",", "region", ",", "name", ")", ":", "ct", "=", "self", ".", "session", ".", "client", "(", "'cloudtrail'", ",", "region_name", "=", "region", ")", "ct", ".", "update_trail", "(", "Name", "=", "name", ",", "S3KeyPr...
Sets the S3 prefix for a CloudTrail Trail Args: region (`str`): Name of the AWS region name (`str`): Name of the CloudTrail Trail Returns: `None`
[ "Sets", "the", "S3", "prefix", "for", "a", "CloudTrail", "Trail" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-auditor-cloudtrail/cinq_auditor_cloudtrail/__init__.py#L447-L471
232,110
RiotGames/cloud-inquisitor
plugins/public/cinq-auditor-cloudtrail/cinq_auditor_cloudtrail/__init__.py
CloudTrail.set_s3_bucket
def set_s3_bucket(self, region, name, bucketName): """Sets the S3 bucket location for logfile delivery Args: region (`str`): Name of the AWS region name (`str`): Name of the CloudTrail Trail bucketName (`str`): Name of the S3 bucket to deliver log files to Returns: `None` """ ct = self.session.client('cloudtrail', region_name=region) ct.update_trail(Name=name, S3BucketName=bucketName) auditlog( event='cloudtrail.set_s3_bucket', actor=self.ns, data={ 'account': self.account.account_name, 'region': region } ) self.log.info('Updated S3BucketName to {} for {} in {}/{}'.format( bucketName, name, self.account.account_name, region ))
python
def set_s3_bucket(self, region, name, bucketName): ct = self.session.client('cloudtrail', region_name=region) ct.update_trail(Name=name, S3BucketName=bucketName) auditlog( event='cloudtrail.set_s3_bucket', actor=self.ns, data={ 'account': self.account.account_name, 'region': region } ) self.log.info('Updated S3BucketName to {} for {} in {}/{}'.format( bucketName, name, self.account.account_name, region ))
[ "def", "set_s3_bucket", "(", "self", ",", "region", ",", "name", ",", "bucketName", ")", ":", "ct", "=", "self", ".", "session", ".", "client", "(", "'cloudtrail'", ",", "region_name", "=", "region", ")", "ct", ".", "update_trail", "(", "Name", "=", "n...
Sets the S3 bucket location for logfile delivery Args: region (`str`): Name of the AWS region name (`str`): Name of the CloudTrail Trail bucketName (`str`): Name of the S3 bucket to deliver log files to Returns: `None`
[ "Sets", "the", "S3", "bucket", "location", "for", "logfile", "delivery" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-auditor-cloudtrail/cinq_auditor_cloudtrail/__init__.py#L473-L500
232,111
RiotGames/cloud-inquisitor
plugins/public/cinq-auditor-cloudtrail/cinq_auditor_cloudtrail/__init__.py
CloudTrail.create_s3_bucket
def create_s3_bucket(cls, bucket_name, bucket_region, bucket_account, template): """Creates the S3 bucket on the account specified as the destination account for log files Args: bucket_name (`str`): Name of the S3 bucket bucket_region (`str`): AWS Region for the bucket bucket_account (:obj:`Account`): Account to create the S3 bucket in template (:obj:`Template`): Jinja2 Template object for the bucket policy Returns: `None` """ s3 = get_aws_session(bucket_account).client('s3', region_name=bucket_region) # Check to see if the bucket already exists and if we have access to it try: s3.head_bucket(Bucket=bucket_name) except ClientError as ex: status_code = ex.response['ResponseMetadata']['HTTPStatusCode'] # Bucket exists and we do not have access if status_code == 403: raise Exception('Bucket {} already exists but we do not have access to it and so cannot continue'.format( bucket_name )) # Bucket does not exist, lets create one elif status_code == 404: try: s3.create_bucket( Bucket=bucket_name, CreateBucketConfiguration={ 'LocationConstraint': bucket_region } ) auditlog( event='cloudtrail.create_s3_bucket', actor=cls.ns, data={ 'account': bucket_account.account_name, 'bucket_region': bucket_region, 'bucket_name': bucket_name } ) except Exception: raise Exception('An error occured while trying to create the bucket, cannot continue') try: bucket_acl = template.render( bucket_name=bucket_name, account_id=bucket_account.account_number ) s3.put_bucket_policy(Bucket=bucket_name, Policy=bucket_acl) except Exception as ex: raise Warning('An error occurred while setting bucket policy: {}'.format(ex))
python
def create_s3_bucket(cls, bucket_name, bucket_region, bucket_account, template): s3 = get_aws_session(bucket_account).client('s3', region_name=bucket_region) # Check to see if the bucket already exists and if we have access to it try: s3.head_bucket(Bucket=bucket_name) except ClientError as ex: status_code = ex.response['ResponseMetadata']['HTTPStatusCode'] # Bucket exists and we do not have access if status_code == 403: raise Exception('Bucket {} already exists but we do not have access to it and so cannot continue'.format( bucket_name )) # Bucket does not exist, lets create one elif status_code == 404: try: s3.create_bucket( Bucket=bucket_name, CreateBucketConfiguration={ 'LocationConstraint': bucket_region } ) auditlog( event='cloudtrail.create_s3_bucket', actor=cls.ns, data={ 'account': bucket_account.account_name, 'bucket_region': bucket_region, 'bucket_name': bucket_name } ) except Exception: raise Exception('An error occured while trying to create the bucket, cannot continue') try: bucket_acl = template.render( bucket_name=bucket_name, account_id=bucket_account.account_number ) s3.put_bucket_policy(Bucket=bucket_name, Policy=bucket_acl) except Exception as ex: raise Warning('An error occurred while setting bucket policy: {}'.format(ex))
[ "def", "create_s3_bucket", "(", "cls", ",", "bucket_name", ",", "bucket_region", ",", "bucket_account", ",", "template", ")", ":", "s3", "=", "get_aws_session", "(", "bucket_account", ")", ".", "client", "(", "'s3'", ",", "region_name", "=", "bucket_region", "...
Creates the S3 bucket on the account specified as the destination account for log files Args: bucket_name (`str`): Name of the S3 bucket bucket_region (`str`): AWS Region for the bucket bucket_account (:obj:`Account`): Account to create the S3 bucket in template (:obj:`Template`): Jinja2 Template object for the bucket policy Returns: `None`
[ "Creates", "the", "S3", "bucket", "on", "the", "account", "specified", "as", "the", "destination", "account", "for", "log", "files" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-auditor-cloudtrail/cinq_auditor_cloudtrail/__init__.py#L503-L559
232,112
RiotGames/cloud-inquisitor
plugins/public/cinq-auditor-vpc-flowlogs/cinq_auditor_vpc_flowlogs/__init__.py
VPCFlowLogsAuditor.run
def run(self): """Main entry point for the auditor worker. Returns: `None` """ # Loop through all accounts that are marked as enabled accounts = list(AWSAccount.get_all(include_disabled=False).values()) for account in accounts: self.log.debug('Updating VPC Flow Logs for {}'.format(account)) self.session = get_aws_session(account) role_arn = self.confirm_iam_role(account) # region specific for aws_region in AWS_REGIONS: try: vpc_list = VPC.get_all(account, aws_region).values() need_vpc_flow_logs = [x for x in vpc_list if x.vpc_flow_logs_status != 'ACTIVE'] for vpc in need_vpc_flow_logs: if self.confirm_cw_log(account, aws_region, vpc.id): self.create_vpc_flow_logs(account, aws_region, vpc.id, role_arn) else: self.log.info('Failed to confirm log group for {}/{}'.format( account, aws_region )) except Exception: self.log.exception('Failed processing VPCs for {}/{}.'.format( account, aws_region )) db.session.commit()
python
def run(self): # Loop through all accounts that are marked as enabled accounts = list(AWSAccount.get_all(include_disabled=False).values()) for account in accounts: self.log.debug('Updating VPC Flow Logs for {}'.format(account)) self.session = get_aws_session(account) role_arn = self.confirm_iam_role(account) # region specific for aws_region in AWS_REGIONS: try: vpc_list = VPC.get_all(account, aws_region).values() need_vpc_flow_logs = [x for x in vpc_list if x.vpc_flow_logs_status != 'ACTIVE'] for vpc in need_vpc_flow_logs: if self.confirm_cw_log(account, aws_region, vpc.id): self.create_vpc_flow_logs(account, aws_region, vpc.id, role_arn) else: self.log.info('Failed to confirm log group for {}/{}'.format( account, aws_region )) except Exception: self.log.exception('Failed processing VPCs for {}/{}.'.format( account, aws_region )) db.session.commit()
[ "def", "run", "(", "self", ")", ":", "# Loop through all accounts that are marked as enabled", "accounts", "=", "list", "(", "AWSAccount", ".", "get_all", "(", "include_disabled", "=", "False", ")", ".", "values", "(", ")", ")", "for", "account", "in", "accounts...
Main entry point for the auditor worker. Returns: `None`
[ "Main", "entry", "point", "for", "the", "auditor", "worker", "." ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-auditor-vpc-flowlogs/cinq_auditor_vpc_flowlogs/__init__.py#L30-L64
232,113
RiotGames/cloud-inquisitor
plugins/public/cinq-auditor-vpc-flowlogs/cinq_auditor_vpc_flowlogs/__init__.py
VPCFlowLogsAuditor.confirm_iam_role
def confirm_iam_role(self, account): """Return the ARN of the IAM Role on the provided account as a string. Returns an `IAMRole` object from boto3 Args: account (:obj:`Account`): Account where to locate the role Returns: :obj:`IAMRole` """ try: iam = self.session.client('iam') rolearn = iam.get_role(RoleName=self.role_name)['Role']['Arn'] return rolearn except ClientError as e: if e.response['Error']['Code'] == 'NoSuchEntity': self.create_iam_role(account) else: raise except Exception as e: self.log.exception('Failed validating IAM role for VPC Flow Log Auditing for {}'.format(e))
python
def confirm_iam_role(self, account): try: iam = self.session.client('iam') rolearn = iam.get_role(RoleName=self.role_name)['Role']['Arn'] return rolearn except ClientError as e: if e.response['Error']['Code'] == 'NoSuchEntity': self.create_iam_role(account) else: raise except Exception as e: self.log.exception('Failed validating IAM role for VPC Flow Log Auditing for {}'.format(e))
[ "def", "confirm_iam_role", "(", "self", ",", "account", ")", ":", "try", ":", "iam", "=", "self", ".", "session", ".", "client", "(", "'iam'", ")", "rolearn", "=", "iam", ".", "get_role", "(", "RoleName", "=", "self", ".", "role_name", ")", "[", "'Ro...
Return the ARN of the IAM Role on the provided account as a string. Returns an `IAMRole` object from boto3 Args: account (:obj:`Account`): Account where to locate the role Returns: :obj:`IAMRole`
[ "Return", "the", "ARN", "of", "the", "IAM", "Role", "on", "the", "provided", "account", "as", "a", "string", ".", "Returns", "an", "IAMRole", "object", "from", "boto3" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-auditor-vpc-flowlogs/cinq_auditor_vpc_flowlogs/__init__.py#L67-L88
232,114
RiotGames/cloud-inquisitor
plugins/public/cinq-auditor-vpc-flowlogs/cinq_auditor_vpc_flowlogs/__init__.py
VPCFlowLogsAuditor.create_iam_role
def create_iam_role(self, account): """Create a new IAM role. Returns the ARN of the newly created role Args: account (:obj:`Account`): Account where to create the IAM role Returns: `str` """ try: iam = self.session.client('iam') trust = get_template('vpc_flow_logs_iam_role_trust.json').render() policy = get_template('vpc_flow_logs_role_policy.json').render() newrole = iam.create_role( Path='/', RoleName=self.role_name, AssumeRolePolicyDocument=trust )['Role']['Arn'] # Attach an inline policy to the role to avoid conflicts or hitting the Managed Policy Limit iam.put_role_policy( RoleName=self.role_name, PolicyName='VpcFlowPolicy', PolicyDocument=policy ) self.log.debug('Created VPC Flow Logs role & policy for {}'.format(account.account_name)) auditlog( event='vpc_flow_logs.create_iam_role', actor=self.ns, data={ 'account': account.account_name, 'roleName': self.role_name, 'trustRelationship': trust, 'inlinePolicy': policy } ) return newrole except Exception: self.log.exception('Failed creating the VPC Flow Logs role for {}.'.format(account))
python
def create_iam_role(self, account): try: iam = self.session.client('iam') trust = get_template('vpc_flow_logs_iam_role_trust.json').render() policy = get_template('vpc_flow_logs_role_policy.json').render() newrole = iam.create_role( Path='/', RoleName=self.role_name, AssumeRolePolicyDocument=trust )['Role']['Arn'] # Attach an inline policy to the role to avoid conflicts or hitting the Managed Policy Limit iam.put_role_policy( RoleName=self.role_name, PolicyName='VpcFlowPolicy', PolicyDocument=policy ) self.log.debug('Created VPC Flow Logs role & policy for {}'.format(account.account_name)) auditlog( event='vpc_flow_logs.create_iam_role', actor=self.ns, data={ 'account': account.account_name, 'roleName': self.role_name, 'trustRelationship': trust, 'inlinePolicy': policy } ) return newrole except Exception: self.log.exception('Failed creating the VPC Flow Logs role for {}.'.format(account))
[ "def", "create_iam_role", "(", "self", ",", "account", ")", ":", "try", ":", "iam", "=", "self", ".", "session", ".", "client", "(", "'iam'", ")", "trust", "=", "get_template", "(", "'vpc_flow_logs_iam_role_trust.json'", ")", ".", "render", "(", ")", "poli...
Create a new IAM role. Returns the ARN of the newly created role Args: account (:obj:`Account`): Account where to create the IAM role Returns: `str`
[ "Create", "a", "new", "IAM", "role", ".", "Returns", "the", "ARN", "of", "the", "newly", "created", "role" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-auditor-vpc-flowlogs/cinq_auditor_vpc_flowlogs/__init__.py#L92-L133
232,115
RiotGames/cloud-inquisitor
plugins/public/cinq-auditor-vpc-flowlogs/cinq_auditor_vpc_flowlogs/__init__.py
VPCFlowLogsAuditor.confirm_cw_log
def confirm_cw_log(self, account, region, vpcname): """Create a new CloudWatch log group based on the VPC Name if none exists. Returns `True` if succesful Args: account (:obj:`Account`): Account to create the log group in region (`str`): Region to create the log group in vpcname (`str`): Name of the VPC the log group is fow Returns: `bool` """ try: cw = self.session.client('logs', region) token = None log_groups = [] while True: result = cw.describe_log_groups() if not token else cw.describe_log_groups(nextToken=token) token = result.get('nextToken') log_groups.extend([x['logGroupName'] for x in result.get('logGroups', [])]) if not token: break if vpcname not in log_groups: cw.create_log_group(logGroupName=vpcname) cw_vpc = VPC.get(vpcname) cw_vpc.set_property('vpc_flow_logs_log_group', vpcname) self.log.info('Created log group {}/{}/{}'.format(account.account_name, region, vpcname)) auditlog( event='vpc_flow_logs.create_cw_log_group', actor=self.ns, data={ 'account': account.account_name, 'region': region, 'log_group_name': vpcname, 'vpc': vpcname } ) return True except Exception: self.log.exception('Failed creating log group for {}/{}/{}.'.format( account, region, vpcname ))
python
def confirm_cw_log(self, account, region, vpcname): try: cw = self.session.client('logs', region) token = None log_groups = [] while True: result = cw.describe_log_groups() if not token else cw.describe_log_groups(nextToken=token) token = result.get('nextToken') log_groups.extend([x['logGroupName'] for x in result.get('logGroups', [])]) if not token: break if vpcname not in log_groups: cw.create_log_group(logGroupName=vpcname) cw_vpc = VPC.get(vpcname) cw_vpc.set_property('vpc_flow_logs_log_group', vpcname) self.log.info('Created log group {}/{}/{}'.format(account.account_name, region, vpcname)) auditlog( event='vpc_flow_logs.create_cw_log_group', actor=self.ns, data={ 'account': account.account_name, 'region': region, 'log_group_name': vpcname, 'vpc': vpcname } ) return True except Exception: self.log.exception('Failed creating log group for {}/{}/{}.'.format( account, region, vpcname ))
[ "def", "confirm_cw_log", "(", "self", ",", "account", ",", "region", ",", "vpcname", ")", ":", "try", ":", "cw", "=", "self", ".", "session", ".", "client", "(", "'logs'", ",", "region", ")", "token", "=", "None", "log_groups", "=", "[", "]", "while"...
Create a new CloudWatch log group based on the VPC Name if none exists. Returns `True` if succesful Args: account (:obj:`Account`): Account to create the log group in region (`str`): Region to create the log group in vpcname (`str`): Name of the VPC the log group is fow Returns: `bool`
[ "Create", "a", "new", "CloudWatch", "log", "group", "based", "on", "the", "VPC", "Name", "if", "none", "exists", ".", "Returns", "True", "if", "succesful" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-auditor-vpc-flowlogs/cinq_auditor_vpc_flowlogs/__init__.py#L136-L182
232,116
RiotGames/cloud-inquisitor
plugins/public/cinq-auditor-vpc-flowlogs/cinq_auditor_vpc_flowlogs/__init__.py
VPCFlowLogsAuditor.create_vpc_flow_logs
def create_vpc_flow_logs(self, account, region, vpc_id, iam_role_arn): """Create a new VPC Flow log Args: account (:obj:`Account`): Account to create the flow in region (`str`): Region to create the flow in vpc_id (`str`): ID of the VPC to create the flow for iam_role_arn (`str`): ARN of the IAM role used to post logs to the log group Returns: `None` """ try: flow = self.session.client('ec2', region) flow.create_flow_logs( ResourceIds=[vpc_id], ResourceType='VPC', TrafficType='ALL', LogGroupName=vpc_id, DeliverLogsPermissionArn=iam_role_arn ) fvpc = VPC.get(vpc_id) fvpc.set_property('vpc_flow_logs_status', 'ACTIVE') self.log.info('Enabled VPC Logging {}/{}/{}'.format(account, region, vpc_id)) auditlog( event='vpc_flow_logs.create_vpc_flow', actor=self.ns, data={ 'account': account.account_name, 'region': region, 'vpcId': vpc_id, 'arn': iam_role_arn } ) except Exception: self.log.exception('Failed creating VPC Flow Logs for {}/{}/{}.'.format( account, region, vpc_id ))
python
def create_vpc_flow_logs(self, account, region, vpc_id, iam_role_arn): try: flow = self.session.client('ec2', region) flow.create_flow_logs( ResourceIds=[vpc_id], ResourceType='VPC', TrafficType='ALL', LogGroupName=vpc_id, DeliverLogsPermissionArn=iam_role_arn ) fvpc = VPC.get(vpc_id) fvpc.set_property('vpc_flow_logs_status', 'ACTIVE') self.log.info('Enabled VPC Logging {}/{}/{}'.format(account, region, vpc_id)) auditlog( event='vpc_flow_logs.create_vpc_flow', actor=self.ns, data={ 'account': account.account_name, 'region': region, 'vpcId': vpc_id, 'arn': iam_role_arn } ) except Exception: self.log.exception('Failed creating VPC Flow Logs for {}/{}/{}.'.format( account, region, vpc_id ))
[ "def", "create_vpc_flow_logs", "(", "self", ",", "account", ",", "region", ",", "vpc_id", ",", "iam_role_arn", ")", ":", "try", ":", "flow", "=", "self", ".", "session", ".", "client", "(", "'ec2'", ",", "region", ")", "flow", ".", "create_flow_logs", "(...
Create a new VPC Flow log Args: account (:obj:`Account`): Account to create the flow in region (`str`): Region to create the flow in vpc_id (`str`): ID of the VPC to create the flow for iam_role_arn (`str`): ARN of the IAM role used to post logs to the log group Returns: `None`
[ "Create", "a", "new", "VPC", "Flow", "log" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-auditor-vpc-flowlogs/cinq_auditor_vpc_flowlogs/__init__.py#L185-L225
232,117
RiotGames/cloud-inquisitor
plugins/public/cinq-auditor-required-tags/cinq_auditor_required_tags/__init__.py
RequiredTagsAuditor.get_contacts
def get_contacts(self, issue): """Returns a list of contacts for an issue Args: issue (:obj:`RequiredTagsIssue`): Issue record Returns: `list` of `dict` """ # If the resources has been deleted, just return an empty list, to trigger issue deletion without notification if not issue.resource: return [] account_contacts = issue.resource.account.contacts try: resource_owners = issue.resource.get_owner_emails() # Double check get_owner_emails for it's return value if type(resource_owners) is list: for resource_owner in resource_owners: account_contacts.append({'type': 'email', 'value': resource_owner}) except AttributeError: pass return account_contacts
python
def get_contacts(self, issue): # If the resources has been deleted, just return an empty list, to trigger issue deletion without notification if not issue.resource: return [] account_contacts = issue.resource.account.contacts try: resource_owners = issue.resource.get_owner_emails() # Double check get_owner_emails for it's return value if type(resource_owners) is list: for resource_owner in resource_owners: account_contacts.append({'type': 'email', 'value': resource_owner}) except AttributeError: pass return account_contacts
[ "def", "get_contacts", "(", "self", ",", "issue", ")", ":", "# If the resources has been deleted, just return an empty list, to trigger issue deletion without notification", "if", "not", "issue", ".", "resource", ":", "return", "[", "]", "account_contacts", "=", "issue", "....
Returns a list of contacts for an issue Args: issue (:obj:`RequiredTagsIssue`): Issue record Returns: `list` of `dict`
[ "Returns", "a", "list", "of", "contacts", "for", "an", "issue" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-auditor-required-tags/cinq_auditor_required_tags/__init__.py#L212-L234
232,118
RiotGames/cloud-inquisitor
plugins/public/cinq-auditor-required-tags/cinq_auditor_required_tags/__init__.py
RequiredTagsAuditor.get_actions
def get_actions(self, issues): """Returns a list of actions to executed Args: issues (`list` of :obj:`RequiredTagsIssue`): List of issues Returns: `list` of `dict` """ actions = [] try: for issue in issues: action_item = self.determine_action(issue) if action_item['action'] != AuditActions.IGNORE: action_item['owners'] = self.get_contacts(issue) actions.append(action_item) finally: db.session.rollback() return actions
python
def get_actions(self, issues): actions = [] try: for issue in issues: action_item = self.determine_action(issue) if action_item['action'] != AuditActions.IGNORE: action_item['owners'] = self.get_contacts(issue) actions.append(action_item) finally: db.session.rollback() return actions
[ "def", "get_actions", "(", "self", ",", "issues", ")", ":", "actions", "=", "[", "]", "try", ":", "for", "issue", "in", "issues", ":", "action_item", "=", "self", ".", "determine_action", "(", "issue", ")", "if", "action_item", "[", "'action'", "]", "!...
Returns a list of actions to executed Args: issues (`list` of :obj:`RequiredTagsIssue`): List of issues Returns: `list` of `dict`
[ "Returns", "a", "list", "of", "actions", "to", "executed" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-auditor-required-tags/cinq_auditor_required_tags/__init__.py#L236-L254
232,119
RiotGames/cloud-inquisitor
plugins/public/cinq-auditor-required-tags/cinq_auditor_required_tags/__init__.py
RequiredTagsAuditor.determine_alert
def determine_alert(self, action_schedule, issue_creation_time, last_alert): """Determine if we need to trigger an alert Args: action_schedule (`list`): A list contains the alert schedule issue_creation_time (`int`): Time we create the issue last_alert (`str`): Time we sent the last alert Returns: (`None` or `str`) None if no alert should be sent. Otherwise return the alert we should send """ issue_age = time.time() - issue_creation_time alert_schedule_lookup = {pytimeparse.parse(action_time): action_time for action_time in action_schedule} alert_schedule = sorted(alert_schedule_lookup.keys()) last_alert_time = pytimeparse.parse(last_alert) for alert_time in alert_schedule: if last_alert_time < alert_time <= issue_age and last_alert_time != alert_time: return alert_schedule_lookup[alert_time] else: return None
python
def determine_alert(self, action_schedule, issue_creation_time, last_alert): issue_age = time.time() - issue_creation_time alert_schedule_lookup = {pytimeparse.parse(action_time): action_time for action_time in action_schedule} alert_schedule = sorted(alert_schedule_lookup.keys()) last_alert_time = pytimeparse.parse(last_alert) for alert_time in alert_schedule: if last_alert_time < alert_time <= issue_age and last_alert_time != alert_time: return alert_schedule_lookup[alert_time] else: return None
[ "def", "determine_alert", "(", "self", ",", "action_schedule", ",", "issue_creation_time", ",", "last_alert", ")", ":", "issue_age", "=", "time", ".", "time", "(", ")", "-", "issue_creation_time", "alert_schedule_lookup", "=", "{", "pytimeparse", ".", "parse", "...
Determine if we need to trigger an alert Args: action_schedule (`list`): A list contains the alert schedule issue_creation_time (`int`): Time we create the issue last_alert (`str`): Time we sent the last alert Returns: (`None` or `str`) None if no alert should be sent. Otherwise return the alert we should send
[ "Determine", "if", "we", "need", "to", "trigger", "an", "alert" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-auditor-required-tags/cinq_auditor_required_tags/__init__.py#L256-L277
232,120
RiotGames/cloud-inquisitor
plugins/public/cinq-auditor-required-tags/cinq_auditor_required_tags/__init__.py
RequiredTagsAuditor.determine_action
def determine_action(self, issue): """Determine the action we should take for the issue Args: issue: Issue to determine action for Returns: `dict` """ resource_type = self.resource_types[issue.resource.resource_type_id] issue_alert_schedule = self.alert_schedule[resource_type] if \ resource_type in self.alert_schedule \ else self.alert_schedule['*'] action_item = { 'action': None, 'action_description': None, 'last_alert': issue.last_alert, 'issue': issue, 'resource': self.resource_classes[self.resource_types[issue.resource.resource_type_id]](issue.resource), 'owners': [], 'stop_after': issue_alert_schedule['stop'], 'remove_after': issue_alert_schedule['remove'], 'notes': issue.notes, 'missing_tags': issue.missing_tags } time_elapsed = time.time() - issue.created stop_schedule = pytimeparse.parse(issue_alert_schedule['stop']) remove_schedule = pytimeparse.parse(issue_alert_schedule['remove']) if self.collect_only: action_item['action'] = AuditActions.IGNORE elif remove_schedule and time_elapsed >= remove_schedule: action_item['action'] = AuditActions.REMOVE action_item['action_description'] = 'Resource removed' action_item['last_alert'] = remove_schedule if issue.update({'last_alert': remove_schedule}): db.session.add(issue.issue) elif stop_schedule and time_elapsed >= stop_schedule: action_item['action'] = AuditActions.STOP action_item['action_description'] = 'Resource stopped' action_item['last_alert'] = stop_schedule if issue.update({'last_alert': stop_schedule}): db.session.add(issue.issue) else: alert_selection = self.determine_alert( issue_alert_schedule['alert'], issue.get_property('created').value, issue.get_property('last_alert').value ) if alert_selection: action_item['action'] = AuditActions.ALERT action_item['action_description'] = '{} alert'.format(alert_selection) action_item['last_alert'] = alert_selection if issue.update({'last_alert': alert_selection}): db.session.add(issue.issue) else: action_item['action'] = AuditActions.IGNORE db.session.commit() return action_item
python
def determine_action(self, issue): resource_type = self.resource_types[issue.resource.resource_type_id] issue_alert_schedule = self.alert_schedule[resource_type] if \ resource_type in self.alert_schedule \ else self.alert_schedule['*'] action_item = { 'action': None, 'action_description': None, 'last_alert': issue.last_alert, 'issue': issue, 'resource': self.resource_classes[self.resource_types[issue.resource.resource_type_id]](issue.resource), 'owners': [], 'stop_after': issue_alert_schedule['stop'], 'remove_after': issue_alert_schedule['remove'], 'notes': issue.notes, 'missing_tags': issue.missing_tags } time_elapsed = time.time() - issue.created stop_schedule = pytimeparse.parse(issue_alert_schedule['stop']) remove_schedule = pytimeparse.parse(issue_alert_schedule['remove']) if self.collect_only: action_item['action'] = AuditActions.IGNORE elif remove_schedule and time_elapsed >= remove_schedule: action_item['action'] = AuditActions.REMOVE action_item['action_description'] = 'Resource removed' action_item['last_alert'] = remove_schedule if issue.update({'last_alert': remove_schedule}): db.session.add(issue.issue) elif stop_schedule and time_elapsed >= stop_schedule: action_item['action'] = AuditActions.STOP action_item['action_description'] = 'Resource stopped' action_item['last_alert'] = stop_schedule if issue.update({'last_alert': stop_schedule}): db.session.add(issue.issue) else: alert_selection = self.determine_alert( issue_alert_schedule['alert'], issue.get_property('created').value, issue.get_property('last_alert').value ) if alert_selection: action_item['action'] = AuditActions.ALERT action_item['action_description'] = '{} alert'.format(alert_selection) action_item['last_alert'] = alert_selection if issue.update({'last_alert': alert_selection}): db.session.add(issue.issue) else: action_item['action'] = AuditActions.IGNORE db.session.commit() return action_item
[ "def", "determine_action", "(", "self", ",", "issue", ")", ":", "resource_type", "=", "self", ".", "resource_types", "[", "issue", ".", "resource", ".", "resource_type_id", "]", "issue_alert_schedule", "=", "self", ".", "alert_schedule", "[", "resource_type", "]...
Determine the action we should take for the issue Args: issue: Issue to determine action for Returns: `dict`
[ "Determine", "the", "action", "we", "should", "take", "for", "the", "issue" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-auditor-required-tags/cinq_auditor_required_tags/__init__.py#L279-L342
232,121
RiotGames/cloud-inquisitor
plugins/public/cinq-auditor-required-tags/cinq_auditor_required_tags/__init__.py
RequiredTagsAuditor.process_actions
def process_actions(self, actions): """Process the actions we want to take Args: actions (`list`): List of actions we want to take Returns: `list` of notifications """ notices = {} notification_contacts = {} for action in actions: resource = action['resource'] action_status = ActionStatus.SUCCEED try: if action['action'] == AuditActions.REMOVE: action_status = self.process_action( resource, AuditActions.REMOVE ) if action_status == ActionStatus.SUCCEED: db.session.delete(action['issue'].issue) elif action['action'] == AuditActions.STOP: action_status = self.process_action( resource, AuditActions.STOP ) if action_status == ActionStatus.SUCCEED: action['issue'].update({ 'missing_tags': action['missing_tags'], 'notes': action['notes'], 'last_alert': action['last_alert'], 'state': action['action'] }) elif action['action'] == AuditActions.FIXED: db.session.delete(action['issue'].issue) elif action['action'] == AuditActions.ALERT: action['issue'].update({ 'missing_tags': action['missing_tags'], 'notes': action['notes'], 'last_alert': action['last_alert'], 'state': action['action'] }) db.session.commit() if action_status == ActionStatus.SUCCEED: for owner in [ dict(t) for t in {tuple(d.items()) for d in (action['owners'] + self.permanent_emails)} ]: if owner['value'] not in notification_contacts: contact = NotificationContact(type=owner['type'], value=owner['value']) notification_contacts[owner['value']] = contact notices[contact] = { 'fixed': [], 'not_fixed': [] } else: contact = notification_contacts[owner['value']] if action['action'] == AuditActions.FIXED: notices[contact]['fixed'].append(action) else: notices[contact]['not_fixed'].append(action) except Exception as ex: self.log.exception('Unexpected error while processing resource {}/{}/{}/{}'.format( action['resource'].account.account_name, action['resource'].id, action['resource'], ex )) return notices
python
def process_actions(self, actions): notices = {} notification_contacts = {} for action in actions: resource = action['resource'] action_status = ActionStatus.SUCCEED try: if action['action'] == AuditActions.REMOVE: action_status = self.process_action( resource, AuditActions.REMOVE ) if action_status == ActionStatus.SUCCEED: db.session.delete(action['issue'].issue) elif action['action'] == AuditActions.STOP: action_status = self.process_action( resource, AuditActions.STOP ) if action_status == ActionStatus.SUCCEED: action['issue'].update({ 'missing_tags': action['missing_tags'], 'notes': action['notes'], 'last_alert': action['last_alert'], 'state': action['action'] }) elif action['action'] == AuditActions.FIXED: db.session.delete(action['issue'].issue) elif action['action'] == AuditActions.ALERT: action['issue'].update({ 'missing_tags': action['missing_tags'], 'notes': action['notes'], 'last_alert': action['last_alert'], 'state': action['action'] }) db.session.commit() if action_status == ActionStatus.SUCCEED: for owner in [ dict(t) for t in {tuple(d.items()) for d in (action['owners'] + self.permanent_emails)} ]: if owner['value'] not in notification_contacts: contact = NotificationContact(type=owner['type'], value=owner['value']) notification_contacts[owner['value']] = contact notices[contact] = { 'fixed': [], 'not_fixed': [] } else: contact = notification_contacts[owner['value']] if action['action'] == AuditActions.FIXED: notices[contact]['fixed'].append(action) else: notices[contact]['not_fixed'].append(action) except Exception as ex: self.log.exception('Unexpected error while processing resource {}/{}/{}/{}'.format( action['resource'].account.account_name, action['resource'].id, action['resource'], ex )) return notices
[ "def", "process_actions", "(", "self", ",", "actions", ")", ":", "notices", "=", "{", "}", "notification_contacts", "=", "{", "}", "for", "action", "in", "actions", ":", "resource", "=", "action", "[", "'resource'", "]", "action_status", "=", "ActionStatus",...
Process the actions we want to take Args: actions (`list`): List of actions we want to take Returns: `list` of notifications
[ "Process", "the", "actions", "we", "want", "to", "take" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-auditor-required-tags/cinq_auditor_required_tags/__init__.py#L351-L427
232,122
RiotGames/cloud-inquisitor
plugins/public/cinq-auditor-required-tags/cinq_auditor_required_tags/__init__.py
RequiredTagsAuditor.validate_tag
def validate_tag(self, key, value): """Check whether a tag value is valid Args: key: A tag key value: A tag value Returns: `(True or False)` A boolean indicating whether or not the value is valid """ if key == 'owner': return validate_email(value, self.partial_owner_match) elif key == self.gdpr_tag: return value in self.gdpr_tag_values else: return True
python
def validate_tag(self, key, value): if key == 'owner': return validate_email(value, self.partial_owner_match) elif key == self.gdpr_tag: return value in self.gdpr_tag_values else: return True
[ "def", "validate_tag", "(", "self", ",", "key", ",", "value", ")", ":", "if", "key", "==", "'owner'", ":", "return", "validate_email", "(", "value", ",", "self", ".", "partial_owner_match", ")", "elif", "key", "==", "self", ".", "gdpr_tag", ":", "return"...
Check whether a tag value is valid Args: key: A tag key value: A tag value Returns: `(True or False)` A boolean indicating whether or not the value is valid
[ "Check", "whether", "a", "tag", "value", "is", "valid" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-auditor-required-tags/cinq_auditor_required_tags/__init__.py#L429-L445
232,123
RiotGames/cloud-inquisitor
plugins/public/cinq-auditor-required-tags/cinq_auditor_required_tags/__init__.py
RequiredTagsAuditor.check_required_tags_compliance
def check_required_tags_compliance(self, resource): """Check whether a resource is compliance Args: resource: A single resource Returns: `(list, list)` A tuple contains missing tags (if there were any) and notes """ missing_tags = [] notes = [] resource_tags = {tag.key.lower(): tag.value for tag in resource.tags} # Do not audit this resource if it is not in the Account scope if resource.resource_type in self.alert_schedule: target_accounts = self.alert_schedule[resource.resource_type]['scope'] else: target_accounts = self.alert_schedule['*']['scope'] if not (resource.account.account_name in target_accounts or '*' in target_accounts): return missing_tags, notes # Do not audit this resource if the ignore tag was set if self.audit_ignore_tag.lower() in resource_tags: return missing_tags, notes required_tags = list(self.required_tags) # Add GDPR tag to required tags if the account must be GDPR compliant if self.gdpr_enabled and resource.account.account_name in self.gdpr_accounts: required_tags.append(self.gdpr_tag) ''' # Do not audit this resource if it is still in grace period if (datetime.utcnow() - resource.resource_creation_date).total_seconds() // 3600 < self.grace_period: return missing_tags, notes ''' # Check if the resource is missing required tags or has invalid tag values for key in [tag.lower() for tag in required_tags]: if key not in resource_tags: missing_tags.append(key) elif not self.validate_tag(key, resource_tags[key]): missing_tags.append(key) notes.append('{} tag is not valid'.format(key)) return missing_tags, notes
python
def check_required_tags_compliance(self, resource): missing_tags = [] notes = [] resource_tags = {tag.key.lower(): tag.value for tag in resource.tags} # Do not audit this resource if it is not in the Account scope if resource.resource_type in self.alert_schedule: target_accounts = self.alert_schedule[resource.resource_type]['scope'] else: target_accounts = self.alert_schedule['*']['scope'] if not (resource.account.account_name in target_accounts or '*' in target_accounts): return missing_tags, notes # Do not audit this resource if the ignore tag was set if self.audit_ignore_tag.lower() in resource_tags: return missing_tags, notes required_tags = list(self.required_tags) # Add GDPR tag to required tags if the account must be GDPR compliant if self.gdpr_enabled and resource.account.account_name in self.gdpr_accounts: required_tags.append(self.gdpr_tag) ''' # Do not audit this resource if it is still in grace period if (datetime.utcnow() - resource.resource_creation_date).total_seconds() // 3600 < self.grace_period: return missing_tags, notes ''' # Check if the resource is missing required tags or has invalid tag values for key in [tag.lower() for tag in required_tags]: if key not in resource_tags: missing_tags.append(key) elif not self.validate_tag(key, resource_tags[key]): missing_tags.append(key) notes.append('{} tag is not valid'.format(key)) return missing_tags, notes
[ "def", "check_required_tags_compliance", "(", "self", ",", "resource", ")", ":", "missing_tags", "=", "[", "]", "notes", "=", "[", "]", "resource_tags", "=", "{", "tag", ".", "key", ".", "lower", "(", ")", ":", "tag", ".", "value", "for", "tag", "in", ...
Check whether a resource is compliance Args: resource: A single resource Returns: `(list, list)` A tuple contains missing tags (if there were any) and notes
[ "Check", "whether", "a", "resource", "is", "compliance" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-auditor-required-tags/cinq_auditor_required_tags/__init__.py#L447-L494
232,124
RiotGames/cloud-inquisitor
plugins/public/cinq-auditor-required-tags/cinq_auditor_required_tags/__init__.py
RequiredTagsAuditor.notify
def notify(self, notices): """Send notifications to the recipients provided Args: notices (:obj:`dict` of `str`: `list`): A dictionary mapping notification messages to the recipient. Returns: `None` """ tmpl_html = get_template('required_tags_notice.html') tmpl_text = get_template('required_tags_notice.txt') for recipient, data in list(notices.items()): body_html = tmpl_html.render(data=data) body_text = tmpl_text.render(data=data) send_notification( subsystem=self.ns, recipients=[recipient], subject=self.email_subject, body_html=body_html, body_text=body_text )
python
def notify(self, notices): tmpl_html = get_template('required_tags_notice.html') tmpl_text = get_template('required_tags_notice.txt') for recipient, data in list(notices.items()): body_html = tmpl_html.render(data=data) body_text = tmpl_text.render(data=data) send_notification( subsystem=self.ns, recipients=[recipient], subject=self.email_subject, body_html=body_html, body_text=body_text )
[ "def", "notify", "(", "self", ",", "notices", ")", ":", "tmpl_html", "=", "get_template", "(", "'required_tags_notice.html'", ")", "tmpl_text", "=", "get_template", "(", "'required_tags_notice.txt'", ")", "for", "recipient", ",", "data", "in", "list", "(", "noti...
Send notifications to the recipients provided Args: notices (:obj:`dict` of `str`: `list`): A dictionary mapping notification messages to the recipient. Returns: `None`
[ "Send", "notifications", "to", "the", "recipients", "provided" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-auditor-required-tags/cinq_auditor_required_tags/__init__.py#L496-L517
232,125
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/plugins/types/enforcements.py
Enforcement.get_one
def get_one(cls, enforcement_id): """ Return the properties of any enforcement action""" qry = db.Enforcements.filter(enforcement_id == Enforcements.enforcement_id) return qry
python
def get_one(cls, enforcement_id): qry = db.Enforcements.filter(enforcement_id == Enforcements.enforcement_id) return qry
[ "def", "get_one", "(", "cls", ",", "enforcement_id", ")", ":", "qry", "=", "db", ".", "Enforcements", ".", "filter", "(", "enforcement_id", "==", "Enforcements", ".", "enforcement_id", ")", "return", "qry" ]
Return the properties of any enforcement action
[ "Return", "the", "properties", "of", "any", "enforcement", "action" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/types/enforcements.py#L23-L27
232,126
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/plugins/types/enforcements.py
Enforcement.get_all
def get_all(cls, account_id=None, location=None): """ Return all Enforcements args: `account_id` : Unique Account Identifier `location` : Region associated with the Resource returns: list of enforcement objects """ qry = db.Enforcements.filter() if account_id: qry = qry.filter(account_id == Enforcements.account_id) if location: qry = qry.join(Resource, Resource.location == location) return qry
python
def get_all(cls, account_id=None, location=None): qry = db.Enforcements.filter() if account_id: qry = qry.filter(account_id == Enforcements.account_id) if location: qry = qry.join(Resource, Resource.location == location) return qry
[ "def", "get_all", "(", "cls", ",", "account_id", "=", "None", ",", "location", "=", "None", ")", ":", "qry", "=", "db", ".", "Enforcements", ".", "filter", "(", ")", "if", "account_id", ":", "qry", "=", "qry", ".", "filter", "(", "account_id", "==", ...
Return all Enforcements args: `account_id` : Unique Account Identifier `location` : Region associated with the Resource returns: list of enforcement objects
[ "Return", "all", "Enforcements" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/types/enforcements.py#L30-L49
232,127
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/plugins/types/enforcements.py
Enforcement.create
def create(cls, account_id, resource_id, action, timestamp, metrics): """ Set properties for an enforcement action""" enforcement = Enforcements() enforcement.account_id = account_id enforcement.resource_id = resource_id enforcement.action = action enforcement.timestamp = timestamp enforcement.metrics = metrics try: db.session.add(enforcement) except SQLAlchemyError as e: logging.error('Could not add enforcement entry to database. {}'.format(e))
python
def create(cls, account_id, resource_id, action, timestamp, metrics): enforcement = Enforcements() enforcement.account_id = account_id enforcement.resource_id = resource_id enforcement.action = action enforcement.timestamp = timestamp enforcement.metrics = metrics try: db.session.add(enforcement) except SQLAlchemyError as e: logging.error('Could not add enforcement entry to database. {}'.format(e))
[ "def", "create", "(", "cls", ",", "account_id", ",", "resource_id", ",", "action", ",", "timestamp", ",", "metrics", ")", ":", "enforcement", "=", "Enforcements", "(", ")", "enforcement", ".", "account_id", "=", "account_id", "enforcement", ".", "resource_id",...
Set properties for an enforcement action
[ "Set", "properties", "for", "an", "enforcement", "action" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/types/enforcements.py#L52-L66
232,128
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/schema/issues.py
IssueType.get
def get(cls, issue_type): """Returns the IssueType object for `issue_type`. If no existing object was found, a new type will be created in the database and returned Args: issue_type (str,int,IssueType): Issue type name, id or class Returns: :obj:`IssueType` """ if isinstance(issue_type, str): obj = getattr(db, cls.__name__).find_one(cls.issue_type == issue_type) elif isinstance(issue_type, int): obj = getattr(db, cls.__name__).find_one(cls.issue_type_id == issue_type) elif isinstance(issue_type, cls): return issue_type else: obj = None if not obj: obj = cls() obj.issue_type = issue_type db.session.add(obj) db.session.commit() db.session.refresh(obj) return obj
python
def get(cls, issue_type): if isinstance(issue_type, str): obj = getattr(db, cls.__name__).find_one(cls.issue_type == issue_type) elif isinstance(issue_type, int): obj = getattr(db, cls.__name__).find_one(cls.issue_type_id == issue_type) elif isinstance(issue_type, cls): return issue_type else: obj = None if not obj: obj = cls() obj.issue_type = issue_type db.session.add(obj) db.session.commit() db.session.refresh(obj) return obj
[ "def", "get", "(", "cls", ",", "issue_type", ")", ":", "if", "isinstance", "(", "issue_type", ",", "str", ")", ":", "obj", "=", "getattr", "(", "db", ",", "cls", ".", "__name__", ")", ".", "find_one", "(", "cls", ".", "issue_type", "==", "issue_type"...
Returns the IssueType object for `issue_type`. If no existing object was found, a new type will be created in the database and returned Args: issue_type (str,int,IssueType): Issue type name, id or class Returns: :obj:`IssueType`
[ "Returns", "the", "IssueType", "object", "for", "issue_type", ".", "If", "no", "existing", "object", "was", "found", "a", "new", "type", "will", "be", "created", "in", "the", "database", "and", "returned" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/schema/issues.py#L24-L54
232,129
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/schema/issues.py
Issue.get
def get(issue_id, issue_type_id): """Return issue by ID Args: issue_id (str): Unique Issue identifier issue_type_id (str): Type of issue to get Returns: :obj:`Issue`: Returns Issue object if found, else None """ return db.Issue.find_one( Issue.issue_id == issue_id, Issue.issue_type_id == issue_type_id )
python
def get(issue_id, issue_type_id): return db.Issue.find_one( Issue.issue_id == issue_id, Issue.issue_type_id == issue_type_id )
[ "def", "get", "(", "issue_id", ",", "issue_type_id", ")", ":", "return", "db", ".", "Issue", ".", "find_one", "(", "Issue", ".", "issue_id", "==", "issue_id", ",", "Issue", ".", "issue_type_id", "==", "issue_type_id", ")" ]
Return issue by ID Args: issue_id (str): Unique Issue identifier issue_type_id (str): Type of issue to get Returns: :obj:`Issue`: Returns Issue object if found, else None
[ "Return", "issue", "by", "ID" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/schema/issues.py#L106-L119
232,130
RiotGames/cloud-inquisitor
plugins/public/cinq-auditor-ebs/cinq_auditor_ebs/__init__.py
EBSAuditor.run
def run(self, *args, **kwargs): """Main execution point for the auditor Args: *args: **kwargs: Returns: `None` """ self.log.debug('Starting EBSAuditor') data = self.update_data() notices = defaultdict(list) for account, issues in data.items(): for issue in issues: for recipient in account.contacts: notices[NotificationContact(type=recipient['type'], value=recipient['value'])].append(issue) self.notify(notices)
python
def run(self, *args, **kwargs): self.log.debug('Starting EBSAuditor') data = self.update_data() notices = defaultdict(list) for account, issues in data.items(): for issue in issues: for recipient in account.contacts: notices[NotificationContact(type=recipient['type'], value=recipient['value'])].append(issue) self.notify(notices)
[ "def", "run", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "log", ".", "debug", "(", "'Starting EBSAuditor'", ")", "data", "=", "self", ".", "update_data", "(", ")", "notices", "=", "defaultdict", "(", "list", ")", ...
Main execution point for the auditor Args: *args: **kwargs: Returns: `None`
[ "Main", "execution", "point", "for", "the", "auditor" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-auditor-ebs/cinq_auditor_ebs/__init__.py#L31-L50
232,131
RiotGames/cloud-inquisitor
plugins/public/cinq-auditor-ebs/cinq_auditor_ebs/__init__.py
EBSAuditor.get_unattached_volumes
def get_unattached_volumes(self): """Build a list of all volumes missing tags and not ignored. Returns a `dict` keyed by the issue_id with the volume as the value Returns: :obj:`dict` of `str`: `EBSVolume` """ volumes = {} ignored_tags = dbconfig.get('ignore_tags', self.ns) for volume in EBSVolume.get_all().values(): issue_id = get_resource_id('evai', volume.id) if len(volume.attachments) == 0: if len(list(filter(set(ignored_tags).__contains__, [tag.key for tag in volume.tags]))): continue volumes[issue_id] = volume return volumes
python
def get_unattached_volumes(self): volumes = {} ignored_tags = dbconfig.get('ignore_tags', self.ns) for volume in EBSVolume.get_all().values(): issue_id = get_resource_id('evai', volume.id) if len(volume.attachments) == 0: if len(list(filter(set(ignored_tags).__contains__, [tag.key for tag in volume.tags]))): continue volumes[issue_id] = volume return volumes
[ "def", "get_unattached_volumes", "(", "self", ")", ":", "volumes", "=", "{", "}", "ignored_tags", "=", "dbconfig", ".", "get", "(", "'ignore_tags'", ",", "self", ".", "ns", ")", "for", "volume", "in", "EBSVolume", ".", "get_all", "(", ")", ".", "values",...
Build a list of all volumes missing tags and not ignored. Returns a `dict` keyed by the issue_id with the volume as the value Returns: :obj:`dict` of `str`: `EBSVolume`
[ "Build", "a", "list", "of", "all", "volumes", "missing", "tags", "and", "not", "ignored", ".", "Returns", "a", "dict", "keyed", "by", "the", "issue_id", "with", "the", "volume", "as", "the", "value" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-auditor-ebs/cinq_auditor_ebs/__init__.py#L84-L102
232,132
RiotGames/cloud-inquisitor
plugins/public/cinq-auditor-ebs/cinq_auditor_ebs/__init__.py
EBSAuditor.process_new_issues
def process_new_issues(self, volumes, existing_issues): """Takes a dict of existing volumes missing tags and a dict of existing issues, and finds any new or updated issues. Args: volumes (:obj:`dict` of `str`: `EBSVolume`): Dict of current volumes with issues existing_issues (:obj:`dict` of `str`: `EBSVolumeAuditIssue`): Current list of issues Returns: :obj:`dict` of `str`: `EBSVolumeAuditIssue` """ new_issues = {} for issue_id, volume in volumes.items(): state = EBSIssueState.DETECTED.value if issue_id in existing_issues: issue = existing_issues[issue_id] data = { 'state': state, 'notes': issue.notes, 'last_notice': issue.last_notice } if issue.update(data): new_issues.setdefault(issue.volume.account, []).append(issue) self.log.debug('Updated EBSVolumeAuditIssue {}'.format( issue_id )) else: properties = { 'volume_id': volume.id, 'account_id': volume.account_id, 'location': volume.location, 'state': state, 'last_change': datetime.now(), 'last_notice': None, 'notes': [] } issue = EBSVolumeAuditIssue.create(issue_id, properties=properties) new_issues.setdefault(issue.volume.account, []).append(issue) return new_issues
python
def process_new_issues(self, volumes, existing_issues): new_issues = {} for issue_id, volume in volumes.items(): state = EBSIssueState.DETECTED.value if issue_id in existing_issues: issue = existing_issues[issue_id] data = { 'state': state, 'notes': issue.notes, 'last_notice': issue.last_notice } if issue.update(data): new_issues.setdefault(issue.volume.account, []).append(issue) self.log.debug('Updated EBSVolumeAuditIssue {}'.format( issue_id )) else: properties = { 'volume_id': volume.id, 'account_id': volume.account_id, 'location': volume.location, 'state': state, 'last_change': datetime.now(), 'last_notice': None, 'notes': [] } issue = EBSVolumeAuditIssue.create(issue_id, properties=properties) new_issues.setdefault(issue.volume.account, []).append(issue) return new_issues
[ "def", "process_new_issues", "(", "self", ",", "volumes", ",", "existing_issues", ")", ":", "new_issues", "=", "{", "}", "for", "issue_id", ",", "volume", "in", "volumes", ".", "items", "(", ")", ":", "state", "=", "EBSIssueState", ".", "DETECTED", ".", ...
Takes a dict of existing volumes missing tags and a dict of existing issues, and finds any new or updated issues. Args: volumes (:obj:`dict` of `str`: `EBSVolume`): Dict of current volumes with issues existing_issues (:obj:`dict` of `str`: `EBSVolumeAuditIssue`): Current list of issues Returns: :obj:`dict` of `str`: `EBSVolumeAuditIssue`
[ "Takes", "a", "dict", "of", "existing", "volumes", "missing", "tags", "and", "a", "dict", "of", "existing", "issues", "and", "finds", "any", "new", "or", "updated", "issues", "." ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-auditor-ebs/cinq_auditor_ebs/__init__.py#L104-L147
232,133
RiotGames/cloud-inquisitor
plugins/public/cinq-auditor-ebs/cinq_auditor_ebs/__init__.py
EBSAuditor.process_fixed_issues
def process_fixed_issues(self, volumes, existing_issues): """Provided a list of volumes and existing issues, returns a list of fixed issues to be deleted Args: volumes (`dict`): A dictionary keyed on the issue id, with the :obj:`Volume` object as the value existing_issues (`dict`): A dictionary keyed on the issue id, with the :obj:`EBSVolumeAuditIssue` object as the value Returns: :obj:`list` of :obj:`EBSVolumeAuditIssue` """ fixed_issues = [] for issue_id, issue in list(existing_issues.items()): if issue_id not in volumes: fixed_issues.append(issue) return fixed_issues
python
def process_fixed_issues(self, volumes, existing_issues): fixed_issues = [] for issue_id, issue in list(existing_issues.items()): if issue_id not in volumes: fixed_issues.append(issue) return fixed_issues
[ "def", "process_fixed_issues", "(", "self", ",", "volumes", ",", "existing_issues", ")", ":", "fixed_issues", "=", "[", "]", "for", "issue_id", ",", "issue", "in", "list", "(", "existing_issues", ".", "items", "(", ")", ")", ":", "if", "issue_id", "not", ...
Provided a list of volumes and existing issues, returns a list of fixed issues to be deleted Args: volumes (`dict`): A dictionary keyed on the issue id, with the :obj:`Volume` object as the value existing_issues (`dict`): A dictionary keyed on the issue id, with the :obj:`EBSVolumeAuditIssue` object as the value Returns: :obj:`list` of :obj:`EBSVolumeAuditIssue`
[ "Provided", "a", "list", "of", "volumes", "and", "existing", "issues", "returns", "a", "list", "of", "fixed", "issues", "to", "be", "deleted" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-auditor-ebs/cinq_auditor_ebs/__init__.py#L149-L165
232,134
RiotGames/cloud-inquisitor
plugins/public/cinq-auditor-ebs/cinq_auditor_ebs/__init__.py
EBSAuditor.notify
def notify(self, notices): """Send notifications to the users via. the provided methods Args: notices (:obj:`dict` of `str`: `dict`): List of the notifications to send Returns: `None` """ issues_html = get_template('unattached_ebs_volume.html') issues_text = get_template('unattached_ebs_volume.txt') for recipient, issues in list(notices.items()): if issues: message_html = issues_html.render(issues=issues) message_text = issues_text.render(issues=issues) send_notification( subsystem=self.name, recipients=[recipient], subject=self.subject, body_html=message_html, body_text=message_text )
python
def notify(self, notices): issues_html = get_template('unattached_ebs_volume.html') issues_text = get_template('unattached_ebs_volume.txt') for recipient, issues in list(notices.items()): if issues: message_html = issues_html.render(issues=issues) message_text = issues_text.render(issues=issues) send_notification( subsystem=self.name, recipients=[recipient], subject=self.subject, body_html=message_html, body_text=message_text )
[ "def", "notify", "(", "self", ",", "notices", ")", ":", "issues_html", "=", "get_template", "(", "'unattached_ebs_volume.html'", ")", "issues_text", "=", "get_template", "(", "'unattached_ebs_volume.txt'", ")", "for", "recipient", ",", "issues", "in", "list", "(",...
Send notifications to the users via. the provided methods Args: notices (:obj:`dict` of `str`: `dict`): List of the notifications to send Returns: `None`
[ "Send", "notifications", "to", "the", "users", "via", ".", "the", "provided", "methods" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-auditor-ebs/cinq_auditor_ebs/__init__.py#L167-L190
232,135
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/__init__.py
get_local_aws_session
def get_local_aws_session(): """Returns a session for the local instance, not for a remote account Returns: :obj:`boto3:boto3.session.Session` """ if not all((app_config.aws_api.access_key, app_config.aws_api.secret_key)): return boto3.session.Session() else: # If we are not running on an EC2 instance, assume the instance role # first, then assume the remote role session_args = [app_config.aws_api.access_key, app_config.aws_api.secret_key] if app_config.aws_api.session_token: session_args.append(app_config.aws_api.session_token) return boto3.session.Session(*session_args)
python
def get_local_aws_session(): if not all((app_config.aws_api.access_key, app_config.aws_api.secret_key)): return boto3.session.Session() else: # If we are not running on an EC2 instance, assume the instance role # first, then assume the remote role session_args = [app_config.aws_api.access_key, app_config.aws_api.secret_key] if app_config.aws_api.session_token: session_args.append(app_config.aws_api.session_token) return boto3.session.Session(*session_args)
[ "def", "get_local_aws_session", "(", ")", ":", "if", "not", "all", "(", "(", "app_config", ".", "aws_api", ".", "access_key", ",", "app_config", ".", "aws_api", ".", "secret_key", ")", ")", ":", "return", "boto3", ".", "session", ".", "Session", "(", ")"...
Returns a session for the local instance, not for a remote account Returns: :obj:`boto3:boto3.session.Session`
[ "Returns", "a", "session", "for", "the", "local", "instance", "not", "for", "a", "remote", "account" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/__init__.py#L21-L36
232,136
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/__init__.py
get_aws_session
def get_aws_session(account): """Function to return a boto3 Session based on the account passed in the first argument. Args: account (:obj:`Account`): Account to create the session object for Returns: :obj:`boto3:boto3.session.Session` """ from cloud_inquisitor.config import dbconfig from cloud_inquisitor.plugins.types.accounts import AWSAccount if not isinstance(account, AWSAccount): raise InquisitorError('Non AWSAccount passed to get_aws_session, got {}'.format(account.__class__.__name__)) # If no keys are on supplied for the account, use sts.assume_role instead session = get_local_aws_session() if session.get_credentials().method in ['iam-role', 'env', 'explicit']: sts = session.client('sts') else: # If we are not running on an EC2 instance, assume the instance role # first, then assume the remote role temp_sts = session.client('sts') audit_sts_role = temp_sts.assume_role( RoleArn=app_config.aws_api.instance_role_arn, RoleSessionName='inquisitor' ) sts = boto3.session.Session( audit_sts_role['Credentials']['AccessKeyId'], audit_sts_role['Credentials']['SecretAccessKey'], audit_sts_role['Credentials']['SessionToken'] ).client('sts') role = sts.assume_role( RoleArn='arn:aws:iam::{}:role/{}'.format( account.account_number, dbconfig.get('role_name', default='cinq_role') ), RoleSessionName='inquisitor' ) sess = boto3.session.Session( role['Credentials']['AccessKeyId'], role['Credentials']['SecretAccessKey'], role['Credentials']['SessionToken'] ) return sess
python
def get_aws_session(account): from cloud_inquisitor.config import dbconfig from cloud_inquisitor.plugins.types.accounts import AWSAccount if not isinstance(account, AWSAccount): raise InquisitorError('Non AWSAccount passed to get_aws_session, got {}'.format(account.__class__.__name__)) # If no keys are on supplied for the account, use sts.assume_role instead session = get_local_aws_session() if session.get_credentials().method in ['iam-role', 'env', 'explicit']: sts = session.client('sts') else: # If we are not running on an EC2 instance, assume the instance role # first, then assume the remote role temp_sts = session.client('sts') audit_sts_role = temp_sts.assume_role( RoleArn=app_config.aws_api.instance_role_arn, RoleSessionName='inquisitor' ) sts = boto3.session.Session( audit_sts_role['Credentials']['AccessKeyId'], audit_sts_role['Credentials']['SecretAccessKey'], audit_sts_role['Credentials']['SessionToken'] ).client('sts') role = sts.assume_role( RoleArn='arn:aws:iam::{}:role/{}'.format( account.account_number, dbconfig.get('role_name', default='cinq_role') ), RoleSessionName='inquisitor' ) sess = boto3.session.Session( role['Credentials']['AccessKeyId'], role['Credentials']['SecretAccessKey'], role['Credentials']['SessionToken'] ) return sess
[ "def", "get_aws_session", "(", "account", ")", ":", "from", "cloud_inquisitor", ".", "config", "import", "dbconfig", "from", "cloud_inquisitor", ".", "plugins", ".", "types", ".", "accounts", "import", "AWSAccount", "if", "not", "isinstance", "(", "account", ","...
Function to return a boto3 Session based on the account passed in the first argument. Args: account (:obj:`Account`): Account to create the session object for Returns: :obj:`boto3:boto3.session.Session`
[ "Function", "to", "return", "a", "boto3", "Session", "based", "on", "the", "account", "passed", "in", "the", "first", "argument", "." ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/__init__.py#L39-L87
232,137
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/__init__.py
get_aws_regions
def get_aws_regions(*, force=False): """Load a list of AWS regions from the AWS static data. Args: force (`bool`): Force fetch list of regions even if we already have a cached version Returns: :obj:`list` of `str` """ from cloud_inquisitor.config import dbconfig global __regions if force or not __regions: logger.debug('Loading list of AWS regions from static data') data = requests.get('https://ip-ranges.amazonaws.com/ip-ranges.json').json() rgx = re.compile(dbconfig.get('ignored_aws_regions_regexp', default='(^cn-|GLOBAL|-gov)'), re.I) __regions = sorted(list({x['region'] for x in data['prefixes'] if not rgx.search(x['region'])})) return __regions
python
def get_aws_regions(*, force=False): from cloud_inquisitor.config import dbconfig global __regions if force or not __regions: logger.debug('Loading list of AWS regions from static data') data = requests.get('https://ip-ranges.amazonaws.com/ip-ranges.json').json() rgx = re.compile(dbconfig.get('ignored_aws_regions_regexp', default='(^cn-|GLOBAL|-gov)'), re.I) __regions = sorted(list({x['region'] for x in data['prefixes'] if not rgx.search(x['region'])})) return __regions
[ "def", "get_aws_regions", "(", "*", ",", "force", "=", "False", ")", ":", "from", "cloud_inquisitor", ".", "config", "import", "dbconfig", "global", "__regions", "if", "force", "or", "not", "__regions", ":", "logger", ".", "debug", "(", "'Loading list of AWS r...
Load a list of AWS regions from the AWS static data. Args: force (`bool`): Force fetch list of regions even if we already have a cached version Returns: :obj:`list` of `str`
[ "Load", "a", "list", "of", "AWS", "regions", "from", "the", "AWS", "static", "data", "." ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/__init__.py#L90-L108
232,138
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/plugins/views/accounts.py
AccountList.get
def get(self): """List all accounts""" _, accounts = BaseAccount.search() if ROLE_ADMIN not in session['user'].roles: accounts = list(filter(lambda acct: acct.account_id in session['accounts'], accounts)) if accounts: return self.make_response({ 'message': None, 'accounts': [x.to_json(is_admin=ROLE_ADMIN in session['user'].roles or False) for x in accounts] }) else: return self.make_response({ 'message': 'Unable to find any accounts', 'accounts': None }, HTTP.NOT_FOUND)
python
def get(self): _, accounts = BaseAccount.search() if ROLE_ADMIN not in session['user'].roles: accounts = list(filter(lambda acct: acct.account_id in session['accounts'], accounts)) if accounts: return self.make_response({ 'message': None, 'accounts': [x.to_json(is_admin=ROLE_ADMIN in session['user'].roles or False) for x in accounts] }) else: return self.make_response({ 'message': 'Unable to find any accounts', 'accounts': None }, HTTP.NOT_FOUND)
[ "def", "get", "(", "self", ")", ":", "_", ",", "accounts", "=", "BaseAccount", ".", "search", "(", ")", "if", "ROLE_ADMIN", "not", "in", "session", "[", "'user'", "]", ".", "roles", ":", "accounts", "=", "list", "(", "filter", "(", "lambda", "acct", ...
List all accounts
[ "List", "all", "accounts" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/views/accounts.py#L43-L59
232,139
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/plugins/views/accounts.py
AccountDetail.get
def get(self, accountId): """Fetch a single account""" account = BaseAccount.get(accountId) if account: return self.make_response({ 'message': None, 'account': account.to_json(is_admin=True) }) else: return self.make_response({ 'message': 'Unable to find account', 'account': None }, HTTP.NOT_FOUND)
python
def get(self, accountId): account = BaseAccount.get(accountId) if account: return self.make_response({ 'message': None, 'account': account.to_json(is_admin=True) }) else: return self.make_response({ 'message': 'Unable to find account', 'account': None }, HTTP.NOT_FOUND)
[ "def", "get", "(", "self", ",", "accountId", ")", ":", "account", "=", "BaseAccount", ".", "get", "(", "accountId", ")", "if", "account", ":", "return", "self", ".", "make_response", "(", "{", "'message'", ":", "None", ",", "'account'", ":", "account", ...
Fetch a single account
[ "Fetch", "a", "single", "account" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/views/accounts.py#L117-L129
232,140
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/plugins/views/accounts.py
AccountDetail.put
def put(self, accountId): """Update an account""" self.reqparse.add_argument('accountName', type=str, required=True) self.reqparse.add_argument('accountType', type=str, required=True) self.reqparse.add_argument('contacts', type=dict, required=True, action='append') self.reqparse.add_argument('enabled', type=int, required=True, choices=(0, 1)) self.reqparse.add_argument('requiredRoles', type=str, action='append', default=()) self.reqparse.add_argument('properties', type=dict, required=True) args = self.reqparse.parse_args() account_class = get_plugin_by_name(PLUGIN_NAMESPACES['accounts'], args['accountType']) if not account_class: raise InquisitorError('Invalid account type: {}'.format(args['accountType'])) validate_contacts(args['contacts']) if not args['accountName'].strip(): raise Exception('You must provide an account name') if not args['contacts']: raise Exception('You must provide at least one contact') class_properties = {from_camelcase(key): value for key, value in args['properties'].items()} for prop in account_class.class_properties: if prop['key'] not in class_properties: raise InquisitorError('Missing required property {}'.format(prop)) account = account_class.get(accountId) if account.account_type != args['accountType']: raise InquisitorError('You cannot change the type of an account') account.account_name = args['accountName'] account.contacts = args['contacts'] account.enabled = args['enabled'] account.required_roles = args['requiredRoles'] account.update(**args['properties']) account.save() auditlog(event='account.update', actor=session['user'].username, data=args) return self.make_response({'message': 'Object updated', 'account': account.to_json(is_admin=True)})
python
def put(self, accountId): self.reqparse.add_argument('accountName', type=str, required=True) self.reqparse.add_argument('accountType', type=str, required=True) self.reqparse.add_argument('contacts', type=dict, required=True, action='append') self.reqparse.add_argument('enabled', type=int, required=True, choices=(0, 1)) self.reqparse.add_argument('requiredRoles', type=str, action='append', default=()) self.reqparse.add_argument('properties', type=dict, required=True) args = self.reqparse.parse_args() account_class = get_plugin_by_name(PLUGIN_NAMESPACES['accounts'], args['accountType']) if not account_class: raise InquisitorError('Invalid account type: {}'.format(args['accountType'])) validate_contacts(args['contacts']) if not args['accountName'].strip(): raise Exception('You must provide an account name') if not args['contacts']: raise Exception('You must provide at least one contact') class_properties = {from_camelcase(key): value for key, value in args['properties'].items()} for prop in account_class.class_properties: if prop['key'] not in class_properties: raise InquisitorError('Missing required property {}'.format(prop)) account = account_class.get(accountId) if account.account_type != args['accountType']: raise InquisitorError('You cannot change the type of an account') account.account_name = args['accountName'] account.contacts = args['contacts'] account.enabled = args['enabled'] account.required_roles = args['requiredRoles'] account.update(**args['properties']) account.save() auditlog(event='account.update', actor=session['user'].username, data=args) return self.make_response({'message': 'Object updated', 'account': account.to_json(is_admin=True)})
[ "def", "put", "(", "self", ",", "accountId", ")", ":", "self", ".", "reqparse", ".", "add_argument", "(", "'accountName'", ",", "type", "=", "str", ",", "required", "=", "True", ")", "self", ".", "reqparse", ".", "add_argument", "(", "'accountType'", ","...
Update an account
[ "Update", "an", "account" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/views/accounts.py#L133-L173
232,141
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/plugins/views/accounts.py
AccountDetail.delete
def delete(self, accountId): """Delete an account""" acct = BaseAccount.get(accountId) if not acct: raise Exception('No such account found') acct.delete() auditlog(event='account.delete', actor=session['user'].username, data={'accountId': accountId}) return self.make_response('Account deleted')
python
def delete(self, accountId): acct = BaseAccount.get(accountId) if not acct: raise Exception('No such account found') acct.delete() auditlog(event='account.delete', actor=session['user'].username, data={'accountId': accountId}) return self.make_response('Account deleted')
[ "def", "delete", "(", "self", ",", "accountId", ")", ":", "acct", "=", "BaseAccount", ".", "get", "(", "accountId", ")", "if", "not", "acct", ":", "raise", "Exception", "(", "'No such account found'", ")", "acct", ".", "delete", "(", ")", "auditlog", "("...
Delete an account
[ "Delete", "an", "account" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/views/accounts.py#L177-L186
232,142
RiotGames/cloud-inquisitor
plugins/public/cinq-collector-aws/cinq_collector_aws/account.py
AWSAccountCollector.__get_distribution_tags
def __get_distribution_tags(self, client, arn): """Returns a dict containing the tags for a CloudFront distribution Args: client (botocore.client.CloudFront): Boto3 CloudFront client object arn (str): ARN of the distribution to get tags for Returns: `dict` """ return { t['Key']: t['Value'] for t in client.list_tags_for_resource( Resource=arn )['Tags']['Items'] }
python
def __get_distribution_tags(self, client, arn): return { t['Key']: t['Value'] for t in client.list_tags_for_resource( Resource=arn )['Tags']['Items'] }
[ "def", "__get_distribution_tags", "(", "self", ",", "client", ",", "arn", ")", ":", "return", "{", "t", "[", "'Key'", "]", ":", "t", "[", "'Value'", "]", "for", "t", "in", "client", ".", "list_tags_for_resource", "(", "Resource", "=", "arn", ")", "[", ...
Returns a dict containing the tags for a CloudFront distribution Args: client (botocore.client.CloudFront): Boto3 CloudFront client object arn (str): ARN of the distribution to get tags for Returns: `dict`
[ "Returns", "a", "dict", "containing", "the", "tags", "for", "a", "CloudFront", "distribution" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-collector-aws/cinq_collector_aws/account.py#L418-L432
232,143
RiotGames/cloud-inquisitor
plugins/public/cinq-collector-aws/cinq_collector_aws/account.py
AWSAccountCollector.__fetch_route53_zones
def __fetch_route53_zones(self): """Return a list of all DNS zones hosted in Route53 Returns: :obj:`list` of `dict` """ done = False marker = None zones = {} route53 = self.session.client('route53') try: while not done: if marker: response = route53.list_hosted_zones(Marker=marker) else: response = route53.list_hosted_zones() if response['IsTruncated']: marker = response['NextMarker'] else: done = True for zone_data in response['HostedZones']: zones[get_resource_id('r53z', zone_data['Id'])] = { 'name': zone_data['Name'].rstrip('.'), 'source': 'AWS/{}'.format(self.account), 'comment': zone_data['Config']['Comment'] if 'Comment' in zone_data['Config'] else None, 'zone_id': zone_data['Id'], 'private_zone': zone_data['Config']['PrivateZone'], 'tags': self.__fetch_route53_zone_tags(zone_data['Id']) } return zones finally: del route53
python
def __fetch_route53_zones(self): done = False marker = None zones = {} route53 = self.session.client('route53') try: while not done: if marker: response = route53.list_hosted_zones(Marker=marker) else: response = route53.list_hosted_zones() if response['IsTruncated']: marker = response['NextMarker'] else: done = True for zone_data in response['HostedZones']: zones[get_resource_id('r53z', zone_data['Id'])] = { 'name': zone_data['Name'].rstrip('.'), 'source': 'AWS/{}'.format(self.account), 'comment': zone_data['Config']['Comment'] if 'Comment' in zone_data['Config'] else None, 'zone_id': zone_data['Id'], 'private_zone': zone_data['Config']['PrivateZone'], 'tags': self.__fetch_route53_zone_tags(zone_data['Id']) } return zones finally: del route53
[ "def", "__fetch_route53_zones", "(", "self", ")", ":", "done", "=", "False", "marker", "=", "None", "zones", "=", "{", "}", "route53", "=", "self", ".", "session", ".", "client", "(", "'route53'", ")", "try", ":", "while", "not", "done", ":", "if", "...
Return a list of all DNS zones hosted in Route53 Returns: :obj:`list` of `dict`
[ "Return", "a", "list", "of", "all", "DNS", "zones", "hosted", "in", "Route53" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-collector-aws/cinq_collector_aws/account.py#L435-L470
232,144
RiotGames/cloud-inquisitor
plugins/public/cinq-collector-aws/cinq_collector_aws/account.py
AWSAccountCollector.__fetch_route53_zone_records
def __fetch_route53_zone_records(self, zone_id): """Return all resource records for a specific Route53 zone Args: zone_id (`str`): Name / ID of the hosted zone Returns: `dict` """ route53 = self.session.client('route53') done = False nextName = nextType = None records = {} try: while not done: if nextName and nextType: response = route53.list_resource_record_sets( HostedZoneId=zone_id, StartRecordName=nextName, StartRecordType=nextType ) else: response = route53.list_resource_record_sets(HostedZoneId=zone_id) if response['IsTruncated']: nextName = response['NextRecordName'] nextType = response['NextRecordType'] else: done = True if 'ResourceRecordSets' in response: for record in response['ResourceRecordSets']: # Cannot make this a list, due to a race-condition in the AWS api that might return the same # record more than once, so we use a dict instead to ensure that if we get duplicate records # we simply just overwrite the one already there with the same info. record_id = self._get_resource_hash(zone_id, record) if 'AliasTarget' in record: value = record['AliasTarget']['DNSName'] records[record_id] = { 'id': record_id, 'name': record['Name'].rstrip('.'), 'type': 'ALIAS', 'ttl': 0, 'value': [value] } else: value = [y['Value'] for y in record['ResourceRecords']] records[record_id] = { 'id': record_id, 'name': record['Name'].rstrip('.'), 'type': record['Type'], 'ttl': record['TTL'], 'value': value } return list(records.values()) finally: del route53
python
def __fetch_route53_zone_records(self, zone_id): route53 = self.session.client('route53') done = False nextName = nextType = None records = {} try: while not done: if nextName and nextType: response = route53.list_resource_record_sets( HostedZoneId=zone_id, StartRecordName=nextName, StartRecordType=nextType ) else: response = route53.list_resource_record_sets(HostedZoneId=zone_id) if response['IsTruncated']: nextName = response['NextRecordName'] nextType = response['NextRecordType'] else: done = True if 'ResourceRecordSets' in response: for record in response['ResourceRecordSets']: # Cannot make this a list, due to a race-condition in the AWS api that might return the same # record more than once, so we use a dict instead to ensure that if we get duplicate records # we simply just overwrite the one already there with the same info. record_id = self._get_resource_hash(zone_id, record) if 'AliasTarget' in record: value = record['AliasTarget']['DNSName'] records[record_id] = { 'id': record_id, 'name': record['Name'].rstrip('.'), 'type': 'ALIAS', 'ttl': 0, 'value': [value] } else: value = [y['Value'] for y in record['ResourceRecords']] records[record_id] = { 'id': record_id, 'name': record['Name'].rstrip('.'), 'type': record['Type'], 'ttl': record['TTL'], 'value': value } return list(records.values()) finally: del route53
[ "def", "__fetch_route53_zone_records", "(", "self", ",", "zone_id", ")", ":", "route53", "=", "self", ".", "session", ".", "client", "(", "'route53'", ")", "done", "=", "False", "nextName", "=", "nextType", "=", "None", "records", "=", "{", "}", "try", "...
Return all resource records for a specific Route53 zone Args: zone_id (`str`): Name / ID of the hosted zone Returns: `dict`
[ "Return", "all", "resource", "records", "for", "a", "specific", "Route53", "zone" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-collector-aws/cinq_collector_aws/account.py#L473-L532
232,145
RiotGames/cloud-inquisitor
plugins/public/cinq-collector-aws/cinq_collector_aws/account.py
AWSAccountCollector.__fetch_route53_zone_tags
def __fetch_route53_zone_tags(self, zone_id): """Return a dict with the tags for the zone Args: zone_id (`str`): ID of the hosted zone Returns: :obj:`dict` of `str`: `str` """ route53 = self.session.client('route53') try: return { tag['Key']: tag['Value'] for tag in route53.list_tags_for_resource( ResourceType='hostedzone', ResourceId=zone_id.split('/')[-1] )['ResourceTagSet']['Tags'] } finally: del route53
python
def __fetch_route53_zone_tags(self, zone_id): route53 = self.session.client('route53') try: return { tag['Key']: tag['Value'] for tag in route53.list_tags_for_resource( ResourceType='hostedzone', ResourceId=zone_id.split('/')[-1] )['ResourceTagSet']['Tags'] } finally: del route53
[ "def", "__fetch_route53_zone_tags", "(", "self", ",", "zone_id", ")", ":", "route53", "=", "self", ".", "session", ".", "client", "(", "'route53'", ")", "try", ":", "return", "{", "tag", "[", "'Key'", "]", ":", "tag", "[", "'Value'", "]", "for", "tag",...
Return a dict with the tags for the zone Args: zone_id (`str`): ID of the hosted zone Returns: :obj:`dict` of `str`: `str`
[ "Return", "a", "dict", "with", "the", "tags", "for", "the", "zone" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-collector-aws/cinq_collector_aws/account.py#L535-L555
232,146
RiotGames/cloud-inquisitor
plugins/public/cinq-collector-aws/cinq_collector_aws/account.py
AWSAccountCollector._get_resource_hash
def _get_resource_hash(zone_name, record): """Returns the last ten digits of the sha256 hash of the combined arguments. Useful for generating unique resource IDs Args: zone_name (`str`): The name of the DNS Zone the record belongs to record (`dict`): A record dict to generate the hash from Returns: `str` """ record_data = defaultdict(int, record) if type(record_data['GeoLocation']) == dict: record_data['GeoLocation'] = ":".join(["{}={}".format(k, v) for k, v in record_data['GeoLocation'].items()]) args = [ zone_name, record_data['Name'], record_data['Type'], record_data['Weight'], record_data['Region'], record_data['GeoLocation'], record_data['Failover'], record_data['HealthCheckId'], record_data['TrafficPolicyInstanceId'] ] return get_resource_id('r53r', args)
python
def _get_resource_hash(zone_name, record): record_data = defaultdict(int, record) if type(record_data['GeoLocation']) == dict: record_data['GeoLocation'] = ":".join(["{}={}".format(k, v) for k, v in record_data['GeoLocation'].items()]) args = [ zone_name, record_data['Name'], record_data['Type'], record_data['Weight'], record_data['Region'], record_data['GeoLocation'], record_data['Failover'], record_data['HealthCheckId'], record_data['TrafficPolicyInstanceId'] ] return get_resource_id('r53r', args)
[ "def", "_get_resource_hash", "(", "zone_name", ",", "record", ")", ":", "record_data", "=", "defaultdict", "(", "int", ",", "record", ")", "if", "type", "(", "record_data", "[", "'GeoLocation'", "]", ")", "==", "dict", ":", "record_data", "[", "'GeoLocation'...
Returns the last ten digits of the sha256 hash of the combined arguments. Useful for generating unique resource IDs Args: zone_name (`str`): The name of the DNS Zone the record belongs to record (`dict`): A record dict to generate the hash from Returns: `str`
[ "Returns", "the", "last", "ten", "digits", "of", "the", "sha256", "hash", "of", "the", "combined", "arguments", ".", "Useful", "for", "generating", "unique", "resource", "IDs" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-collector-aws/cinq_collector_aws/account.py#L558-L585
232,147
RiotGames/cloud-inquisitor
plugins/public/cinq-collector-aws/cinq_collector_aws/account.py
AWSAccountCollector._get_bucket_statistics
def _get_bucket_statistics(self, bucket_name, bucket_region, storage_type, statistic, days): """ Returns datapoints from cloudwatch for bucket statistics. Args: bucket_name `(str)`: The name of the bucket statistic `(str)`: The statistic you want to fetch from days `(int)`: Sample period for the statistic """ cw = self.session.client('cloudwatch', region_name=bucket_region) # gather cw stats try: obj_stats = cw.get_metric_statistics( Namespace='AWS/S3', MetricName=statistic, Dimensions=[ { 'Name': 'StorageType', 'Value': storage_type }, { 'Name': 'BucketName', 'Value': bucket_name } ], Period=86400, StartTime=datetime.utcnow() - timedelta(days=days), EndTime=datetime.utcnow(), Statistics=[ 'Average' ] ) stat_value = obj_stats['Datapoints'][0]['Average'] if obj_stats['Datapoints'] else 'NO_DATA' return stat_value except Exception as e: self.log.error( 'Could not get bucket statistic for account {} / bucket {} / {}'.format(self.account.account_name, bucket_name, e)) finally: del cw
python
def _get_bucket_statistics(self, bucket_name, bucket_region, storage_type, statistic, days): cw = self.session.client('cloudwatch', region_name=bucket_region) # gather cw stats try: obj_stats = cw.get_metric_statistics( Namespace='AWS/S3', MetricName=statistic, Dimensions=[ { 'Name': 'StorageType', 'Value': storage_type }, { 'Name': 'BucketName', 'Value': bucket_name } ], Period=86400, StartTime=datetime.utcnow() - timedelta(days=days), EndTime=datetime.utcnow(), Statistics=[ 'Average' ] ) stat_value = obj_stats['Datapoints'][0]['Average'] if obj_stats['Datapoints'] else 'NO_DATA' return stat_value except Exception as e: self.log.error( 'Could not get bucket statistic for account {} / bucket {} / {}'.format(self.account.account_name, bucket_name, e)) finally: del cw
[ "def", "_get_bucket_statistics", "(", "self", ",", "bucket_name", ",", "bucket_region", ",", "storage_type", ",", "statistic", ",", "days", ")", ":", "cw", "=", "self", ".", "session", ".", "client", "(", "'cloudwatch'", ",", "region_name", "=", "bucket_region...
Returns datapoints from cloudwatch for bucket statistics. Args: bucket_name `(str)`: The name of the bucket statistic `(str)`: The statistic you want to fetch from days `(int)`: Sample period for the statistic
[ "Returns", "datapoints", "from", "cloudwatch", "for", "bucket", "statistics", "." ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-collector-aws/cinq_collector_aws/account.py#L587-L632
232,148
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/schema/resource.py
ResourceType.get
def get(cls, resource_type): """Returns the ResourceType object for `resource_type`. If no existing object was found, a new type will be created in the database and returned Args: resource_type (str): Resource type name Returns: :obj:`ResourceType` """ if isinstance(resource_type, str): obj = getattr(db, cls.__name__).find_one(cls.resource_type == resource_type) elif isinstance(resource_type, int): obj = getattr(db, cls.__name__).find_one(cls.resource_type_id == resource_type) elif isinstance(resource_type, cls): return resource_type else: obj = None if not obj: obj = cls() obj.resource_type = resource_type db.session.add(obj) db.session.commit() db.session.refresh(obj) return obj
python
def get(cls, resource_type): if isinstance(resource_type, str): obj = getattr(db, cls.__name__).find_one(cls.resource_type == resource_type) elif isinstance(resource_type, int): obj = getattr(db, cls.__name__).find_one(cls.resource_type_id == resource_type) elif isinstance(resource_type, cls): return resource_type else: obj = None if not obj: obj = cls() obj.resource_type = resource_type db.session.add(obj) db.session.commit() db.session.refresh(obj) return obj
[ "def", "get", "(", "cls", ",", "resource_type", ")", ":", "if", "isinstance", "(", "resource_type", ",", "str", ")", ":", "obj", "=", "getattr", "(", "db", ",", "cls", ".", "__name__", ")", ".", "find_one", "(", "cls", ".", "resource_type", "==", "re...
Returns the ResourceType object for `resource_type`. If no existing object was found, a new type will be created in the database and returned Args: resource_type (str): Resource type name Returns: :obj:`ResourceType`
[ "Returns", "the", "ResourceType", "object", "for", "resource_type", ".", "If", "no", "existing", "object", "was", "found", "a", "new", "type", "will", "be", "created", "in", "the", "database", "and", "returned" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/schema/resource.py#L72-L101
232,149
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/schema/accounts.py
Account.get
def get(account_id, account_type_id=None): """Return account by ID and type Args: account_id (`int`, `str`): Unique Account identifier account_type_id (str): Type of account to get Returns: :obj:`Account`: Returns an Account object if found, else None """ if type(account_id) == str: args = {'account_name': account_id} else: args = {'account_id': account_id} if account_type_id: args['account_type_id'] = account_type_id return db.Account.find_one(**args)
python
def get(account_id, account_type_id=None): if type(account_id) == str: args = {'account_name': account_id} else: args = {'account_id': account_id} if account_type_id: args['account_type_id'] = account_type_id return db.Account.find_one(**args)
[ "def", "get", "(", "account_id", ",", "account_type_id", "=", "None", ")", ":", "if", "type", "(", "account_id", ")", "==", "str", ":", "args", "=", "{", "'account_name'", ":", "account_id", "}", "else", ":", "args", "=", "{", "'account_id'", ":", "acc...
Return account by ID and type Args: account_id (`int`, `str`): Unique Account identifier account_type_id (str): Type of account to get Returns: :obj:`Account`: Returns an Account object if found, else None
[ "Return", "account", "by", "ID", "and", "type" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/schema/accounts.py#L96-L114
232,150
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/schema/accounts.py
Account.user_has_access
def user_has_access(self, user): """Check if a user has access to view information for the account Args: user (:obj:`User`): User object to check Returns: True if user has access to the account, else false """ if ROLE_ADMIN in user.roles: return True # Non-admin users should only see active accounts if self.enabled: if not self.required_roles: return True for role in self.required_roles: if role in user.roles: return True return False
python
def user_has_access(self, user): if ROLE_ADMIN in user.roles: return True # Non-admin users should only see active accounts if self.enabled: if not self.required_roles: return True for role in self.required_roles: if role in user.roles: return True return False
[ "def", "user_has_access", "(", "self", ",", "user", ")", ":", "if", "ROLE_ADMIN", "in", "user", ".", "roles", ":", "return", "True", "# Non-admin users should only see active accounts", "if", "self", ".", "enabled", ":", "if", "not", "self", ".", "required_roles...
Check if a user has access to view information for the account Args: user (:obj:`User`): User object to check Returns: True if user has access to the account, else false
[ "Check", "if", "a", "user", "has", "access", "to", "view", "information", "for", "the", "account" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/schema/accounts.py#L116-L137
232,151
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/plugins/__init__.py
BaseScheduler.load_plugins
def load_plugins(self): """Refresh the list of available collectors and auditors Returns: `None` """ for entry_point in CINQ_PLUGINS['cloud_inquisitor.plugins.collectors']['plugins']: cls = entry_point.load() if cls.enabled(): self.log.debug('Collector loaded: {} in module {}'.format(cls.__name__, cls.__module__)) self.collectors.setdefault(cls.type, []).append(Worker( cls.name, cls.interval, { 'name': entry_point.name, 'module_name': entry_point.module_name, 'attrs': entry_point.attrs } )) else: self.log.debug('Collector disabled: {} in module {}'.format(cls.__name__, cls.__module__)) for entry_point in CINQ_PLUGINS['cloud_inquisitor.plugins.auditors']['plugins']: cls = entry_point.load() if cls.enabled(): self.log.debug('Auditor loaded: {} in module {}'.format(cls.__name__, cls.__module__)) self.auditors.append(Worker( cls.name, cls.interval, { 'name': entry_point.name, 'module_name': entry_point.module_name, 'attrs': entry_point.attrs } )) else: self.log.debug('Auditor disabled: {} in module {}'.format(cls.__name__, cls.__module__)) collector_count = sum(len(x) for x in self.collectors.values()) auditor_count = len(self.auditors) if collector_count + auditor_count == 0: raise Exception('No auditors or collectors loaded, aborting scheduler') self.log.info('Scheduler loaded {} collectors and {} auditors'.format(collector_count, auditor_count))
python
def load_plugins(self): for entry_point in CINQ_PLUGINS['cloud_inquisitor.plugins.collectors']['plugins']: cls = entry_point.load() if cls.enabled(): self.log.debug('Collector loaded: {} in module {}'.format(cls.__name__, cls.__module__)) self.collectors.setdefault(cls.type, []).append(Worker( cls.name, cls.interval, { 'name': entry_point.name, 'module_name': entry_point.module_name, 'attrs': entry_point.attrs } )) else: self.log.debug('Collector disabled: {} in module {}'.format(cls.__name__, cls.__module__)) for entry_point in CINQ_PLUGINS['cloud_inquisitor.plugins.auditors']['plugins']: cls = entry_point.load() if cls.enabled(): self.log.debug('Auditor loaded: {} in module {}'.format(cls.__name__, cls.__module__)) self.auditors.append(Worker( cls.name, cls.interval, { 'name': entry_point.name, 'module_name': entry_point.module_name, 'attrs': entry_point.attrs } )) else: self.log.debug('Auditor disabled: {} in module {}'.format(cls.__name__, cls.__module__)) collector_count = sum(len(x) for x in self.collectors.values()) auditor_count = len(self.auditors) if collector_count + auditor_count == 0: raise Exception('No auditors or collectors loaded, aborting scheduler') self.log.info('Scheduler loaded {} collectors and {} auditors'.format(collector_count, auditor_count))
[ "def", "load_plugins", "(", "self", ")", ":", "for", "entry_point", "in", "CINQ_PLUGINS", "[", "'cloud_inquisitor.plugins.collectors'", "]", "[", "'plugins'", "]", ":", "cls", "=", "entry_point", ".", "load", "(", ")", "if", "cls", ".", "enabled", "(", ")", ...
Refresh the list of available collectors and auditors Returns: `None`
[ "Refresh", "the", "list", "of", "available", "collectors", "and", "auditors" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/__init__.py#L155-L199
232,152
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/plugins/commands/scheduler.py
BaseSchedulerCommand.load_scheduler_plugins
def load_scheduler_plugins(self): """Refresh the list of available schedulers Returns: `list` of :obj:`BaseScheduler` """ if not self.scheduler_plugins: for entry_point in CINQ_PLUGINS['cloud_inquisitor.plugins.schedulers']['plugins']: cls = entry_point.load() self.scheduler_plugins[cls.__name__] = cls if cls.__name__ == self.active_scheduler: self.log.debug('Scheduler loaded: {} in module {}'.format(cls.__name__, cls.__module__)) else: self.log.debug('Scheduler disabled: {} in module {}'.format(cls.__name__, cls.__module__))
python
def load_scheduler_plugins(self): if not self.scheduler_plugins: for entry_point in CINQ_PLUGINS['cloud_inquisitor.plugins.schedulers']['plugins']: cls = entry_point.load() self.scheduler_plugins[cls.__name__] = cls if cls.__name__ == self.active_scheduler: self.log.debug('Scheduler loaded: {} in module {}'.format(cls.__name__, cls.__module__)) else: self.log.debug('Scheduler disabled: {} in module {}'.format(cls.__name__, cls.__module__))
[ "def", "load_scheduler_plugins", "(", "self", ")", ":", "if", "not", "self", ".", "scheduler_plugins", ":", "for", "entry_point", "in", "CINQ_PLUGINS", "[", "'cloud_inquisitor.plugins.schedulers'", "]", "[", "'plugins'", "]", ":", "cls", "=", "entry_point", ".", ...
Refresh the list of available schedulers Returns: `list` of :obj:`BaseScheduler`
[ "Refresh", "the", "list", "of", "available", "schedulers" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/commands/scheduler.py#L27-L40
232,153
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/plugins/commands/scheduler.py
Scheduler.run
def run(self, **kwargs): """Execute the scheduler. Returns: `None` """ if not super().run(**kwargs): return if kwargs['list']: self.log.info('--- List of Scheduler Modules ---') for name, scheduler in list(self.scheduler_plugins.items()): if self.active_scheduler == name: self.log.info('{} (active)'.format(name)) else: self.log.info(name) self.log.info('--- End list of Scheduler Modules ---') return scheduler = self.scheduler_plugins[self.active_scheduler]() scheduler.execute_scheduler()
python
def run(self, **kwargs): if not super().run(**kwargs): return if kwargs['list']: self.log.info('--- List of Scheduler Modules ---') for name, scheduler in list(self.scheduler_plugins.items()): if self.active_scheduler == name: self.log.info('{} (active)'.format(name)) else: self.log.info(name) self.log.info('--- End list of Scheduler Modules ---') return scheduler = self.scheduler_plugins[self.active_scheduler]() scheduler.execute_scheduler()
[ "def", "run", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "not", "super", "(", ")", ".", "run", "(", "*", "*", "kwargs", ")", ":", "return", "if", "kwargs", "[", "'list'", "]", ":", "self", ".", "log", ".", "info", "(", "'--- List of ...
Execute the scheduler. Returns: `None`
[ "Execute", "the", "scheduler", "." ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/commands/scheduler.py#L59-L79
232,154
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/plugins/commands/scheduler.py
Worker.run
def run(self, **kwargs): """Execute the worker thread. Returns: `None` """ super().run(**kwargs) scheduler = self.scheduler_plugins[self.active_scheduler]() if not kwargs['no_daemon']: self.log.info('Starting {} worker with {} threads checking for new messages every {} seconds'.format( scheduler.name, kwargs['threads'], kwargs['delay'] )) for i in range(kwargs['threads']): thd = threading.Thread( target=self.execute_worker_thread, args=(scheduler.execute_worker, kwargs['delay']) ) thd.start() else: self.log.info('Starting {} worker for a single non-daemon execution'.format( scheduler.name )) scheduler.execute_worker()
python
def run(self, **kwargs): super().run(**kwargs) scheduler = self.scheduler_plugins[self.active_scheduler]() if not kwargs['no_daemon']: self.log.info('Starting {} worker with {} threads checking for new messages every {} seconds'.format( scheduler.name, kwargs['threads'], kwargs['delay'] )) for i in range(kwargs['threads']): thd = threading.Thread( target=self.execute_worker_thread, args=(scheduler.execute_worker, kwargs['delay']) ) thd.start() else: self.log.info('Starting {} worker for a single non-daemon execution'.format( scheduler.name )) scheduler.execute_worker()
[ "def", "run", "(", "self", ",", "*", "*", "kwargs", ")", ":", "super", "(", ")", ".", "run", "(", "*", "*", "kwargs", ")", "scheduler", "=", "self", ".", "scheduler_plugins", "[", "self", ".", "active_scheduler", "]", "(", ")", "if", "not", "kwargs...
Execute the worker thread. Returns: `None`
[ "Execute", "the", "worker", "thread", "." ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/commands/scheduler.py#L94-L120
232,155
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/plugins/views/templates.py
TemplateList.post
def post(self): """Create a new template""" self.reqparse.add_argument('templateName', type=str, required=True) self.reqparse.add_argument('template', type=str, required=True) args = self.reqparse.parse_args() template = db.Template.find_one(template_name=args['templateName']) if template: return self.make_response('Template already exists, update the existing template instead', HTTP.CONFLICT) template = Template() template.template_name = args['templateName'] template.template = args['template'] db.session.add(template) db.session.commit() auditlog(event='template.create', actor=session['user'].username, data=args) return self.make_response('Template {} has been created'.format(template.template_name), HTTP.CREATED)
python
def post(self): self.reqparse.add_argument('templateName', type=str, required=True) self.reqparse.add_argument('template', type=str, required=True) args = self.reqparse.parse_args() template = db.Template.find_one(template_name=args['templateName']) if template: return self.make_response('Template already exists, update the existing template instead', HTTP.CONFLICT) template = Template() template.template_name = args['templateName'] template.template = args['template'] db.session.add(template) db.session.commit() auditlog(event='template.create', actor=session['user'].username, data=args) return self.make_response('Template {} has been created'.format(template.template_name), HTTP.CREATED)
[ "def", "post", "(", "self", ")", ":", "self", ".", "reqparse", ".", "add_argument", "(", "'templateName'", ",", "type", "=", "str", ",", "required", "=", "True", ")", "self", ".", "reqparse", ".", "add_argument", "(", "'template'", ",", "type", "=", "s...
Create a new template
[ "Create", "a", "new", "template" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/views/templates.py#L37-L55
232,156
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/plugins/views/templates.py
TemplateList.put
def put(self): """Re-import all templates, overwriting any local changes made""" try: _import_templates(force=True) return self.make_response('Imported templates') except: self.log.exception('Failed importing templates') return self.make_response('Failed importing templates', HTTP.SERVER_ERROR)
python
def put(self): try: _import_templates(force=True) return self.make_response('Imported templates') except: self.log.exception('Failed importing templates') return self.make_response('Failed importing templates', HTTP.SERVER_ERROR)
[ "def", "put", "(", "self", ")", ":", "try", ":", "_import_templates", "(", "force", "=", "True", ")", "return", "self", ".", "make_response", "(", "'Imported templates'", ")", "except", ":", "self", ".", "log", ".", "exception", "(", "'Failed importing templ...
Re-import all templates, overwriting any local changes made
[ "Re", "-", "import", "all", "templates", "overwriting", "any", "local", "changes", "made" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/views/templates.py#L59-L66
232,157
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/plugins/views/templates.py
TemplateGet.get
def get(self, template_name): """Get a specific template""" template = db.Template.find_one(template_name=template_name) if not template: return self.make_response('No such template found', HTTP.NOT_FOUND) return self.make_response({'template': template})
python
def get(self, template_name): template = db.Template.find_one(template_name=template_name) if not template: return self.make_response('No such template found', HTTP.NOT_FOUND) return self.make_response({'template': template})
[ "def", "get", "(", "self", ",", "template_name", ")", ":", "template", "=", "db", ".", "Template", ".", "find_one", "(", "template_name", "=", "template_name", ")", "if", "not", "template", ":", "return", "self", ".", "make_response", "(", "'No such template...
Get a specific template
[ "Get", "a", "specific", "template" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/views/templates.py#L74-L81
232,158
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/plugins/views/templates.py
TemplateGet.put
def put(self, template_name): """Update a template""" self.reqparse.add_argument('template', type=str, required=True) args = self.reqparse.parse_args() template = db.Template.find_one(template_name=template_name) if not template: return self.make_response('No such template found', HTTP.NOT_FOUND) changes = diff(template.template, args['template']) template.template = args['template'] template.is_modified = True db.session.add(template) db.session.commit() auditlog( event='template.update', actor=session['user'].username, data={ 'template_name': template_name, 'template_changes': changes } ) return self.make_response('Template {} has been updated'.format(template_name))
python
def put(self, template_name): self.reqparse.add_argument('template', type=str, required=True) args = self.reqparse.parse_args() template = db.Template.find_one(template_name=template_name) if not template: return self.make_response('No such template found', HTTP.NOT_FOUND) changes = diff(template.template, args['template']) template.template = args['template'] template.is_modified = True db.session.add(template) db.session.commit() auditlog( event='template.update', actor=session['user'].username, data={ 'template_name': template_name, 'template_changes': changes } ) return self.make_response('Template {} has been updated'.format(template_name))
[ "def", "put", "(", "self", ",", "template_name", ")", ":", "self", ".", "reqparse", ".", "add_argument", "(", "'template'", ",", "type", "=", "str", ",", "required", "=", "True", ")", "args", "=", "self", ".", "reqparse", ".", "parse_args", "(", ")", ...
Update a template
[ "Update", "a", "template" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/views/templates.py#L85-L110
232,159
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/plugins/views/templates.py
TemplateGet.delete
def delete(self, template_name): """Delete a template""" template = db.Template.find_one(template_name=template_name) if not template: return self.make_response('No such template found', HTTP.NOT_FOUND) db.session.delete(template) db.session.commit() auditlog(event='template.delete', actor=session['user'].username, data={'template_name': template_name}) return self.make_response({ 'message': 'Template has been deleted', 'templateName': template_name })
python
def delete(self, template_name): template = db.Template.find_one(template_name=template_name) if not template: return self.make_response('No such template found', HTTP.NOT_FOUND) db.session.delete(template) db.session.commit() auditlog(event='template.delete', actor=session['user'].username, data={'template_name': template_name}) return self.make_response({ 'message': 'Template has been deleted', 'templateName': template_name })
[ "def", "delete", "(", "self", ",", "template_name", ")", ":", "template", "=", "db", ".", "Template", ".", "find_one", "(", "template_name", "=", "template_name", ")", "if", "not", "template", ":", "return", "self", ".", "make_response", "(", "'No such templ...
Delete a template
[ "Delete", "a", "template" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/views/templates.py#L114-L127
232,160
RiotGames/cloud-inquisitor
plugins/public/cinq-auditor-required-tags/cinq_auditor_required_tags/providers.py
process_action
def process_action(resource, action, action_issuer='unknown'): """Process an audit action for a resource, if possible Args: resource (:obj:`Resource`): A resource object to perform the action on action (`str`): Type of action to perform (`kill` or `stop`) action_issuer (`str`): The issuer of the action Returns: `ActionStatus` """ from cinq_collector_aws import AWSRegionCollector func_action = action_mapper[resource.resource_type][action] extra_info = {} action_status = ActionStatus.UNKNOWN if func_action: if action_mapper[resource.resource_type]['service_name'] == 'lambda': client = get_aws_session( AWSAccount.get(dbconfig.get('rds_collector_account', AWSRegionCollector.ns, '')) ).client( 'lambda', dbconfig.get('rds_collector_region', AWSRegionCollector.ns, '') ) else: client = get_aws_session(AWSAccount(resource.account)).client( action_mapper[resource.resource_type]['service_name'], region_name=resource.location ) try: logger.info(f'Trying to {action} resource {resource.id} for account {resource.account.account_name} / region {resource.location}') action_status, extra_info = func_action(client, resource) Enforcement.create(resource.account.account_id, resource.id, action, datetime.now(), extra_info) except Exception as ex: action_status = ActionStatus.FAILED logger.exception('Failed to apply action {} to {}: {}'.format(action, resource.id, ex)) finally: auditlog( event='{}.{}.{}.{}'.format(action_issuer, resource.resource_type, action, action_status), actor=action_issuer, data={ 'resource_id': resource.id, 'account_name': resource.account.account_name, 'location': resource.location, 'info': extra_info } ) return action_status else: logger.error('Failed to apply action {} to {}: Not supported'.format(action, resource.id)) return ActionStatus.FAILED
python
def process_action(resource, action, action_issuer='unknown'): from cinq_collector_aws import AWSRegionCollector func_action = action_mapper[resource.resource_type][action] extra_info = {} action_status = ActionStatus.UNKNOWN if func_action: if action_mapper[resource.resource_type]['service_name'] == 'lambda': client = get_aws_session( AWSAccount.get(dbconfig.get('rds_collector_account', AWSRegionCollector.ns, '')) ).client( 'lambda', dbconfig.get('rds_collector_region', AWSRegionCollector.ns, '') ) else: client = get_aws_session(AWSAccount(resource.account)).client( action_mapper[resource.resource_type]['service_name'], region_name=resource.location ) try: logger.info(f'Trying to {action} resource {resource.id} for account {resource.account.account_name} / region {resource.location}') action_status, extra_info = func_action(client, resource) Enforcement.create(resource.account.account_id, resource.id, action, datetime.now(), extra_info) except Exception as ex: action_status = ActionStatus.FAILED logger.exception('Failed to apply action {} to {}: {}'.format(action, resource.id, ex)) finally: auditlog( event='{}.{}.{}.{}'.format(action_issuer, resource.resource_type, action, action_status), actor=action_issuer, data={ 'resource_id': resource.id, 'account_name': resource.account.account_name, 'location': resource.location, 'info': extra_info } ) return action_status else: logger.error('Failed to apply action {} to {}: Not supported'.format(action, resource.id)) return ActionStatus.FAILED
[ "def", "process_action", "(", "resource", ",", "action", ",", "action_issuer", "=", "'unknown'", ")", ":", "from", "cinq_collector_aws", "import", "AWSRegionCollector", "func_action", "=", "action_mapper", "[", "resource", ".", "resource_type", "]", "[", "action", ...
Process an audit action for a resource, if possible Args: resource (:obj:`Resource`): A resource object to perform the action on action (`str`): Type of action to perform (`kill` or `stop`) action_issuer (`str`): The issuer of the action Returns: `ActionStatus`
[ "Process", "an", "audit", "action", "for", "a", "resource", "if", "possible" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-auditor-required-tags/cinq_auditor_required_tags/providers.py#L23-L73
232,161
RiotGames/cloud-inquisitor
plugins/public/cinq-auditor-required-tags/cinq_auditor_required_tags/providers.py
stop_ec2_instance
def stop_ec2_instance(client, resource): """Stop an EC2 Instance This function will attempt to stop a running instance. Args: client (:obj:`boto3.session.Session.client`): A boto3 client object resource (:obj:`Resource`): The resource object to stop Returns: `ActionStatus` """ instance = EC2Instance.get(resource.id) if instance.state in ('stopped', 'terminated'): return ActionStatus.IGNORED, {} client.stop_instances(InstanceIds=[resource.id]) return ActionStatus.SUCCEED, {'instance_type': resource.instance_type, 'public_ip': resource.public_ip}
python
def stop_ec2_instance(client, resource): instance = EC2Instance.get(resource.id) if instance.state in ('stopped', 'terminated'): return ActionStatus.IGNORED, {} client.stop_instances(InstanceIds=[resource.id]) return ActionStatus.SUCCEED, {'instance_type': resource.instance_type, 'public_ip': resource.public_ip}
[ "def", "stop_ec2_instance", "(", "client", ",", "resource", ")", ":", "instance", "=", "EC2Instance", ".", "get", "(", "resource", ".", "id", ")", "if", "instance", ".", "state", "in", "(", "'stopped'", ",", "'terminated'", ")", ":", "return", "ActionStatu...
Stop an EC2 Instance This function will attempt to stop a running instance. Args: client (:obj:`boto3.session.Session.client`): A boto3 client object resource (:obj:`Resource`): The resource object to stop Returns: `ActionStatus`
[ "Stop", "an", "EC2", "Instance" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-auditor-required-tags/cinq_auditor_required_tags/providers.py#L76-L93
232,162
RiotGames/cloud-inquisitor
plugins/public/cinq-auditor-required-tags/cinq_auditor_required_tags/providers.py
terminate_ec2_instance
def terminate_ec2_instance(client, resource): """Terminate an EC2 Instance This function will terminate an EC2 Instance. Args: client (:obj:`boto3.session.Session.client`): A boto3 client object resource (:obj:`Resource`): The resource object to terminate Returns: `ActionStatus` """ # TODO: Implement disabling of TerminationProtection instance = EC2Instance.get(resource.id) if instance.state == 'terminated': return ActionStatus.IGNORED, {} client.terminate_instances(InstanceIds=[resource.id]) return ActionStatus.SUCCEED, {'instance_type': resource.instance_type, 'public_ip': resource.public_ip}
python
def terminate_ec2_instance(client, resource): # TODO: Implement disabling of TerminationProtection instance = EC2Instance.get(resource.id) if instance.state == 'terminated': return ActionStatus.IGNORED, {} client.terminate_instances(InstanceIds=[resource.id]) return ActionStatus.SUCCEED, {'instance_type': resource.instance_type, 'public_ip': resource.public_ip}
[ "def", "terminate_ec2_instance", "(", "client", ",", "resource", ")", ":", "# TODO: Implement disabling of TerminationProtection", "instance", "=", "EC2Instance", ".", "get", "(", "resource", ".", "id", ")", "if", "instance", ".", "state", "==", "'terminated'", ":",...
Terminate an EC2 Instance This function will terminate an EC2 Instance. Args: client (:obj:`boto3.session.Session.client`): A boto3 client object resource (:obj:`Resource`): The resource object to terminate Returns: `ActionStatus`
[ "Terminate", "an", "EC2", "Instance" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-auditor-required-tags/cinq_auditor_required_tags/providers.py#L96-L113
232,163
RiotGames/cloud-inquisitor
plugins/public/cinq-auditor-required-tags/cinq_auditor_required_tags/providers.py
stop_s3_bucket
def stop_s3_bucket(client, resource): """ Stop an S3 bucket from being used This function will try to 1. Add lifecycle policy to make sure objects inside it will expire 2. Block certain access to the bucket """ bucket_policy = { 'Version': '2012-10-17', 'Id': 'PutObjPolicy', 'Statement': [ { 'Sid': 'cinqDenyObjectUploads', 'Effect': 'Deny', 'Principal': '*', 'Action': ['s3:PutObject', 's3:GetObject'], 'Resource': 'arn:aws:s3:::{}/*'.format(resource.id) } ] } s3_removal_lifecycle_policy = { 'Rules': [ {'Status': 'Enabled', 'NoncurrentVersionExpiration': {u'NoncurrentDays': 1}, 'Filter': {u'Prefix': ''}, 'Expiration': { u'Date': datetime.utcnow().replace( hour=0, minute=0, second=0, microsecond=0 ) + timedelta(days=dbconfig.get('lifecycle_expiration_days', NS_AUDITOR_REQUIRED_TAGS, 3)) }, 'AbortIncompleteMultipartUpload': {u'DaysAfterInitiation': 3}, 'ID': 'cloudInquisitor'} ] } policy_exists = s3_removal_policy_exists(client, resource) lifecycle_policy_exists = s3_removal_lifecycle_policy_exists(client, resource) if policy_exists and lifecycle_policy_exists: return ActionStatus.IGNORED, {} if not policy_exists: client.put_bucket_policy(Bucket=resource.id, Policy=json.dumps(bucket_policy)) logger.info('Added policy to prevent putObject in s3 bucket {} in {}'.format( resource.id, resource.account.account_name )) if not lifecycle_policy_exists: # Grab S3 Metrics before lifecycle policies start removing objects client.put_bucket_lifecycle_configuration( Bucket=resource.id, LifecycleConfiguration=s3_removal_lifecycle_policy ) logger.info('Added policy to delete bucket contents in s3 bucket {} in {}'.format( resource.id, resource.account.account_name )) return ActionStatus.SUCCEED, resource.metrics()
python
def stop_s3_bucket(client, resource): bucket_policy = { 'Version': '2012-10-17', 'Id': 'PutObjPolicy', 'Statement': [ { 'Sid': 'cinqDenyObjectUploads', 'Effect': 'Deny', 'Principal': '*', 'Action': ['s3:PutObject', 's3:GetObject'], 'Resource': 'arn:aws:s3:::{}/*'.format(resource.id) } ] } s3_removal_lifecycle_policy = { 'Rules': [ {'Status': 'Enabled', 'NoncurrentVersionExpiration': {u'NoncurrentDays': 1}, 'Filter': {u'Prefix': ''}, 'Expiration': { u'Date': datetime.utcnow().replace( hour=0, minute=0, second=0, microsecond=0 ) + timedelta(days=dbconfig.get('lifecycle_expiration_days', NS_AUDITOR_REQUIRED_TAGS, 3)) }, 'AbortIncompleteMultipartUpload': {u'DaysAfterInitiation': 3}, 'ID': 'cloudInquisitor'} ] } policy_exists = s3_removal_policy_exists(client, resource) lifecycle_policy_exists = s3_removal_lifecycle_policy_exists(client, resource) if policy_exists and lifecycle_policy_exists: return ActionStatus.IGNORED, {} if not policy_exists: client.put_bucket_policy(Bucket=resource.id, Policy=json.dumps(bucket_policy)) logger.info('Added policy to prevent putObject in s3 bucket {} in {}'.format( resource.id, resource.account.account_name )) if not lifecycle_policy_exists: # Grab S3 Metrics before lifecycle policies start removing objects client.put_bucket_lifecycle_configuration( Bucket=resource.id, LifecycleConfiguration=s3_removal_lifecycle_policy ) logger.info('Added policy to delete bucket contents in s3 bucket {} in {}'.format( resource.id, resource.account.account_name )) return ActionStatus.SUCCEED, resource.metrics()
[ "def", "stop_s3_bucket", "(", "client", ",", "resource", ")", ":", "bucket_policy", "=", "{", "'Version'", ":", "'2012-10-17'", ",", "'Id'", ":", "'PutObjPolicy'", ",", "'Statement'", ":", "[", "{", "'Sid'", ":", "'cinqDenyObjectUploads'", ",", "'Effect'", ":"...
Stop an S3 bucket from being used This function will try to 1. Add lifecycle policy to make sure objects inside it will expire 2. Block certain access to the bucket
[ "Stop", "an", "S3", "bucket", "from", "being", "used" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-auditor-required-tags/cinq_auditor_required_tags/providers.py#L116-L178
232,164
RiotGames/cloud-inquisitor
plugins/public/cinq-auditor-required-tags/cinq_auditor_required_tags/providers.py
delete_s3_bucket
def delete_s3_bucket(client, resource): """Delete an S3 bucket This function will try to delete an S3 bucket Args: client (:obj:`boto3.session.Session.client`): A boto3 client object resource (:obj:`Resource`): The resource object to terminate Returns: `ActionStatus` """ if dbconfig.get('enable_delete_s3_buckets', NS_AUDITOR_REQUIRED_TAGS, False): client.delete_bucket(Bucket=resource.id) return ActionStatus.SUCCEED, resource.metrics()
python
def delete_s3_bucket(client, resource): if dbconfig.get('enable_delete_s3_buckets', NS_AUDITOR_REQUIRED_TAGS, False): client.delete_bucket(Bucket=resource.id) return ActionStatus.SUCCEED, resource.metrics()
[ "def", "delete_s3_bucket", "(", "client", ",", "resource", ")", ":", "if", "dbconfig", ".", "get", "(", "'enable_delete_s3_buckets'", ",", "NS_AUDITOR_REQUIRED_TAGS", ",", "False", ")", ":", "client", ".", "delete_bucket", "(", "Bucket", "=", "resource", ".", ...
Delete an S3 bucket This function will try to delete an S3 bucket Args: client (:obj:`boto3.session.Session.client`): A boto3 client object resource (:obj:`Resource`): The resource object to terminate Returns: `ActionStatus`
[ "Delete", "an", "S3", "bucket" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-auditor-required-tags/cinq_auditor_required_tags/providers.py#L181-L196
232,165
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/plugins/types/resources.py
BaseResource.get
def get(cls, resource_id): """Returns the class object identified by `resource_id` Args: resource_id (str): Unique EC2 Instance ID to load from database Returns: EC2 Instance object if found, else None """ res = Resource.get(resource_id) return cls(res) if res else None
python
def get(cls, resource_id): res = Resource.get(resource_id) return cls(res) if res else None
[ "def", "get", "(", "cls", ",", "resource_id", ")", ":", "res", "=", "Resource", ".", "get", "(", "resource_id", ")", "return", "cls", "(", "res", ")", "if", "res", "else", "None" ]
Returns the class object identified by `resource_id` Args: resource_id (str): Unique EC2 Instance ID to load from database Returns: EC2 Instance object if found, else None
[ "Returns", "the", "class", "object", "identified", "by", "resource_id" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/types/resources.py#L120-L130
232,166
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/plugins/types/resources.py
BaseResource.create
def create(cls, resource_id, *, account_id, properties=None, tags=None, location=None, auto_add=True, auto_commit=False): """Creates a new Resource object with the properties and tags provided Args: resource_id (str): Unique identifier for the resource object account_id (int): Account ID which owns the resource properties (dict): Dictionary of properties for the resource object. tags (dict): Key / value dictionary of tags. Values must be `str` types location (str): Location of the resource, if applicable auto_add (bool): Automatically add the new resource to the DB session. Default: True auto_commit (bool): Automatically commit the change to the database. Default: False """ if cls.get(resource_id): raise ResourceException('Resource {} already exists'.format(resource_id)) res = Resource() res.resource_id = resource_id res.account_id = account_id res.location = location res.resource_type_id = ResourceType.get(cls.resource_type).resource_type_id if properties: for name, value in properties.items(): prop = ResourceProperty() prop.resource_id = res.resource_id prop.name = name prop.value = value.isoformat() if type(value) == datetime else value res.properties.append(prop) db.session.add(prop) if tags: for key, value in tags.items(): if type(value) != str: raise ValueError('Invalid object type for tag value: {}'.format(key)) tag = Tag() tag.resource_id = resource_id tag.key = key tag.value = value res.tags.append(tag) db.session.add(tag) if auto_add: db.session.add(res) if auto_commit: db.session.commit() return cls.get(res.resource_id) else: return cls(res)
python
def create(cls, resource_id, *, account_id, properties=None, tags=None, location=None, auto_add=True, auto_commit=False): if cls.get(resource_id): raise ResourceException('Resource {} already exists'.format(resource_id)) res = Resource() res.resource_id = resource_id res.account_id = account_id res.location = location res.resource_type_id = ResourceType.get(cls.resource_type).resource_type_id if properties: for name, value in properties.items(): prop = ResourceProperty() prop.resource_id = res.resource_id prop.name = name prop.value = value.isoformat() if type(value) == datetime else value res.properties.append(prop) db.session.add(prop) if tags: for key, value in tags.items(): if type(value) != str: raise ValueError('Invalid object type for tag value: {}'.format(key)) tag = Tag() tag.resource_id = resource_id tag.key = key tag.value = value res.tags.append(tag) db.session.add(tag) if auto_add: db.session.add(res) if auto_commit: db.session.commit() return cls.get(res.resource_id) else: return cls(res)
[ "def", "create", "(", "cls", ",", "resource_id", ",", "*", ",", "account_id", ",", "properties", "=", "None", ",", "tags", "=", "None", ",", "location", "=", "None", ",", "auto_add", "=", "True", ",", "auto_commit", "=", "False", ")", ":", "if", "cls...
Creates a new Resource object with the properties and tags provided Args: resource_id (str): Unique identifier for the resource object account_id (int): Account ID which owns the resource properties (dict): Dictionary of properties for the resource object. tags (dict): Key / value dictionary of tags. Values must be `str` types location (str): Location of the resource, if applicable auto_add (bool): Automatically add the new resource to the DB session. Default: True auto_commit (bool): Automatically commit the change to the database. Default: False
[ "Creates", "a", "new", "Resource", "object", "with", "the", "properties", "and", "tags", "provided" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/types/resources.py#L133-L184
232,167
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/plugins/types/resources.py
BaseResource.get_all
def get_all(cls, account=None, location=None, include_disabled=False): """Returns a list of all resources for a given account, location and resource type. Attributes: account (:obj:`Account`): Account owning the resources location (`str`): Location of the resources to return (region) include_disabled (`bool`): Include resources from disabled accounts (default: False) Returns: list of resource objects """ qry = db.Resource.filter( Resource.resource_type_id == ResourceType.get(cls.resource_type).resource_type_id ) if account: qry = qry.filter(Resource.account_id == account.account_id) if not include_disabled: qry = qry.join(Account, Resource.account_id == Account.account_id).filter(Account.enabled == 1) if location: qry = qry.filter(Resource.location == location) return {res.resource_id: cls(res) for res in qry.all()}
python
def get_all(cls, account=None, location=None, include_disabled=False): qry = db.Resource.filter( Resource.resource_type_id == ResourceType.get(cls.resource_type).resource_type_id ) if account: qry = qry.filter(Resource.account_id == account.account_id) if not include_disabled: qry = qry.join(Account, Resource.account_id == Account.account_id).filter(Account.enabled == 1) if location: qry = qry.filter(Resource.location == location) return {res.resource_id: cls(res) for res in qry.all()}
[ "def", "get_all", "(", "cls", ",", "account", "=", "None", ",", "location", "=", "None", ",", "include_disabled", "=", "False", ")", ":", "qry", "=", "db", ".", "Resource", ".", "filter", "(", "Resource", ".", "resource_type_id", "==", "ResourceType", "....
Returns a list of all resources for a given account, location and resource type. Attributes: account (:obj:`Account`): Account owning the resources location (`str`): Location of the resources to return (region) include_disabled (`bool`): Include resources from disabled accounts (default: False) Returns: list of resource objects
[ "Returns", "a", "list", "of", "all", "resources", "for", "a", "given", "account", "location", "and", "resource", "type", "." ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/types/resources.py#L187-L211
232,168
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/plugins/types/resources.py
BaseResource.search
def search(cls, *, limit=100, page=1, accounts=None, locations=None, resources=None, properties=None, include_disabled=False, return_query=False): """Search for resources based on the provided filters. If `return_query` a sub-class of `sqlalchemy.orm.Query` is returned instead of the resource list. Args: limit (`int`): Number of results to return. Default: 100 page (`int`): Pagination offset for results. Default: 1 accounts (`list` of `int`): A list of account id's to limit the returned resources to locations (`list` of `str`): A list of locations as strings to limit the search for resources ('list' of `str`): A list of resource_ids properties (`dict`): A `dict` containing property name and value pairs. Values can be either a str or a list of strings, in which case a boolean OR search is performed on the values include_disabled (`bool`): Include resources from disabled accounts. Default: False return_query (`bool`): Returns the query object prior to adding the limit and offset functions. Allows for sub-classes to amend the search feature with extra conditions. The calling function must handle pagination on its own Returns: `list` of `Resource`, `sqlalchemy.orm.Query` """ qry = db.Resource.order_by(Resource.resource_id).filter( Resource.resource_type_id == ResourceType.get(cls.resource_type).resource_type_id ) if not include_disabled: qry = qry.join(Account, Resource.account_id == Account.account_id).filter(Account.enabled == 1) if session: qry = qry.filter(Resource.account_id.in_(session['accounts'])) if accounts: qry = qry.filter(Resource.account_id.in_([Account.get(acct).account_id for acct in accounts])) if locations: qry = qry.filter(Resource.location.in_(locations)) if resources: qry = qry.filter(Resource.resource_id.in_(resources)) if properties: for prop_name, value in properties.items(): alias = aliased(ResourceProperty) qry = qry.join(alias, Resource.resource_id == alias.resource_id) if type(value) == list: where_clause = [] for item in value: where_clause.append(alias.value == item) qry = qry.filter( and_( alias.name == prop_name, or_(*where_clause) ).self_group() ) else: qry = qry.filter( and_( alias.name == prop_name, alias.value == value ).self_group() ) if return_query: return qry total = qry.count() qry = qry.limit(limit) qry = qry.offset((page - 1) * limit if page > 1 else 0) return total, [cls(x) for x in qry.all()]
python
def search(cls, *, limit=100, page=1, accounts=None, locations=None, resources=None, properties=None, include_disabled=False, return_query=False): qry = db.Resource.order_by(Resource.resource_id).filter( Resource.resource_type_id == ResourceType.get(cls.resource_type).resource_type_id ) if not include_disabled: qry = qry.join(Account, Resource.account_id == Account.account_id).filter(Account.enabled == 1) if session: qry = qry.filter(Resource.account_id.in_(session['accounts'])) if accounts: qry = qry.filter(Resource.account_id.in_([Account.get(acct).account_id for acct in accounts])) if locations: qry = qry.filter(Resource.location.in_(locations)) if resources: qry = qry.filter(Resource.resource_id.in_(resources)) if properties: for prop_name, value in properties.items(): alias = aliased(ResourceProperty) qry = qry.join(alias, Resource.resource_id == alias.resource_id) if type(value) == list: where_clause = [] for item in value: where_clause.append(alias.value == item) qry = qry.filter( and_( alias.name == prop_name, or_(*where_clause) ).self_group() ) else: qry = qry.filter( and_( alias.name == prop_name, alias.value == value ).self_group() ) if return_query: return qry total = qry.count() qry = qry.limit(limit) qry = qry.offset((page - 1) * limit if page > 1 else 0) return total, [cls(x) for x in qry.all()]
[ "def", "search", "(", "cls", ",", "*", ",", "limit", "=", "100", ",", "page", "=", "1", ",", "accounts", "=", "None", ",", "locations", "=", "None", ",", "resources", "=", "None", ",", "properties", "=", "None", ",", "include_disabled", "=", "False",...
Search for resources based on the provided filters. If `return_query` a sub-class of `sqlalchemy.orm.Query` is returned instead of the resource list. Args: limit (`int`): Number of results to return. Default: 100 page (`int`): Pagination offset for results. Default: 1 accounts (`list` of `int`): A list of account id's to limit the returned resources to locations (`list` of `str`): A list of locations as strings to limit the search for resources ('list' of `str`): A list of resource_ids properties (`dict`): A `dict` containing property name and value pairs. Values can be either a str or a list of strings, in which case a boolean OR search is performed on the values include_disabled (`bool`): Include resources from disabled accounts. Default: False return_query (`bool`): Returns the query object prior to adding the limit and offset functions. Allows for sub-classes to amend the search feature with extra conditions. The calling function must handle pagination on its own Returns: `list` of `Resource`, `sqlalchemy.orm.Query`
[ "Search", "for", "resources", "based", "on", "the", "provided", "filters", ".", "If", "return_query", "a", "sub", "-", "class", "of", "sqlalchemy", ".", "orm", ".", "Query", "is", "returned", "instead", "of", "the", "resource", "list", "." ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/types/resources.py#L214-L286
232,169
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/plugins/types/resources.py
BaseResource.get_owner_emails
def get_owner_emails(self, partial_owner_match=True): """Return a list of email addresses associated with the instance, based on tags Returns: List of email addresses if any, else None """ for tag in self.tags: if tag.key.lower() == 'owner': rgx = re.compile(RGX_EMAIL_VALIDATION_PATTERN, re.I) if partial_owner_match: match = rgx.findall(tag.value) if match: return [NotificationContact('email', email) for email in match] else: match = rgx.match(tag.value) if match: return [NotificationContact('email', email) for email in match.groups()] return None
python
def get_owner_emails(self, partial_owner_match=True): for tag in self.tags: if tag.key.lower() == 'owner': rgx = re.compile(RGX_EMAIL_VALIDATION_PATTERN, re.I) if partial_owner_match: match = rgx.findall(tag.value) if match: return [NotificationContact('email', email) for email in match] else: match = rgx.match(tag.value) if match: return [NotificationContact('email', email) for email in match.groups()] return None
[ "def", "get_owner_emails", "(", "self", ",", "partial_owner_match", "=", "True", ")", ":", "for", "tag", "in", "self", ".", "tags", ":", "if", "tag", ".", "key", ".", "lower", "(", ")", "==", "'owner'", ":", "rgx", "=", "re", ".", "compile", "(", "...
Return a list of email addresses associated with the instance, based on tags Returns: List of email addresses if any, else None
[ "Return", "a", "list", "of", "email", "addresses", "associated", "with", "the", "instance", "based", "on", "tags" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/types/resources.py#L291-L308
232,170
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/plugins/types/resources.py
BaseResource.get_property
def get_property(self, name): """Return a named property for a resource, if available. Will raise an `AttributeError` if the property does not exist Args: name (str): Name of the property to return Returns: `ResourceProperty` """ for prop in self.resource.properties: if prop.name == name: return prop raise AttributeError(name)
python
def get_property(self, name): for prop in self.resource.properties: if prop.name == name: return prop raise AttributeError(name)
[ "def", "get_property", "(", "self", ",", "name", ")", ":", "for", "prop", "in", "self", ".", "resource", ".", "properties", ":", "if", "prop", ".", "name", "==", "name", ":", "return", "prop", "raise", "AttributeError", "(", "name", ")" ]
Return a named property for a resource, if available. Will raise an `AttributeError` if the property does not exist Args: name (str): Name of the property to return Returns: `ResourceProperty`
[ "Return", "a", "named", "property", "for", "a", "resource", "if", "available", ".", "Will", "raise", "an", "AttributeError", "if", "the", "property", "does", "not", "exist" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/types/resources.py#L310-L324
232,171
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/plugins/types/resources.py
BaseResource.set_property
def set_property(self, name, value, update_session=True): """Create or set the value of a property. Returns `True` if the property was created or updated, or `False` if there were no changes to the value of the property. Args: name (str): Name of the property to create or update value (any): Value of the property. This can be any type of JSON serializable data update_session (bool): Automatically add the change to the SQLAlchemy session. Default: True Returns: `bool` """ if type(value) == datetime: value = value.isoformat() else: value = value try: prop = self.get_property(name) if prop.value == value: return False prop.value = value except AttributeError: prop = ResourceProperty() prop.resource_id = self.id prop.name = name prop.value = value if update_session: db.session.add(prop) return True
python
def set_property(self, name, value, update_session=True): if type(value) == datetime: value = value.isoformat() else: value = value try: prop = self.get_property(name) if prop.value == value: return False prop.value = value except AttributeError: prop = ResourceProperty() prop.resource_id = self.id prop.name = name prop.value = value if update_session: db.session.add(prop) return True
[ "def", "set_property", "(", "self", ",", "name", ",", "value", ",", "update_session", "=", "True", ")", ":", "if", "type", "(", "value", ")", "==", "datetime", ":", "value", "=", "value", ".", "isoformat", "(", ")", "else", ":", "value", "=", "value"...
Create or set the value of a property. Returns `True` if the property was created or updated, or `False` if there were no changes to the value of the property. Args: name (str): Name of the property to create or update value (any): Value of the property. This can be any type of JSON serializable data update_session (bool): Automatically add the change to the SQLAlchemy session. Default: True Returns: `bool`
[ "Create", "or", "set", "the", "value", "of", "a", "property", ".", "Returns", "True", "if", "the", "property", "was", "created", "or", "updated", "or", "False", "if", "there", "were", "no", "changes", "to", "the", "value", "of", "the", "property", "." ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/types/resources.py#L326-L359
232,172
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/plugins/types/resources.py
BaseResource.get_tag
def get_tag(self, key, *, case_sensitive=True): """Return a tag by key, if found Args: key (str): Name/key of the tag to locate case_sensitive (bool): Should tag keys be treated case-sensitive (default: true) Returns: `Tag`,`None` """ key = key if case_sensitive else key.lower() for tag in self.resource.tags: if not case_sensitive: if tag.key.lower() == key: return tag elif key == tag.key: return tag return None
python
def get_tag(self, key, *, case_sensitive=True): key = key if case_sensitive else key.lower() for tag in self.resource.tags: if not case_sensitive: if tag.key.lower() == key: return tag elif key == tag.key: return tag return None
[ "def", "get_tag", "(", "self", ",", "key", ",", "*", ",", "case_sensitive", "=", "True", ")", ":", "key", "=", "key", "if", "case_sensitive", "else", "key", ".", "lower", "(", ")", "for", "tag", "in", "self", ".", "resource", ".", "tags", ":", "if"...
Return a tag by key, if found Args: key (str): Name/key of the tag to locate case_sensitive (bool): Should tag keys be treated case-sensitive (default: true) Returns: `Tag`,`None`
[ "Return", "a", "tag", "by", "key", "if", "found" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/types/resources.py#L384-L402
232,173
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/plugins/types/resources.py
BaseResource.set_tag
def set_tag(self, key, value, update_session=True): """Create or set the value of the tag with `key` to `value`. Returns `True` if the tag was created or updated or `False` if there were no changes to be made. Args: key (str): Key of the tag value (str): Value of the tag update_session (bool): Automatically add the change to the SQLAlchemy session. Default: True Returns: `bool` """ existing_tags = {x.key: x for x in self.tags} if key in existing_tags: tag = existing_tags[key] if tag.value == value: return False tag.value = value else: tag = Tag() tag.resource_id = self.id tag.key = key tag.value = value self.tags.append(tag) if update_session: db.session.add(tag) return True
python
def set_tag(self, key, value, update_session=True): existing_tags = {x.key: x for x in self.tags} if key in existing_tags: tag = existing_tags[key] if tag.value == value: return False tag.value = value else: tag = Tag() tag.resource_id = self.id tag.key = key tag.value = value self.tags.append(tag) if update_session: db.session.add(tag) return True
[ "def", "set_tag", "(", "self", ",", "key", ",", "value", ",", "update_session", "=", "True", ")", ":", "existing_tags", "=", "{", "x", ".", "key", ":", "x", "for", "x", "in", "self", ".", "tags", "}", "if", "key", "in", "existing_tags", ":", "tag",...
Create or set the value of the tag with `key` to `value`. Returns `True` if the tag was created or updated or `False` if there were no changes to be made. Args: key (str): Key of the tag value (str): Value of the tag update_session (bool): Automatically add the change to the SQLAlchemy session. Default: True Returns: `bool`
[ "Create", "or", "set", "the", "value", "of", "the", "tag", "with", "key", "to", "value", ".", "Returns", "True", "if", "the", "tag", "was", "created", "or", "updated", "or", "False", "if", "there", "were", "no", "changes", "to", "be", "made", "." ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/types/resources.py#L404-L433
232,174
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/plugins/types/resources.py
BaseResource.delete_tag
def delete_tag(self, key, update_session=True): """Removes a tag from a resource based on the tag key. Returns `True` if the tag was removed or `False` if the tag didn't exist Args: key (str): Key of the tag to delete update_session (bool): Automatically add the change to the SQLAlchemy session. Default: True Returns: """ existing_tags = {x.key: x for x in self.tags} if key in existing_tags: if update_session: db.session.delete(existing_tags[key]) self.tags.remove(existing_tags[key]) return True return False
python
def delete_tag(self, key, update_session=True): existing_tags = {x.key: x for x in self.tags} if key in existing_tags: if update_session: db.session.delete(existing_tags[key]) self.tags.remove(existing_tags[key]) return True return False
[ "def", "delete_tag", "(", "self", ",", "key", ",", "update_session", "=", "True", ")", ":", "existing_tags", "=", "{", "x", ".", "key", ":", "x", "for", "x", "in", "self", ".", "tags", "}", "if", "key", "in", "existing_tags", ":", "if", "update_sessi...
Removes a tag from a resource based on the tag key. Returns `True` if the tag was removed or `False` if the tag didn't exist Args: key (str): Key of the tag to delete update_session (bool): Automatically add the change to the SQLAlchemy session. Default: True Returns:
[ "Removes", "a", "tag", "from", "a", "resource", "based", "on", "the", "tag", "key", ".", "Returns", "True", "if", "the", "tag", "was", "removed", "or", "False", "if", "the", "tag", "didn", "t", "exist" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/types/resources.py#L435-L454
232,175
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/plugins/types/resources.py
BaseResource.save
def save(self, *, auto_commit=False): """Save the resource to the database Args: auto_commit (bool): Automatically commit the transaction. Default: `False` Returns: `None` """ try: db.session.add(self.resource) if auto_commit: db.session.commit() except SQLAlchemyError as ex: self.log.exception('Failed updating resource: {}'.format(ex)) db.session.rollback()
python
def save(self, *, auto_commit=False): try: db.session.add(self.resource) if auto_commit: db.session.commit() except SQLAlchemyError as ex: self.log.exception('Failed updating resource: {}'.format(ex)) db.session.rollback()
[ "def", "save", "(", "self", ",", "*", ",", "auto_commit", "=", "False", ")", ":", "try", ":", "db", ".", "session", ".", "add", "(", "self", ".", "resource", ")", "if", "auto_commit", ":", "db", ".", "session", ".", "commit", "(", ")", "except", ...
Save the resource to the database Args: auto_commit (bool): Automatically commit the transaction. Default: `False` Returns: `None`
[ "Save", "the", "resource", "to", "the", "database" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/types/resources.py#L456-L471
232,176
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/plugins/types/resources.py
BaseResource.delete
def delete(self, *, auto_commit=False): """Removes a resource from the database Args: auto_commit (bool): Automatically commit the transaction. Default: `False` Returns: `None` """ try: db.session.delete(self.resource) if auto_commit: db.session.commit() except SQLAlchemyError: self.log.exception('Failed deleting resource: {}'.format(self.id)) db.session.rollback()
python
def delete(self, *, auto_commit=False): try: db.session.delete(self.resource) if auto_commit: db.session.commit() except SQLAlchemyError: self.log.exception('Failed deleting resource: {}'.format(self.id)) db.session.rollback()
[ "def", "delete", "(", "self", ",", "*", ",", "auto_commit", "=", "False", ")", ":", "try", ":", "db", ".", "session", ".", "delete", "(", "self", ".", "resource", ")", "if", "auto_commit", ":", "db", ".", "session", ".", "commit", "(", ")", "except...
Removes a resource from the database Args: auto_commit (bool): Automatically commit the transaction. Default: `False` Returns: `None`
[ "Removes", "a", "resource", "from", "the", "database" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/types/resources.py#L473-L488
232,177
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/plugins/types/resources.py
BaseResource.to_json
def to_json(self): """Return a `dict` representation of the resource, including all properties and tags Returns: `dict` """ return { 'resourceType': self.resource.resource_type_id, 'resourceId': self.id, 'accountId': self.resource.account_id, 'account': self.account, 'location': self.resource.location, 'properties': {to_camelcase(prop.name): prop.value for prop in self.resource.properties}, 'tags': [{'key': t.key, 'value': t.value} for t in self.resource.tags] }
python
def to_json(self): return { 'resourceType': self.resource.resource_type_id, 'resourceId': self.id, 'accountId': self.resource.account_id, 'account': self.account, 'location': self.resource.location, 'properties': {to_camelcase(prop.name): prop.value for prop in self.resource.properties}, 'tags': [{'key': t.key, 'value': t.value} for t in self.resource.tags] }
[ "def", "to_json", "(", "self", ")", ":", "return", "{", "'resourceType'", ":", "self", ".", "resource", ".", "resource_type_id", ",", "'resourceId'", ":", "self", ".", "id", ",", "'accountId'", ":", "self", ".", "resource", ".", "account_id", ",", "'accoun...
Return a `dict` representation of the resource, including all properties and tags Returns: `dict`
[ "Return", "a", "dict", "representation", "of", "the", "resource", "including", "all", "properties", "and", "tags" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/types/resources.py#L490-L504
232,178
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/plugins/types/resources.py
EC2Instance.volumes
def volumes(self): """Returns a list of the volumes attached to the instance Returns: `list` of `EBSVolume` """ return [ EBSVolume(res) for res in db.Resource.join( ResourceProperty, Resource.resource_id == ResourceProperty.resource_id ).filter( Resource.resource_type_id == ResourceType.get('aws_ebs_volume').resource_type_id, ResourceProperty.name == 'attachments', func.JSON_CONTAINS(ResourceProperty.value, func.JSON_QUOTE(self.id)) ).all() ]
python
def volumes(self): return [ EBSVolume(res) for res in db.Resource.join( ResourceProperty, Resource.resource_id == ResourceProperty.resource_id ).filter( Resource.resource_type_id == ResourceType.get('aws_ebs_volume').resource_type_id, ResourceProperty.name == 'attachments', func.JSON_CONTAINS(ResourceProperty.value, func.JSON_QUOTE(self.id)) ).all() ]
[ "def", "volumes", "(", "self", ")", ":", "return", "[", "EBSVolume", "(", "res", ")", "for", "res", "in", "db", ".", "Resource", ".", "join", "(", "ResourceProperty", ",", "Resource", ".", "resource_id", "==", "ResourceProperty", ".", "resource_id", ")", ...
Returns a list of the volumes attached to the instance Returns: `list` of `EBSVolume`
[ "Returns", "a", "list", "of", "the", "volumes", "attached", "to", "the", "instance" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/types/resources.py#L581-L595
232,179
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/plugins/types/resources.py
EC2Instance.get_name_or_instance_id
def get_name_or_instance_id(self, with_id=False): """Returns the name of an instance if existant, else return the instance id Args: with_id (bool): Include the instance ID even if the name is found (default: False) Returns: Name and/or instance ID of the instance object """ name = self.get_tag('Name', case_sensitive=False) if name and len(name.value.strip()) > 0: return '{0} ({1})'.format(name.value, self.id) if with_id else name.value return self.id
python
def get_name_or_instance_id(self, with_id=False): name = self.get_tag('Name', case_sensitive=False) if name and len(name.value.strip()) > 0: return '{0} ({1})'.format(name.value, self.id) if with_id else name.value return self.id
[ "def", "get_name_or_instance_id", "(", "self", ",", "with_id", "=", "False", ")", ":", "name", "=", "self", ".", "get_tag", "(", "'Name'", ",", "case_sensitive", "=", "False", ")", "if", "name", "and", "len", "(", "name", ".", "value", ".", "strip", "(...
Returns the name of an instance if existant, else return the instance id Args: with_id (bool): Include the instance ID even if the name is found (default: False) Returns: Name and/or instance ID of the instance object
[ "Returns", "the", "name", "of", "an", "instance", "if", "existant", "else", "return", "the", "instance", "id" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/types/resources.py#L635-L648
232,180
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/plugins/types/resources.py
EC2Instance.search_by_age
def search_by_age(cls, *, limit=100, page=1, accounts=None, locations=None, age=720, properties=None, include_disabled=False): """Search for resources based on the provided filters Args: limit (`int`): Number of results to return. Default: 100 page (`int`): Pagination offset for results. Default: 1 accounts (`list` of `int`): A list of account id's to limit the returned resources to locations (`list` of `str`): A list of locations as strings to limit the search for age (`int`): Age of instances older than `age` days to return properties (`dict`): A `dict` containing property name and value pairs. Values can be either a str or a list of strings, in which case a boolean OR search is performed on the values include_disabled (`bool`): Include resources from disabled accounts. Default: False Returns: `list` of `Resource` """ qry = cls.search( limit=limit, page=page, accounts=accounts, locations=locations, properties=properties, include_disabled=include_disabled, return_query=True ) age_alias = aliased(ResourceProperty) qry = ( qry.join(age_alias, Resource.resource_id == age_alias.resource_id) .filter( age_alias.name == 'launch_date', cast(func.JSON_UNQUOTE(age_alias.value), DATETIME) < datetime.now() - timedelta(days=age) ) ) total = qry.count() qry = qry.limit(limit) qry = qry.offset((page - 1) * limit if page > 1 else 0) return total, [cls(x) for x in qry.all()]
python
def search_by_age(cls, *, limit=100, page=1, accounts=None, locations=None, age=720, properties=None, include_disabled=False): qry = cls.search( limit=limit, page=page, accounts=accounts, locations=locations, properties=properties, include_disabled=include_disabled, return_query=True ) age_alias = aliased(ResourceProperty) qry = ( qry.join(age_alias, Resource.resource_id == age_alias.resource_id) .filter( age_alias.name == 'launch_date', cast(func.JSON_UNQUOTE(age_alias.value), DATETIME) < datetime.now() - timedelta(days=age) ) ) total = qry.count() qry = qry.limit(limit) qry = qry.offset((page - 1) * limit if page > 1 else 0) return total, [cls(x) for x in qry.all()]
[ "def", "search_by_age", "(", "cls", ",", "*", ",", "limit", "=", "100", ",", "page", "=", "1", ",", "accounts", "=", "None", ",", "locations", "=", "None", ",", "age", "=", "720", ",", "properties", "=", "None", ",", "include_disabled", "=", "False",...
Search for resources based on the provided filters Args: limit (`int`): Number of results to return. Default: 100 page (`int`): Pagination offset for results. Default: 1 accounts (`list` of `int`): A list of account id's to limit the returned resources to locations (`list` of `str`): A list of locations as strings to limit the search for age (`int`): Age of instances older than `age` days to return properties (`dict`): A `dict` containing property name and value pairs. Values can be either a str or a list of strings, in which case a boolean OR search is performed on the values include_disabled (`bool`): Include resources from disabled accounts. Default: False Returns: `list` of `Resource`
[ "Search", "for", "resources", "based", "on", "the", "provided", "filters" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/types/resources.py#L651-L691
232,181
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/plugins/types/resources.py
EC2Instance.to_json
def to_json(self, with_volumes=True): """Augment the base `to_json` function, adding information about volumes Returns: `dict` """ data = super().to_json() if with_volumes: data['volumes'] = [ { 'volumeId': vol.id, 'volumeType': vol.volume_type, 'size': vol.size } for vol in self.volumes ] return data
python
def to_json(self, with_volumes=True): data = super().to_json() if with_volumes: data['volumes'] = [ { 'volumeId': vol.id, 'volumeType': vol.volume_type, 'size': vol.size } for vol in self.volumes ] return data
[ "def", "to_json", "(", "self", ",", "with_volumes", "=", "True", ")", ":", "data", "=", "super", "(", ")", ".", "to_json", "(", ")", "if", "with_volumes", ":", "data", "[", "'volumes'", "]", "=", "[", "{", "'volumeId'", ":", "vol", ".", "id", ",", ...
Augment the base `to_json` function, adding information about volumes Returns: `dict`
[ "Augment", "the", "base", "to_json", "function", "adding", "information", "about", "volumes" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/types/resources.py#L693-L709
232,182
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/plugins/types/resources.py
DNSZone.delete_record
def delete_record(self, record): """Remove a DNSRecord Args: record (:obj:`DNSRecord`): :obj:`DNSRecord` to remove Returns: `None` """ self.children.remove(record.resource) record.delete()
python
def delete_record(self, record): self.children.remove(record.resource) record.delete()
[ "def", "delete_record", "(", "self", ",", "record", ")", ":", "self", ".", "children", ".", "remove", "(", "record", ".", "resource", ")", "record", ".", "delete", "(", ")" ]
Remove a DNSRecord Args: record (:obj:`DNSRecord`): :obj:`DNSRecord` to remove Returns: `None`
[ "Remove", "a", "DNSRecord" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/types/resources.py#L1258-L1268
232,183
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/plugins/views/config.py
ConfigList.get
def get(self): """List existing config namespaces and their items""" namespaces = db.ConfigNamespace.order_by( ConfigNamespace.sort_order, ConfigNamespace.name ).all() return self.make_response({ 'message': None, 'namespaces': namespaces }, HTTP.OK)
python
def get(self): namespaces = db.ConfigNamespace.order_by( ConfigNamespace.sort_order, ConfigNamespace.name ).all() return self.make_response({ 'message': None, 'namespaces': namespaces }, HTTP.OK)
[ "def", "get", "(", "self", ")", ":", "namespaces", "=", "db", ".", "ConfigNamespace", ".", "order_by", "(", "ConfigNamespace", ".", "sort_order", ",", "ConfigNamespace", ".", "name", ")", ".", "all", "(", ")", "return", "self", ".", "make_response", "(", ...
List existing config namespaces and their items
[ "List", "existing", "config", "namespaces", "and", "their", "items" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/views/config.py#L63-L73
232,184
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/plugins/views/config.py
ConfigList.post
def post(self): """Create a new config item""" self.reqparse.add_argument('namespacePrefix', type=str, required=True) self.reqparse.add_argument('description', type=str, required=True) self.reqparse.add_argument('key', type=str, required=True) self.reqparse.add_argument('value', required=True) self.reqparse.add_argument('type', type=str, required=True) args = self.reqparse.parse_args() if not self.dbconfig.namespace_exists(args['namespacePrefix']): return self.make_response('The namespace doesnt exist', HTTP.NOT_FOUND) if self.dbconfig.key_exists(args['namespacePrefix'], args['key']): return self.make_response('This config item already exists', HTTP.CONFLICT) self.dbconfig.set(args['namespacePrefix'], args['key'], _to_dbc_class(args), description=args['description']) auditlog(event='configItem.create', actor=session['user'].username, data=args) return self.make_response('Config item added', HTTP.CREATED)
python
def post(self): self.reqparse.add_argument('namespacePrefix', type=str, required=True) self.reqparse.add_argument('description', type=str, required=True) self.reqparse.add_argument('key', type=str, required=True) self.reqparse.add_argument('value', required=True) self.reqparse.add_argument('type', type=str, required=True) args = self.reqparse.parse_args() if not self.dbconfig.namespace_exists(args['namespacePrefix']): return self.make_response('The namespace doesnt exist', HTTP.NOT_FOUND) if self.dbconfig.key_exists(args['namespacePrefix'], args['key']): return self.make_response('This config item already exists', HTTP.CONFLICT) self.dbconfig.set(args['namespacePrefix'], args['key'], _to_dbc_class(args), description=args['description']) auditlog(event='configItem.create', actor=session['user'].username, data=args) return self.make_response('Config item added', HTTP.CREATED)
[ "def", "post", "(", "self", ")", ":", "self", ".", "reqparse", ".", "add_argument", "(", "'namespacePrefix'", ",", "type", "=", "str", ",", "required", "=", "True", ")", "self", ".", "reqparse", ".", "add_argument", "(", "'description'", ",", "type", "="...
Create a new config item
[ "Create", "a", "new", "config", "item" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/views/config.py#L77-L95
232,185
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/plugins/views/config.py
ConfigGet.get
def get(self, namespace, key): """Get a specific configuration item""" cfg = self.dbconfig.get(key, namespace, as_object=True) return self.make_response({ 'message': None, 'config': cfg })
python
def get(self, namespace, key): cfg = self.dbconfig.get(key, namespace, as_object=True) return self.make_response({ 'message': None, 'config': cfg })
[ "def", "get", "(", "self", ",", "namespace", ",", "key", ")", ":", "cfg", "=", "self", ".", "dbconfig", ".", "get", "(", "key", ",", "namespace", ",", "as_object", "=", "True", ")", "return", "self", ".", "make_response", "(", "{", "'message'", ":", ...
Get a specific configuration item
[ "Get", "a", "specific", "configuration", "item" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/views/config.py#L103-L109
232,186
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/plugins/views/config.py
ConfigGet.put
def put(self, namespace, key): """Update a single configuration item""" args = request.json if not self.dbconfig.key_exists(namespace, key): return self.make_response('No such config entry: {}/{}'.format(namespace, key), HTTP.BAD_REQUEST) if (args['type'] == 'choice' and not args['value']['min_items'] <= len(args['value']['enabled']) <= args['value']['max_items']): return self.make_response( 'You should select {} {}item{}'.format( args['value']['min_items'], '' if args['value']['min_items'] == args['value']['max_items'] else 'to {} '.format( args['value']['max_items'] ), 's' if args['value']['max_items'] > 1 else '' ), HTTP.BAD_REQUEST ) if args['type'] == 'choice' and not set(args['value']['enabled']).issubset(args['value']['available']): return self.make_response('Invalid item', HTTP.BAD_REQUEST) item = db.ConfigItem.find_one( ConfigItem.namespace_prefix == namespace, ConfigItem.key == key ) if item.value != args['value']: item.value = args['value'] if item.type != args['type']: item.type = args['type'] if item.description != args['description']: item.description = args['description'] self.dbconfig.set(namespace, key, _to_dbc_class(args)) auditlog(event='configItem.update', actor=session['user'].username, data=args) return self.make_response('Config entry updated')
python
def put(self, namespace, key): args = request.json if not self.dbconfig.key_exists(namespace, key): return self.make_response('No such config entry: {}/{}'.format(namespace, key), HTTP.BAD_REQUEST) if (args['type'] == 'choice' and not args['value']['min_items'] <= len(args['value']['enabled']) <= args['value']['max_items']): return self.make_response( 'You should select {} {}item{}'.format( args['value']['min_items'], '' if args['value']['min_items'] == args['value']['max_items'] else 'to {} '.format( args['value']['max_items'] ), 's' if args['value']['max_items'] > 1 else '' ), HTTP.BAD_REQUEST ) if args['type'] == 'choice' and not set(args['value']['enabled']).issubset(args['value']['available']): return self.make_response('Invalid item', HTTP.BAD_REQUEST) item = db.ConfigItem.find_one( ConfigItem.namespace_prefix == namespace, ConfigItem.key == key ) if item.value != args['value']: item.value = args['value'] if item.type != args['type']: item.type = args['type'] if item.description != args['description']: item.description = args['description'] self.dbconfig.set(namespace, key, _to_dbc_class(args)) auditlog(event='configItem.update', actor=session['user'].username, data=args) return self.make_response('Config entry updated')
[ "def", "put", "(", "self", ",", "namespace", ",", "key", ")", ":", "args", "=", "request", ".", "json", "if", "not", "self", ".", "dbconfig", ".", "key_exists", "(", "namespace", ",", "key", ")", ":", "return", "self", ".", "make_response", "(", "'No...
Update a single configuration item
[ "Update", "a", "single", "configuration", "item" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/views/config.py#L113-L152
232,187
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/plugins/views/config.py
ConfigGet.delete
def delete(self, namespace, key): """Delete a specific configuration item""" if not self.dbconfig.key_exists(namespace, key): return self.make_response('No such config entry exists: {}/{}'.format(namespace, key), HTTP.BAD_REQUEST) self.dbconfig.delete(namespace, key) auditlog(event='configItem.delete', actor=session['user'].username, data={'namespace': namespace, 'key': key}) return self.make_response('Config entry deleted')
python
def delete(self, namespace, key): if not self.dbconfig.key_exists(namespace, key): return self.make_response('No such config entry exists: {}/{}'.format(namespace, key), HTTP.BAD_REQUEST) self.dbconfig.delete(namespace, key) auditlog(event='configItem.delete', actor=session['user'].username, data={'namespace': namespace, 'key': key}) return self.make_response('Config entry deleted')
[ "def", "delete", "(", "self", ",", "namespace", ",", "key", ")", ":", "if", "not", "self", ".", "dbconfig", ".", "key_exists", "(", "namespace", ",", "key", ")", ":", "return", "self", ".", "make_response", "(", "'No such config entry exists: {}/{}'", ".", ...
Delete a specific configuration item
[ "Delete", "a", "specific", "configuration", "item" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/views/config.py#L156-L163
232,188
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/plugins/views/config.py
NamespaceGet.get
def get(self, namespacePrefix): """Get a specific configuration namespace""" ns = db.ConfigNamespace.find_one(ConfigNamespace.namespace_prefix == namespacePrefix) if not ns: return self.make_response('No such namespace: {}'.format(namespacePrefix), HTTP.NOT_FOUND) return self.make_response({ 'message': None, 'namespace': ns })
python
def get(self, namespacePrefix): ns = db.ConfigNamespace.find_one(ConfigNamespace.namespace_prefix == namespacePrefix) if not ns: return self.make_response('No such namespace: {}'.format(namespacePrefix), HTTP.NOT_FOUND) return self.make_response({ 'message': None, 'namespace': ns })
[ "def", "get", "(", "self", ",", "namespacePrefix", ")", ":", "ns", "=", "db", ".", "ConfigNamespace", ".", "find_one", "(", "ConfigNamespace", ".", "namespace_prefix", "==", "namespacePrefix", ")", "if", "not", "ns", ":", "return", "self", ".", "make_respons...
Get a specific configuration namespace
[ "Get", "a", "specific", "configuration", "namespace" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/views/config.py#L171-L180
232,189
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/plugins/views/config.py
NamespaceGet.put
def put(self, namespacePrefix): """Update a specific configuration namespace""" self.reqparse.add_argument('name', type=str, required=True) self.reqparse.add_argument('sortOrder', type=int, required=True) args = self.reqparse.parse_args() ns = db.ConfigNamespace.find_one(ConfigNamespace.namespace_prefix == namespacePrefix) if not ns: return self.make_response('No such namespace: {}'.format(namespacePrefix), HTTP.NOT_FOUND) ns.name = args['name'] ns.sort_order = args['sortOrder'] db.session.add(ns) db.session.commit() self.dbconfig.reload_data() auditlog(event='configNamespace.update', actor=session['user'].username, data=args) return self.make_response('Namespace updated')
python
def put(self, namespacePrefix): self.reqparse.add_argument('name', type=str, required=True) self.reqparse.add_argument('sortOrder', type=int, required=True) args = self.reqparse.parse_args() ns = db.ConfigNamespace.find_one(ConfigNamespace.namespace_prefix == namespacePrefix) if not ns: return self.make_response('No such namespace: {}'.format(namespacePrefix), HTTP.NOT_FOUND) ns.name = args['name'] ns.sort_order = args['sortOrder'] db.session.add(ns) db.session.commit() self.dbconfig.reload_data() auditlog(event='configNamespace.update', actor=session['user'].username, data=args) return self.make_response('Namespace updated')
[ "def", "put", "(", "self", ",", "namespacePrefix", ")", ":", "self", ".", "reqparse", ".", "add_argument", "(", "'name'", ",", "type", "=", "str", ",", "required", "=", "True", ")", "self", ".", "reqparse", ".", "add_argument", "(", "'sortOrder'", ",", ...
Update a specific configuration namespace
[ "Update", "a", "specific", "configuration", "namespace" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/views/config.py#L184-L202
232,190
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/plugins/views/config.py
NamespaceGet.delete
def delete(self, namespacePrefix): """Delete a specific configuration namespace""" ns = db.ConfigNamespace.find_one(ConfigNamespace.namespace_prefix == namespacePrefix) if not ns: return self.make_response('No such namespace: {}'.format(namespacePrefix), HTTP.NOT_FOUND) db.session.delete(ns) db.session.commit() self.dbconfig.reload_data() auditlog( event='configNamespace.delete', actor=session['user'].username, data={'namespacePrefix': namespacePrefix} ) return self.make_response('Namespace deleted')
python
def delete(self, namespacePrefix): ns = db.ConfigNamespace.find_one(ConfigNamespace.namespace_prefix == namespacePrefix) if not ns: return self.make_response('No such namespace: {}'.format(namespacePrefix), HTTP.NOT_FOUND) db.session.delete(ns) db.session.commit() self.dbconfig.reload_data() auditlog( event='configNamespace.delete', actor=session['user'].username, data={'namespacePrefix': namespacePrefix} ) return self.make_response('Namespace deleted')
[ "def", "delete", "(", "self", ",", "namespacePrefix", ")", ":", "ns", "=", "db", ".", "ConfigNamespace", ".", "find_one", "(", "ConfigNamespace", ".", "namespace_prefix", "==", "namespacePrefix", ")", "if", "not", "ns", ":", "return", "self", ".", "make_resp...
Delete a specific configuration namespace
[ "Delete", "a", "specific", "configuration", "namespace" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/views/config.py#L206-L221
232,191
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/plugins/views/config.py
Namespaces.post
def post(self): """Create a new configuration namespace""" self.reqparse.add_argument('namespacePrefix', type=str, required=True) self.reqparse.add_argument('name', type=str, required=True) self.reqparse.add_argument('sortOrder', type=int, required=True) args = self.reqparse.parse_args() if self.dbconfig.namespace_exists(args['namespacePrefix']): return self.make_response('Namespace {} already exists'.format(args['namespacePrefix']), HTTP.CONFLICT) ns = ConfigNamespace() ns.namespace_prefix = args['namespacePrefix'] ns.name = args['name'] ns.sort_order = args['sortOrder'] db.session.add(ns) db.session.commit() self.dbconfig.reload_data() auditlog(event='configNamespace.create', actor=session['user'].username, data=args) return self.make_response('Namespace created', HTTP.CREATED)
python
def post(self): self.reqparse.add_argument('namespacePrefix', type=str, required=True) self.reqparse.add_argument('name', type=str, required=True) self.reqparse.add_argument('sortOrder', type=int, required=True) args = self.reqparse.parse_args() if self.dbconfig.namespace_exists(args['namespacePrefix']): return self.make_response('Namespace {} already exists'.format(args['namespacePrefix']), HTTP.CONFLICT) ns = ConfigNamespace() ns.namespace_prefix = args['namespacePrefix'] ns.name = args['name'] ns.sort_order = args['sortOrder'] db.session.add(ns) db.session.commit() self.dbconfig.reload_data() auditlog(event='configNamespace.create', actor=session['user'].username, data=args) return self.make_response('Namespace created', HTTP.CREATED)
[ "def", "post", "(", "self", ")", ":", "self", ".", "reqparse", ".", "add_argument", "(", "'namespacePrefix'", ",", "type", "=", "str", ",", "required", "=", "True", ")", "self", ".", "reqparse", ".", "add_argument", "(", "'name'", ",", "type", "=", "st...
Create a new configuration namespace
[ "Create", "a", "new", "configuration", "namespace" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/views/config.py#L229-L251
232,192
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/log.py
_get_syslog_format
def _get_syslog_format(event_type): """Take an event type argument and return a python logging format In order to properly format the syslog messages to current standard, load the template and perform necessary replacements and return the string. Args: event_type (str): Event type name Returns: `str` """ syslog_format_template = get_template('syslog_format.json') fmt = syslog_format_template.render( event_type=event_type, host=dbconfig.get('instance_name', default='local') ) # Load and redump string, to get rid of any extraneous whitespaces return json.dumps(json.loads(fmt))
python
def _get_syslog_format(event_type): syslog_format_template = get_template('syslog_format.json') fmt = syslog_format_template.render( event_type=event_type, host=dbconfig.get('instance_name', default='local') ) # Load and redump string, to get rid of any extraneous whitespaces return json.dumps(json.loads(fmt))
[ "def", "_get_syslog_format", "(", "event_type", ")", ":", "syslog_format_template", "=", "get_template", "(", "'syslog_format.json'", ")", "fmt", "=", "syslog_format_template", ".", "render", "(", "event_type", "=", "event_type", ",", "host", "=", "dbconfig", ".", ...
Take an event type argument and return a python logging format In order to properly format the syslog messages to current standard, load the template and perform necessary replacements and return the string. Args: event_type (str): Event type name Returns: `str`
[ "Take", "an", "event", "type", "argument", "and", "return", "a", "python", "logging", "format" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/log.py#L80-L99
232,193
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/log.py
setup_logging
def setup_logging(): """Utility function to setup the logging systems based on the `logging.json` configuration file""" config = json.load(open(os.path.join(config_path, 'logging.json'))) # If syslogging is disabled, set the pipeline handler to NullHandler if dbconfig.get('enable_syslog_forwarding', NS_LOG, False): try: config['formatters']['syslog'] = { 'format': _get_syslog_format('cloud-inquisitor-logs') } config['handlers']['syslog'] = { 'class': 'cloud_inquisitor.log.SyslogPipelineHandler', 'formatter': 'syslog', 'filters': ['standard'] } config['loggers']['cloud_inquisitor']['handlers'].append('syslog') # Configure the audit log handler audit_handler = SyslogPipelineHandler() audit_handler.setFormatter(logging.Formatter(_get_syslog_format('cloud-inquisitor-audit'))) audit_handler.setLevel(logging.DEBUG) _AUDIT_LOGGER.addHandler(audit_handler) _AUDIT_LOGGER.propagate = False except Exception as ex: print('An error occured while configuring the syslogger: {}'.format(ex)) logging.config.dictConfig(config)
python
def setup_logging(): config = json.load(open(os.path.join(config_path, 'logging.json'))) # If syslogging is disabled, set the pipeline handler to NullHandler if dbconfig.get('enable_syslog_forwarding', NS_LOG, False): try: config['formatters']['syslog'] = { 'format': _get_syslog_format('cloud-inquisitor-logs') } config['handlers']['syslog'] = { 'class': 'cloud_inquisitor.log.SyslogPipelineHandler', 'formatter': 'syslog', 'filters': ['standard'] } config['loggers']['cloud_inquisitor']['handlers'].append('syslog') # Configure the audit log handler audit_handler = SyslogPipelineHandler() audit_handler.setFormatter(logging.Formatter(_get_syslog_format('cloud-inquisitor-audit'))) audit_handler.setLevel(logging.DEBUG) _AUDIT_LOGGER.addHandler(audit_handler) _AUDIT_LOGGER.propagate = False except Exception as ex: print('An error occured while configuring the syslogger: {}'.format(ex)) logging.config.dictConfig(config)
[ "def", "setup_logging", "(", ")", ":", "config", "=", "json", ".", "load", "(", "open", "(", "os", ".", "path", ".", "join", "(", "config_path", ",", "'logging.json'", ")", ")", ")", "# If syslogging is disabled, set the pipeline handler to NullHandler", "if", "...
Utility function to setup the logging systems based on the `logging.json` configuration file
[ "Utility", "function", "to", "setup", "the", "logging", "systems", "based", "on", "the", "logging", ".", "json", "configuration", "file" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/log.py#L102-L131
232,194
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/log.py
DBLogger.emit
def emit(self, record): """Persist a record into the database Args: record (`logging.Record`): The logging.Record object to store Returns: `None` """ # Skip records less than min_level if record.levelno < logging.getLevelName(self.min_level): return evt = LogEvent() evt.level = record.levelname evt.levelno = record.levelno evt.timestamp = datetime.fromtimestamp(record.created) evt.message = record.message evt.filename = record.filename evt.lineno = record.lineno evt.module = record.module evt.funcname = record.funcName evt.pathname = record.pathname evt.process_id = record.process # Only log stacktraces if its the level is ERROR or higher if record.levelno >= 40: evt.stacktrace = traceback.format_exc() try: db.session.add(evt) db.session.commit() except Exception: db.session.rollback()
python
def emit(self, record): # Skip records less than min_level if record.levelno < logging.getLevelName(self.min_level): return evt = LogEvent() evt.level = record.levelname evt.levelno = record.levelno evt.timestamp = datetime.fromtimestamp(record.created) evt.message = record.message evt.filename = record.filename evt.lineno = record.lineno evt.module = record.module evt.funcname = record.funcName evt.pathname = record.pathname evt.process_id = record.process # Only log stacktraces if its the level is ERROR or higher if record.levelno >= 40: evt.stacktrace = traceback.format_exc() try: db.session.add(evt) db.session.commit() except Exception: db.session.rollback()
[ "def", "emit", "(", "self", ",", "record", ")", ":", "# Skip records less than min_level", "if", "record", ".", "levelno", "<", "logging", ".", "getLevelName", "(", "self", ".", "min_level", ")", ":", "return", "evt", "=", "LogEvent", "(", ")", "evt", ".",...
Persist a record into the database Args: record (`logging.Record`): The logging.Record object to store Returns: `None`
[ "Persist", "a", "record", "into", "the", "database" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/log.py#L25-L58
232,195
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/schema/base.py
ConfigItem.get
def get(cls, ns, key): """Fetch an item by namespace and key Args: ns (str): Namespace prefix key (str): Item key Returns: :obj:`Configitem`: Returns config item object if found, else `None` """ return getattr(db, cls.__name__).find_one( ConfigItem.namespace_prefix == ns, ConfigItem.key == key )
python
def get(cls, ns, key): return getattr(db, cls.__name__).find_one( ConfigItem.namespace_prefix == ns, ConfigItem.key == key )
[ "def", "get", "(", "cls", ",", "ns", ",", "key", ")", ":", "return", "getattr", "(", "db", ",", "cls", ".", "__name__", ")", ".", "find_one", "(", "ConfigItem", ".", "namespace_prefix", "==", "ns", ",", "ConfigItem", ".", "key", "==", "key", ")" ]
Fetch an item by namespace and key Args: ns (str): Namespace prefix key (str): Item key Returns: :obj:`Configitem`: Returns config item object if found, else `None`
[ "Fetch", "an", "item", "by", "namespace", "and", "key" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/schema/base.py#L221-L234
232,196
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/schema/base.py
User.add_role
def add_role(user, roles): """Map roles for user in database Args: user (User): User to add roles to roles ([Role]): List of roles to add Returns: None """ def _add_role(role): user_role = UserRole() user_role.user_id = user.user_id user_role.role_id = role.role_id db.session.add(user_role) db.session.commit() [_add_role(role) for role in roles]
python
def add_role(user, roles): def _add_role(role): user_role = UserRole() user_role.user_id = user.user_id user_role.role_id = role.role_id db.session.add(user_role) db.session.commit() [_add_role(role) for role in roles]
[ "def", "add_role", "(", "user", ",", "roles", ")", ":", "def", "_add_role", "(", "role", ")", ":", "user_role", "=", "UserRole", "(", ")", "user_role", ".", "user_id", "=", "user", ".", "user_id", "user_role", ".", "role_id", "=", "role", ".", "role_id...
Map roles for user in database Args: user (User): User to add roles to roles ([Role]): List of roles to add Returns: None
[ "Map", "roles", "for", "user", "in", "database" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/schema/base.py#L333-L349
232,197
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/config.py
DBConfig.reload_data
def reload_data(self): """Reloads the configuration from the database Returns: `None` """ # We must force a rollback here to ensure that we are working on a fresh session, without any cache db.session.rollback() self.__data = {} try: for ns in db.ConfigNamespace.all(): self.__data[ns.namespace_prefix] = {x.key: x.value for x in ns.config_items} except SQLAlchemyError as ex: if str(ex).find('1146') != -1: pass
python
def reload_data(self): # We must force a rollback here to ensure that we are working on a fresh session, without any cache db.session.rollback() self.__data = {} try: for ns in db.ConfigNamespace.all(): self.__data[ns.namespace_prefix] = {x.key: x.value for x in ns.config_items} except SQLAlchemyError as ex: if str(ex).find('1146') != -1: pass
[ "def", "reload_data", "(", "self", ")", ":", "# We must force a rollback here to ensure that we are working on a fresh session, without any cache", "db", ".", "session", ".", "rollback", "(", ")", "self", ".", "__data", "=", "{", "}", "try", ":", "for", "ns", "in", ...
Reloads the configuration from the database Returns: `None`
[ "Reloads", "the", "configuration", "from", "the", "database" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/config.py#L53-L69
232,198
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/config.py
DBConfig.key_exists
def key_exists(self, namespace, key): """Checks a namespace for the existence of a specific key Args: namespace (str): Namespace to check in key (str): Name of the key to check for Returns: `True` if key exists in the namespace, else `False` """ return namespace in self.__data and key in self.__data[namespace]
python
def key_exists(self, namespace, key): return namespace in self.__data and key in self.__data[namespace]
[ "def", "key_exists", "(", "self", ",", "namespace", ",", "key", ")", ":", "return", "namespace", "in", "self", ".", "__data", "and", "key", "in", "self", ".", "__data", "[", "namespace", "]" ]
Checks a namespace for the existence of a specific key Args: namespace (str): Namespace to check in key (str): Name of the key to check for Returns: `True` if key exists in the namespace, else `False`
[ "Checks", "a", "namespace", "for", "the", "existence", "of", "a", "specific", "key" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/config.py#L83-L94
232,199
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/config.py
DBConfig.delete
def delete(self, namespace, key): """Remove a configuration item from the database Args: namespace (`str`): Namespace of the config item key (`str`): Key to delete Returns: `None` """ if self.key_exists(namespace, key): obj = db.ConfigItem.find_one( ConfigItem.namespace_prefix == namespace, ConfigItem.key == key ) del self.__data[namespace][key] db.session.delete(obj) db.session.commit() else: raise KeyError('{}/{}'.format(namespace, key))
python
def delete(self, namespace, key): if self.key_exists(namespace, key): obj = db.ConfigItem.find_one( ConfigItem.namespace_prefix == namespace, ConfigItem.key == key ) del self.__data[namespace][key] db.session.delete(obj) db.session.commit() else: raise KeyError('{}/{}'.format(namespace, key))
[ "def", "delete", "(", "self", ",", "namespace", ",", "key", ")", ":", "if", "self", ".", "key_exists", "(", "namespace", ",", "key", ")", ":", "obj", "=", "db", ".", "ConfigItem", ".", "find_one", "(", "ConfigItem", ".", "namespace_prefix", "==", "name...
Remove a configuration item from the database Args: namespace (`str`): Namespace of the config item key (`str`): Key to delete Returns: `None`
[ "Remove", "a", "configuration", "item", "from", "the", "database" ]
181dc2566ca59fc855f695b7fcc2c3b934e6ee9f
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/config.py#L188-L209