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`
327455
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)})
648091
def get_accounts_for_service(cls, service_type):
        
        return [
            a for a in cls.get_accounts().values()
            if a.service_type == service_type
        ]
852181
def close(account_id: str) -> None:
    
    logger.info('closing-account', account_id=account_id)
    with transaction.atomic():
        account = Account.objects.get(pk=account_id)
        account.close()
        account.save()
1283846
def get_holding_accounts(self) -> List[Account]:
        
        if not self.__holding_accounts:
            self.__holding_accounts = self.__get_holding_accounts_query().all()

        return self.__holding_accounts
747708
def accounts(self):
        
        response = self.graph.get('%s/accounts' % self.id)

        accounts = []
        for item in response['data']:
            account = Structure(
                page = Page(
                    id = item['id'],
                    name = item['name'],
                    category = item['category']
                ),
                access_token = item['access_token'],
                permissions = item['perms']
            )

            accounts.append(account)

        return accounts
310688
async def serviceQueues(self, limit=None) -> int:
        
        return await self._inbox_router.handleAll(self._inbox, limit)
421798
def post_accounts(new_account)
      @options = {path: '/accounts/content',
                  body:  Megam::JSONCompat.to_json(new_account)}.merge(@options)

      request(
        :expects  => 201,
        :method   => :post,
        :body     => @options[:body]
        )
    end
1011829
def accounts(self):
        
        if self._accounts is None:
            from twilio.rest.accounts import Accounts
            self._accounts = Accounts(self)
        return self._accounts
788120
def cancel(self, orderNumbers, account=None, **kwargs):
        
        if not account:
            if "default_account" in self.config:
                account = self.config["default_account"]
        if not account:
            raise ValueError("You need to provide an account")
        account = Account(account, full=False, blockchain_instance=self)

        if not isinstance(orderNumbers, (list, set, tuple)):
            orderNumbers = {orderNumbers}

        op = []
        for order in orderNumbers:
            op.append(
                operations.Limit_order_cancel(
                    **{
                        "fee": {"amount": 0, "asset_id": "1.3.0"},
                        "fee_paying_account": account["id"],
                        "order": order,
                        "extensions": [],
                        "prefix": self.prefix,
                    }
                )
            )
        return self.finalizeOp(op, account["name"], "active", **kwargs)
903503
def _remove_account(self, accounts):
        
        for account in to_list(accounts):
            if account not in self.accounts:
                msg = 'attempt to remove unknown account %s' % account
                raise Exception(msg)
            if account not in self.unlocked_accounts:
                raise Exception('account %s should be unlocked' % account)
            account.acquired_event.disconnect(self._on_account_acquired)
            account.released_event.disconnect(self._on_account_released)
            self.accounts.remove(account)
            self.unlocked_accounts.remove(account)
400299
def accounts(self):
        
        d = {}

        if False and not self._account_password:
            from ambry.dbexceptions import ConfigurationError
            raise ConfigurationError(
                "Can't access accounts without setting an account password"
                " either in the accounts.password config, or in the AMBRY_ACCOUNT_PASSWORD"
                " env var.")

        for act in self.database.session.query(Account).all():
            if self._account_password:
                act.secret_password = self._account_password
            e = act.dict
            a_id = e['account_id']
            d[a_id] = e

        return d
61161
public void setAccountQuotas(java.util.Collection<AccountQuota> accountQuotas) {
        if (accountQuotas == null) {
            this.accountQuotas = null;
            return;
        }

        this.accountQuotas = new java.util.ArrayList<AccountQuota>(accountQuotas);
    }
82091
public void setAccounts(java.util.Collection<Account> accounts) {
        if (accounts == null) {
            this.accounts = null;
            return;
        }

        this.accounts = new java.util.ArrayList<Account>(accounts);
    }
394158
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()
348277
def ls(args):
    
    table = []
    queues = list(resources.sqs.queues.filter(QueueNamePrefix="github"))
    max_age = datetime.now(tzutc()) - timedelta(days=15)
    for topic in resources.sns.topics.all():
        account_id = ARN(topic.arn).account_id
        try:
            bucket = resources.s3.Bucket("deploy-status-{}".format(account_id))
            status_objects = bucket.objects.filter(Prefix=ARN(topic.arn).resource)
            recent_status_objects = {o.key: o for o in status_objects if o.last_modified > max_age}
        except ClientError:
            continue
        if ARN(topic.arn).resource.startswith("github"):
            for queue in queues:
                queue_name = os.path.basename(queue.url)
                if queue_name.startswith(ARN(topic.arn).resource):
                    row = dict(Topic=topic, Queue=queue)
                    status_object = bucket.Object(os.path.join(queue_name, "status"))
                    if status_object.key not in recent_status_objects:
                        continue
                    try:
                        github, owner, repo, events, instance = os.path.dirname(status_object.key).split("-", 4)
                        status = json.loads(status_object.get()["Body"].read().decode("utf-8"))
                        row.update(status, Owner=owner, Repo=repo, Instance=instance,
                                   Updated=status_object.last_modified)
                    except Exception:
                        pass
                    table.append(row)
    args.columns = ["Owner", "Repo", "Instance", "Status", "Ref", "Commit", "Updated", "Topic", "Queue"]
    page_output(tabulate(table, args))
1200119
def access(config, region, accounts=()):
    """"""
    config = validate.callback(config)
    accounts_report = []

    def check_access(account):
        accounts_report.append(account)
        session = get_session(account['role'], region)
        identity = session.client('sts').get_caller_identity()
        account['account_id'] = identity['Account']
        account.pop('groups')
        account.pop('role')
        client = session.client('iam')
        policy_arn = identity['Arn']
        if policy_arn.count('/') > 1:
            policy_arn = policy_arn.rsplit('/', 1)[0]
        if ':sts:' in policy_arn:
            policy_arn = policy_arn.replace(':sts', ':iam')
        if ':assumed-role' in policy_arn:
            policy_arn = policy_arn.replace(':assumed-role', ':role')
        evaluation = client.simulate_principal_policy(
            PolicySourceArn=policy_arn,
            ActionNames=['logs:CreateExportTask'])['EvaluationResults']
        account['access'] = evaluation[0]['EvalDecision']

    with ThreadPoolExecutor(max_workers=16) as w:
        futures = {}
        for account in config.get('accounts', ()):
            if accounts and account['name'] not in accounts:
                continue
            futures[w.submit(check_access, account)] = None
        for f in as_completed(futures):
            pass
    accounts_report.sort(key=operator.itemgetter('access'), reverse=True)
    print(tabulate(accounts_report, headers='keys'))
880571
def validate_account_alias(iam_client, account_alias):
    """"""
    # Super overkill here using pagination when an account can only
    # have a single alias, but at least this implementation should be
    # future-proof
    current_account_aliases = []
    paginator = iam_client.get_paginator('list_account_aliases')
    response_iterator = paginator.paginate()
    for page in response_iterator:
        current_account_aliases.extend(page.get('AccountAliases', []))
    if account_alias in current_account_aliases:
        LOGGER.info('Verified current AWS account alias matches required '
                    'alias %s.',
                    account_alias)
    else:
        LOGGER.error('Current AWS account aliases "%s" do not match '
                     'required account alias %s in Runway config.',
                     ','.join(current_account_aliases),
                     account_alias)
        sys.exit(1)