Ejemplo n.º 1
0
def networkIPv6_deploy(request, network_id):
    '''Deploy network L3 configuration in the environment routers for network ipv6

    Receives optional parameter equipments to specify what equipment should
    receive network configuration
    '''

    networkipv6 = NetworkIPv6.get_by_pk(int(network_id))
    environment = networkipv6.vlan.ambiente
    equipments_id_list = None
    if request.DATA is not None:
        equipments_id_list = request.DATA.get("equipments", None)

    equipment_list = []
    
    if equipments_id_list is not None:
        if type(equipments_id_list) is not list:
            raise api_exceptions.ValidationException("equipments")

        for equip in equipments_id_list:
            try:
                int(equip)
            except ValueError, e:
                raise api_exceptions.ValidationException("equipments")

        #Check that equipments received as parameters are in correct vlan environment
        equipment_list = Equipamento.objects.filter(
            equipamentoambiente__ambiente = environment,
            id__in=equipments_id_list)
        log.info ("list = %s" % equipment_list)
        if len(equipment_list) != len(equipments_id_list):
            log.error("Error: equipments %s are not part of network environment." % equipments_id_list)
            raise exceptions.EquipmentIDNotInCorrectEnvException()
Ejemplo n.º 2
0
	def create(self, ipv6_id, networkipv6_id):
		ipv6 = Ipv6.get_by_pk(ipv6_id)
		networkipv6 = NetworkIPv6.get_by_pk(networkipv6_id)

		if len(DHCPRelayIPv6.objects.filter(ipv6=ipv6, networkipv6=networkipv6)) > 0:
			raise exceptions.DHCPRelayAlreadyExistsError(ipv6_id, networkipv6_id)
		
		self.ipv6 = ipv6
		self.networkipv6 = networkipv6
Ejemplo n.º 3
0
def networksIPv6_by_pk(request, network_id):
    """
    Lists network ipv6.
    """
    try:

        networkipv6_obj = NetworkIPv6.get_by_pk(network_id)

        serializer_options = NetworkIPv6Serializer(networkipv6_obj, many=False)

        return Response(serializer_options.data)
    except NetworkIPv6NotFoundError, exception:
        raise exceptions.InvalidNetworkIDException()
Ejemplo n.º 4
0
def networksIPv6_by_pk(request, network_id):
    '''Lists network ipv6
    '''
    try:

        networkIPv6_obj = NetworkIPv6.get_by_pk(network_id)

        serializer_options = NetworkIPv6Serializer(
            networkIPv6_obj,
            many=False
        )

        return Response(serializer_options.data)
    except NetworkIPv6NotFoundError, exception:
        raise exceptions.InvalidNetworkIDException()
Ejemplo n.º 5
0
    def test_task_id_create_in_delete_one_netipv6_success(self, *args):
        """Test success of id task generate for netipv6 delete success."""

        mock_get_netv6 = args[1]
        mock_delete_netv6 = args[2]

        net = NetworkIPv6(id=1)
        user = Usuario(id='1', nome='test')

        mock_delete_netv6.return_value = net
        mock_get_netv6.return_value = net

        delete_networkv6(1, user.id)

        mock_delete_netv6.assert_called_with(1)
Ejemplo n.º 6
0
    def test_task_id_create_in_post_deploy_one_netipv6_success(self, *args):
        """Test success of id task generate for netipv6 post deploy success."""

        mock_get_user = args[1]
        mock_get_netv6 = args[2]
        mock_deploy_netv6 = args[3]

        user = Usuario(id=1, nome='test')

        net = NetworkIPv6(id=1)

        mock_deploy_netv6.return_value = net
        mock_get_netv6.return_value = net
        mock_get_user.return_value = user

        deploy_networkv6(net.id, user.id)

        mock_deploy_netv6.assert_called_with(net.id, user)
Ejemplo n.º 7
0
    def activate_network(self, user, id):
        # id => ex: '55-v4' or '55-v6'
        value = id.split('-')

        if len(value) != 2:
            self.log.error(
                u'The id network parameter is invalid format: %s.', value)
            raise InvalidValueError(None, 'id_network', value)

        id_net = value[0]
        network_type = value[1]

        if not is_valid_int_greater_zero_param(id_net):
            self.log.error(
                u'The id network parameter is invalid. Value: %s.', id_net)
            raise InvalidValueError(None, 'id_network', id_net)

        if not is_valid_version_ip(network_type, IP_VERSION):
            self.log.error(
                u'The type network parameter is invalid value: %s.', network_type)
            raise InvalidValueError(None, 'network_type', network_type)

        if network_type == 'v4':
            # network_type = 'v4'

            # Make command
            command = NETWORKIPV4_CREATE % int(id_net)
            code, stdout, stderr = exec_script(command)
            if code == 0:
                # Change column 'active = 1'
                net = NetworkIPv4.get_by_pk(id_net)
                net.activate(user)
        else:
            # network_type = 'v6'

            # Make command
            command = NETWORKIPV6_CREATE % int(id_net)
            code, stdout, stderr = exec_script(command)
            if code == 0:
                # Change column 'active = 1'
                net = NetworkIPv6.get_by_pk(id_net)
                net.activate(user)

        return code, stdout, stderr
    def activate_network(self, user, id):
        # id => ex: '55-v4' or '55-v6'
        value = id.split('-')

        if len(value) != 2:
            self.log.error(
                u'The id network parameter is invalid format: %s.', value)
            raise InvalidValueError(None, 'id_network', value)

        id_net = value[0]
        network_type = value[1]

        if not is_valid_int_greater_zero_param(id_net):
            self.log.error(
                u'The id network parameter is invalid. Value: %s.', id_net)
            raise InvalidValueError(None, 'id_network', id_net)

        if not is_valid_version_ip(network_type, IP_VERSION):
            self.log.error(
                u'The type network parameter is invalid value: %s.', network_type)
            raise InvalidValueError(None, 'network_type', network_type)

        if network_type == 'v4':
            # network_type = 'v4'

            # Make command
            command = NETWORKIPV4_CREATE % int(id_net)
            code, stdout, stderr = exec_script(command)
            if code == 0:
                # Change column 'active = 1'
                net = NetworkIPv4.get_by_pk(id_net)
                net.activate(user)
        else:
            # network_type = 'v6'

            # Make command
            command = NETWORKIPV6_CREATE % int(id_net)
            code, stdout, stderr = exec_script(command)
            if code == 0:
                # Change column 'active = 1'
                net = NetworkIPv6.get_by_pk(id_net)
                net.activate(user)

        return code, stdout, stderr
Ejemplo n.º 9
0
def criar_rede_ipv6(user, tipo_rede, variablestochangecore1, vlan, active=1):

    tiporede = TipoRede()
    net_id = tiporede.get_by_name(tipo_rede)
    network_type = tiporede.get_by_pk(net_id.id)

    network_ip = NetworkIPv6()
    network_ip.vlan = vlan
    network_ip.network_type = network_type
    network_ip.ambient_vip = None
    network_ip.active = active
    network_ip.block = variablestochangecore1.get('REDE_MASK')

    while str(variablestochangecore1.get('REDE_IP')).endswith(':'):
        variablestochangecore1['REDE_IP'] = variablestochangecore1[
            'REDE_IP'][:-1]

    while str(variablestochangecore1.get('NETMASK')).endswith(':'):
        variablestochangecore1['NETMASK'] = variablestochangecore1[
            'NETMASK'][:-1]

    len_ip_ipv6 = len(str(variablestochangecore1.get('REDE_IP')).split(':'))
    len_mask = len(str(variablestochangecore1.get('NETMASK')).split(':'))

    while (8 - len_ip_ipv6 > 0):  # 8-6=2--8-7=1--8-8=0
        len_ip_ipv6 = len_ip_ipv6 + 1
        variablestochangecore1['REDE_IP'] = variablestochangecore1.get(
            'REDE_IP') + ':0'

    while (8 - len_mask > 0):
        len_mask = len_mask + 1
        variablestochangecore1['NETMASK'] = variablestochangecore1.get(
            'NETMASK') + ':0'

    network_ip.block1, network_ip.block2, network_ip.block3, network_ip.block4, network_ip.block5, network_ip.block6, network_ip.block7, network_ip.block8 = str(
        variablestochangecore1.get('REDE_IP')).split(':')
    network_ip.mask1, network_ip.mask2, network_ip.mask3, network_ip.mask4, network_ip.mask5, network_ip.mask6, network_ip.mask7, network_ip.mask8 = str(
        variablestochangecore1.get('NETMASK')).split(':')

    destroy_cache_function([vlan.id])
    network_ip.save()

    return network_ip
    def deactivate_network(self, user, id):

        id_network, network_type = self.get_id_and_net_type(id)

        if not is_valid_int_greater_zero_param(id_network):
            self.log.error(
                u'The id network parameter is invalid. Value: %s.', id_network)
            raise InvalidValueError(None, 'id_network', id_network)

        if not is_valid_version_ip(network_type, IP_VERSION):
            self.log.error(
                u'The type network parameter is invalid value: %s.', network_type)
            raise InvalidValueError(None, 'network_type', network_type)

        if network_type == self.NETWORK_TYPE_V4:
            net = NetworkIPv4.get_by_pk(id_network)

            if not self.is_active_netwok(net):
                raise NetworkInactiveError(
                    message=error_messages.get(self.CODE_MESSAGE_INACTIVE_NETWORK))

            command = NETWORKIPV4_REMOVE % int(id_network)

            code, stdout, stderr = exec_script(command)
            if code == 0:
                net = NetworkIPv4.get_by_pk(id_network)
                net.deactivate(user)
        else:

            net = NetworkIPv6.get_by_pk(id_network)

            if not self.is_active_netwok(net):
                raise NetworkInactiveError(
                    message=error_messages.get(self.CODE_MESSAGE_INACTIVE_NETWORK))

            command = NETWORKIPV6_REMOVE % int(id_network)

            code, stdout, stderr = exec_script(command)
            if code == 0:
                net.deactivate(user)

        return code, stdout, stderr
    def handle_get(self, request, user, *args, **kwargs):
        """Handles GET requests to list all network IPv6 by network ipv6 id.

        URLs: network/ipv6/id/id_rede6      
         """

        try:

            # Commons Validations

            # User permission
            if not has_perm(user, AdminPermission.VLAN_MANAGEMENT,
                            AdminPermission.READ_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                return self.not_authorized()

            # Business Validations

            # Valid id access
            id_network = kwargs.get('id_rede6')

            if not is_valid_int_greater_zero_param(id_network):
                self.log.error(u'Parameter id_rede is invalid. Value: %s.',
                               id_network)
                raise InvalidValueError(None, 'id_rede6', id_network)

            # Business Rules

            network = NetworkIPv6.get_by_pk(id_network)

            network_map = dict()
            network_map['network'] = model_to_dict(network)

            # Return XML
            return self.response(dumps_networkapi(network_map))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
    def deactivate_network(self, user, id):

        id_network, network_type = self.get_id_and_net_type(id)

        if not is_valid_int_greater_zero_param(id_network):
            self.log.error(u'The id network parameter is invalid. Value: %s.',
                           id_network)
            raise InvalidValueError(None, 'id_network', id_network)

        if not is_valid_version_ip(network_type, IP_VERSION):
            self.log.error(u'The type network parameter is invalid value: %s.',
                           network_type)
            raise InvalidValueError(None, 'network_type', network_type)

        if not self.is_active_netwok(net):
            code = 0
            stdout = 'Nothing to do. Network is not active.'
            stderr = ''
        else:
            if network_type == self.NETWORK_TYPE_V4:
                net = NetworkIPv4.get_by_pk(id_network)

                command = NETWORKIPV4_REMOVE % int(id_network)

                code, stdout, stderr = exec_script(command)
                if code == 0:
                    net = NetworkIPv4.get_by_pk(id_network)
                    net.deactivate(user)
            else:
                net = NetworkIPv6.get_by_pk(id_network)

                command = NETWORKIPV6_REMOVE % int(id_network)

                code, stdout, stderr = exec_script(command)
                if code == 0:
                    net.deactivate(user)

        return code, stdout, stderr
    def handle_get(self, request, user, *args, **kwargs):
        """Handles GET requests to list all network IPv6 by network ipv6 id.

        URLs: network/ipv6/id/id_rede6      
         """

        try:

            # Commons Validations

            # User permission
            if not has_perm(user, AdminPermission.VLAN_MANAGEMENT, AdminPermission.READ_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                return self.not_authorized()

            # Business Validations

            # Valid id access
            id_network = kwargs.get('id_rede6')

            if not is_valid_int_greater_zero_param(id_network):
                self.log.error(
                    u'Parameter id_rede is invalid. Value: %s.', id_network)
                raise InvalidValueError(None, 'id_rede6', id_network)

            # Business Rules

            network = NetworkIPv6.get_by_pk(id_network)

            network_map = dict()
            network_map['network'] = model_to_dict(network)

            # Return XML
            return self.response(dumps_networkapi(network_map))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
    def deactivate_network(self, user, id):

        id_network, network_type = self.get_id_and_net_type(id)

        if not is_valid_int_greater_zero_param(id_network):
            self.log.error(
                u'The id network parameter is invalid. Value: %s.', id_network)
            raise InvalidValueError(None, 'id_network', id_network)

        if not is_valid_version_ip(network_type, IP_VERSION):
            self.log.error(
                u'The type network parameter is invalid value: %s.', network_type)
            raise InvalidValueError(None, 'network_type', network_type)

        if not self.is_active_netwok(net):
            code = 0
            stdout = 'Nothing to do. Network is not active.'
            stderr = ''
        else:
            if network_type == self.NETWORK_TYPE_V4:
                net = NetworkIPv4.get_by_pk(id_network)

                command = NETWORKIPV4_REMOVE % int(id_network)

                code, stdout, stderr = exec_script(command)
                if code == 0:
                    net = NetworkIPv4.get_by_pk(id_network)
                    net.deactivate(user)
            else:
                net = NetworkIPv6.get_by_pk(id_network)

                command = NETWORKIPV6_REMOVE % int(id_network)

                code, stdout, stderr = exec_script(command)
                if code == 0:
                    net.deactivate(user)

        return code, stdout, stderr
    def setUp(self):
        self.user = Usuario()
        self.equipment_list = [Equipamento(id=1, nome='router')]
        self.ambiente = Ambiente()
        self.vlan = Vlan(id=1, ambiente=self.ambiente)
        self.networkv4 = NetworkIPv4(id=1,
                                     vlan=self.vlan,
                                     oct1=192,
                                     oct2=168,
                                     oct3=0,
                                     oct4=0,
                                     mask_oct1=255,
                                     mask_oct2=255,
                                     mask_oct3=255,
                                     mask_oct4=0)

        self.networkv6 = NetworkIPv6(id=1,
                                     vlan=self.vlan,
                                     block1='fff',
                                     block2='fff',
                                     block3='fff',
                                     block4='fff',
                                     block5='fff',
                                     block6='fff',
                                     block7='fff',
                                     block8='fff',
                                     mask1='fff',
                                     mask2='fff',
                                     mask3='fff',
                                     mask4='fff',
                                     mask5='fff',
                                     mask6='fff',
                                     mask7='fff',
                                     mask8='fff')

        self.mock_distributed_lock()
        self.mock_transaction()
Ejemplo n.º 16
0
    def handle_post(self, request, user, *args, **kwargs):
        """Treat POST requests to insert vlan

        URL: vlan/insert/
        """

        try:
            # Generic method for v4 and v6
            network_version = kwargs.get('network_version')

            # Commons Validations

            # User permission
            if not has_perm(user, AdminPermission.VLAN_MANAGEMENT, AdminPermission.WRITE_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                return self.not_authorized()

            # Business Validations

            # Load XML data
            xml_map, attrs_map = loads(request.raw_post_data)

            # XML data format
            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is None:
                msg = u'There is no value to the networkapi tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)
            vlan_map = networkapi_map.get('vlan')
            if vlan_map is None:
                msg = u'There is no value to the vlan tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)

            # Get XML data
            environment_id = vlan_map.get('environment_id')
            number = vlan_map.get('number')
            name = vlan_map.get('name')
            acl_file = vlan_map.get('acl_file')
            acl_file_v6 = vlan_map.get('acl_file_v6')
            description = vlan_map.get('description')
            network_ipv4 = vlan_map.get('network_ipv4')
            network_ipv6 = vlan_map.get('network_ipv6')
            vrf = vlan_map.get('vrf')

            # Valid environment_id ID
            if not is_valid_int_greater_zero_param(environment_id):
                self.log.error(
                    u'Parameter environment_id is invalid. Value: %s.', environment_id)
                raise InvalidValueError(None, 'environment_id', environment_id)

            # Valid number of Vlan
            if not is_valid_int_greater_zero_param(number):
                self.log.error(
                    u'Parameter number is invalid. Value: %s', number)
                raise InvalidValueError(None, 'number', number)

            # Valid name of Vlan
            if not is_valid_string_minsize(name, 3) or not is_valid_string_maxsize(name, 50):
                self.log.error(u'Parameter name is invalid. Value: %s', name)
                raise InvalidValueError(None, 'name', name)

            if not network_ipv4 or not str(network_ipv4).isdigit():
                self.log.error(
                    u'Parameter network_ipv4 is invalid. Value: %s.', network_ipv4)
                raise InvalidValueError(None, 'network_ipv4', network_ipv4)

            if not network_ipv6 or not str(network_ipv6).isdigit():
                self.log.error(
                    u'Parameter network_ipv6 is invalid. Value: %s.', network_ipv6)
                raise InvalidValueError(None, 'network_ipv6', network_ipv6)

            # vrf can NOT be greater than 100
            if not is_valid_string_maxsize(vrf, 100, False):
                self.log.error(
                    u'Parameter vrf is invalid. Value: %s.', vrf)
                raise InvalidValueError(None, 'vrf', vrf)

            network_ipv4 = int(network_ipv4)
            network_ipv6 = int(network_ipv6)

            if network_ipv4 not in range(0, 2):
                self.log.error(
                    u'Parameter network_ipv4 is invalid. Value: %s.', network_ipv4)
                raise InvalidValueError(None, 'network_ipv4', network_ipv4)

            if network_ipv6 not in range(0, 2):
                self.log.error(
                    u'Parameter network_ipv6 is invalid. Value: %s.', network_ipv6)
                raise InvalidValueError(None, 'network_ipv6', network_ipv6)

            p = re.compile('^[A-Z0-9-_]+$')
            m = p.match(name)

            if not m:
                name = name.upper()
                m = p.match(name)

                if not m:
                    raise InvalidValueError(None, 'name', name)

            # Valid description of Vlan
            if not is_valid_string_minsize(description, 3, False) or not is_valid_string_maxsize(description, 200, False):
                self.log.error(
                    u'Parameter description is invalid. Value: %s', description)
                raise InvalidValueError(None, 'description', description)

            vlan = Vlan()

            # Valid acl_file Vlan
            if acl_file is not None:
                if not is_valid_string_minsize(acl_file, 3) or not is_valid_string_maxsize(acl_file, 200):
                    self.log.error(
                        u'Parameter acl_file is invalid. Value: %s', acl_file)
                    raise InvalidValueError(None, 'acl_file', acl_file)
                p = re.compile('^[A-Z0-9-_]+$')
                m = p.match(acl_file)
                if not m:
                    raise InvalidValueError(None, 'acl_file', acl_file)

                # VERIFICA SE VLAN COM MESMO ACL JA EXISTE OU NAO
                # commenting acl name check - issue #55
                # vlan.get_vlan_by_acl(acl_file)

            # Valid acl_file_v6 Vlan
            if acl_file_v6 is not None:
                if not is_valid_string_minsize(acl_file_v6, 3) or not is_valid_string_maxsize(acl_file_v6, 200):
                    self.log.error(
                        u'Parameter acl_file_v6 is invalid. Value: %s', acl_file_v6)
                    raise InvalidValueError(None, 'acl_file_v6', acl_file_v6)
                p = re.compile('^[A-Z0-9-_]+$')
                m = p.match(acl_file_v6)
                if not m:
                    raise InvalidValueError(None, 'acl_file_v6', acl_file_v6)

                # VERIFICA SE VLAN COM MESMO ACL JA EXISTE OU NAO
                # commenting acl name check - issue #55
                # vlan.get_vlan_by_acl_v6(acl_file_v6)

            ambiente = Ambiente()
            ambiente = ambiente.get_by_pk(environment_id)

            vlan.acl_file_name = acl_file
            vlan.acl_file_name_v6 = acl_file_v6
            vlan.num_vlan = number
            vlan.nome = name
            vlan.descricao = description
            vlan.ambiente = ambiente
            vlan.ativada = 0
            vlan.acl_valida = 0
            vlan.acl_valida_v6 = 0

            vlan.insert_vlan(user)

            if network_ipv4:
                network_ipv4 = NetworkIPv4()
                vlan_map = network_ipv4.add_network_ipv4(
                    user, vlan.id, None, None, None)
                list_equip_routers_ambient = EquipamentoAmbiente.objects.select_related('equipamento').filter(
                    ambiente=vlan.ambiente.id, is_router=True)

                if list_equip_routers_ambient:

                    # Add Adds the first available ipv4 on all equipment
                    # that is configured as a router for the environment related to
                    # network
                    ip = Ip.get_first_available_ip(network_ipv4.id)

                    ip = str(ip).split('.')

                    ip_model = Ip()
                    ip_model.oct1 = ip[0]
                    ip_model.oct2 = ip[1]
                    ip_model.oct3 = ip[2]
                    ip_model.oct4 = ip[3]
                    ip_model.networkipv4_id = network_ipv4.id

                    ip_model.save(user)

                    if len(list_equip_routers_ambient) > 1 and network_ipv4.block < 30:
                        multiple_ips = True
                    else:
                        multiple_ips = False

                    for equip in list_equip_routers_ambient:
                        IpEquipamento().create(user, ip_model.id, equip.equipamento.id)

                        if multiple_ips:
                            router_ip = Ip.get_first_available_ip(
                                network_ipv4.id, True)
                            router_ip = str(router_ip).split('.')
                            ip_model2 = Ip()
                            ip_model2.oct1 = router_ip[0]
                            ip_model2.oct2 = router_ip[1]
                            ip_model2.oct3 = router_ip[2]
                            ip_model2.oct4 = router_ip[3]
                            ip_model2.networkipv4_id = network_ipv4.id
                            ip_model2.save(user)
                            IpEquipamento().create(user, ip_model2.id, equip.equipamento.id)

            if network_ipv6:
                network_ipv6 = NetworkIPv6()
                vlan_map = network_ipv6.add_network_ipv6(
                    user, vlan.id, None, None, None)

                list_equip_routers_ambient = EquipamentoAmbiente.objects.filter(
                    ambiente=vlan.ambiente.id, is_router=True)

                if list_equip_routers_ambient:

                    # Add Adds the first available ipv6 on all equipment
                    # that is configured as a router for the environment related to
                    # network
                    ipv6 = Ipv6.get_first_available_ip6(network_ipv6.id)

                    ipv6 = str(ipv6).split(':')

                    ipv6_model = Ipv6()
                    ipv6_model.block1 = ipv6[0]
                    ipv6_model.block2 = ipv6[1]
                    ipv6_model.block3 = ipv6[2]
                    ipv6_model.block4 = ipv6[3]
                    ipv6_model.block5 = ipv6[4]
                    ipv6_model.block6 = ipv6[5]
                    ipv6_model.block7 = ipv6[6]
                    ipv6_model.block8 = ipv6[7]
                    ipv6_model.networkipv6_id = network_ipv6.id

                    ipv6_model.save(user)

                    if len(list_equip_routers_ambient) > 1:
                        multiple_ips = True
                    else:
                        multiple_ips = False

                    for equip in list_equip_routers_ambient:

                        Ipv6Equipament().create(
                            user, ipv6_model.id, equip.equipamento.id)

                        if multiple_ips:
                            router_ip = Ipv6.get_first_available_ip6(
                                network_ipv6.id, True)
                            router_ip = str(router_ip).split(':')
                            ipv6_model2 = Ipv6()
                            ipv6_model2.block1 = router_ip[0]
                            ipv6_model2.block2 = router_ip[1]
                            ipv6_model2.block3 = router_ip[2]
                            ipv6_model2.block4 = router_ip[3]
                            ipv6_model2.block5 = router_ip[4]
                            ipv6_model2.block6 = router_ip[5]
                            ipv6_model2.block7 = router_ip[6]
                            ipv6_model2.block8 = router_ip[7]
                            ipv6_model2.networkipv6_id = network_ipv6.id
                            ipv6_model2.save(user)
                            Ipv6Equipament().create(user, ipv6_model2.id, equip.equipamento.id)

            map = dict()
            listaVlan = dict()
            listaVlan['id'] = vlan.id
            listaVlan['nome'] = vlan.nome
            listaVlan['acl_file_name'] = vlan.acl_file_name
            listaVlan['descricao'] = vlan.descricao
            listaVlan['id_ambiente'] = vlan.ambiente.id
            listaVlan['ativada'] = vlan.ativada
            listaVlan['acl_valida'] = vlan.acl_valida
            map['vlan'] = listaVlan

            # Delete vlan's cache
            # destroy_cache_function()

            # Return XML
            return self.response(dumps_networkapi(map))

        except VlanACLDuplicatedError, e:
            return self.response_error(311, acl_file)
Ejemplo n.º 17
0
    def handle_post(self, request, user, *args, **kwargs):
        """Handles POST requests to add an IP6 and associate it to an equipment.

        URL: ipv6/save/
        """

        self.log.info('Add an IP6 and associate it to an equipment')

        try:
            # Load XML data
            xml_map, attrs_map = loads(request.raw_post_data)

            # XML data format
            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is None:
                msg = u'There is no value to the networkapi tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)
            ip_map = networkapi_map.get('ip_map')
            if ip_map is None:
                msg = u'There is no value to the ip tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)

            # Get XML data
            equip_id = ip_map.get('id_equip')
            network_ipv6_id = ip_map.get('id_net')
            description = ip_map.get('descricao')
            ip6 = ip_map.get('ip6')

            # Valid equip_id
            if not is_valid_int_greater_zero_param(equip_id):
                self.log.error(u'Parameter equip_id is invalid. Value: %s.',
                               equip_id)
                raise InvalidValueError(None, 'equip_id', equip_id)

            # Valid network_ipv4_id
            if not is_valid_int_greater_zero_param(network_ipv6_id):
                self.log.error(
                    u'Parameter network_ipv6_id is invalid. Value: %s.',
                    network_ipv6_id)
                raise InvalidValueError(None, 'network_ipv6_id',
                                        network_ipv6_id)

            # Description can NOT be greater than 100
            if not is_valid_string_maxsize(ip6, 39):
                self.log.error(u'Parameter ip6 is invalid. Value: %s.', ip6)
                raise InvalidValueError(None, 'ip6', ip6)

            if description is not None:
                if not is_valid_string_maxsize(
                        description, 100) or not is_valid_string_minsize(
                            description, 3):
                    self.log.error(
                        u'Parameter description is invalid. Value: %s.',
                        description)
                    raise InvalidValueError(None, 'description', description)

            # User permission
            if not has_perm(user, AdminPermission.IPS,
                            AdminPermission.WRITE_OPERATION, None, equip_id,
                            AdminPermission.EQUIP_WRITE_OPERATION):
                raise UserNotAuthorizedError(
                    None,
                    u'User does not have permission to perform the operation.')

            # Business Rules

            # New IP
            ipv6 = Ipv6()

            net = NetworkIPv6.get_by_pk(network_ipv6_id)

            with distributedlock(LOCK_NETWORK_IPV6 % network_ipv6_id):

                # Caso haja erro para retornar o ip corretamente
                ip_error = ip6
                ip6 = ip6.split(':')

                # Ip informado de maneira incorreta
                if len(ip6) is not 8:
                    raise InvalidValueError(None, 'ip6', ip_error)

                ipv6.description = description
                ipv6.block1 = ip6[0]
                ipv6.block2 = ip6[1]
                ipv6.block3 = ip6[2]
                ipv6.block4 = ip6[3]
                ipv6.block5 = ip6[4]
                ipv6.block6 = ip6[5]
                ipv6.block7 = ip6[6]
                ipv6.block8 = ip6[7]
                # Persist

                equip = Equipamento.get_by_pk(equip_id)

                listaVlansDoEquip = []

                for ipequip in equip.ipv6equipament_set.all():
                    vlan = ipequip.ip.networkipv6.vlan
                    if vlan not in listaVlansDoEquip:
                        listaVlansDoEquip.append(vlan)

                for ipequip in equip.ipequipamento_set.all():
                    vlan = ipequip.ip.networkipv4.vlan
                    if vlan not in listaVlansDoEquip:
                        listaVlansDoEquip.append(vlan)

                vlan_atual = net.vlan

                ambiente_aux = None
                vlan_aux = None

                for vlan in listaVlansDoEquip:
                    if vlan.num_vlan == vlan_atual.num_vlan:
                        if vlan.id != vlan_atual.id:

                            # Filter case 3 - Vlans with same number cannot
                            # share equipments ##

                            flag_vlan_error = False
                            # Filter testing
                            if vlan.ambiente.filter is None or vlan_atual.ambiente.filter is None:
                                flag_vlan_error = True
                            else:
                                # Test both environment's filters
                                tp_equip_list_one = list()
                                for fet in FilterEquipType.objects.filter(
                                        filter=vlan_atual.ambiente.filter.id):
                                    tp_equip_list_one.append(fet.equiptype)

                                tp_equip_list_two = list()
                                for fet in FilterEquipType.objects.filter(
                                        filter=vlan.ambiente.filter.id):
                                    tp_equip_list_two.append(fet.equiptype)

                                if equip.tipo_equipamento not in tp_equip_list_one or equip.tipo_equipamento not in tp_equip_list_two:
                                    flag_vlan_error = True

                            ## Filter case 3 - end ##

                            if flag_vlan_error:

                                vlan_aux = vlan
                                ambiente_aux = vlan.ambiente
                                nome_ambiente = '%s - %s - %s' % (
                                    vlan.ambiente.divisao_dc.nome,
                                    vlan.ambiente.ambiente_logico.nome,
                                    vlan.ambiente.grupo_l3.nome)
                                raise VlanNumberNotAvailableError(
                                    None,
                                    """O ip informado não pode ser cadastrado, pois o equipamento %s, faz parte do ambiente %s (id %s),
                                                                    que possui a Vlan de id %s, que também possui o número %s, e não é permitido que vlans que compartilhem o mesmo ambiente,
                                                                    por meio de equipamentos, possuam o mesmo número, edite o número de uma das Vlans ou adicione um filtro no ambiente para efetuar o cadastro desse IP no Equipamento Informado.
                                                                    """ %
                                    (equip.nome, nome_ambiente,
                                     ambiente_aux.id, vlan_aux.id,
                                     vlan_atual.num_vlan))

                ipv6.save_ipv6(equip_id, user, net)

                list_ip = []
                lequips = list()

                if ipv6.id is None:
                    ipv6 = Ipv6.get_by_blocks_and_net(ipv6.block1, ipv6.block2,
                                                      ipv6.block3, ipv6.block4,
                                                      ipv6.block5, ipv6.block6,
                                                      ipv6.block7, ipv6.block8,
                                                      net.id)

                equips = Ipv6Equipament.list_by_ip6(ipv6.id)
                ip_maps = dict()
                ip_maps['id'] = ipv6.id
                ip_maps['block1'] = ipv6.block1
                ip_maps['block2'] = ipv6.block2
                ip_maps['block3'] = ipv6.block3
                ip_maps['block4'] = ipv6.block4
                ip_maps['block5'] = ipv6.block5
                ip_maps['block6'] = ipv6.block6
                ip_maps['block7'] = ipv6.block7
                ip_maps['block8'] = ipv6.block8
                ip_maps['descricao'] = ipv6.description

                list_id_equip = []

                for equip in equips:
                    list_id_equip.append(equip.equipamento.id)
                    equip = Equipamento.get_by_pk(equip.equipamento.id)
                    lequips.append(model_to_dict(equip))
                ip_maps['equipamento'] = lequips
                list_ip.append(ip_maps)

                network_map = dict()
                network_map['ipv6'] = list_ip

                # Delete vlan's cache
                destroy_cache_function([net.vlan_id])

                # Delete equipment's cache
                destroy_cache_function(list_id_equip, True)

                return self.response(dumps_networkapi(network_map))

        except IpRangeAlreadyAssociation, e:
            return self.response_error(347)
    def handle_post(self, request, user, *args, **kwargs):
        '''Handles POST requests to add an IP6 and associate it to an equipment.

        URL: ipv6/save/
        '''

        self.log.info('Add an IP6 and associate it to an equipment')

        try:
            # Load XML data
            xml_map, attrs_map = loads(request.raw_post_data)

            # XML data format
            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is None:
                msg = u'There is no value to the networkapi tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)
            ip_map = networkapi_map.get('ip_map')
            if ip_map is None:
                msg = u'There is no value to the ip tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)

            # Get XML data
            equip_id = ip_map.get('id_equip')
            network_ipv6_id = ip_map.get('id_net')
            description = ip_map.get('descricao')
            ip6 = ip_map.get('ip6')

            # Valid equip_id
            if not is_valid_int_greater_zero_param(equip_id):
                self.log.error(
                    u'Parameter equip_id is invalid. Value: %s.', equip_id)
                raise InvalidValueError(None, 'equip_id', equip_id)

            # Valid network_ipv4_id
            if not is_valid_int_greater_zero_param(network_ipv6_id):
                self.log.error(
                    u'Parameter network_ipv6_id is invalid. Value: %s.', network_ipv6_id)
                raise InvalidValueError(
                    None, 'network_ipv6_id', network_ipv6_id)

            # Description can NOT be greater than 100
            if not is_valid_string_maxsize(ip6, 39):
                self.log.error(u'Parameter ip6 is invalid. Value: %s.', ip6)
                raise InvalidValueError(None, 'ip6', ip6)

            if description is not None:
                if not is_valid_string_maxsize(description, 100) or not is_valid_string_minsize(description, 3):
                    self.log.error(
                        u'Parameter description is invalid. Value: %s.', description)
                    raise InvalidValueError(None, 'description', description)

            # User permission
            if not has_perm(user,
                            AdminPermission.IPS,
                            AdminPermission.WRITE_OPERATION,
                            None,
                            equip_id,
                            AdminPermission.EQUIP_WRITE_OPERATION):
                raise UserNotAuthorizedError(
                    None, u'User does not have permission to perform the operation.')

            # Business Rules

            # New IP
            ipv6 = Ipv6()

            net = NetworkIPv6.get_by_pk(network_ipv6_id)

            with distributedlock(LOCK_NETWORK_IPV6 % network_ipv6_id):

                # Caso haja erro para retornar o ip corretamente
                ip_error = ip6
                ip6 = ip6.split(":")

                # Ip informado de maneira incorreta
                if len(ip6) is not 8:
                    raise InvalidValueError(None, 'ip6', ip_error)

                ipv6.description = description
                ipv6.block1 = ip6[0]
                ipv6.block2 = ip6[1]
                ipv6.block3 = ip6[2]
                ipv6.block4 = ip6[3]
                ipv6.block5 = ip6[4]
                ipv6.block6 = ip6[5]
                ipv6.block7 = ip6[6]
                ipv6.block8 = ip6[7]
                # Persist

                equip = Equipamento.get_by_pk(equip_id)

                listaVlansDoEquip = []

                for ipequip in equip.ipv6equipament_set.all():
                    vlan = ipequip.ip.networkipv6.vlan
                    if vlan not in listaVlansDoEquip:
                        listaVlansDoEquip.append(vlan)

                for ipequip in equip.ipequipamento_set.all():
                    vlan = ipequip.ip.networkipv4.vlan
                    if vlan not in listaVlansDoEquip:
                        listaVlansDoEquip.append(vlan)

                vlan_atual = net.vlan

                ambiente_aux = None
                vlan_aux = None

                for vlan in listaVlansDoEquip:
                    if vlan.num_vlan == vlan_atual.num_vlan:
                        if vlan.id != vlan_atual.id:

                            # Filter case 3 - Vlans with same number cannot
                            # share equipments ##

                            flag_vlan_error = False
                            # Filter testing
                            if vlan.ambiente.filter is None or vlan_atual.ambiente.filter is None:
                                flag_vlan_error = True
                            else:
                                # Test both environment's filters
                                tp_equip_list_one = list()
                                for fet in FilterEquipType.objects.filter(filter=vlan_atual.ambiente.filter.id):
                                    tp_equip_list_one.append(fet.equiptype)

                                tp_equip_list_two = list()
                                for fet in FilterEquipType.objects.filter(filter=vlan.ambiente.filter.id):
                                    tp_equip_list_two.append(fet.equiptype)

                                if equip.tipo_equipamento not in tp_equip_list_one or equip.tipo_equipamento not in tp_equip_list_two:
                                    flag_vlan_error = True

                            ## Filter case 3 - end ##

                            if flag_vlan_error:

                                vlan_aux = vlan
                                ambiente_aux = vlan.ambiente
                                nome_ambiente = "%s - %s - %s" % (
                                    vlan.ambiente.divisao_dc.nome, vlan.ambiente.ambiente_logico.nome, vlan.ambiente.grupo_l3.nome)
                                raise VlanNumberNotAvailableError(None,
                                                                  '''O ip informado não pode ser cadastrado, pois o equipamento %s, faz parte do ambiente %s (id %s), 
                                                                    que possui a Vlan de id %s, que também possui o número %s, e não é permitido que vlans que compartilhem o mesmo ambiente,
                                                                    por meio de equipamentos, possuam o mesmo número, edite o número de uma das Vlans ou adicione um filtro no ambiente para efetuar o cadastro desse IP no Equipamento Informado.
                                                                    ''' % (equip.nome, nome_ambiente, ambiente_aux.id, vlan_aux.id, vlan_atual.num_vlan))

                ipv6.save_ipv6(equip_id, user, net)

                list_ip = []
                lequips = list()

                if ipv6.id is None:
                    ipv6 = Ipv6.get_by_blocks_and_net(
                        ipv6.block1, ipv6.block2, ipv6.block3, ipv6.block4, ipv6.block5, ipv6.block6, ipv6.block7, ipv6.block8, net.id)

                equips = Ipv6Equipament.list_by_ip6(ipv6.id)
                ip_maps = dict()
                ip_maps['id'] = ipv6.id
                ip_maps['block1'] = ipv6.block1
                ip_maps['block2'] = ipv6.block2
                ip_maps['block3'] = ipv6.block3
                ip_maps['block4'] = ipv6.block4
                ip_maps['block5'] = ipv6.block5
                ip_maps['block6'] = ipv6.block6
                ip_maps['block7'] = ipv6.block7
                ip_maps['block8'] = ipv6.block8
                ip_maps['descricao'] = ipv6.description

                list_id_equip = []

                for equip in equips:
                    list_id_equip.append(equip.equipamento.id)
                    equip = Equipamento.get_by_pk(equip.equipamento.id)
                    lequips.append(model_to_dict(equip))
                ip_maps['equipamento'] = lequips
                list_ip.append(ip_maps)

                network_map = dict()
                network_map['ipv6'] = list_ip

                # Delete vlan's cache
                destroy_cache_function([net.vlan_id])

                # Delete equipment's cache
                destroy_cache_function(list_id_equip, True)

                return self.response(dumps_networkapi(network_map))

        except IpRangeAlreadyAssociation, e:
            return self.response_error(347)
Ejemplo n.º 19
0
    def handle_get(self, request, user, *args, **kwargs):
        """Handles GET requests to list all network IPv6 by network ipv6 id.

        URLs: ip/id_network_ipv6/id_rede
         """

        try:
            # Commons Validations

            # User permission
            if not has_perm(user, AdminPermission.IPS,
                            AdminPermission.READ_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                return self.not_authorized()

            # Business Validations

            # Valid id access
            id_network = kwargs.get('id_rede')

            if not is_valid_int_greater_zero_param(id_network):
                raise InvalidValueError(None, 'id_rede', id_network)

            # Business Rules

            NetworkIPv6.get_by_pk(id_network)

            ips = Ipv6.list_by_network(id_network)

            try:
                len(ips)
            except Exception, e:
                raise InvalidValueError(None, 'id_rede', id_network)

            if ips is None or len(ips) <= 0:
                raise IpNotFoundError(305, id_network)

            EquipIps = []
            mapa = dict()
            # lista = []

            try:
                for ip in ips:
                    EquipIps = []
                    equipsIp = Ipv6Equipament.list_by_ip6(ip.id)
                    for eIp in equipsIp:
                        EquipIps.append(eIp)
                    mapa[ip.id] = EquipIps
                    # lista.append(mapa)bora pegar cafe

            except IpEquipmentNotFoundError:
                EquipIps.append(None)
            except IpError:
                EquipIps.append(None)

            network_map = dict()
            list_ips = []
            lequips = []

            for ip in ips:
                lequips = []
                ip_maps = dict()
                ip_maps['id'] = ip.id
                ip_maps['block1'] = ip.block1
                ip_maps['block2'] = ip.block2
                ip_maps['block3'] = ip.block3
                ip_maps['block4'] = ip.block4
                ip_maps['block5'] = ip.block5
                ip_maps['block6'] = ip.block6
                ip_maps['block7'] = ip.block7
                ip_maps['block8'] = ip.block8
                ip_maps['descricao'] = ip.description
                for equip in mapa.get(ip.id):
                    equip = Equipamento.get_by_pk(equip.equipamento.id)
                    lequips.append(model_to_dict(equip))
                ip_maps['equipamento'] = lequips
                list_ips.append(ip_maps)

            network_map['ips'] = list_ips

            network_map
            # Return XML
            return self.response(dumps_networkapi(network_map))
    def handle_post(self, request, user, *args, **kwargs):
        '''Handles POST requests to associate and IPv6 to an equipment.

        URL: ipv6/assoc/
        '''

        self.log.info('Associate Ipv6 to an Equipment')

        try:
            # Load XML data
            xml_map, attrs_map = loads(request.raw_post_data)

            # XML data format
            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is None:
                msg = u'There is no value to the networkapi tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)

            ip_map = networkapi_map.get('ip_map')
            if ip_map is None:
                msg = u'There is no value to the ip tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)

            # Get XML data
            ip_id = ip_map.get('id_ip')
            equip_id = ip_map.get('id_equip')
            network_ipv6_id = ip_map.get('id_net')

            # Valid ip_id
            if not is_valid_int_greater_zero_param(ip_id):
                self.log.error(
                    u'Parameter ip_id is invalid. Value: %s.', ip_id)
                raise InvalidValueError(None, 'ip_id', ip_id)

            # Valid equip_id
            if not is_valid_int_greater_zero_param(equip_id):
                self.log.error(
                    u'Parameter equip_id is invalid. Value: %s.', equip_id)
                raise InvalidValueError(None, 'equip_id', equip_id)

            # Valid network_ipv6_id
            if not is_valid_int_greater_zero_param(network_ipv6_id):
                self.log.error(
                    u'Parameter network_ipv6_id is invalid. Value: %s.', network_ipv6_id)
                raise InvalidValueError(
                    None, 'network_ipv6_id', network_ipv6_id)

            # User permission
            if not has_perm(user,
                            AdminPermission.IPS,
                            AdminPermission.WRITE_OPERATION,
                            None,
                            equip_id,
                            AdminPermission.EQUIP_WRITE_OPERATION):
                raise UserNotAuthorizedError(
                    None, u'User does not have permission to perform the operation.')

            # Business Rules

            # Get net
            net = NetworkIPv6.get_by_pk(network_ipv6_id)

            with distributedlock(LOCK_NETWORK_IPV6 % network_ipv6_id):

                # Get ip
                ip = Ipv6.get_by_pk(ip_id)
                # Get equipment
                equip = Equipamento.get_by_pk(equip_id)

                listaVlansDoEquip = []

                for ipequip in equip.ipequipamento_set.all():
                    vlan = ipequip.ip.networkipv4.vlan
                    if vlan not in listaVlansDoEquip:
                        listaVlansDoEquip.append(vlan)

                for ipequip in equip.ipv6equipament_set.all():
                    vlan = ipequip.ip.networkipv6.vlan
                    if vlan not in listaVlansDoEquip:
                        listaVlansDoEquip.append(vlan)

                vlan_atual = net.vlan
                vlan_aux = None
                ambiente_aux = None

                for vlan in listaVlansDoEquip:
                    if vlan.num_vlan == vlan_atual.num_vlan:
                        if vlan.id != vlan_atual.id:

                            # Filter case 3 - Vlans with same number cannot
                            # share equipments ##

                            flag_vlan_error = False
                            # Filter testing
                            if vlan.ambiente.filter is None or vlan_atual.ambiente.filter is None:
                                flag_vlan_error = True
                            else:
                                # Test both environment's filters
                                tp_equip_list_one = list()
                                for fet in FilterEquipType.objects.filter(filter=vlan_atual.ambiente.filter.id):
                                    tp_equip_list_one.append(fet.equiptype)

                                tp_equip_list_two = list()
                                for fet in FilterEquipType.objects.filter(filter=vlan.ambiente.filter.id):
                                    tp_equip_list_two.append(fet.equiptype)

                                if equip.tipo_equipamento not in tp_equip_list_one or equip.tipo_equipamento not in tp_equip_list_two:
                                    flag_vlan_error = True

                            ## Filter case 3 - end ##

                            if flag_vlan_error:
                                ambiente_aux = vlan.ambiente
                                vlan_aux = vlan
                                nome_ambiente = "%s - %s - %s" % (
                                    vlan.ambiente.divisao_dc.nome, vlan.ambiente.ambiente_logico.nome, vlan.ambiente.grupo_l3.nome)
                                raise VlanNumberNotAvailableError(None,
                                                                  '''O ip informado não pode ser cadastrado, pois o equipamento %s, faz parte do ambiente %s (id %s), 
                                                                    que possui a Vlan de id %s, que também possui o número %s, e não é permitido que vlans que compartilhem o mesmo ambiente 
                                                                    por meio de equipamentos, possuam o mesmo número, edite o número de uma das Vlans ou adicione um filtro no ambiente para efetuar o cadastro desse IP no Equipamento Informado.
                                                                    ''' % (equip.nome, nome_ambiente, ambiente_aux.id, vlan_aux.id, vlan_atual.num_vlan))

                # Persist
                try:

                    try:
                        ipEquip = Ipv6Equipament()
                        ipEquip.get_by_ip_equipment(ip.id, equip_id)

                        raise IpEquipmentAlreadyAssociation(None, u'Ipv6 %s:%s:%s:%s:%s:%s:%s:%s already has association with Equipament %s.' % (
                            ip.block1, ip.block2, ip.block3, ip.block4, ip.block5, ip.block6, ip.block7, ip.block8, equip_id))
                    except IpEquipmentNotFoundError, e:
                        pass

                    equipment = Equipamento().get_by_pk(equip_id)
                    ip_equipment = Ipv6Equipament()
                    ip_equipment.ip = ip

                    ip_equipment.equipamento = equipment

                    # Filter case 2 - Adding new IpEquip for a equip that
                    # already have ip in other network with the same range ##

                    # Get all Ipv6Equipament related to this equipment
                    ip_equips = Ipv6Equipament.objects.filter(
                        equipamento=equip_id)

                    for ip_test in [ip_equip.ip for ip_equip in ip_equips]:
                        if ip_test.networkipv6.block1 == ip.networkipv6.block1 and \
                                ip_test.networkipv6.block2 == ip.networkipv6.block2 and \
                                ip_test.networkipv6.block3 == ip.networkipv6.block3 and \
                                ip_test.networkipv6.block4 == ip.networkipv6.block4 and \
                                ip_test.networkipv6.block5 == ip.networkipv6.block5 and \
                                ip_test.networkipv6.block6 == ip.networkipv6.block6 and \
                                ip_test.networkipv6.block7 == ip.networkipv6.block7 and \
                                ip_test.networkipv6.block8 == ip.networkipv6.block8 and \
                                ip_test.networkipv6.block == ip.networkipv6.block and \
                                ip_test.networkipv6 != ip.networkipv6:

                            # Filter testing
                            if ip_test.networkipv6.vlan.ambiente.filter is None or ip.networkipv6.vlan.ambiente.filter is None:
                                raise IpRangeAlreadyAssociation(
                                    None, u'Equipment is already associated with another ip with the same ip range.')
                            else:
                                # Test both environment's filters
                                tp_equip_list_one = list()
                                for fet in FilterEquipType.objects.filter(filter=ip.networkipv6.vlan.ambiente.filter.id):
                                    tp_equip_list_one.append(fet.equiptype)

                                tp_equip_list_two = list()
                                for fet in FilterEquipType.objects.filter(filter=ip_test.networkipv6.vlan.ambiente.filter.id):
                                    tp_equip_list_two.append(fet.equiptype)

                                if equipment.tipo_equipamento not in tp_equip_list_one or equipment.tipo_equipamento not in tp_equip_list_two:
                                    raise IpRangeAlreadyAssociation(
                                        None, u'Equipment is already associated with another ip with the same ip range.')

                    ## Filter case 2 - end ##

                    # Delete vlan's cache
                    destroy_cache_function([net.vlan_id])
                    ip_equipment.save(user)

                    # Makes Environment Equipment association
                    try:
                        equipment_environment = EquipamentoAmbiente()
                        equipment_environment.equipamento = equipment
                        equipment_environment.ambiente = net.vlan.ambiente
                        equipment_environment.create(user)

                    except EquipamentoAmbienteDuplicatedError, e:
                        # If already exists, OK !
                        pass

                except IpRangeAlreadyAssociation, e:
                    raise IpRangeAlreadyAssociation(None, e.message)
    def handle_post(self, request, user, *args, **kwargs):
        """Treat POST requests to add new Network

        URL: network/add/
        """

        try:

            if not has_perm(user, AdminPermission.VLAN_MANAGEMENT,
                            AdminPermission.WRITE_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                return self.not_authorized()

            xml_map, attrs_map = loads(request.raw_post_data)

            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is None:
                msg = u'There is no value to the networkapi tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)

            network_map = networkapi_map.get('network')
            if network_map is None:
                msg = u'There is no value to the vlan tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)

            # Get XML data
            network = network_map.get('network')
            id_vlan = network_map.get('id_vlan')
            network_type = network_map.get('id_network_type')
            environment_vip = network_map.get('id_environment_vip')
            cluster_unit = network_map.get('cluster_unit')

            try:
                net = IPNetwork(network)
            except ValueError:
                raise InvalidValueError(None, 'network', network)

            # Valid vlan ID
            if not is_valid_int_greater_zero_param(id_vlan):
                raise InvalidValueError(None, 'id_vlan', id_vlan)
            if not is_valid_int_greater_zero_param(network_type):
                raise InvalidValueError(None, 'id_network_type', network_type)

            vlan = Vlan().get_by_pk(id_vlan)
            net_type = TipoRede.get_by_pk(network_type)

            if environment_vip is not None:

                if not is_valid_int_greater_zero_param(environment_vip):
                    raise InvalidValueError(None, 'id_environment_vip',
                                            environment_vip)

                evips = EnvironmentVip.objects.all()
                evip_list = EnvironmentVip.available_evips(
                    EnvironmentVip(), evips, int(id_vlan))

                # Check if the chose environment is in the same environment
                if any(
                        int(environment_vip) == item['id']
                        for item in evip_list):
                    # Find Environment VIP by ID to check if it exist
                    env_vip = EnvironmentVip.get_by_pk(environment_vip)
                else:
                    raise InvalidValueError(None, 'id_environment_vip',
                                            environment_vip)

            else:
                env_vip = None

            # Check unchecked exception
            blocks, network, version = break_network(network)

            expl = split(net.network.exploded,
                         '.' if version == IP_VERSION.IPv4[0] else ':')
            expl.append(str(net.prefixlen))

            if blocks != expl:
                raise InvalidValueError(None, 'rede', network)

            if version == IP_VERSION.IPv4[0]:

                # Find all networks related to environment
                nets = NetworkIPv4.objects.filter(
                    vlan__ambiente__id=vlan.ambiente.id)

                # Cast to API class
                networks = set([
                    IPv4Network('%d.%d.%d.%d/%d' %
                                (net_ip.oct1, net_ip.oct2, net_ip.oct3,
                                 net_ip.oct4, net_ip.block)) for net_ip in nets
                ])

                # If network selected not in use
                for network_aux in networks:
                    if net in network_aux or network_aux in net:
                        self.log.debug(
                            'Network %s cannot be allocated. It conflicts with %s already '
                            'in use in this environment.' % (net, network))
                        raise NetworkIPv4AddressNotAvailableError(
                            None,
                            u'Network cannot be allocated. %s already in use in this environment.'
                            % network_aux)

                if env_vip is not None:

                    # Find all networks related to environment vip
                    nets = NetworkIPv4.objects.filter(
                        ambient_vip__id=env_vip.id)

                    # Cast to API class
                    networks = set([
                        IPv4Network('%d.%d.%d.%d/%d' %
                                    (net_ip.oct1, net_ip.oct2, net_ip.oct3,
                                     net_ip.oct4, net_ip.block))
                        for net_ip in nets
                    ])

                    # If there is already a network with the same  range ip as
                    # related the environment  vip
                    for network_aux in networks:
                        if net in network_aux or network_aux in net:
                            self.log.debug(
                                'Network %s cannot be allocated. It conflicts with %s already in use '
                                'in this environment VIP.' % (net, network))
                            raise NetworkIPv4AddressNotAvailableError(
                                None,
                                u'Network cannot be allocated. %s already in use '
                                u'in this environment VIP.' % network_aux)

                # Check if the new network is in the range of the Environment Network
                try:
                    vlan = Vlan().get_by_pk(id_vlan)
                    vlan_env_id = vlan.ambiente

                    try:
                        config_env = ConfigEnvironment()
                        environment_conf = config_env.get_by_environment(
                            vlan_env_id)

                        if environment_conf:
                            for env_config in environment_conf:

                                ipconfig = env_config.ip_config
                                subnet = ipconfig.subnet

                            env_net = IPNetwork(subnet)

                            try:
                                if net in env_net:
                                    self.log.debug(
                                        'Network "%s" can be allocated because is in the '
                                        'environment network(%s) subnets.' %
                                        (net, subnet))

                                else:
                                    raise NetworkSubnetRange(
                                        None,
                                        'A rede a ser cadastrada (%s) não pertence às '
                                        'subredes do ambiente (rede ambiente: %s). '
                                        'Cadastre o range desejado no '
                                        'ambiente.' % (net, subnet))

                            except NetworkSubnetRange:
                                self.log.error(
                                    'Network "%s" can not be allocated because is not in the '
                                    'environment network(%s) subnets.' %
                                    (net, subnet))
                                return self.response_error(414)

                        else:
                            raise NetworkEnvironmentError(
                                None, 'O ambiente não está configurado. '
                                'É necessário efetuar a configuração.')

                    except NetworkEnvironmentError:
                        self.log.error(
                            'The environment does not have a registered network'
                        )
                        return self.response_error(415)

                except Exception as ERROR:
                    self.log.error(ERROR)

                # # Filter case 1 - Adding new network with same ip range to another network on other environment ##
                # Get environments with networks with the same ip range
                nets = NetworkIPv4.objects.filter(oct1=expl[0],
                                                  oct2=expl[1],
                                                  oct3=expl[2],
                                                  oct4=expl[3],
                                                  block=expl[4])
                env_ids = list()
                for net_ip in nets:
                    env_ids.append(net_ip.vlan.ambiente.id)

                # If other network with same ip range exists
                if len(env_ids) > 0:

                    # Get equipments related to this network's environment
                    env_equips = EquipamentoAmbiente.objects.filter(
                        ambiente=vlan.ambiente.id)

                    # Verify equipments related with all other environments
                    # that contains networks with same ip range
                    for env_id in env_ids:
                        # Equipments related to other environments
                        other_env_equips = EquipamentoAmbiente.objects.filter(
                            ambiente=env_id)
                        # Adjust to equipments
                        equip_list = list()
                        for equip_env in other_env_equips:
                            equip_list.append(equip_env.equipamento.id)

                        for env_equip in env_equips:
                            if env_equip.equipamento.id in equip_list:

                                # Filter testing
                                if other_env_equips[
                                        0].ambiente.filter is None or vlan.ambiente.filter is None:
                                    raise NetworkIPRangeEnvError(
                                        None,
                                        u'Um dos equipamentos associados com o ambiente '
                                        u'desta rede também está associado com outro ambiente '
                                        u'que tem uma rede com essa mesma faixa, adicione '
                                        u'filtros nos ambientes se necessário.'
                                    )
                                else:
                                    # Test both environment's filters
                                    tp_equip_list_one = list()
                                    for fet in FilterEquipType.objects.filter(
                                            filter=vlan.ambiente.filter.id):
                                        tp_equip_list_one.append(fet.equiptype)

                                    tp_equip_list_two = list()
                                    for fet in FilterEquipType.objects.filter(
                                            filter=other_env_equips[0].
                                            ambiente.filter.id):
                                        tp_equip_list_two.append(fet.equiptype)

                                    if env_equip.equipamento.tipo_equipamento not in tp_equip_list_one or \
                                            env_equip.equipamento.tipo_equipamento not in tp_equip_list_two:
                                        raise NetworkIPRangeEnvError(
                                            None,
                                            u'Um dos equipamentos associados com o '
                                            u'ambiente desta rede também está associado '
                                            u'com outro ambiente que tem uma rede com '
                                            u'essa mesma faixa, adicione filtros nos '
                                            u'ambientes se necessário.')

                # # Filter case 1 - end ##

                # New NetworkIPv4
                network_ip = NetworkIPv4()

                network_ip.oct1, network_ip.oct2, network_ip.oct3, network_ip.oct4 = str(
                    net.network).split('.')
                network_ip.block = net.prefixlen
                network_ip.mask_oct1, network_ip.mask_oct2, network_ip.mask_oct3, network_ip.mask_oct4 = \
                    str(net.netmask).split('.')
                network_ip.broadcast = net.broadcast.compressed

            else:
                # Find all networks ralated to environment
                nets = NetworkIPv6.objects.filter(
                    vlan__ambiente__id=vlan.ambiente.id)

                networks = set([
                    IPv6Network('%s:%s:%s:%s:%s:%s:%s:%s/%d' %
                                (net_ip.block1, net_ip.block2, net_ip.block3,
                                 net_ip.block4, net_ip.block5, net_ip.block6,
                                 net_ip.block7, net_ip.block8, net_ip.block))
                    for net_ip in nets
                ])

                # If network selected not in use
                for network_aux in networks:
                    if net in network_aux or network_aux in net:
                        self.log.debug(
                            'Network %s cannot be allocated. It conflicts with %s already in use '
                            'in this environment.' % (net, network))
                        raise NetworkIPv4AddressNotAvailableError(
                            None,
                            u'Network cannot be allocated. %s already in '
                            u'use in this environment.' % network_aux)

                if env_vip is not None:

                    # Find all networks related to environment vip
                    nets = NetworkIPv6.objects.filter(
                        ambient_vip__id=env_vip.id)

                    networks = set([
                        IPv6Network(
                            '%s:%s:%s:%s:%s:%s:%s:%s/%d' %
                            (net_ip.block1, net_ip.block2, net_ip.block3,
                             net_ip.block4, net_ip.block5, net_ip.block6,
                             net_ip.block7, net_ip.block8, net_ip.block))
                        for net_ip in nets
                    ])

                    # If there is already a network with the same  range ip as
                    # related the environment  vip
                    for network_aux in networks:
                        if net in network_aux or network_aux in net:
                            self.log.debug(
                                'Network %s cannot be allocated. It conflicts with %s already in '
                                'use in this environment VIP.' %
                                (net, network))
                            raise NetworkIPv4AddressNotAvailableError(
                                None, u'Network cannot be allocated. %s '
                                u'already in use in this environment '
                                u'VIP.' % network_aux)

                # # Filter case 1 - Adding new network with same ip range to another network on other environment ##
                # Get environments with networks with the same ip range
                nets = NetworkIPv6.objects.filter(block1=expl[0],
                                                  block2=expl[1],
                                                  block3=expl[2],
                                                  block4=expl[3],
                                                  block5=expl[4],
                                                  block6=expl[5],
                                                  block7=expl[6],
                                                  block8=expl[7],
                                                  block=expl[8])
                env_ids = list()
                for net_ip in nets:
                    env_ids.append(net_ip.vlan.ambiente.id)

                # If other network with same ip range exists
                if len(env_ids) > 0:

                    # Get equipments related to this network's environment
                    env_equips = EquipamentoAmbiente.objects.filter(
                        ambiente=vlan.ambiente.id)

                    # Verify equipments related with all other environments
                    # that contains networks with same ip range
                    for env_id in env_ids:
                        # Equipments related to other environments
                        other_env_equips = EquipamentoAmbiente.objects.filter(
                            ambiente=env_id)
                        # Adjust to equipments
                        equip_list = list()
                        for equip_env in other_env_equips:
                            equip_list.append(equip_env.equipamento.id)

                        for env_equip in env_equips:
                            if env_equip.equipamento.id in equip_list:

                                # Filter testing
                                if other_env_equips[
                                        0].ambiente.filter is None or vlan.ambiente.filter is None:
                                    raise NetworkIPRangeEnvError(
                                        None,
                                        u'Um dos equipamentos associados com o '
                                        u'ambiente desta rede também está associado '
                                        u'com outro ambiente que tem uma rede com '
                                        u'essa mesma faixa, adicione filtros nos '
                                        u'ambientes se necessário.')
                                else:
                                    # Test both environment's filters
                                    tp_equip_list_one = list()
                                    for fet in FilterEquipType.objects.filter(
                                            filter=vlan.ambiente.filter.id):
                                        tp_equip_list_one.append(fet.equiptype)

                                    tp_equip_list_two = list()
                                    for fet in FilterEquipType.objects.filter(
                                            filter=other_env_equips[0].
                                            ambiente.filter.id):
                                        tp_equip_list_two.append(fet.equiptype)

                                    if env_equip.equipamento.tipo_equipamento not in tp_equip_list_one or \
                                            env_equip.equipamento.tipo_equipamento not in tp_equip_list_two:
                                        raise NetworkIPRangeEnvError(
                                            None,
                                            u'Um dos equipamentos associados com o '
                                            u'ambiente desta rede também está '
                                            u'associado com outro ambiente que tem '
                                            u'uma rede com essa mesma faixa, adicione '
                                            u'filtros nos ambientes se necessário.'
                                        )

                # # Filter case 1 - end ##

                # New NetworkIPv6
                network_ip = NetworkIPv6()
                network_ip.block1, network_ip.block2, network_ip.block3, network_ip.block4, network_ip.block5, \
                    network_ip.block6, network_ip.block7, network_ip.block8 = str(net.network.exploded).split(':')
                network_ip.block = net.prefixlen
                network_ip.mask1, network_ip.mask2, network_ip.mask3, network_ip.mask4, network_ip.mask5, \
                    network_ip.mask6, network_ip.mask7, network_ip.mask8 = str(net.netmask.exploded).split(':')

            # Get all vlans environments from equipments of the current
            # environment
            ambiente = vlan.ambiente

            equips = list()
            envs = list()

            # equips = all equipments from the environment which this network
            # is about to be allocated on
            for env in ambiente.equipamentoambiente_set.all():
                equips.append(env.equipamento)

            # envs = all environments from all equips above
            # This will be used to test all networks from the environments.
            for equip in equips:
                for env in equip.equipamentoambiente_set.all():
                    if env.ambiente not in envs:
                        envs.append(env.ambiente)

            network_ip_verify = IPNetwork(network)

            # For all vlans in all common environments,
            # check if any network is a subnetwork or supernetwork
            # of the desired network network_ip_verify
            for env in envs:
                for vlan_obj in env.vlan_set.all():

                    is_subnet = verify_subnet(vlan_obj, network_ip_verify,
                                              version)

                    if is_subnet:
                        if vlan_obj.ambiente == ambiente:
                            raise NetworkIPRangeEnvError(None)

                        if ambiente.filter_id is None or vlan_obj.ambiente.filter_id is None or \
                                int(vlan_obj.ambiente.filter_id) != int(ambiente.filter_id):
                            raise NetworkIPRangeEnvError(None)

            network_ip.vlan = vlan
            network_ip.network_type = net_type
            network_ip.ambient_vip = env_vip
            network_ip.cluster_unit = cluster_unit

            try:

                destroy_cache_function([id_vlan])
                network_ip.save()

                list_equip_routers_ambient = EquipamentoAmbiente.objects.filter(
                    ambiente=network_ip.vlan.ambiente.id, is_router=True)

                if list_equip_routers_ambient:
                    if version == IP_VERSION.IPv4[0]:
                        if network_ip.block < 31:

                            # Add the first available ipv4 on all equipment
                            # that is configured as a router for the environment
                            # related to network
                            ip = Ip.get_first_available_ip(network_ip.id)

                            ip = str(ip).split('.')

                            ip_model = Ip()
                            ip_model.oct1 = ip[0]
                            ip_model.oct2 = ip[1]
                            ip_model.oct3 = ip[2]
                            ip_model.oct4 = ip[3]
                            ip_model.networkipv4_id = network_ip.id

                            ip_model.save()

                            if len(list_equip_routers_ambient
                                   ) > 1 and network_ip.block < 30:
                                multiple_ips = True
                            else:
                                multiple_ips = False

                            logging.debug('vxlan: %s' % vlan.vxlan)

                            if vlan.vxlan:

                                logging.debug('vxlan ok')
                                for equip in list_equip_routers_ambient:
                                    IpEquipamento().create(
                                        user, ip_model.id,
                                        equip.equipamento.id)

                                if multiple_ips:
                                    debug_ip = Ip.get_first_available_ip(
                                        network_ip.id, True)

                                    ips = Ip()
                                    ips.oct1, ips.oct2, ips.oct3, ips.oct4 = str(
                                        debug_ip).split('.')
                                    ips.networkipv4_id = network_ip.id
                                    ips.descricao = "IP alocado para debug"
                                    ips.save(user)

                                    IpEquipamento().create(
                                        user, ips.id,
                                        list_equip_routers_ambient[0].
                                        equipamento.id)

                            else:

                                for equip in list_equip_routers_ambient:
                                    IpEquipamento().create(
                                        user, ip_model.id,
                                        equip.equipamento.id)

                                    if multiple_ips:
                                        router_ip = Ip.get_first_available_ip(
                                            network_ip.id, True)
                                        router_ip = str(router_ip).split('.')
                                        ip_model2 = Ip()
                                        ip_model2.oct1 = router_ip[0]
                                        ip_model2.oct2 = router_ip[1]
                                        ip_model2.oct3 = router_ip[2]
                                        ip_model2.oct4 = router_ip[3]
                                        ip_model2.networkipv4_id = network_ip.id
                                        ip_model2.save(user)
                                        IpEquipamento().create(
                                            user, ip_model2.id,
                                            equip.equipamento.id)

                    else:
                        if network_ip.block < 127:

                            # Add the first available ipv6 on all equipment
                            # that is configured as a router for the environment
                            # related to network
                            ipv6 = Ipv6.get_first_available_ip6(network_ip.id)

                            ipv6 = str(ipv6).split(':')

                            ipv6_model = Ipv6()
                            ipv6_model.block1 = ipv6[0]
                            ipv6_model.block2 = ipv6[1]
                            ipv6_model.block3 = ipv6[2]
                            ipv6_model.block4 = ipv6[3]
                            ipv6_model.block5 = ipv6[4]
                            ipv6_model.block6 = ipv6[5]
                            ipv6_model.block7 = ipv6[6]
                            ipv6_model.block8 = ipv6[7]
                            ipv6_model.networkipv6_id = network_ip.id

                            ipv6_model.save()

                            if len(list_equip_routers_ambient
                                   ) > 1 and network_ip.block < 126:
                                multiple_ips = True
                            else:
                                multiple_ips = False

                            if vlan.vxlan:

                                for equip in list_equip_routers_ambient:
                                    Ipv6Equipament().create(
                                        user, ipv6_model.id,
                                        equip.equipamento.id)

                                if multiple_ips:
                                    router_ip = Ipv6.get_first_available_ip6(
                                        network_ip.id, True)

                                    ipv6s = Ipv6()
                                    ipv6s.block1, ipv6s.block2, ipv6s.block3, ipv6s.block4, ipv6s.block5, \
                                        ipv6s.block6, ipv6s.block7, ipv6s.block8 = str(router_ip).split(':')
                                    ipv6s.networkipv6_id = network_ip.id
                                    ipv6s.descricao = "IPv6 alocado para debug"
                                    ipv6s.save(user)

                                    Ipv6Equipament().create(
                                        user, ipv6s.id,
                                        list_equip_routers_ambient[0].
                                        equipamento.id)

                            else:

                                for equip in list_equip_routers_ambient:
                                    Ipv6Equipament().create(
                                        user, ipv6_model.id,
                                        equip.equipamento.id)

                                    if multiple_ips:
                                        router_ip = Ipv6.get_first_available_ip6(
                                            network_ip.id, True)
                                        router_ip = str(router_ip).split(':')
                                        ipv6_model2 = Ipv6()
                                        ipv6_model2.block1 = router_ip[0]
                                        ipv6_model2.block2 = router_ip[1]
                                        ipv6_model2.block3 = router_ip[2]
                                        ipv6_model2.block4 = router_ip[3]
                                        ipv6_model2.block5 = router_ip[4]
                                        ipv6_model2.block6 = router_ip[5]
                                        ipv6_model2.block7 = router_ip[6]
                                        ipv6_model2.block8 = router_ip[7]
                                        ipv6_model2.networkipv6_id = network_ip.id
                                        ipv6_model2.save(user)
                                        Ipv6Equipament().create(
                                            user, ipv6_model2.id,
                                            equip.equipamento.id)

            except Exception as e:
                raise IpError(e, u'Error persisting Network.')

            network_map = dict()
            network_map['id'] = network_ip.id
            network_map['rede'] = str(net)
            network_map[
                'broadcast'] = net.broadcast if net.version == 4 else ''
            network_map['mask'] = net.netmask.exploded
            network_map['id_vlan'] = vlan.id
            network_map['id_tipo_rede'] = net_type.id
            network_map[
                'id_ambiente_vip'] = env_vip.id if env_vip is not None else ''
            network_map['active'] = network_ip

            return self.response(dumps_networkapi({'network': network_map}))

        except NetworkIPRangeEnvError:
            return self.response_error(346)
        except InvalidValueError as e:
            self.log.error(u'Parameter %s is invalid. Value: %s.' %
                           (e.param, e.value))
            return self.response_error(269, e.param, e.value)
        except NetworkTypeNotFoundError:
            self.log.error(u'The network_type parameter does not exist.')
            return self.response_error(111)
        except VlanNotFoundError:
            self.log.error(u'Vlan not found')
            return self.response_error(116)
        except EnvironmentVipNotFoundError:
            return self.response_error(283)
        except NetworkIPv4AddressNotAvailableError:
            return self.response_error(295)
        except NetworkIPv6AddressNotAvailableError:
            return self.response_error(296)
        except ConfigEnvironmentInvalidError:
            return self.response_error(294)
        except NetworkIpAddressNotAvailableError:
            return self.response_error(335)
        except (IpError, NetworkIPv6Error, NetworkIPv4Error, GrupoError,
                VlanError):
            return self.response_error(1)
        except XMLError as e:
            self.log.error(u'Error reading the XML request.')
            return self.response_error(3, e)
Ejemplo n.º 22
0
def networkIPv6_deploy(request, network_id):
    """Deploy network L3 configuration in the environment routers for network ipv6

    Receives optional parameter equipments to specify what equipment should
    receive network configuration
    """

    networkipv6 = NetworkIPv6.get_by_pk(int(network_id))
    environment = networkipv6.vlan.ambiente
    equipments_id_list = None
    if request.DATA is not None:
        equipments_id_list = request.DATA.get('equipments', None)

    equipment_list = []

    if equipments_id_list is not None:
        if type(equipments_id_list) is not list:
            raise api_exceptions.ValidationException('equipments')

        for equip in equipments_id_list:
            try:
                int(equip)
            except ValueError:
                raise api_exceptions.ValidationException('equipments')

        # Check that equipments received as parameters are in correct vlan
        # environment
        equipment_list = Equipamento.objects.filter(
            equipamentoambiente__ambiente=environment,
            id__in=equipments_id_list)
        log.info('list = %s' % equipment_list)
        if len(equipment_list) != len(equipments_id_list):
            log.error(
                'Error: equipments %s are not part of network environment.' % equipments_id_list)
            raise exceptions.EquipmentIDNotInCorrectEnvException()
    else:
        # TODO GET network routers
        equipment_list = Equipamento.objects.filter(
            ipv6equipament__ip__networkipv6=networkipv6,
            equipamentoambiente__ambiente=networkipv6.vlan.ambiente,
            equipamentoambiente__is_router=1).distinct()
        if len(equipment_list) == 0:
            raise exceptions.NoEnvironmentRoutersFoundException()

    # Check permission to configure equipments
    for equip in equipment_list:
        # User permission
        if not has_perm(request.user, AdminPermission.EQUIPMENT_MANAGEMENT, AdminPermission.WRITE_OPERATION, None, equip.id, AdminPermission.EQUIP_WRITE_OPERATION):
            log.error(u'User does not have permission to perform the operation.')
            raise PermissionDenied(
                'No permission to configure equipment %s-%s' % (equip.id, equip.nome))

    if all_equipments_are_in_maintenance(equipment_list):
        raise AllEquipmentsAreInMaintenanceException()

    try:
        # deploy network configuration
        if request.method == 'POST':
            returned_data = facade.deploy_networkIPv6_configuration(
                request.user, networkipv6, equipment_list)
        elif request.method == 'DELETE':
            returned_data = facade.remove_deploy_networkIPv6_configuration(
                request.user, networkipv6, equipment_list)

        return Response(returned_data)

    except Exception, exception:
        log.error(exception)
        raise api_exceptions.NetworkAPIException()
Ejemplo n.º 23
0
    def handle_post(self, request, user, *args, **kwargs):
        """Treat requests POST to allocate a new VLAN IPv6.

        URL: vlan/ipv6/
        """

        self.log.info("Allocate a new VLAN IPv6")

        try:
            # User permission
            if not has_perm(user, AdminPermission.VLAN_MANAGEMENT,
                            AdminPermission.WRITE_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                return self.not_authorized()

            # Load XML data
            xml_map, attrs_map = loads(request.raw_post_data)

            # XML data format
            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is None:
                return self.response_error(
                    3,
                    u'There is no value to the networkapi tag  of XML request.'
                )

            vlan_map = networkapi_map.get('vlan')
            if vlan_map is None:
                return self.response_error(
                    3, u'There is no value to the vlan tag  of XML request.')

            # Get XML data
            environment = vlan_map.get('id_environment')
            network_type = vlan_map.get('id_network_type')
            name = vlan_map.get('name')
            description = vlan_map.get('description')
            environment_vip = vlan_map.get('id_environment_vip')

            # Name must NOT be none and NOT be greater than 50
            if not is_valid_string_minsize(
                    name, 3) or not is_valid_string_maxsize(name, 50):
                self.log.error(u'Parameter name is invalid. Value: %s.', name)
                raise InvalidValueError(None, 'name', name)

            # Description can NOT be greater than 200
            if not is_valid_string_minsize(
                    description, 3, False) or not is_valid_string_maxsize(
                        description, 200, False):
                self.log.error(u'Parameter descricao is invalid. Value: %s.',
                               description)
                raise InvalidValueError(None, 'descricao', description)

            # Environment

            # Valid environment ID
            if not is_valid_int_greater_zero_param(environment):
                self.log.error(
                    u'Parameter id_environment is invalid. Value: %s.',
                    environment)
                raise InvalidValueError(None, 'id_environment', environment)

            # Find environment by ID to check if it exist
            env = Ambiente.get_by_pk(environment)

            # Environment Vip

            if environment_vip is not None:

                # Valid environment_vip ID
                if not is_valid_int_greater_zero_param(environment_vip):
                    self.log.error(
                        u'Parameter id_environment_vip is invalid. Value: %s.',
                        environment_vip)
                    raise InvalidValueError(None, 'id_environment_vip',
                                            environment_vip)

                # Find Environment VIP by ID to check if it exist
                evip = EnvironmentVip.get_by_pk(environment_vip)

            else:
                evip = None

            # Network Type

            # Valid network_type ID
            if not is_valid_int_greater_zero_param(network_type):
                self.log.error(
                    u'Parameter id_network_type is invalid. Value: %s.',
                    network_type)
                raise InvalidValueError(None, 'id_network_type', network_type)

            # Find network_type by ID to check if it exist
            net = TipoRede.get_by_pk(network_type)

            # New Vlan
            vlan = Vlan()
            vlan.nome = name
            vlan.descricao = description
            vlan.ambiente = env

            # Check if environment has min/max num_vlan value or use the value
            # thas was configured in settings
            if (vlan.ambiente.min_num_vlan_1 and vlan.ambiente.max_num_vlan_1
                ) or (vlan.ambiente.min_num_vlan_2
                      and vlan.ambiente.max_num_vlan_2):
                min_num_01 = vlan.ambiente.min_num_vlan_1 if vlan.ambiente.min_num_vlan_1 and vlan.ambiente.max_num_vlan_1 else vlan.ambiente.min_num_vlan_2
                max_num_01 = vlan.ambiente.max_num_vlan_1 if vlan.ambiente.min_num_vlan_1 and vlan.ambiente.max_num_vlan_1 else vlan.ambiente.max_num_vlan_2
                min_num_02 = vlan.ambiente.min_num_vlan_2 if vlan.ambiente.min_num_vlan_2 and vlan.ambiente.max_num_vlan_2 else vlan.ambiente.min_num_vlan_1
                max_num_02 = vlan.ambiente.max_num_vlan_2 if vlan.ambiente.min_num_vlan_2 and vlan.ambiente.max_num_vlan_2 else vlan.ambiente.max_num_vlan_1
            else:
                min_num_01 = settings.MIN_VLAN_NUMBER_01
                max_num_01 = settings.MAX_VLAN_NUMBER_01
                min_num_02 = settings.MIN_VLAN_NUMBER_02
                max_num_02 = settings.MAX_VLAN_NUMBER_02

            # Persist
            vlan.create_new(user, min_num_01, max_num_01, min_num_02,
                            max_num_02)

            # New NetworkIPv6
            network_ipv6 = NetworkIPv6()
            vlan_map = network_ipv6.add_network_ipv6(user, vlan.id, net, evip)

            # Return XML
            return self.response(dumps_networkapi(vlan_map))

        except XMLError, x:
            self.log.error(u'Error reading the XML request.')
            return self.response_error(3, x)
    def handle_get(self, request, user, *args, **kwargs):
        """Handles GET requests to list all network IPv6 by network ipv6 id.

        URLs: ip/id_network_ipv6/id_rede 
         """

        try:
            # Commons Validations

            # User permission
            if not has_perm(user, AdminPermission.IPS, AdminPermission.READ_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                return self.not_authorized()

            # Business Validations

            # Valid id access
            id_network = kwargs.get('id_rede')

            if not is_valid_int_greater_zero_param(id_network):
                raise InvalidValueError(None, 'id_rede', id_network)

            # Business Rules

            NetworkIPv6.get_by_pk(id_network)

            ips = Ipv6.list_by_network(id_network)

            try:
                len(ips)
            except Exception, e:
                raise InvalidValueError(None, 'id_rede', id_network)

            if ips == None or len(ips) <= 0:
                raise IpNotFoundError(305, id_network)

            EquipIps = []
            mapa = dict()
            #lista = []

            try:
                for ip in ips:
                    EquipIps = []
                    equipsIp = Ipv6Equipament.list_by_ip6(ip.id)
                    for eIp in equipsIp:
                        EquipIps.append(eIp)
                    mapa[ip.id] = EquipIps
                    # lista.append(mapa)bora pegar cafe

            except IpEquipmentNotFoundError:
                EquipIps.append(None)
            except IpError:
                EquipIps.append(None)

            network_map = dict()
            list_ips = []
            lequips = []

            for ip in ips:
                lequips = []
                ip_maps = dict()
                ip_maps['id'] = ip.id
                ip_maps['block1'] = ip.block1
                ip_maps['block2'] = ip.block2
                ip_maps['block3'] = ip.block3
                ip_maps['block4'] = ip.block4
                ip_maps['block5'] = ip.block5
                ip_maps['block6'] = ip.block6
                ip_maps['block7'] = ip.block7
                ip_maps['block8'] = ip.block8
                ip_maps['descricao'] = ip.description
                for equip in mapa.get(ip.id):
                    equip = Equipamento.get_by_pk(equip.equipamento.id)
                    lequips.append(model_to_dict(equip))
                ip_maps['equipamento'] = lequips
                list_ips.append(ip_maps)

            network_map['ips'] = list_ips

            network_map
            # Return XML
            return self.response(dumps_networkapi(network_map))
    def handle_post(self, request, user, *args, **kwargs):
        '''Handles POST requests to associate and IPv6 to an equipment.

        URL: ipv6/assoc/
        '''

        self.log.info('Associate Ipv6 to an Equipment')

        try:
            # Load XML data
            xml_map, attrs_map = loads(request.raw_post_data)

            # XML data format
            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is None:
                msg = u'There is no value to the networkapi tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)

            ip_map = networkapi_map.get('ip_map')
            if ip_map is None:
                msg = u'There is no value to the ip tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)

            # Get XML data
            ip_id = ip_map.get('id_ip')
            equip_id = ip_map.get('id_equip')
            network_ipv6_id = ip_map.get('id_net')

            # Valid ip_id
            if not is_valid_int_greater_zero_param(ip_id):
                self.log.error(u'Parameter ip_id is invalid. Value: %s.',
                               ip_id)
                raise InvalidValueError(None, 'ip_id', ip_id)

            # Valid equip_id
            if not is_valid_int_greater_zero_param(equip_id):
                self.log.error(u'Parameter equip_id is invalid. Value: %s.',
                               equip_id)
                raise InvalidValueError(None, 'equip_id', equip_id)

            # Valid network_ipv6_id
            if not is_valid_int_greater_zero_param(network_ipv6_id):
                self.log.error(
                    u'Parameter network_ipv6_id is invalid. Value: %s.',
                    network_ipv6_id)
                raise InvalidValueError(None, 'network_ipv6_id',
                                        network_ipv6_id)

            # User permission
            if not has_perm(user, AdminPermission.IPS,
                            AdminPermission.WRITE_OPERATION, None, equip_id,
                            AdminPermission.EQUIP_WRITE_OPERATION):
                raise UserNotAuthorizedError(
                    None,
                    u'User does not have permission to perform the operation.')

            # Business Rules

            # Get net
            net = NetworkIPv6.get_by_pk(network_ipv6_id)

            with distributedlock(LOCK_NETWORK_IPV6 % network_ipv6_id):

                # Get ip
                ip = Ipv6.get_by_pk(ip_id)
                # Get equipment
                equip = Equipamento.get_by_pk(equip_id)

                listaVlansDoEquip = []

                for ipequip in equip.ipequipamento_set.all():
                    vlan = ipequip.ip.networkipv4.vlan
                    if vlan not in listaVlansDoEquip:
                        listaVlansDoEquip.append(vlan)

                for ipequip in equip.ipv6equipament_set.all():
                    vlan = ipequip.ip.networkipv6.vlan
                    if vlan not in listaVlansDoEquip:
                        listaVlansDoEquip.append(vlan)

                vlan_atual = net.vlan
                vlan_aux = None
                ambiente_aux = None

                for vlan in listaVlansDoEquip:
                    if vlan.num_vlan == vlan_atual.num_vlan:
                        if vlan.id != vlan_atual.id:

                            # Filter case 3 - Vlans with same number cannot
                            # share equipments ##

                            flag_vlan_error = False
                            # Filter testing
                            if vlan.ambiente.filter is None or vlan_atual.ambiente.filter is None:
                                flag_vlan_error = True
                            else:
                                # Test both environment's filters
                                tp_equip_list_one = list()
                                for fet in FilterEquipType.objects.filter(
                                        filter=vlan_atual.ambiente.filter.id):
                                    tp_equip_list_one.append(fet.equiptype)

                                tp_equip_list_two = list()
                                for fet in FilterEquipType.objects.filter(
                                        filter=vlan.ambiente.filter.id):
                                    tp_equip_list_two.append(fet.equiptype)

                                if equip.tipo_equipamento not in tp_equip_list_one or equip.tipo_equipamento not in tp_equip_list_two:
                                    flag_vlan_error = True

                            ## Filter case 3 - end ##

                            if flag_vlan_error:
                                ambiente_aux = vlan.ambiente
                                vlan_aux = vlan
                                nome_ambiente = "%s - %s - %s" % (
                                    vlan.ambiente.divisao_dc.nome,
                                    vlan.ambiente.ambiente_logico.nome,
                                    vlan.ambiente.grupo_l3.nome)
                                raise VlanNumberNotAvailableError(
                                    None,
                                    '''O ip informado não pode ser cadastrado, pois o equipamento %s, faz parte do ambiente %s (id %s), 
                                                                    que possui a Vlan de id %s, que também possui o número %s, e não é permitido que vlans que compartilhem o mesmo ambiente 
                                                                    por meio de equipamentos, possuam o mesmo número, edite o número de uma das Vlans ou adicione um filtro no ambiente para efetuar o cadastro desse IP no Equipamento Informado.
                                                                    ''' %
                                    (equip.nome, nome_ambiente,
                                     ambiente_aux.id, vlan_aux.id,
                                     vlan_atual.num_vlan))

                # Persist
                try:

                    try:
                        ipEquip = Ipv6Equipament()
                        ipEquip.get_by_ip_equipment(ip.id, equip_id)

                        raise IpEquipmentAlreadyAssociation(
                            None,
                            u'Ipv6 %s:%s:%s:%s:%s:%s:%s:%s already has association with Equipament %s.'
                            % (ip.block1, ip.block2, ip.block3, ip.block4,
                               ip.block5, ip.block6, ip.block7, ip.block8,
                               equip_id))
                    except IpEquipmentNotFoundError, e:
                        pass

                    equipment = Equipamento().get_by_pk(equip_id)
                    ip_equipment = Ipv6Equipament()
                    ip_equipment.ip = ip

                    ip_equipment.equipamento = equipment

                    # Filter case 2 - Adding new IpEquip for a equip that
                    # already have ip in other network with the same range ##

                    # Get all Ipv6Equipament related to this equipment
                    ip_equips = Ipv6Equipament.objects.filter(
                        equipamento=equip_id)

                    for ip_test in [ip_equip.ip for ip_equip in ip_equips]:
                        if ip_test.networkipv6.block1 == ip.networkipv6.block1 and \
                                ip_test.networkipv6.block2 == ip.networkipv6.block2 and \
                                ip_test.networkipv6.block3 == ip.networkipv6.block3 and \
                                ip_test.networkipv6.block4 == ip.networkipv6.block4 and \
                                ip_test.networkipv6.block5 == ip.networkipv6.block5 and \
                                ip_test.networkipv6.block6 == ip.networkipv6.block6 and \
                                ip_test.networkipv6.block7 == ip.networkipv6.block7 and \
                                ip_test.networkipv6.block8 == ip.networkipv6.block8 and \
                                ip_test.networkipv6.block == ip.networkipv6.block and \
                                ip_test.networkipv6 != ip.networkipv6:

                            # Filter testing
                            if ip_test.networkipv6.vlan.ambiente.filter is None or ip.networkipv6.vlan.ambiente.filter is None:
                                raise IpRangeAlreadyAssociation(
                                    None,
                                    u'Equipment is already associated with another ip with the same ip range.'
                                )
                            else:
                                # Test both environment's filters
                                tp_equip_list_one = list()
                                for fet in FilterEquipType.objects.filter(
                                        filter=ip.networkipv6.vlan.ambiente.
                                        filter.id):
                                    tp_equip_list_one.append(fet.equiptype)

                                tp_equip_list_two = list()
                                for fet in FilterEquipType.objects.filter(
                                        filter=ip_test.networkipv6.vlan.
                                        ambiente.filter.id):
                                    tp_equip_list_two.append(fet.equiptype)

                                if equipment.tipo_equipamento not in tp_equip_list_one or equipment.tipo_equipamento not in tp_equip_list_two:
                                    raise IpRangeAlreadyAssociation(
                                        None,
                                        u'Equipment is already associated with another ip with the same ip range.'
                                    )

                    ## Filter case 2 - end ##

                    # Delete vlan's cache
                    destroy_cache_function([net.vlan_id])
                    ip_equipment.save()

                    # Makes Environment Equipment association
                    try:
                        equipment_environment = EquipamentoAmbiente()
                        equipment_environment.equipamento = equipment
                        equipment_environment.ambiente = net.vlan.ambiente
                        equipment_environment.create(user)

                    except EquipamentoAmbienteDuplicatedError, e:
                        # If already exists, OK !
                        pass

                except IpRangeAlreadyAssociation, e:
                    raise IpRangeAlreadyAssociation(None, e.message)
    def handle_post(self, request, user, *args, **kwargs):
        '''Treat POST requests to run script creation for vlan and networks

        URL: vlan/v4/create/ or vlan/v6/create/
        '''

        try:

            # Generic method for v4 and v6
            network_version = kwargs.get('network_version')

            # Commons Validations

            # User permission
            if not has_perm(user, AdminPermission.VLAN_MANAGEMENT, AdminPermission.WRITE_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                return self.not_authorized()

            # Business Validations

            # Load XML data
            xml_map, attrs_map = loads(request.raw_post_data)

            # XML data format
            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is None:
                msg = u'There is no value to the networkapi tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)
            vlan_map = networkapi_map.get('vlan')
            if vlan_map is None:
                msg = u'There is no value to the vlan tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)

            # Get XML data
            network_ip_id = vlan_map.get('id_network_ip')

            # Valid network_ip ID
            if not is_valid_int_greater_zero_param(network_ip_id):
                self.log.error(
                    u'Parameter id_network_ip is invalid. Value: %s.', network_ip_id)
                raise InvalidValueError(None, 'id_network_ip', network_ip_id)

            # Network must exists in database
            if IP_VERSION.IPv4[0] == network_version:
                network_ip = NetworkIPv4().get_by_pk(network_ip_id)
            else:
                network_ip = NetworkIPv6().get_by_pk(network_ip_id)

            # Vlan must be active if Network is
            if network_ip.active:
                return self.response_error(299)

            # Check permission group equipments
            equips_from_ipv4 = Equipamento.objects.filter(
                ipequipamento__ip__networkipv4__vlan=network_ip.vlan.id, equipamentoambiente__is_router=1)
            equips_from_ipv6 = Equipamento.objects.filter(
                ipv6equipament__ip__networkipv6__vlan=network_ip.vlan.id, equipamentoambiente__is_router=1)
            for equip in equips_from_ipv4:
                # User permission
                if not has_perm(user, AdminPermission.EQUIPMENT_MANAGEMENT, AdminPermission.WRITE_OPERATION, None, equip.id, AdminPermission.EQUIP_WRITE_OPERATION):
                    self.log.error(
                        u'User does not have permission to perform the operation.')
                    return self.not_authorized()
            for equip in equips_from_ipv6:
                # User permission
                if not has_perm(user, AdminPermission.EQUIPMENT_MANAGEMENT, AdminPermission.WRITE_OPERATION, None, equip.id, AdminPermission.EQUIP_WRITE_OPERATION):
                    self.log.error(
                        u'User does not have permission to perform the operation.')
                    return self.not_authorized()

            # Business Rules

            success_map = dict()

            # If Vlan is not active, need to be created before network
            if not network_ip.vlan.ativada:

                # Make command
                vlan_command = VLAN_CREATE % (network_ip.vlan.id)

                # Execute command
                code, stdout, stderr = exec_script(vlan_command)

                if code == 0:

                    # After execute script, change to activated
                    network_ip.vlan.activate(user)

                    vlan_success = dict()
                    vlan_success['codigo'] = '%04d' % code
                    vlan_success['descricao'] = {
                        'stdout': stdout, 'stderr': stderr}

                    success_map['vlan'] = vlan_success

                else:
                    return self.response_error(2, stdout + stderr)

            # Make command to create Network

            if IP_VERSION.IPv4[0] == network_version:
                command = NETWORKIPV4_CREATE % (network_ip.id)
            else:
                command = NETWORKIPV6_CREATE % (network_ip.id)
            # Execute command
            code, stdout, stderr = exec_script(command)

            if code == 0:

                # After execute script, change the Network to activated
                network_ip.activate(user)

                network_success = dict()
                network_success['codigo'] = '%04d' % code
                network_success['descricao'] = {
                    'stdout': stdout, 'stderr': stderr}

                success_map['network'] = network_success

            else:
                return self.response_error(2, stdout + stderr)

            map = dict()
            map['sucesso'] = success_map

            vlan_obj = network_ip.vlan

            # Return XML
            return self.response(dumps_networkapi(map))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
    def network_ipv6_add(self, user, vlan_id, network_type, environment_vip, prefix=None):

        try:
            # Valid vlan ID
            if not is_valid_int_greater_zero_param(vlan_id):
                self.log.error(
                    u'Parameter id_vlan is invalid. Value: %s.', vlan_id)
                raise InvalidValueError(None, 'id_vlan', vlan_id)

            # Network Type

            # Valid network_type ID
            """
            if not is_valid_int_greater_zero_param(network_type):
                self.log.error(
                    u'Parameter id_tipo_rede is invalid. Value: %s.', network_type)
                raise InvalidValueError(None, 'id_tipo_rede', network_type)
            """
            # Find network_type by ID to check if it exist
            net = None
            if network_type:
                net = TipoRede.get_by_pk(network_type)

            # Environment Vip

            if environment_vip is not None:

                # Valid environment_vip ID
                if not is_valid_int_greater_zero_param(environment_vip):
                    self.log.error(
                        u'Parameter id_ambiente_vip is invalid. Value: %s.', environment_vip)
                    raise InvalidValueError(
                        None, 'id_ambiente_vip', environment_vip)

                # Find Environment VIP by ID to check if it exist
                evip = EnvironmentVip.get_by_pk(environment_vip)

            else:
                evip = None

            # Business Rules

            # New NetworkIPv6
            network_ipv6 = NetworkIPv6()
            vlan_map = network_ipv6.add_network_ipv6(
                user, vlan_id, net, evip, prefix)

            list_equip_routers_ambient = EquipamentoAmbiente.get_routers_by_environment(
                vlan_map['vlan']['id_ambiente'])

            if list_equip_routers_ambient:

                # Add Adds the first available ipv6 on all equipment
                # that is configured as a router for the environment related to
                # network
                ipv6 = Ipv6.get_first_available_ip6(
                    vlan_map['vlan']['id_network'])

                ipv6 = str(ipv6).split(':')

                ipv6_model = Ipv6()
                ipv6_model.block1 = ipv6[0]
                ipv6_model.block2 = ipv6[1]
                ipv6_model.block3 = ipv6[2]
                ipv6_model.block4 = ipv6[3]
                ipv6_model.block5 = ipv6[4]
                ipv6_model.block6 = ipv6[5]
                ipv6_model.block7 = ipv6[6]
                ipv6_model.block8 = ipv6[7]
                ipv6_model.networkipv6_id = vlan_map['vlan']['id_network']

                ipv6_model.save()

                if len(list_equip_routers_ambient) > 1:
                    multiple_ips = True
                else:
                    multiple_ips = False

                for equip in list_equip_routers_ambient:

                    Ipv6Equipament().create(
                        user, ipv6_model.id, equip.equipamento.id)

                    if multiple_ips:
                        router_ip = Ipv6.get_first_available_ip6(
                            vlan_map['vlan']['id_network'], True)
                        router_ip = str(router_ip).split(':')
                        ipv6_model2 = Ipv6()
                        ipv6_model2.block1 = router_ip[0]
                        ipv6_model2.block2 = router_ip[1]
                        ipv6_model2.block3 = router_ip[2]
                        ipv6_model2.block4 = router_ip[3]
                        ipv6_model2.block5 = router_ip[4]
                        ipv6_model2.block6 = router_ip[5]
                        ipv6_model2.block7 = router_ip[6]
                        ipv6_model2.block8 = router_ip[7]
                        ipv6_model2.networkipv6_id = vlan_map[
                            'vlan']['id_network']
                        ipv6_model2.save()
                        Ipv6Equipament().create(user, ipv6_model2.id, equip.equipamento.id)

            # Return XML
            return self.response(dumps_networkapi(vlan_map))

        except XMLError, e:
            self.log.error(u'Error reading the XML request.')
            return self.response_error(3, e)
    def handle_post(self, request, user, *args, **kwargs):
        '''Handles POST requests to edit an Network.

        URL: network/edit/
        '''

        self.log.info('Edit an Network')

        try:
            # Load XML data
            xml_map, attrs_map = loads(request.raw_post_data)

            # XML data format
            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is None:
                msg = u'There is no value to the networkapi tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)
            net_map = networkapi_map.get('net')
            if net_map is None:
                msg = u'There is no value to the ip tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)

            # Get XML data
            id_network = net_map.get('id_network')
            ip_type = net_map.get('ip_type')
            id_net_type = net_map.get('id_net_type')
            id_env_vip = net_map.get('id_env_vip')

            # Valid id_network
            if not is_valid_int_greater_zero_param(id_network):
                self.log.error(
                    u'Parameter id_network is invalid. Value: %s.', id_network)
                raise InvalidValueError(None, 'id_network', id_network)

            # Valid ip_type
            if not is_valid_int_param(ip_type):
                self.log.error(
                    u'Parameter ip_type is invalid. Value: %s.', ip_type)
                raise InvalidValueError(None, 'ip_type', ip_type)

            list_choice = [0, 1]
            # Valid ip_type choice
            if int(ip_type) not in list_choice:
                self.log.error(
                    u'Parameter ip_type is invalid. Value: %s.', ip_type)
                raise InvalidValueError(None, 'ip_type', ip_type)

            # Valid id_net_type
            if not is_valid_int_greater_zero_param(id_net_type):
                self.log.error(
                    u'Parameter id_net_type is invalid. Value: %s.', id_net_type)
                raise InvalidValueError(None, 'id_net_type', id_net_type)

            # Valid id_env_vip
            if id_env_vip is not None:
                if not is_valid_int_greater_zero_param(id_env_vip):
                    self.log.error(
                        u'Parameter id_env_vip is invalid. Value: %s.', id_env_vip)
                    raise InvalidValueError(None, 'id_env_vip', id_env_vip)

            # User permission
            if not has_perm(user, AdminPermission.VLAN_MANAGEMENT, AdminPermission.WRITE_OPERATION):
                raise UserNotAuthorizedError(
                    None, u'User does not have permission to perform the operation.')

            # Business Rules

            if (id_env_vip is not None):
                id_env_vip = EnvironmentVip.get_by_pk(id_env_vip)
            id_net_type = TipoRede.get_by_pk(id_net_type)

            # New network_tyoe

            # EDIT NETWORK IP4
            if int(ip_type) == 0:
                net = NetworkIPv4.get_by_pk(id_network)

                with distributedlock(LOCK_NETWORK_IPV4 % id_network):

                    if id_env_vip is not None:

                        if net.ambient_vip is None or net.ambient_vip.id != id_env_vip.id:

                            network = IPNetwork(
                                '%d.%d.%d.%d/%d' % (net.oct1, net.oct2, net.oct3, net.oct4, net.block))

                            # Find all networks related to environment vip
                            nets = NetworkIPv4.objects.select_related().filter(
                                ambient_vip__id=id_env_vip.id)

                            # Cast to API class
                            networks = set([IPv4Network(
                                '%d.%d.%d.%d/%d' % (net_ip.oct1, net_ip.oct2, net_ip.oct3, net_ip.oct4, net_ip.block)) for net_ip in nets])

                            # If there is already a network with the same ip
                            # range as related the environment vip
                            if network in networks:
                                raise NetworkIpAddressNotAvailableError(
                                    None, u'Unavailable address to create a NetworkIPv4.')

                    net.edit_network_ipv4(user, id_net_type, id_env_vip)

            # EDIT NETWORK IP6
            else:
                net = NetworkIPv6.get_by_pk(id_network)

                with distributedlock(LOCK_NETWORK_IPV6 % id_network):

                    if id_env_vip is not None:

                        if net.ambient_vip is None or net.ambient_vip.id != id_env_vip.id:

                            network = IPNetwork('%s:%s:%s:%s:%s:%s:%s:%s/%d' % (
                                net.block1, net.block2, net.block3, net.block4, net.block5, net.block6, net.block7, net.block8, net.block))

                            # Find all networks related to environment vip
                            nets = NetworkIPv6.objects.select_related().filter(
                                ambient_vip__id=id_env_vip.id)

                            # Cast to API class
                            networks = set([IPv6Network('%s:%s:%s:%s:%s:%s:%s:%s/%d' % (net_ip.block1, net_ip.block2, net_ip.block3,
                                                                                        net_ip.block4, net_ip.block5, net_ip.block6, net_ip.block7, net_ip.block8, net_ip.block)) for net_ip in nets])

                            # If there is already a network with the same
                            # range ip as related the environment  vip
                            if net in networks:
                                raise NetworkIpAddressNotAvailableError(
                                    None, u'Unavailable address to create a NetworkIPv6.')

                    net.edit_network_ipv6(user, id_net_type, id_env_vip)

            # Delete vlan's cache
            # destroy_cache_function()

            return self.response(dumps_networkapi({}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
    def handle_post(self, request, user, *args, **kwargs):
        """Treat POST requests to add new Network

        URL: network/add/
        """

        try:

            # Commons Validations

            # User permission
            if not has_perm(user, AdminPermission.VLAN_MANAGEMENT,
                            AdminPermission.WRITE_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                return self.not_authorized()

            # Business Validations

            # Load XML data
            xml_map, attrs_map = loads(request.raw_post_data)

            # XML data format
            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is None:
                msg = u'There is no value to the networkapi tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)
            network_map = networkapi_map.get('network')
            if network_map is None:
                msg = u'There is no value to the vlan tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)

            # Get XML data
            network = network_map.get('network')
            id_vlan = network_map.get('id_vlan')
            network_type = network_map.get('id_network_type')
            environment_vip = network_map.get('id_environment_vip')
            cluster_unit = network_map.get('cluster_unit')

            # Valid Network
            try:
                net = IPNetwork(network)
            except ValueError, e:
                raise InvalidValueError(None, 'network', network)

            # VLAN

            # Valid vlan ID
            if not is_valid_int_greater_zero_param(id_vlan):
                raise InvalidValueError(None, 'id_vlan', id_vlan)

            # Find vlan by ID to check if it exist
            vlan = Vlan().get_by_pk(id_vlan)

            # Network Type

            # Valid network_type ID
            if not is_valid_int_greater_zero_param(network_type):
                raise InvalidValueError(None, 'id_network_type', network_type)

            # Find network_type by ID to check if it exist
            net_type = TipoRede.get_by_pk(network_type)

            # Environment Vip

            if environment_vip is not None:

                # Valid environment_vip ID
                if not is_valid_int_greater_zero_param(environment_vip):
                    raise InvalidValueError(None, 'id_environment_vip',
                                            environment_vip)

                evips = EnvironmentVip.objects.all()

                evip_list = EnvironmentVip.available_evips(
                    EnvironmentVip(), evips, int(id_vlan))

                # Check if the chose environment is in the same environment
                if any(
                        int(environment_vip) == item['id']
                        for item in evip_list):
                    # Find Environment VIP by ID to check if it exist
                    env_vip = EnvironmentVip.get_by_pk(environment_vip)
                else:
                    raise InvalidValueError(None, 'id_environment_vip',
                                            environment_vip)

            else:
                env_vip = None

            # Check unchecked exception
            blocks, network, version = break_network(network)

            expl = split(net.network.exploded,
                         '.' if version == IP_VERSION.IPv4[0] else ':')
            expl.append(str(net.prefixlen))

            if blocks != expl:
                raise InvalidValueError(None, 'rede', network)

            # Business Rules

            if version == IP_VERSION.IPv4[0]:

                # Find all networks related to environment
                nets = NetworkIPv4.objects.filter(
                    vlan__ambiente__id=vlan.ambiente.id)

                # Cast to API class
                networks = set([
                    IPv4Network('%d.%d.%d.%d/%d' %
                                (net_ip.oct1, net_ip.oct2, net_ip.oct3,
                                 net_ip.oct4, net_ip.block)) for net_ip in nets
                ])

                # If network selected not in use
                for network_aux in networks:
                    if net in network_aux or network_aux in net:
                        self.log.debug(
                            'Network %s cannot be allocated. It conflicts with %s already in use in this environment.'
                            % (net, network))
                        raise NetworkIPv4AddressNotAvailableError(
                            None,
                            u'Network cannot be allocated. %s already in use in this environment.'
                            % network_aux)

                if env_vip is not None:

                    # Find all networks related to environment vip
                    nets = NetworkIPv4.objects.filter(
                        ambient_vip__id=env_vip.id)

                    # Cast to API class
                    networks = set([
                        IPv4Network('%d.%d.%d.%d/%d' %
                                    (net_ip.oct1, net_ip.oct2, net_ip.oct3,
                                     net_ip.oct4, net_ip.block))
                        for net_ip in nets
                    ])

                    # If there is already a network with the same  range ip as
                    # related the environment  vip
                    for network_aux in networks:
                        if net in network_aux or network_aux in net:
                            self.log.debug(
                                'Network %s cannot be allocated. It conflicts with %s already in use in this environment VIP.'
                                % (net, network))
                            raise NetworkIPv4AddressNotAvailableError(
                                None,
                                u'Network cannot be allocated. %s already in use in this environment VIP.'
                                % network_aux)

                # # Filter case 1 - Adding new network with same ip range to another network on other environment ##
                # Get environments with networks with the same ip range
                nets = NetworkIPv4.objects.filter(oct1=expl[0],
                                                  oct2=expl[1],
                                                  oct3=expl[2],
                                                  oct4=expl[3],
                                                  block=expl[4])
                env_ids = list()
                for net_ip in nets:
                    env_ids.append(net_ip.vlan.ambiente.id)

                # If other network with same ip range exists
                if len(env_ids) > 0:

                    # Get equipments related to this network's environment
                    env_equips = EquipamentoAmbiente.objects.filter(
                        ambiente=vlan.ambiente.id)

                    # Verify equipments related with all other environments
                    # that contains networks with same ip range
                    for env_id in env_ids:
                        # Equipments related to other environments
                        other_env_equips = EquipamentoAmbiente.objects.filter(
                            ambiente=env_id)
                        # Adjust to equipments
                        equip_list = list()
                        for equip_env in other_env_equips:
                            equip_list.append(equip_env.equipamento.id)

                        for env_equip in env_equips:
                            if env_equip.equipamento.id in equip_list:

                                # Filter testing
                                if other_env_equips[
                                        0].ambiente.filter is None or vlan.ambiente.filter is None:
                                    raise NetworkIPRangeEnvError(
                                        None,
                                        u'Um dos equipamentos associados com o ambiente desta rede também está associado com outro ambiente que tem uma rede com essa mesma faixa, adicione filtros nos ambientes se necessário.'
                                    )
                                else:
                                    # Test both environment's filters
                                    tp_equip_list_one = list()
                                    for fet in FilterEquipType.objects.filter(
                                            filter=vlan.ambiente.filter.id):
                                        tp_equip_list_one.append(fet.equiptype)

                                    tp_equip_list_two = list()
                                    for fet in FilterEquipType.objects.filter(
                                            filter=other_env_equips[0].
                                            ambiente.filter.id):
                                        tp_equip_list_two.append(fet.equiptype)

                                    if env_equip.equipamento.tipo_equipamento not in tp_equip_list_one or env_equip.equipamento.tipo_equipamento not in tp_equip_list_two:
                                        raise NetworkIPRangeEnvError(
                                            None,
                                            u'Um dos equipamentos associados com o ambiente desta rede também está associado com outro ambiente que tem uma rede com essa mesma faixa, adicione filtros nos ambientes se necessário.'
                                        )

                # # Filter case 1 - end ##

                # New NetworkIPv4
                network_ip = NetworkIPv4()

                # Set octs by network generated
                network_ip.oct1, network_ip.oct2, network_ip.oct3, network_ip.oct4 = str(
                    net.network).split('.')
                # Set block by network generated
                network_ip.block = net.prefixlen
                # Set mask by network generated
                network_ip.mask_oct1, network_ip.mask_oct2, network_ip.mask_oct3, network_ip.mask_oct4 = str(
                    net.netmask).split('.')
                # Set broadcast by network generated
                network_ip.broadcast = net.broadcast.compressed

            else:
                # Find all networks ralated to environment
                nets = NetworkIPv6.objects.filter(
                    vlan__ambiente__id=vlan.ambiente.id)

                # Cast to API class
                networks = set([
                    IPv6Network('%s:%s:%s:%s:%s:%s:%s:%s/%d' %
                                (net_ip.block1, net_ip.block2, net_ip.block3,
                                 net_ip.block4, net_ip.block5, net_ip.block6,
                                 net_ip.block7, net_ip.block8, net_ip.block))
                    for net_ip in nets
                ])

                # If network selected not in use
                for network_aux in networks:
                    if net in network_aux or network_aux in net:
                        self.log.debug(
                            'Network %s cannot be allocated. It conflicts with %s already in use in this environment.'
                            % (net, network))
                        raise NetworkIPv4AddressNotAvailableError(
                            None,
                            u'Network cannot be allocated. %s already in use in this environment.'
                            % network_aux)

                if env_vip is not None:

                    # Find all networks related to environment vip
                    nets = NetworkIPv6.objects.filter(
                        ambient_vip__id=env_vip.id)

                    # Cast to API class
                    networks = set([
                        IPv6Network(
                            '%s:%s:%s:%s:%s:%s:%s:%s/%d' %
                            (net_ip.block1, net_ip.block2, net_ip.block3,
                             net_ip.block4, net_ip.block5, net_ip.block6,
                             net_ip.block7, net_ip.block8, net_ip.block))
                        for net_ip in nets
                    ])

                    # If there is already a network with the same  range ip as
                    # related the environment  vip
                    for network_aux in networks:
                        if net in network_aux or network_aux in net:
                            self.log.debug(
                                'Network %s cannot be allocated. It conflicts with %s already in use in this environment VIP.'
                                % (net, network))
                            raise NetworkIPv4AddressNotAvailableError(
                                None,
                                u'Network cannot be allocated. %s already in use in this environment VIP.'
                                % network_aux)

                # # Filter case 1 - Adding new network with same ip range to another network on other environment ##
                # Get environments with networks with the same ip range
                nets = NetworkIPv6.objects.filter(block1=expl[0],
                                                  block2=expl[1],
                                                  block3=expl[2],
                                                  block4=expl[3],
                                                  block5=expl[4],
                                                  block6=expl[5],
                                                  block7=expl[6],
                                                  block8=expl[7],
                                                  block=expl[8])
                env_ids = list()
                for net_ip in nets:
                    env_ids.append(net_ip.vlan.ambiente.id)

                # If other network with same ip range exists
                if len(env_ids) > 0:

                    # Get equipments related to this network's environment
                    env_equips = EquipamentoAmbiente.objects.filter(
                        ambiente=vlan.ambiente.id)

                    # Verify equipments related with all other environments
                    # that contains networks with same ip range
                    for env_id in env_ids:
                        # Equipments related to other environments
                        other_env_equips = EquipamentoAmbiente.objects.filter(
                            ambiente=env_id)
                        # Adjust to equipments
                        equip_list = list()
                        for equip_env in other_env_equips:
                            equip_list.append(equip_env.equipamento.id)

                        for env_equip in env_equips:
                            if env_equip.equipamento.id in equip_list:

                                # Filter testing
                                if other_env_equips[
                                        0].ambiente.filter is None or vlan.ambiente.filter is None:
                                    raise NetworkIPRangeEnvError(
                                        None,
                                        u'Um dos equipamentos associados com o ambiente desta rede também está associado com outro ambiente que tem uma rede com essa mesma faixa, adicione filtros nos ambientes se necessário.'
                                    )
                                else:
                                    # Test both environment's filters
                                    tp_equip_list_one = list()
                                    for fet in FilterEquipType.objects.filter(
                                            filter=vlan.ambiente.filter.id):
                                        tp_equip_list_one.append(fet.equiptype)

                                    tp_equip_list_two = list()
                                    for fet in FilterEquipType.objects.filter(
                                            filter=other_env_equips[0].
                                            ambiente.filter.id):
                                        tp_equip_list_two.append(fet.equiptype)

                                    if env_equip.equipamento.tipo_equipamento not in tp_equip_list_one or env_equip.equipamento.tipo_equipamento not in tp_equip_list_two:
                                        raise NetworkIPRangeEnvError(
                                            None,
                                            u'Um dos equipamentos associados com o ambiente desta rede também está associado com outro ambiente que tem uma rede com essa mesma faixa, adicione filtros nos ambientes se necessário.'
                                        )

                # # Filter case 1 - end ##

                # New NetworkIPv6
                network_ip = NetworkIPv6()

                # Set block by network generated
                network_ip.block1, network_ip.block2, network_ip.block3, network_ip.block4, network_ip.block5, network_ip.block6, network_ip.block7, network_ip.block8 = str(
                    net.network.exploded).split(':')
                # Set block by network generated
                network_ip.block = net.prefixlen
                # Set mask by network generated
                network_ip.mask1, network_ip.mask2, network_ip.mask3, network_ip.mask4, network_ip.mask5, network_ip.mask6, network_ip.mask7, network_ip.mask8 = str(
                    net.netmask.exploded).split(':')

            # Get all vlans environments from equipments of the current
            # environment
            ambiente = vlan.ambiente

            equips = list()
            envs = list()

            # equips = all equipments from the environment which this network
            # is about to be allocated on
            for env in ambiente.equipamentoambiente_set.all():
                equips.append(env.equipamento)

            # envs = all environments from all equips above
            # This will be used to test all networks from the environments.
            for equip in equips:
                for env in equip.equipamentoambiente_set.all():
                    if env.ambiente not in envs:
                        envs.append(env.ambiente)

            network_ip_verify = IPNetwork(network)
            # For all vlans in all common environments,
            # check if any network is a subnetwork or supernetwork
            # of the desired network network_ip_verify
            for env in envs:
                for vlan_obj in env.vlan_set.all():
                    is_subnet = verify_subnet(vlan_obj, network_ip_verify,
                                              version)

                    if is_subnet:
                        if vlan_obj.ambiente == ambiente:
                            raise NetworkIPRangeEnvError(None)

                        if ambiente.filter_id is None or vlan_obj.ambiente.filter_id is None or int(
                                vlan_obj.ambiente.filter_id) != int(
                                    ambiente.filter_id):
                            raise NetworkIPRangeEnvError(None)

            # Set Vlan
            network_ip.vlan = vlan

            # Set Network Type
            network_ip.network_type = net_type

            # Set Environment VIP
            network_ip.ambient_vip = env_vip

            # Set Cluster Unit
            network_ip.cluster_unit = cluster_unit

            # Persist
            try:

                # Delete vlan's cache
                destroy_cache_function([id_vlan])
                network_ip.save()

                list_equip_routers_ambient = EquipamentoAmbiente.objects.filter(
                    ambiente=network_ip.vlan.ambiente.id, is_router=True)

                if list_equip_routers_ambient:

                    if version == IP_VERSION.IPv4[0]:

                        if network_ip.block < 31:

                            # Add Adds the first available ipv4 on all equipment
                            # that is configured as a router for the environment
                            # related to network
                            ip = Ip.get_first_available_ip(network_ip.id)

                            ip = str(ip).split('.')

                            ip_model = Ip()
                            ip_model.oct1 = ip[0]
                            ip_model.oct2 = ip[1]
                            ip_model.oct3 = ip[2]
                            ip_model.oct4 = ip[3]
                            ip_model.networkipv4_id = network_ip.id

                            ip_model.save()

                            if len(list_equip_routers_ambient
                                   ) > 1 and network_ip.block < 30:
                                multiple_ips = True
                            else:
                                multiple_ips = False

                            for equip in list_equip_routers_ambient:
                                IpEquipamento().create(user, ip_model.id,
                                                       equip.equipamento.id)

                                if multiple_ips:
                                    router_ip = Ip.get_first_available_ip(
                                        network_ip.id, True)
                                    router_ip = str(router_ip).split('.')
                                    ip_model2 = Ip()
                                    ip_model2.oct1 = router_ip[0]
                                    ip_model2.oct2 = router_ip[1]
                                    ip_model2.oct3 = router_ip[2]
                                    ip_model2.oct4 = router_ip[3]
                                    ip_model2.networkipv4_id = network_ip.id
                                    ip_model2.save(user)
                                    IpEquipamento().create(
                                        user, ip_model2.id,
                                        equip.equipamento.id)

                    else:
                        if network_ip.block < 127:

                            # Add Adds the first available ipv6 on all equipment
                            # that is configured as a router for the environment
                            # related to network
                            ipv6 = Ipv6.get_first_available_ip6(network_ip.id)

                            ipv6 = str(ipv6).split(':')

                            ipv6_model = Ipv6()
                            ipv6_model.block1 = ipv6[0]
                            ipv6_model.block2 = ipv6[1]
                            ipv6_model.block3 = ipv6[2]
                            ipv6_model.block4 = ipv6[3]
                            ipv6_model.block5 = ipv6[4]
                            ipv6_model.block6 = ipv6[5]
                            ipv6_model.block7 = ipv6[6]
                            ipv6_model.block8 = ipv6[7]
                            ipv6_model.networkipv6_id = network_ip.id

                            ipv6_model.save()

                            if len(list_equip_routers_ambient
                                   ) > 1 and network_ip.block < 126:
                                multiple_ips = True
                            else:
                                multiple_ips = False

                            for equip in list_equip_routers_ambient:
                                Ipv6Equipament().create(
                                    user, ipv6_model.id, equip.equipamento.id)

                                if multiple_ips:
                                    router_ip = Ipv6.get_first_available_ip6(
                                        network_ip.id, True)
                                    router_ip = str(router_ip).split(':')
                                    ipv6_model2 = Ipv6()
                                    ipv6_model2.block1 = router_ip[0]
                                    ipv6_model2.block2 = router_ip[1]
                                    ipv6_model2.block3 = router_ip[2]
                                    ipv6_model2.block4 = router_ip[3]
                                    ipv6_model2.block5 = router_ip[4]
                                    ipv6_model2.block6 = router_ip[5]
                                    ipv6_model2.block7 = router_ip[6]
                                    ipv6_model2.block8 = router_ip[7]
                                    ipv6_model2.networkipv6_id = network_ip.id
                                    ipv6_model2.save(user)
                                    Ipv6Equipament().create(
                                        user, ipv6_model2.id,
                                        equip.equipamento.id)

            except Exception, e:
                raise IpError(e, u'Error persisting Network.')
Ejemplo n.º 30
0
    def handle_delete(self, request, user, *args, **kwargs):
        '''Handles DELETE requests to deallocate all relationships between NetworkIPv6.

        URL: network/ipv6/<id_ipv6>/deallocate/
        '''

        self.log.info("Deallocate all relationships between NetworkIPv6.")

        try:

            # Commons Validations

            # User permission
            if not has_perm(user, AdminPermission.VLAN_MANAGEMENT,
                            AdminPermission.WRITE_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                return self.not_authorized()

            # Business Validations

            # Load URL param
            network_ipv6_id = kwargs.get('id_network_ipv6')

            # Valid NetworkIpv6 ID
            if not is_valid_int_greater_zero_param(network_ipv6_id):
                self.log.error(
                    u'Parameter id_network_ipv6 is invalid. Value: %s.',
                    network_ipv6_id)
                raise InvalidValueError(None, 'id_network_ipv6',
                                        network_ipv6_id)

            # Existing NetworkIpv6 ID
            network_ipv6 = NetworkIPv6().get_by_pk(network_ipv6_id)

            for ip in network_ipv6.ipv6_set.all():

                server_pool_member_list = ServerPoolMember.objects.filter(
                    ipv6=ip)

                if server_pool_member_list.count() != 0:

                    # IP associated with Server Pool
                    server_pool_name_list = set()

                    for member in server_pool_member_list:
                        item = '{}: {}'.format(member.server_pool.id,
                                               member.server_pool.identifier)
                        server_pool_name_list.add(item)

                    server_pool_name_list = list(server_pool_name_list)
                    server_pool_identifiers = ', '.join(server_pool_name_list)

                    ip_formated = mount_ipv6_string(ip)
                    network_ipv6_ip = mount_ipv6_string(network_ipv6)

                    raise IpCantRemoveFromServerPool(
                        {
                            'ip': ip_formated,
                            'network_ipv6_ip': network_ipv6_ip,
                            'server_pool_identifiers': server_pool_identifiers
                        },
                        "Não foi possível excluir a rede de id %s pois o ip %s contido nela esta sendo usado nos Server Pools (id:identifier) %s"
                        % (network_ipv6_ip, ip_formated,
                           server_pool_identifiers))

            with distributedlock(LOCK_NETWORK_IPV6 % network_ipv6_id):

                destroy_cache_function([network_ipv6.vlan_id])
                key_list_eqs = Equipamento.objects.filter(
                    ipv6equipament__ip__networkipv6=network_ipv6).values_list(
                        'id', flat=True)
                destroy_cache_function(key_list_eqs, True)
                # Remove NetworkIPv6 (will remove all relationships by cascade)
                network_ipv6.delete()

                # Return nothing
                return self.response(dumps_networkapi({}))

        except IpCantRemoveFromServerPool, e:
            return self.response_error(386, e.cause.get('network_ipv6_ip'),
                                       e.cause.get('ip'),
                                       e.cause.get('server_pool_identifiers'))
Ejemplo n.º 31
0
    def handle_post(self, request, user, *args, **kwargs):
        """Handles POST requests to edit an Network.

        URL: network/edit/
        """

        self.log.info('Edit an Network')

        try:
            # Load XML data
            xml_map, attrs_map = loads(request.raw_post_data)

            # XML data format
            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is None:
                msg = u'There is no value to the networkapi tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)
            net_map = networkapi_map.get('net')
            if net_map is None:
                msg = u'There is no value to the ip tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)

            # Get XML data
            id_network = net_map.get('id_network')
            ip_type = net_map.get('ip_type')
            id_net_type = net_map.get('id_net_type')
            id_env_vip = net_map.get('id_env_vip')
            cluster_unit = net_map.get('cluster_unit')

            # Valid id_network
            if not is_valid_int_greater_zero_param(id_network):
                self.log.error(
                    u'Parameter id_network is invalid. Value: %s.', id_network)
                raise InvalidValueError(None, 'id_network', id_network)

            # Valid ip_type
            if not is_valid_int_param(ip_type):
                self.log.error(
                    u'Parameter ip_type is invalid. Value: %s.', ip_type)
                raise InvalidValueError(None, 'ip_type', ip_type)

            list_choice = [0, 1]
            # Valid ip_type choice
            if int(ip_type) not in list_choice:
                self.log.error(
                    u'Parameter ip_type is invalid. Value: %s.', ip_type)
                raise InvalidValueError(None, 'ip_type', ip_type)

            # Valid id_net_type
            if not is_valid_int_greater_zero_param(id_net_type):
                self.log.error(
                    u'Parameter id_net_type is invalid. Value: %s.', id_net_type)
                raise InvalidValueError(None, 'id_net_type', id_net_type)

            # Valid id_env_vip
            if id_env_vip is not None:
                if not is_valid_int_greater_zero_param(id_env_vip):
                    self.log.error(
                        u'Parameter id_env_vip is invalid. Value: %s.', id_env_vip)
                    raise InvalidValueError(None, 'id_env_vip', id_env_vip)

            # User permission
            if not has_perm(user, AdminPermission.VLAN_MANAGEMENT, AdminPermission.WRITE_OPERATION):
                raise UserNotAuthorizedError(
                    None, u'User does not have permission to perform the operation.')

            # Business Rules

            if (id_env_vip is not None):
                id_env_vip = EnvironmentVip.get_by_pk(id_env_vip)
            id_net_type = TipoRede.get_by_pk(id_net_type)

            # New network_tyoe

            # EDIT NETWORK IP4
            if int(ip_type) == 0:
                net = NetworkIPv4.get_by_pk(id_network)

                with distributedlock(LOCK_NETWORK_IPV4 % id_network):

                    if id_env_vip is not None:

                        if net.ambient_vip is None or net.ambient_vip.id != id_env_vip.id:

                            network = IPNetwork(
                                '%d.%d.%d.%d/%d' % (net.oct1, net.oct2, net.oct3, net.oct4, net.block))

                            # Find all networks related to environment vip
                            nets = NetworkIPv4.objects.filter(
                                ambient_vip__id=id_env_vip.id)

                            # Cast to API class
                            networks = set([IPv4Network(
                                '%d.%d.%d.%d/%d' % (net_ip.oct1, net_ip.oct2, net_ip.oct3, net_ip.oct4, net_ip.block)) for net_ip in nets])

                            # If there is already a network with the same ip
                            # range as related the environment vip
                            if network in networks:
                                raise NetworkIpAddressNotAvailableError(
                                    None, u'Unavailable address to create a NetworkIPv4.')

                    net.edit_network_ipv4(
                        user, id_net_type, id_env_vip, cluster_unit)

            # EDIT NETWORK IP6
            else:
                net = NetworkIPv6.get_by_pk(id_network)

                with distributedlock(LOCK_NETWORK_IPV6 % id_network):

                    if id_env_vip is not None:

                        if net.ambient_vip is None or net.ambient_vip.id != id_env_vip.id:

                            network = IPNetwork('%s:%s:%s:%s:%s:%s:%s:%s/%d' % (
                                net.block1, net.block2, net.block3, net.block4, net.block5, net.block6, net.block7, net.block8, net.block))

                            # Find all networks related to environment vip
                            nets = NetworkIPv6.objects.filter(
                                ambient_vip__id=id_env_vip.id)

                            # Cast to API class
                            networks = set([IPv6Network('%s:%s:%s:%s:%s:%s:%s:%s/%d' % (net_ip.block1, net_ip.block2, net_ip.block3,
                                                                                        net_ip.block4, net_ip.block5, net_ip.block6, net_ip.block7, net_ip.block8, net_ip.block)) for net_ip in nets])

                            # If there is already a network with the same
                            # range ip as related the environment  vip
                            if net in networks:
                                raise NetworkIpAddressNotAvailableError(
                                    None, u'Unavailable address to create a NetworkIPv6.')

                    net.edit_network_ipv6(user, id_net_type, id_env_vip)

            # Delete vlan's cache
            # destroy_cache_function()

            return self.response(dumps_networkapi({}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
Ejemplo n.º 32
0
def networkIPv6_deploy(request, network_id):
    """Deploy network L3 configuration in the environment routers for network ipv6

    Receives optional parameter equipments to specify what equipment should
    receive network configuration
    """

    networkipv6 = NetworkIPv6.get_by_pk(int(network_id))
    environment = networkipv6.vlan.ambiente
    equipments_id_list = None
    if request.DATA is not None:
        equipments_id_list = request.DATA.get('equipments', None)

    equipment_list = []

    if equipments_id_list is not None:
        if type(equipments_id_list) is not list:
            raise api_exceptions.ValidationException('equipments')

        for equip in equipments_id_list:
            try:
                int(equip)
            except ValueError:
                raise api_exceptions.ValidationException('equipments')

        # Check that equipments received as parameters are in correct vlan
        # environment
        equipment_list = Equipamento.objects.filter(
            equipamentoambiente__ambiente=environment,
            id__in=equipments_id_list)
        log.info('list = %s' % equipment_list)
        if len(equipment_list) != len(equipments_id_list):
            log.error(
                'Error: equipments %s are not part of network environment.' %
                equipments_id_list)
            raise exceptions.EquipmentIDNotInCorrectEnvException()
    else:
        # TODO GET network routers
        equipment_list = Equipamento.objects.filter(
            ipv6equipament__ip__networkipv6=networkipv6,
            equipamentoambiente__ambiente=networkipv6.vlan.ambiente,
            equipamentoambiente__is_router=1).distinct()
        if len(equipment_list) == 0:
            raise exceptions.NoEnvironmentRoutersFoundException()

    # Check permission to configure equipments
    for equip in equipment_list:
        # User permission
        if not has_perm(request.user, AdminPermission.EQUIPMENT_MANAGEMENT,
                        AdminPermission.WRITE_OPERATION, None, equip.id,
                        AdminPermission.EQUIP_WRITE_OPERATION):
            log.error(
                u'User does not have permission to perform the operation.')
            raise PermissionDenied(
                'No permission to configure equipment %s-%s' %
                (equip.id, equip.nome))

    if all_equipments_are_in_maintenance(equipment_list):
        raise AllEquipmentsAreInMaintenanceException()

    try:
        # deploy network configuration
        if request.method == 'POST':
            returned_data = facade.deploy_networkIPv6_configuration(
                request.user, networkipv6, equipment_list)
        elif request.method == 'DELETE':
            returned_data = facade.remove_deploy_networkIPv6_configuration(
                request.user, networkipv6, equipment_list)

        return Response(returned_data)

    except Exception, exception:
        log.error(exception)
        raise api_exceptions.NetworkAPIException()