helper method for present. ensure that ELB policies are set

def _policies_present(name, policies, policies_from_pillar, listeners, backends,
                      region, key, keyid, profile):
    '''helper method for present. ensure that ELB policies are set'''
    if policies is None:
        policies = []
    pillar_policies = __salt__['config.option'](policies_from_pillar, [])
    policies = policies + pillar_policies
    if backends is None:
        backends = []

    # check for policy name uniqueness and correct type
    policy_names = set()
    for p in policies:
        if 'policy_name' not in p:
            raise SaltInvocationError('policy_name is a required value for '
                                      'policies.')
        if 'policy_type' not in p:
            raise SaltInvocationError('policy_type is a required value for '
                                      'policies.')
        if 'policy' not in p:
            raise SaltInvocationError('policy is a required value for '
                                      'listeners.')
        # check for unique policy names
        if p['policy_name'] in policy_names:
            raise SaltInvocationError('Policy names must be unique: policy {0}'
                    ' is declared twice.'.format(p['policy_name']))
        policy_names.add(p['policy_name'])

    # check that listeners refer to valid policy names
    for l in listeners:
        for p in l.get('policies', []):
            if p not in policy_names:
                raise SaltInvocationError('Listener {0} on ELB {1} refers to '
                        'undefined policy {2}.'.format(l['elb_port'], name, p))

    # check that backends refer to valid policy names
    for b in backends:
        for p in b.get('policies', []):
            if p not in policy_names:
                raise SaltInvocationError('Backend {0} on ELB {1} refers to '
                        'undefined policy '
                        '{2}.'.format(b['instance_port'], name, p))

    ret = {'result': True, 'comment': '', 'changes': {}}

    lb = __salt__['boto_elb.get_elb_config'](name, region, key, keyid, profile)
    if not lb:
        ret['comment'] = '{0} ELB configuration could not be retrieved.'.format(name)
        ret['result'] = False
        return ret

    # Policies have two names:
    # - a short name ('name') that's only the policy name (e.g. testpolicy)
    # - a canonical name ('cname') that contains the policy type and hash
    #   (e.g. SSLNegotiationPolicy-testpolicy-14b32f668639cc8ea1391e062af98524)

    policies_by_cname = {}
    cnames_by_name = {}
    for p in policies:
        cname = _policy_cname(p)
        policies_by_cname[cname] = p
        cnames_by_name[p['policy_name']] = cname

    expected_policy_names = policies_by_cname.keys()
    actual_policy_names = lb['policies']

    # This is sadly a huge hack to get around the fact that AWS assigns a
    # default SSLNegotiationPolicyType policy (with the naming scheme
    # ELBSecurityPolicy-YYYY-MM) to all ELBs terminating SSL without an
    # explicit policy set. If we don't keep track of the default policies and
    # explicitly exclude them from deletion, orchestration will fail because we
    # attempt to delete the default policy that's being used by listeners that
    # were created with no explicit policy.
    default_aws_policies = set()

    expected_policies_by_listener = {}
    for l in listeners:
        expected_policies_by_listener[l['elb_port']] = set(
                [cnames_by_name[p] for p in l.get('policies', [])])

    actual_policies_by_listener = {}
    for l in lb['listeners']:
        listener_policies = set(l.get('policies', []))
        actual_policies_by_listener[l['elb_port']] = listener_policies
        # Determine if any actual listener policies look like default policies,
        # so we can exclude them from deletion below (see note about this hack
        # above).
        for p in listener_policies:
            if re.match(r'^ELBSecurityPolicy-\d{4}-\d{2}$', p):
                default_aws_policies.add(p)

    expected_policies_by_backend = {}
    for b in backends:
        expected_policies_by_backend[b['instance_port']] = set(
                [cnames_by_name[p] for p in b.get('policies', [])])

    actual_policies_by_backend = {}
    for b in lb['backends']:
        backend_policies = set(b.get('policies', []))
        actual_policies_by_backend[b['instance_port']] = backend_policies

    to_delete = []
    to_create = []

    for policy_name in expected_policy_names:
        if policy_name not in actual_policy_names:
            to_create.append(policy_name)
    for policy_name in actual_policy_names:
        if policy_name not in expected_policy_names:
            if policy_name not in default_aws_policies:
                to_delete.append(policy_name)

    listeners_to_update = set()
    for port, policies in six.iteritems(expected_policies_by_listener):
        if policies != actual_policies_by_listener.get(port, set()):
            listeners_to_update.add(port)
    for port, policies in six.iteritems(actual_policies_by_listener):
        if policies != expected_policies_by_listener.get(port, set()):
            listeners_to_update.add(port)

    backends_to_update = set()
    for port, policies in six.iteritems(expected_policies_by_backend):
        if policies != actual_policies_by_backend.get(port, set()):
            backends_to_update.add(port)
    for port, policies in six.iteritems(actual_policies_by_backend):
        if policies != expected_policies_by_backend.get(port, set()):
            backends_to_update.add(port)

    if __opts__['test']:
        msg = []
        if to_create or to_delete:
            msg.append('ELB {0} set to have policies modified:'.format(name))
            for policy in to_create:
                msg.append('Policy {0} added.'.format(policy))
            for policy in to_delete:
                msg.append('Policy {0} deleted.'.format(policy))
            ret['result'] = None
        else:
            msg.append('Policies already set on ELB {0}.'.format(name))
        for listener in listeners_to_update:
            msg.append('Listener {0} policies updated.'.format(listener))
        for backend in backends_to_update:
            msg.append('Backend {0} policies updated.'.format(backend))
        ret['comment'] = '  '.join(msg)
        return ret

    if to_create:
        for policy_name in to_create:
            created = __salt__['boto_elb.create_policy'](
                name=name,
                policy_name=policy_name,
                policy_type=policies_by_cname[policy_name]['policy_type'],
                policy=policies_by_cname[policy_name]['policy'],
                region=region,
                key=key,
                keyid=keyid,
                profile=profile)
            if created:
                ret['changes'].setdefault(policy_name, {})['new'] = policy_name
                comment = "Policy {0} was created on ELB {1}".format(
                        policy_name, name)
                ret['comment'] = '  '.join([ret['comment'], comment])
                ret['result'] = True
            else:
                ret['result'] = False
                return ret

    for port in listeners_to_update:
        policy_set = __salt__['boto_elb.set_listener_policy'](
                name=name,
                port=port,
                policies=list(expected_policies_by_listener.get(port, [])),
                region=region,
                key=key,
                keyid=keyid,
                profile=profile)
        if policy_set:
            policy_key = 'listener_{0}_policy'.format(port)
            ret['changes'][policy_key] = {
                    'old': list(actual_policies_by_listener.get(port, [])),
                    'new': list(expected_policies_by_listener.get(port, [])),
                    }
            comment = "Policy {0} was created on ELB {1} listener {2}".format(
                    expected_policies_by_listener[port], name, port)
            ret['comment'] = '  '.join([ret['comment'], comment])
            ret['result'] = True
        else:
            ret['result'] = False
            return ret

    for port in backends_to_update:
        policy_set = __salt__['boto_elb.set_backend_policy'](
                name=name,
                port=port,
                policies=list(expected_policies_by_backend.get(port, [])),
                region=region,
                key=key,
                keyid=keyid,
                profile=profile)
        if policy_set:
            policy_key = 'backend_{0}_policy'.format(port)
            ret['changes'][policy_key] = {
                    'old': list(actual_policies_by_backend.get(port, [])),
                    'new': list(expected_policies_by_backend.get(port, [])),
                    }
            comment = "Policy {0} was created on ELB {1} backend {2}".format(
                    expected_policies_by_backend[port], name, port)
            ret['comment'] = '  '.join([ret['comment'], comment])
            ret['result'] = True
        else:
            ret['result'] = False
            return ret

    if to_delete:
        for policy_name in to_delete:
            deleted = __salt__['boto_elb.delete_policy'](
                name=name,
                policy_name=policy_name,
                region=region,
                key=key,
                keyid=keyid,
                profile=profile)
            if deleted:
                ret['changes'].setdefault(policy_name, {})['old'] = policy_name
                comment = "Policy {0} was deleted from ELB {1}".format(
                        policy_name, name)
                ret['comment'] = '  '.join([ret['comment'], comment])
                ret['result'] = True
            else:
                ret['result'] = False
                return ret
    return ret