run a custodian policy across accounts
779990
def run(config, use, output_dir, accounts, tags, region,
        policy, policy_tags, cache_period, cache_path, metrics,
        dryrun, debug, verbose, metrics_uri):
    """"""
    accounts_config, custodian_config, executor = init(
        config, use, debug, verbose, accounts, tags, policy, policy_tags=policy_tags)
    policy_counts = Counter()
    success = True

    if metrics_uri:
        metrics = metrics_uri

    if not cache_path:
        cache_path = os.path.expanduser("~/.cache/c7n-org")
        if not os.path.exists(cache_path):
            os.makedirs(cache_path)

    with executor(max_workers=WORKER_COUNT) as w:
        futures = {}
        for a in accounts_config['accounts']:
            for r in resolve_regions(region or a.get('regions', ())):
                futures[w.submit(
                    run_account,
                    a, r,
                    custodian_config,
                    output_dir,
                    cache_period,
                    cache_path,
                    metrics,
                    dryrun,
                    debug)] = (a, r)

        for f in as_completed(futures):
            a, r = futures[f]
            if f.exception():
                if debug:
                    raise
                log.warning(
                    "Error running policy in %s @ %s exception: %s",
                    a['name'], r, f.exception())

            account_region_pcounts, account_region_success = f.result()
            for p in account_region_pcounts:
                policy_counts[p] += account_region_pcounts[p]

            if not account_region_success:
                success = False

    log.info("Policy resource counts %s" % policy_counts)

    if not success:
        sys.exit(1)
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()
1072622
def cli(env, account_id):
    """"""

    manager = SoftLayer.CDNManager(env.client)
    account = manager.get_account(account_id)

    table = formatting.KeyValueTable(['name', 'value'])
    table.align['name'] = 'r'
    table.align['value'] = 'l'

    table.add_row(['id', account['id']])
    table.add_row(['account_name', account['cdnAccountName']])
    table.add_row(['type', account['cdnSolutionName']])
    table.add_row(['status', account['status']['name']])
    table.add_row(['created', account['createDate']])
    table.add_row(['notes',
                   account.get('cdnAccountNote', formatting.blank())])

    env.fout(table)
876283
def rbac_policy_get(request, policy_id, **kwargs):
    """"""
    policy = neutronclient(request).show_rbac_policy(
        policy_id, **kwargs).get('rbac_policy')
    return RBACPolicy(policy)
597479
private void switchAccountStatus(Account account, Account.Status status,
            UserIdentityContext userIdentityContext) {
        if (logger.isDebugEnabled()) {
            logger.debug("Switching status for account:" + account.getSid() + ",status:" + status);
        }
        switch (status) {
            case CLOSED:
                sendRVDStatusNotification(account,userIdentityContext);
                // then proceed to dependency removal
                removeAccoundDependencies(account.getSid());
                break;
            default:
                break;

        }
        // finally, set and persist account status
        account = account.setStatus(status);
        accountsDao.updateAccount(account);
    }
17856
def clean(self):
        '''
        
        '''

        if self.staffMember and self.staffMember.userAccount and \
        self.user and not self.staffMember.userAccount == self.user:
            raise ValidationError(_('Transaction party user does not match staff member user.'))

        if self.location and (self.user or self.staffMember):
            raise ValidationError(_('Transaction party may not be both a Location and a User or StaffMember.'))
114321
private void setupDefaultAccountInfoHandler() {
		final BitfinexAccountSymbol accountSymbol = BitfinexSymbols.account(BitfinexApiKeyPermissions.NO_PERMISSIONS);
		final AccountInfoHandler accountInfoHandler = new AccountInfoHandler(ACCCOUNT_INFO_CHANNEL, accountSymbol);
		accountInfoHandler.onHeartbeatEvent(timestamp -> this.updateConnectionHeartbeat());
		channelIdToHandlerMap.put(ACCCOUNT_INFO_CHANNEL, accountInfoHandler);
	}
275166
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)})
141812
def runlogs_policy(log_group_ref):
    """"""
    p = Policy(
        Statement=[
            Statement(
                Effect=Allow,
                Resource=[
                    Join('', [
                        'arn:aws:logs:*:*:log-group:',
                        log_group_ref,
                        ':log-stream:*'])],
                Action=[
                    logs.CreateLogStream,
                    logs.PutLogEvents,
                ])])
    return p
416825
def conditionally_inline_policies(role_name, sr_entry):
  
  service_type = sr_entry['type']
  if not (service_type in SERVICE_TYPE_ROLE and "policies" in sr_entry):
    print_if_verbose("not eligible for policies; service_type: {} is not valid for policies "
                     "or no 'policies' key in service registry for this role".format(service_type))
    return

  for policy_name in sr_entry['policies']:
    print_if_verbose("loading policy: {} for role: {}".format(policy_name, role_name))
    try:
      policy_document = resolve_policy_document(policy_name)
    except:
      fail("Exception loading policy: {} for role: {}".format(policy_name, role_name), sys.exc_info())

    # inline the policy onto the role
    if CONTEXT.commit:
      try:
        CLIENTS["iam"].put_role_policy(RoleName=role_name, PolicyName=policy_name, PolicyDocument=policy_document)
      except:
        fail("Exception putting policy: {} onto role: {}".format(policy_name, role_name), sys.exc_info())
537984
def allow(ctx, foreign_account, permission, weight, threshold, account):
    
    if not foreign_account:
        from bitsharesbase.account import PasswordKey

        pwd = click.prompt(
            "Password for Key Derivation", hide_input=True, confirmation_prompt=True
        )
        foreign_account = format(
            PasswordKey(account, pwd, permission).get_public(), "BTS"
        )
    print_tx(
        ctx.bitshares.allow(
            foreign_account,
            weight=weight,
            account=account,
            permission=permission,
            threshold=threshold,
        )
    )
349959
def set_interactive_policy(*, locals=None, banner=None, serve=None,
                           prompt_control=None):
    """"""
    policy = InteractiveEventLoopPolicy(
        locals=locals,
        banner=banner,
        serve=serve,
        prompt_control=prompt_control)
    asyncio.set_event_loop_policy(policy)
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'))
173299
def build_policy(region=None, key=None, keyid=None, profile=None):
    '''
    
    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
    if hasattr(conn, 'build_policy'):
        policy = salt.utils.json.loads(conn.build_policy())
    elif hasattr(conn, '_build_policy'):
        policy = salt.utils.json.loads(conn._build_policy())
    else:
        return {}
    # The format we get from build_policy isn't going to be what we get back
    # from AWS for the exact same policy. AWS converts single item list values
    # into strings, so let's do the same here.
    for key, policy_val in policy.items():
        for statement in policy_val:
            if (isinstance(statement['Action'], list)
                    and len(statement['Action']) == 1):
                statement['Action'] = statement['Action'][0]
            if (isinstance(statement['Principal']['Service'], list)
                    and len(statement['Principal']['Service']) == 1):
                statement['Principal']['Service'] = statement['Principal']['Service'][0]
    # build_policy doesn't add a version field, which AWS is going to set to a
    # default value, when we get it back, so let's set it.
    policy['Version'] = '2008-10-17'
    return policy
260387
def hold_policy(document, policy, server=False):
    
    old_policy = document._hold
    document._hold = policy
    try:
        yield
    finally:
        if server and not old_policy:
            document.unhold()
        else:
            document._hold = old_policy
513093
def reset(self):
        
        with self.unlock_cond:
            for owner in self.owner2account:
                self.release_accounts(owner)
            self._remove_account(self.accounts.copy())
            self.unlock_cond.notify_all()
1101972
def _run_as(user, group):
        
        def wrapper():
            if user is not None:
                os.setuid(user)
            if group is not None:
                os.setgid(group)
        return wrapper