Query the neutron DB for Security Groups and Rules

        Groups and rules are returned as a dict of rule sets:
        {<eos_acl1_name>: set([<eos_acl1_rules>]),
         <eos_acl2_name>: set([<eos_acl2_rules>]),
         ...,
        }
760328
def get_expected_acls(self):
        
        security_groups = db_lib.get_security_groups()

        expected_acls = collections.defaultdict(set)
        for sg in security_groups:
            in_rules, out_rules = self._format_rules_for_eos(sg['rules'])
            ingress_acl_name = self._acl_name(sg['id'],
                                              n_const.INGRESS_DIRECTION)
            egress_acl_name = self._acl_name(sg['id'],
                                             n_const.EGRESS_DIRECTION)
            expected_acls[ingress_acl_name].update(in_rules)
            expected_acls[egress_acl_name].update(out_rules)
        return expected_acls
541106
def _rule_block(self):
        

        name = self._get_token(self.RE_NAME)
        self._expect_token('{')

        # consume additional options if available
        options = []
        while self._lookahead_token() != '}':
            options.append(self._rule_option())

        self._expect_token('}')
        return [name, options]
1201067
def listPhysicsGroups(self, physics_group_name=""):
        
        if not isinstance(physics_group_name, basestring):
            dbsExceptionHandler('dbsException-invalid-input',
                'physics group name given is not valid : %s' %
                 physics_group_name)
        else:
            try:
                physics_group_name = str(physics_group_name)
            except:
                 dbsExceptionHandler('dbsException-invalid-input',
                                 'physics group name given is not valid : %s' %
                                  physics_group_name)

        conn = self.dbi.connection()
        try:
            result = self.pglist.execute(conn, physics_group_name)
            return result
        finally:
            if conn:
                conn.close()
814027
def _format_rules_for_eos(self, rules):
        """"""
        in_rules = []
        eg_rules = []
        for rule in rules:
            protocol = rule.get('protocol')
            cidr = rule.get('remote_ip_prefix', 'any')
            min_port = rule.get('port_range_min')
            max_port = rule.get('port_range_max')
            direction = rule.get('direction')
            ethertype = rule.get('ethertype')
            if not self._supported_rule(protocol, ethertype):
                continue
            formatted_rule = self._format_rule(protocol, cidr, min_port,
                                               max_port, direction)
            if rule['direction'] == n_const.INGRESS_DIRECTION:
                in_rules.append(formatted_rule)
            elif rule['direction'] == n_const.EGRESS_DIRECTION:
                eg_rules.append(formatted_rule)
        return in_rules, eg_rules
818538
public static Set<String> getGroups(AclRuleSetSource source){
        HashSet<String> strings = new HashSet<>();
        for (AclRule rule : source.getRuleSet().getRules()) {
            if(rule.getGroup()!=null) {
                strings.add(rule.getGroup());
            }
        }
        return strings;
    }
1301409
def _rule_container(self):
        

        type_name = self._get_token(self.RE_NAME)
        self._expect_token('{')

        # consume elements if available
        options = []
        blocks = []
        dupe_blocks = {}

        while self._lookahead_token() != '}':
            # is it a block?
            if self._lookahead_token(count=2) == '{':
                block = self._rule_block()
                name = block[0]

                # duplicate found, hold for replace
                if name in self._block_map:
                    dupe_blocks[name] = block
                else:
                    # update block index and add to block list
                    self._block_map[name] = len(blocks)
                    blocks.append(block)

            else:
                # otherwise, let's go with non-block option
                options.append(self._rule_option())

        # replace duplicate block definitions
        if dupe_blocks:
            for name, block in dupe_blocks.iteritems():
                block_idx = self._block_map[name]
                blocks[block_idx] = block

        self._expect_token('}')
        self._expect_empty()

        return [type_name, options, blocks]
1167102
def parse_security_group(self, global_params, region, security_group):
        
        name = security_group.pop('ClusterSecurityGroupName')
        security_group['name'] = name
        self.security_groups['name'] = security_group
517671
def queryables(self):
        

        # compute the values_axes queryables
        return dict(
            [(a.cname, a) for a in self.index_axes] +
            [(self.storage_obj_type._AXIS_NAMES[axis], None)
             for axis, values in self.non_index_axes] +
            [(v.cname, v) for v in self.values_axes
             if v.name in set(self.data_columns)]
        )
934782
def get_event_rule_names_for_lambda(self, lambda_arn):
        
        response = self.events_client.list_rule_names_by_target(TargetArn=lambda_arn)
        rule_names = response['RuleNames']
        # Iterate when the results are paginated
        while 'NextToken' in response:
            response = self.events_client.list_rule_names_by_target(TargetArn=lambda_arn,
                                                                    NextToken=response['NextToken'])
            rule_names.extend(response['RuleNames'])
        return rule_names
695073
def _get_rules_from_aws(self):
        
        list_of_rules = list()

        if self.profile:
            boto3.setup_default_session(profile_name=self.profile)

        if self.region:
            ec2 = boto3.client('ec2', region_name=self.region)
        else:
            ec2 = boto3.client('ec2')

        security_groups = ec2.describe_security_groups(Filters=self.filters)

        for group in security_groups['SecurityGroups']:
            group_dict = dict()
            group_dict['id'] = group['GroupId']
            group_dict['name'] = group['GroupName']
            group_dict['description'] = group.get('Description', None)

            if (group.get('IpPermissions', None) or
                    group.get('IpPermissionsEgress', None)):
                group_dict['rules'] = list()

            for rule in group.get('IpPermissions', None):
                rule_dict = self._build_rule(rule)
                rule_dict['direction'] = "INGRESS"

                group_dict['rules'].append(rule_dict)

            for rule in group.get('IpPermissionsEgress', None):
                rule_dict = self._build_rule(rule)
                rule_dict['direction'] = "EGRESS"

                group_dict['rules'].append(rule_dict)

            list_of_rules.append(group_dict)

        return list_of_rules
793095
def _get_limits_networking(self):
        
        limits = {}
        limits['Security groups per VPC'] = AwsLimit(
            'Security groups per VPC',
            self,
            500,
            self.warning_threshold,
            self.critical_threshold,
            limit_type='AWS::EC2::SecurityGroup',
            limit_subtype='AWS::EC2::VPC',
        )
        limits['Rules per VPC security group'] = AwsLimit(
            'Rules per VPC security group',
            self,
            50,
            self.warning_threshold,
            self.critical_threshold,
            limit_type='AWS::EC2::SecurityGroup',
            limit_subtype='AWS::EC2::VPC',
        )
        limits['VPC Elastic IP addresses (EIPs)'] = AwsLimit(
            'VPC Elastic IP addresses (EIPs)',
            self,
            5,
            self.warning_threshold,
            self.critical_threshold,
            limit_type='AWS::EC2::EIP',
            limit_subtype='AWS::EC2::VPC',
            ta_service_name='VPC'  # TA shows this as VPC not EC2
        )
        # the EC2 limits screen calls this 'EC2-Classic Elastic IPs'
        # but Trusted Advisor just calls it 'Elastic IP addresses (EIPs)'
        limits['Elastic IP addresses (EIPs)'] = AwsLimit(
            'Elastic IP addresses (EIPs)',
            self,
            5,
            self.warning_threshold,
            self.critical_threshold,
            limit_type='AWS::EC2::EIP',
        )
        limits['VPC security groups per elastic network interface'] = AwsLimit(
            'VPC security groups per elastic network interface',
            self,
            5,
            self.warning_threshold,
            self.critical_threshold,
            limit_type='AWS::EC2::SecurityGroup',
            limit_subtype='AWS::EC2::NetworkInterface',
        )
        return limits
49327
def create_secgroup_rule(self, protocol, from_port, to_port,
            source, target):
        
        nova = self.nova

        def get_id(gname):
            sg = nova.security_groups.find(name=gname)
            if not sg:
                raise BangError("Security group not found, %s" % gname)
            return str(sg.id)

        kwargs = {
                'ip_protocol': protocol,
                'from_port': str(from_port),
                'to_port': str(to_port),
                'parent_group_id': get_id(target),
                }
        if '/' in source:
            kwargs['cidr'] = source
        else:
            kwargs['group_id'] = get_id(source)
            # not sure if this is an openstack hack or an hpcloud hack, but
            # this is definitely required to get it working on hpcloud:
            kwargs['cidr'] = 'null'
        nova.security_group_rules.create(**kwargs)
85117
def list_lbaas_l7rules(self, l7policy, retrieve_all=True, **_params):
        """"""
        return self.list('rules', self.lbaas_l7rules_path % l7policy,
                         retrieve_all, **_params)
492071
def list_securitygroup(call=None):
    '''
    
    '''
    if call == 'action':
        raise SaltCloudSystemExit(
            'The list_nodes function must be called with -f or --function.'
        )

    params = {
        'Action': 'DescribeSecurityGroups',
        'RegionId': get_location(),
        'PageSize': '50',
    }

    result = query(params)
    if 'Code' in result:
        return {}

    ret = {}
    for sg in result['SecurityGroups']['SecurityGroup']:
        ret[sg['SecurityGroupId']] = {}
        for item in sg:
            ret[sg['SecurityGroupId']][item] = sg[item]

    return ret
464457
def secgroup_list(self):
        '''
        
        '''
        nt_ks = self.compute_conn
        ret = {}
        for item in nt_ks.security_groups.list():
            ret[item.name] = {
                'name': item.name,
                'description': item.description,
                'id': item.id,
                'tenant_id': item.tenant_id,
                'rules': item.rules,
            }
        return ret
583107
def parse_rules(content=None):
    
    rules = content.split(DELIMITER)
    parsed_rules = list()
    order = 1
    for rule in rules:
        if rule.strip() == '':
            continue
        parsed_rule = {}
        lines = rule.split("\n")
        parsed_rule['orderValue'] = order
        order += 1
        for line in lines:
            if line.strip() == '':
                continue
            key_value = line.strip().split(':')
            key = key_value[0].strip()
            value = key_value[1].strip()
            if key == 'action':
                parsed_rule['action'] = value
            elif key == 'protocol':
                parsed_rule['protocol'] = value
            elif key == 'source_ip_address':
                parsed_rule['sourceIpAddress'] = value
            elif key == 'source_ip_subnet_mask':
                parsed_rule['sourceIpSubnetMask'] = value
            elif key == 'destination_ip_address':
                parsed_rule['destinationIpAddress'] = value
            elif key == 'destination_ip_subnet_mask':
                parsed_rule['destinationIpSubnetMask'] = value
            elif key == 'destination_port_range_start':
                parsed_rule['destinationPortRangeStart'] = int(value)
            elif key == 'destination_port_range_end':
                parsed_rule['destinationPortRangeEnd'] = int(value)
            elif key == 'version':
                parsed_rule['version'] = int(value)
        parsed_rules.append(parsed_rule)
    return parsed_rules
864204
def fill_fw_dict_from_db(self, fw_data):
        
        rule_dict = fw_data.get('rules').get('rules')
        fw_dict = {'fw_id': fw_data.get('fw_id'),
                   'fw_name': fw_data.get('name'),
                   'firewall_policy_id': fw_data.get('firewall_policy_id'),
                   'fw_type': fw_data.get('fw_type'),
                   'router_id': fw_data.get('router_id'), 'rules': {}}
        for rule in rule_dict:
            fw_dict['rules'][rule] = rule_dict.get(rule)
        return fw_dict