subscribe accounts log groups to target account log group destination

def subscribe(config, accounts, region, merge, debug):
    """subscribe accounts log groups to target account log group destination"""
    config = validate.callback(config)
    subscription = config.get('subscription')

    if subscription is None:
        log.error("config file: logs subscription missing")
        sys.exit(1)

    def converge_destination_policy(client, config):
        destination_name = subscription['destination-arn'].rsplit(':', 1)[-1]
        try:
            extant_destinations = client.describe_destinations(
                DestinationNamePrefix=destination_name).get('destinations')
        except ClientError:
            log.error("Log group destination not found: %s",
                      subscription['destination-arn'])
            sys.exit(1)

        account_ids = set()
        for a in accounts:
            if isinstance(a['role'], list):
                account_ids.add(a['role'][-1].split(':')[4])
            else:
                account_ids.add(a['role'].split(':')[4])

        if merge:
            for d in extant_destinations:
                if d['destinationName'] == destination_name:
                    for s in json.loads(d['accessPolicy']):
                        if s['Sid'] == 'CrossAccountDelivery':
                            account_ids.update(s['Principal']['AWS'])

        client.put_destination_policy(
            destinationName=destination_name,
            accessPolicy=json.dumps({
                'Statement': [{
                    'Action': 'logs:PutSubscriptionFilter',
                    'Effect': 'Allow',
                    'Principal': {'AWS': list(account_ids)},
                    'Resource': subscription['destination-arn'],
                    'Sid': 'CrossAccountDelivery'}]}))

    def subscribe_account(t_account, subscription, region):
        session = get_session(t_account['role'], region)
        client = session.client('logs')
        distribution = subscription.get('distribution', 'ByLogStream')

        for g in account.get('groups'):
            if (g.endswith('*')):
                g = g.replace('*', '')
                paginator = client.get_paginator('describe_log_groups')
                allLogGroups = paginator.paginate(logGroupNamePrefix=g).build_full_result()
                for l in allLogGroups:
                    _process_subscribe_group(
                        client, l['logGroupName'], subscription, distribution)
            else:
                _process_subscribe_group(client, g, subscription, distribution)

    if subscription.get('managed-policy'):
        if subscription.get('destination-role'):
            session = get_session(subscription['destination-role'], region)
        else:
            session = boto3.Session()
        converge_destination_policy(session.client('logs'), config)

    executor = debug and MainThreadExecutor or ThreadPoolExecutor

    with executor(max_workers=32) as w:
        futures = {}
        for account in config.get('accounts', ()):
            if accounts and account['name'] not in accounts:
                continue
            futures[w.submit(subscribe_account, account, subscription, region)] = account

        for f in as_completed(futures):
            account = futures[f]
            if f.exception():
                log.error("Error on account %s err: %s",
                          account['name'], f.exception())
            log.info("Completed %s", account['name'])