예제 #1
0
def create_vlan(vlan, user):
    """Create vlan"""
    vlan_obj = Vlan()

    vlan_obj.create_v3(vlan)

    return vlan_obj
예제 #2
0
def create_vlan(vlan, user):
    """Create vlan."""

    try:
        vlan_obj = Vlan()
        vlan_obj.create_v3(vlan, user)
    except ObjectDoesNotExistException, e:
        raise ObjectDoesNotExistException(str(e))
def remover_vlan_so(user, rack):

    nome = "OOB_SO_"+rack.nome

    vlan = Vlan()
    try:
        vlan = vlan.get_by_name(nome)
        vlan.delete()
    except:
        pass
def remover_vlan_so(user, rack):

    nome = 'OOB_SO_' + rack.nome

    vlan = Vlan()
    try:
        vlan = vlan.get_by_name(nome)
        vlan.delete()
    except:
        pass
예제 #5
0
    def create_vlan(self, user, vlan_id):

        if not has_perm(user, AdminPermission.VLAN_MANAGEMENT, AdminPermission.WRITE_OPERATION):
            return self.not_authorized()

        vlan = Vlan().get_by_pk(vlan_id)

        # Check permission group equipments
        equips_from_ipv4 = Equipamento.objects.filter(
            ipequipamento__ip__networkipv4__vlan=vlan_id, equipamentoambiente__is_router=1)
        equips_from_ipv6 = Equipamento.objects.filter(
            ipv6equipament__ip__networkipv6__vlan=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()

        if vlan.ativada:
            return self.response_error(122)

        command = settings.VLAN_CREATE % (vlan.id)

        code, stdout, stderr = exec_script(command)
        if code == 0:
            vlan.activate(user)

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

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

            # Send to Queue
            queue_manager = QueueManager()

            serializer = VlanSerializer(vlan)
            data_to_queue = serializer.data
            data_to_queue.update({'description': queue_keys.VLAN_CREATE})
            queue_manager.append({'action': queue_keys.VLAN_CREATE,'kind': queue_keys.VLAN_KEY,'data': data_to_queue})

            queue_manager.send()

            return self.response(dumps_networkapi(map))
        else:
            return self.response_error(2, stdout + stderr)
    def handle_put(self, request, user, *args, **kwargs):
        """Treat PUT requests to Validate a vlan

        URL: vlan/<id_vlan>/validate/<network>
        """

        try:

            id_vlan = kwargs.get('id_vlan')

            network = kwargs.get('network')

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

            # Valid Vlan ID
            if not is_valid_int_greater_zero_param(id_vlan):
                self.log.error(
                    u'The id_vlan parameter is not a valid value: %s.', id_vlan)
                raise InvalidValueError(None, 'vlan_id', id_vlan)

            # Valid Network
            if not is_valid_version_ip(network, IP_VERSION):
                self.log.error(
                    u'The network parameter is not a valid value: %s.', network)
                raise InvalidValueError(None, 'network', network)

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

            with distributedlock(LOCK_VLAN % id_vlan):

                # Set Values
                if network == IP_VERSION.IPv4[0]:
                    vlan.acl_valida = 1

                else:
                    vlan.acl_valida_v6 = 1

                vlan.save()

                return self.response(dumps_networkapi({}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
예제 #7
0
def get_vlan_by_id(vlan_id):
    """Get vlan by id."""

    try:
        vlan = Vlan().get_by_pk(vlan_id)
    except VlanNotFoundError, e:
        raise ObjectDoesNotExistException(str(e))
    def setUp(self):
        self.user = Usuario()
        self.vlan = Vlan(id=1, ambiente=Ambiente(id=1))
        self.network_type = TipoRede(id=1)
        self.vip_env = EnvironmentVip(id=1)
        self.network = NetworkIPv4(oct1=10, oct2=126, oct3=1, oct4=0, block=24)

        self.mock_distributed_lock()
        self.mock_transaction()
예제 #9
0
    def create_vlan(self, user, vlan_id):

        if not has_perm(user, AdminPermission.VLAN_MANAGEMENT, AdminPermission.WRITE_OPERATION):
            return self.not_authorized()

        vlan = Vlan().get_by_pk(vlan_id)

        # Check permission group equipments
        equips_from_ipv4 = Equipamento.objects.filter(
            ipequipamento__ip__networkipv4__vlan=vlan_id, equipamentoambiente__is_router=1)
        equips_from_ipv6 = Equipamento.objects.filter(
            ipv6equipament__ip__networkipv6__vlan=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()

        if vlan.ativada:
            return self.response_error(122)

        command = settings.VLAN_CREATE % (vlan.id)

        code, stdout, stderr = exec_script(command)
        if code == 0:
            vlan.activate(user)

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

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

            return self.response(dumps_networkapi(map))
        else:
            return self.response_error(2, stdout + stderr)
예제 #10
0
    def handle_put(self, request, user, *args, **kwargs):
        '''Treat PUT requests to Invalidate a vlan 

        URL: vlan/<id_vlan>/invalidate/<network>
        '''

        try:

            id_vlan = kwargs.get('id_vlan')

            network = kwargs.get('network')

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

            # Valid Vlan ID
            if not is_valid_int_greater_zero_param(id_vlan):
                self.log.error(
                    u'The id_vlan parameter is not a valid value: %s.',
                    id_vlan)
                raise InvalidValueError(None, 'vlan_id', id_vlan)

            # Valid Network
            if not is_valid_version_ip(network, IP_VERSION):
                self.log.error(
                    u'The network parameter is not a valid value: %s.',
                    network)
                raise InvalidValueError(None, 'network', network)

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

            with distributedlock(LOCK_VLAN % id_vlan):

                # Set Values
                if network == IP_VERSION.IPv4[0]:
                    vlan.acl_valida = 0
                    vlan.acl_file_name = None

                else:
                    vlan.acl_valida_v6 = 0
                    vlan.acl_file_name_v6 = None

                vlan.save()

                return self.response(dumps_networkapi({}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
예제 #11
0
    def handle_get(self, request, user, *args, **kwargs):
        """Handles GET requests to search VLAN by ID.
        Network IPv4/IPv6 related will also be fetched.

        URLs: /vlan/<id_vlan>/network/
        """

        self.log.info('Search VLAN by ID')

        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

            # Load URL param
            vlan_id = kwargs.get('id_vlan')

            # 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)

            # Existing VLAN ID
            vlan = Vlan().get_by_pk(vlan_id)

            # Get all network_ipv4/ipv6 related to vlan
            try:
                network_ipv4 = NetworkIPv4.objects.filter(
                    vlan=vlan).order_by('id')
                network_ipv6 = NetworkIPv6.objects.filter(
                    vlan=vlan).order_by('id')
            except Exception, e:
                self.log.error(
                    u'Error finding the first network_ipv4 from vlan.')
                raise NetworkIPv4NotFoundError(
                    e, u'Error finding the first network_ipv4 from vlan.')

            vlan_map = self.get_vlan_map(vlan, network_ipv4, network_ipv6)

            map = dict()
            map['vlan'] = vlan_map

            return self.response(dumps_networkapi(map))
    def test_task_id_create_in_post_one_vlan_success(self, *args):
        """Test success of id task generate for vlan post success."""

        mock_get_user = args[1]
        mock_create_vlan = args[2]

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

        mock_create_vlan.return_value = vlan
        mock_get_user.return_value = user

        create_vlan({}, user.id)

        mock_create_vlan.assert_called_with({}, user)
    def test_task_id_create_in_delete_one_vlan_success(self, *args):
        """Test success of id task generate for vlan delete success."""

        mock_get_vlan = args[1]
        mock_delete_vlan = args[2]

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

        mock_delete_vlan.return_value = vlan
        mock_get_vlan.return_value = vlan

        delete_vlan(1, user.id)

        mock_delete_vlan.assert_called_with(1)
예제 #14
0
    def handle_get(self, request, user, *args, **kwargs):
        """Treat GET requests to find VLAN by id.

        URLs: /vlan/<id_vlan>/
        """

        try:
            if not has_perm(user, AdminPermission.VLAN_MANAGEMENT, AdminPermission.READ_OPERATION):
                return self.not_authorized()

            id_vlan = kwargs.get('id_vlan')

            # Get vlan by id
            if id_vlan is not None:
                self.log.debug('id_vlan = %s', kwargs['id_vlan'])

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

                vlan = Vlan().get_by_pk(id_vlan)

                # Get first network_ipv4 or network_ipv6 related to vlan
                try:
                    network_ipv4 = vlan.networkipv4_set.order_by('id')[0]
                    vlan_map = self.get_vlan_map(vlan, network_ipv4)
                except IndexError, e:
                    self.log.error(
                        u'Error finding the first network_ipv4 from vlan, trying network_ipv6.')
                    try:
                        network_ipv6 = vlan.networkipv6_set.order_by('id')[0]
                        vlan_map = self.get_vlan_map_ipv6(vlan, network_ipv6)
                    except IndexError, e:
                        self.log.error(
                            u'Error findind the first network_ipv6, raising exception.')
                        raise NetworkIPvXNotFoundError(
                            e, u'Error finding the first network_ipv4 and network_ipv6 from vlan.')

                map = dict()
                map['vlan'] = vlan_map

                return self.response(dumps_networkapi(map))
    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()
예제 #16
0
def get_vlan_by_id(vlan_id):
    """Get vlan by id"""

    vlan = Vlan().get_by_pk(vlan_id)

    return vlan
    def handle_get(self, request, user, *args, **kwargs):
        """Handle GET requests to check if environment has a number available.

        URLs: /vlan/check_number_available/<environment>/<num_vlan>/
        """
        try:
            id_env = kwargs.get('id_environment')
            num_vlan = kwargs.get('num_vlan')
            id_vlan = kwargs.get('id_vlan')

            # 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.')
                raise UserNotAuthorizedError(None)

            # Valid env ID
            if not is_valid_int_greater_zero_param(id_env):
                self.log.error(
                    u'The id_env parameter is not a valid value: %s.', id_env)
                raise InvalidValueError(None, 'env_id', id_env)

            # Valid num Vlan
            if not is_valid_int_greater_zero_param(num_vlan):
                self.log.error(
                    u'The num_vlan parameter is not a valid value: %s.', num_vlan)
                raise InvalidValueError(None, 'num_vlan', id_env)
            else:
                num_vlan = int(num_vlan)

            if is_valid_int_greater_zero_param(id_vlan):
                vlan_to_edit = Vlan().get_by_pk(id_vlan)
                if vlan_to_edit.num_vlan == num_vlan:
                    return self.response(dumps_networkapi({'has_numbers_availables': True}))

            environment = Ambiente().get_by_pk(id_env)
            vlan = Vlan()
            vlan.ambiente = environment

            # Check if environment has min/max num_vlan value or use the value
            # that 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 = MIN_VLAN_NUMBER_01
                max_num_01 = MAX_VLAN_NUMBER_01
                min_num_02 = MIN_VLAN_NUMBER_02
                max_num_02 = MAX_VLAN_NUMBER_02

            has_numbers_availables = False
            availables_numbers = vlan.calculate_vlan_number(
                min_num_01, max_num_01, True)
            if num_vlan not in availables_numbers:
                availables_numbers = vlan.calculate_vlan_number(
                    min_num_02, max_num_02, True)
                if num_vlan in availables_numbers:
                    has_numbers_availables = True
            else:
                has_numbers_availables = True

            if Vlan.objects.filter(num_vlan=num_vlan, ambiente=environment):
                has_numbers_availables = True

            return self.response(dumps_networkapi({'has_numbers_availables': has_numbers_availables}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
예제 #18
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)
    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
                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
                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:
                NetworkIPv4().add_network_ipv4(user, vlan.id, None, None, None)

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

            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)
예제 #20
0
    def handle_post(self, request, user, *args, **kwargs):
        '''Treat POST requests to Create Script ACL

        URL: vlan/create/script/acl/
        '''
        self.log.info('Create Script ACL Vlan')

        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, _ = loads(request.raw_post_data,
                               ["searchable_columns", "asorting_cols"])

            # XML data format
            networkapi_map = xml_map.get('networkapi')
            self.validate_networkapi_map(networkapi_map)

            vlan_map = networkapi_map.get('vlan')
            self.validate_vlan_map(vlan_map)

            id_vlan = vlan_map.get('id_vlan')
            network_type = vlan_map.get('network_type')

            self.validate_id_vlan(id_vlan)

            self.validate_ip_version(network_type)

            vlan = Vlan().get_by_pk(id_vlan)

            network_ipv4 = NetworkIPv4.objects.filter(vlan=vlan).order_by('id')
            network_ipv6 = NetworkIPv6.objects.filter(vlan=vlan).order_by('id')

            vlan_formated = get_vlan_map(vlan, network_ipv4, network_ipv6)

            environment = get_environment_map(vlan.ambiente)

            if network_type == NETWORK_TYPES.v4:
                template_name = environment['ipv4_template']
                acl_name = vlan.acl_file_name
            else:
                template_name = environment['ipv6_template']
                acl_name = vlan.acl_file_name_v6

            self.validate_required_acl(acl_name)

            scriptAclCvs(acl_name, vlan_formated, environment, network_type,
                         user, template_name)

            # Send to Queue
            queue_manager = QueueManager()

            serializer = VlanSerializer(vlan)
            data_to_queue = serializer.data
            data_to_queue.update(
                {'description': queue_keys.VLAN_CREATE_SCRIPT_ACL})
            queue_manager.append({
                'action': queue_keys.VLAN_CREATE_SCRIPT_ACL,
                'kind': queue_keys.VLAN_KEY,
                'data': data_to_queue
            })

            queue_manager.send()

            return self.response(dumps_networkapi({'vlan': vlan_formated}))

        except InvalidValueError, e:
            return self.response_error(self.CODE_MESSAGE_INVALID_PARAM,
                                       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.')
예제 #22
0
    def handle_get(self, request, user, *args, **kwargs):
        '''Treat GET requests to check if a vlan need confimation to insert

        URL: vlan/confirm/
        '''

        try:

            # Get XML data
            ip_version = kwargs.get('ip_version')

            if ip_version == 'None':
                is_number = True
                number = kwargs.get('number')
                id_environment = kwargs.get('id_environment')
            else:
                network = kwargs.get('number')
                network = network.replace('net_replace', '/')
                id_vlan = kwargs.get('id_environment')
                if ip_version == '1':
                    version = 'v6'
                else:
                    version = 'v4'
                is_number = False

            # 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()

            if is_number:
                # Valid number

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

                ambiente = Ambiente.get_by_pk(id_environment)

                equips = list()
                envs = list()
                envs_aux = list()

                for env in ambiente.equipamentoambiente_set.all():
                    equips.append(env.equipamento)

                for equip in equips:
                    for env in equip.equipamentoambiente_set.all():
                        if env.ambiente_id not in envs_aux:
                            envs.append(env.ambiente)
                            envs_aux.append(env.ambiente_id)

                # Valid number
                map = dict()
                map['needs_confirmation'] = True

                for env in envs:
                    for vlan in env.vlan_set.all():
                        if int(vlan.num_vlan) == int(number):
                            if ambiente.filter_id is None or vlan.ambiente.filter_id is None or int(
                                    vlan.ambiente.filter_id) != int(
                                        ambiente.filter_id):
                                map['needs_confirmation'] = False
                            else:
                                map['needs_confirmation'] = True
                                break
            else:
                # Valid subnet

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

                # Get all vlans environments from equipments of the current
                # environment
                vlan = Vlan()
                vlan = vlan.get_by_pk(id_vlan)
                ambiente = vlan.ambiente

                equips = list()
                envs = list()
                envs_aux = list()

                for env in ambiente.equipamentoambiente_set.all():
                    equips.append(env.equipamento)

                for equip in equips:
                    for env in equip.equipamentoambiente_set.all():
                        if env.ambiente_id not in envs_aux:
                            envs.append(env.ambiente)
                            envs_aux.append(env.ambiente_id)

                # Check subnet's
                network = str(network)
                prefix = split(network, "/")
                net_explode = prefix[0]

                if version == IP_VERSION.IPv4[0]:
                    expl = split(net_explode, ".")
                else:
                    expl = split(net_explode, ":")

                expl.append(str(prefix[1]))

                ids_exclude = []
                ids_all = []

                network_ip_verify = IPNetwork(network)
                for env in envs:
                    for vlan_obj in env.vlan_set.all():
                        ids_all.append(vlan_obj.id)
                        is_subnet = verify_subnet(vlan_obj, network_ip_verify,
                                                  version)

                        if not is_subnet:
                            ids_exclude.append(vlan_obj.id)
                        else:
                            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):
                                pass
                            else:
                                ids_exclude.append(vlan_obj.id)

                                # Valid number
                map = dict()
                map['needs_confirmation'] = True

                # Ignore actual vlan
                if envs != [] and long(id_vlan) not in ids_exclude:
                    ids_exclude.append(id_vlan)

                # Check if have duplicated vlan's with same net range in an
                # environment with shared equipment
                if len(ids_all) != len(ids_exclude):
                    map['needs_confirmation'] = False
                else:
                    map['needs_confirmation'] = True

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

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
    def handle_put(self, request, user, *args, **kwargs):
        '''Handles PUT requests to create Network and Vlan.

        URL: network/create/
        '''

        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')
            network_map = networkapi_map.get('network')
            ids = network_map.get('ids')
            id_vlan = network_map.get('id_vlan')

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

            vlan = Vlan()
            vlan = vlan.get_by_pk(id_vlan)

            # Check permission group equipments
            equips_from_ipv4 = Equipamento.objects.filter(
                ipequipamento__ip__networkipv4__vlan=id_vlan, equipamentoambiente__is_router=1).distinct()
            equips_from_ipv6 = Equipamento.objects.filter(
                ipv6equipament__ip__networkipv6__vlan=id_vlan, equipamentoambiente__is_router=1).distinct()
            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()

            with distributedlock(LOCK_VLAN % id_vlan):
                if vlan.ativada == 0:
                    # Make command - VLAN'
                    vlan_command = VLAN_CREATE % int(id_vlan)

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

                    # code = 0 means OK
                    if code == 0:
                        vlan.activate(user)
                    else:
                        return self.response_error(2, stdout + stderr)

                # if 'ids' is a list
                if isinstance(ids, list):
                    for id in ids:
                        code, stdout, stderr = self.activate_network(user, id)
                else:
                    code, stdout, stderr = self.activate_network(user, ids)

                if code != 0:
                    return self.response_error(2, stdout + stderr)

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

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
예제 #24
0
    def handle_delete(self, request, user, *args, **kwargs):
        """Treat requests DELETE to deallocate all relationships between Vlan.

        URL: vlan/<id_vlan>/deallocate/
        """

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

        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.')
                raise UserNotAuthorizedError(None)

            # Load URL param
            id_vlan = kwargs.get('id_vlan')

            # Valid vlan id
            if not is_valid_int_greater_zero_param(id_vlan):
                self.log.error(
                    u'The id_vlan parameter is not a valid value: %s.',
                    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)

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

            # Delete equipment's cache
            equip_id_list = []

            for netv4 in vlan.networkipv4_set.all():
                for ipv4 in netv4.ip_set.all():

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

                    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_ipv4_string(ipv4)
                        vlan_name = vlan.nome
                        network_ip = mount_ipv4_string(netv4)

                        raise IpCantRemoveFromServerPool(
                            {
                                'ip': ip_formated,
                                'vlan_name': vlan_name,
                                'network_ip': network_ip,
                                'server_pool_identifiers':
                                server_pool_identifiers
                            },
                            "Não foi possível excluir a vlan %s pois ela possui a rede %s e essa rede possui o ip %s contido nela, e esse ip esta sendo usado nos Server Pools (id:identifier) %s"
                            % (vlan_name, network_ip, ip_formated,
                               server_pool_identifiers))

                    for ip_equip in ipv4.ipequipamento_set.all():
                        equip_id_list.append(ip_equip.equipamento_id)

            for netv6 in vlan.networkipv6_set.all():
                for ip in netv6.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)
                        vlan_name = vlan.nome
                        network_ip = mount_ipv6_string(netv6)

                        raise IpCantRemoveFromServerPool(
                            {
                                'ip': ip_formated,
                                'vlan_name': vlan_name,
                                'network_ip': network_ip,
                                'server_pool_identifiers':
                                server_pool_identifiers
                            },
                            "Não foi possível excluir a vlan %s pois ela possui a rede %s e essa rede possui o ip %s contido nela, e esse ip esta sendo usado nos Server Pools (id:identifier) %s"
                            % (vlan_name, network_ip, ip_formated,
                               server_pool_identifiers))

                    for ip_equip in ip.ipv6equipament_set.all():
                        equip_id_list.append(ip_equip.equipamento_id)

            destroy_cache_function(equip_id_list, True)

            with distributedlock(LOCK_VLAN % id_vlan):

                # Remove Vlan
                vlan.delete()

                return self.response(dumps_networkapi({}))

        except IpCantRemoveFromServerPool, e:
            return self.response_error(387, e.cause.get('vlan_name'),
                                       e.cause.get('network_ip'),
                                       e.cause.get('ip'),
                                       e.cause.get('server_pool_identifiers'))
    def handle_put(self, request, user, *args, **kwargs):
        """Treat PUT requests to activate a vlan
           Set column ativada = 1

        URL: vlan/create/
        """

        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')
            vlan_map = networkapi_map.get('vlan')

            id_vlan = vlan_map.get('vlan_id')

            vlan = Vlan()
            vlan = vlan.get_by_pk(id_vlan)

            # Check permission group equipments
            equips_from_ipv4 = Equipamento.objects.filter(
                ipequipamento__ip__networkipv4__vlan=id_vlan, equipamentoambiente__is_router=1)
            equips_from_ipv6 = Equipamento.objects.filter(
                ipv6equipament__ip__networkipv6__vlan=id_vlan, 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()

            if vlan.ativada:
                return self.response(dumps_networkapi({}))

            # Make command
            vlan_command = settings.VLAN_CREATE % int(id_vlan)

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

            # if command was successfully executed
            if code == 0:

                # After execute script, change to activated
                vlan.activate(user)
            else:
                return self.response_error(2, stdout + stderr)

            return self.response(dumps_networkapi({}))

        except InvalidValueError as e:
            return self.response_error(269, e.param, e.value)
        except AmbienteNotFoundError as e:
            return self.response_error(112)
        except VlanNameDuplicatedError as e:
            return self.response_error(108)
        except VlanNumberNotAvailableError as e:
            return self.response_error(306, vlan.num_vlan)
        except VlanNumberEnvironmentNotAvailableError as e:
            return self.response_error(315, e.message)
        except VlanNotFoundError as e:
            return self.response_error(150, e.message)
        except XMLError as e:
            self.log.error(u'Error reading the XML request.')
            return self.response_error(3, e)
        except (VlanError, AmbienteError) as e:
            return self.response_error(1)
예제 #26
0
    def handle_post(self, request, user, *args, **kwargs):
        """
        Handles POST requests to allocate a new VLAN.

        URL: vlan/
        """

        self.log.info('Allocate new VLAN')

        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)
            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 = vlan_map.get('id_ambiente')
            network_type = vlan_map.get('id_tipo_rede')
            name = vlan_map.get('nome')
            description = vlan_map.get('descricao')
            environment_vip = vlan_map.get('id_ambiente_vip')
            vrf = vlan_map.get('vrf')

            # Name must NOT be none and 50 is the maxsize
            if not is_valid_string_minsize(name, 3) or not is_valid_string_maxsize(name, 50):
                self.log.error(u'Parameter nome is invalid. Value: %s.', name)
                raise InvalidValueError(None, 'nome', 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)

            # 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)

            # Environment
            # Valid environment ID
            if not is_valid_int_greater_zero_param(environment):
                self.log.error(
                    u'Parameter id_ambiente is invalid. Value: %s.', environment)
                raise InvalidValueError(None, 'id_ambiente', 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_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

            # 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 = TipoRede.get_by_pk(network_type)

            # Business Rules

            # 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 NetworkIPv4
            network_ipv4 = NetworkIPv4()
            vlan_map = network_ipv4.add_network_ipv4(user, vlan.id, net, evip)

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

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

        URL: vlan/edit/
        """

        try:

            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')
            id_vlan = vlan_map.get('vlan_id')

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

            # 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)

            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()
            vlan = vlan.get_by_pk(id_vlan)

            with distributedlock(LOCK_VLAN % id_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)

                change_name = False
                change_number_environment = False

                redes4 = vlan.networkipv4_set.all()
                redes6 = vlan.networkipv6_set.all()

                listaIpsv4 = []
                listaIpsv6 = []

                listaEquips4 = []
                listaEquips6 = []

                for rede in redes4:
                    for ip in rede.ip_set.all():
                        listaIpsv4.append(ip)

                for rede in redes6:
                    for ip in rede.ipv6_set.all():
                        listaIpsv6.append(ip)

                for ip in listaIpsv4:
                    for ipequip in ip.ipequipamento_set.all():
                        listaEquips4.append(ipequip.equipamento)

                for ip in listaIpsv6:
                    for ipequip in ip.ipv6equipament_set.all():
                        listaEquips6.append(ipequip.equipamento)

                listaDeIps4DoEquip = []
                listaDeIps6DoEquip = []
                listaDeVlansDoEquip = []

                for equip in listaEquips4:
                    for ipequip in equip.ipequipamento_set.all():
                        ip_aux = ipequip.ip
                        if ip_aux not in listaDeIps4DoEquip:
                            listaDeIps4DoEquip.append(ip_aux)

                for equip in listaEquips6:
                    for ipequip in equip.ipv6equipament_set.all():
                        ip_aux = ipequip.ip
                        if ip_aux not in listaDeIps4DoEquip:
                            listaDeIps6DoEquip.append(ip_aux)

                for ip in listaDeIps4DoEquip:
                    vlan_aux = ip.networkipv4.vlan
                    if vlan_aux not in listaDeVlansDoEquip:
                        listaDeVlansDoEquip.append(vlan_aux)

                for ip in listaDeIps6DoEquip:
                    vlan_aux = ip.networkipv6.vlan
                    if vlan_aux not in listaDeVlansDoEquip:
                        listaDeVlansDoEquip.append(vlan_aux)

                if vlan.nome != name:
                    change_name = True
                    vlan.nome = name
                if int(vlan.num_vlan) != int(number) or int(vlan.ambiente.id) != int(environment_id):
                    change_number_environment = True
                    vlan.num_vlan = number
                    vlan.ambiente = ambiente

                vlan.acl_file_name = acl_file
                vlan.acl_file_name_v6 = acl_file_v6
                vlan.descricao = description

                vlan_id_cache = [id_vlan]
                # Delete vlan's cache
                destroy_cache_function(vlan_id_cache)

                # Delete equipment's cache
                equip_id_list = []

                for netv4 in vlan.networkipv4_set.all():
                    for ip in netv4.ip_set.all():
                        for ip_equip in ip.ipequipamento_set.all():
                            equip_id_list.append(ip_equip.equipamento_id)

                for netv6 in vlan.networkipv6_set.all():
                    for ip in netv6.ipv6_set.all():
                        for ip_equip in ip.ipv6equipament_set.all():
                            equip_id_list.append(ip_equip.equipamento_id)

                destroy_cache_function(equip_id_list, True)

                vlan.edit_vlan(user, change_name, change_number_environment)
                # Return XML

                return self.response(dumps_networkapi({}))

        except VlanACLDuplicatedError, e:
            return self.response_error(311, acl_file)
예제 #28
0
    def handle_put(self, request, user, *args, **kwargs):
        '''Treat PUT requests to activate a vlan 
           Set column ativada = 1

        URL: vlan/create/
        '''

        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')
            vlan_map = networkapi_map.get('vlan')

            id_vlan = vlan_map.get('vlan_id')

            vlan = Vlan()
            vlan = vlan.get_by_pk(id_vlan)

            # Check permission group equipments
            equips_from_ipv4 = Equipamento.objects.filter(
                ipequipamento__ip__networkipv4__vlan=id_vlan, equipamentoambiente__is_router=1)
            equips_from_ipv6 = Equipamento.objects.filter(
                ipv6equipament__ip__networkipv6__vlan=id_vlan, 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()

            if vlan.ativada:
                return self.response_error(122)

            # Make command
            vlan_command = settings.VLAN_CREATE % int(id_vlan)

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

            # if command was successfully executed
            if code == 0:

                # After execute script, change to activated
                vlan.activate(user)
            else:
                return self.response_error(2, stdout + stderr)

            # Send to Queue
            queue_manager = QueueManager()

            serializer = VlanSerializer(vlan)
            data_to_queue = serializer.data
            data_to_queue.update({'description': queue_keys.VLAN_ACTIVATE})
            queue_manager.append({'action': queue_keys.VLAN_ACTIVATE,'kind': queue_keys.VLAN_KEY,'data': data_to_queue})

            queue_manager.send()

            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):
        """Handles POST requests to create new VLAN without add NetworkIPv4.

        URLs: /vlan/no-network/
        """

        self.log.info('Create new VLAN without add NetworkIPv4')

        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)
            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 = vlan_map.get('environment_id')
            name = vlan_map.get('name')
            description = vlan_map.get('description')
            vrf = vlan_map.get('vrf')

            # Name must NOT be none and 50 is the maxsize
            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 description is invalid. Value: %s.', description)
                raise InvalidValueError(None, 'description', description)
                
            # 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)

            # Environment
            try:

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

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

            except AmbienteNotFoundError, e:
                self.log.error(u'The environment parameter does not exist.')
                return self.response_error(112)

            # Business Rules

            # 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

            #To avoid allocation same vlan number twice for different environments in same equipments
            #Lock all environments related to this environment when allocating vlan number
            #select all equipments from this environment that are not part of a filter
            # and them selects all environments from all these equipments and lock them out
            filtered_equipment_type_ids = list()

            env_filter = None
            try:
                env_filter = env.filter.id
            except:
                pass
                
            for fet in FilterEquipType.objects.filter(filter=env_filter):
                filtered_equipment_type_ids.append(fet.equiptype.id)

            filtered_environment_equips = Equipamento.objects.filter(equipamentoambiente__ambiente=env).exclude(
                tipo_equipamento__in=filtered_equipment_type_ids)

            #select all environments from the equips that were not filtered
            locks_list = list()
            environments_list = Ambiente.objects.filter(equipamentoambiente__equipamento__in=filtered_environment_equips).distinct()
            for environment in environments_list:
                lock = distributedlock(LOCK_ENVIRONMENT % environment.id)
                lock.__enter__()
                locks_list.append(lock)

            # Persist
            try:
                vlan.create_new(user,
                            min_num_01,
                            max_num_01,
                            min_num_02,
                            max_num_02
                            )
            except Exception, e:
                #release all the locks if failed
                for lock in locks_list:
                    lock.__exit__('', '', '')
                raise e
def criar_vlan(user, variablestochangecore1, ambientes, active=1):

    #get environment
    ambiente = Ambiente()
    divisaodc = DivisaoDc()
    divisaodc = divisaodc.get_by_name(ambientes.get('DC'))
    ambiente_log = AmbienteLogico()
    ambiente_log = ambiente_log.get_by_name(ambientes.get('LOG'))
    ambiente = ambiente.search(divisaodc.id, ambiente_log.id)
    for  amb in ambiente:
        if amb.grupo_l3.nome==ambientes.get('L3'):
            id_ambiente = amb
    # set vlan
    vlan = Vlan()
    vlan.acl_file_name = None
    vlan.acl_file_name_v6 = None
    vlan.num_vlan = variablestochangecore1.get("VLAN_NUM")
    vlan.nome = variablestochangecore1.get("VLAN_NAME")
    vlan.descricao = ""
    vlan.ambiente = id_ambiente
    vlan.ativada = active
    vlan.acl_valida = 0
    vlan.acl_valida_v6 = 0

    vlan.insert_vlan(user)

    return vlan
    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)
예제 #32
0
def criar_vlan(user, variablestochangecore1, ambientes, active=1):

    # get environment
    ambiente = Ambiente()
    divisaodc = DivisaoDc()
    divisaodc = divisaodc.get_by_name(ambientes.get('DC'))
    ambiente_log = AmbienteLogico()
    ambiente_log = ambiente_log.get_by_name(ambientes.get('LOG'))
    ambiente = ambiente.search(divisaodc.id, ambiente_log.id)
    for amb in ambiente:
        if amb.grupo_l3.nome == ambientes.get('L3'):
            id_ambiente = amb
    # set vlan
    vlan = Vlan()
    vlan.acl_file_name = None
    vlan.acl_file_name_v6 = None
    vlan.num_vlan = variablestochangecore1.get('VLAN_NUM')
    vlan.nome = variablestochangecore1.get('VLAN_NAME')
    vlan.descricao = ''
    vlan.ambiente = id_ambiente
    vlan.ativada = active
    vlan.acl_valida = 0
    vlan.acl_valida_v6 = 0

    vlan.insert_vlan(user)

    return vlan
    def handle_get(self, request, user, *args, **kwargs):
        """Handle GET requests to check if environment has a number available.

        URLs: /vlan/check_number_available/<environment>/<num_vlan>/
        """
        try:
            id_env = kwargs.get('id_environment')
            num_vlan = kwargs.get('num_vlan')
            id_vlan = kwargs.get('id_vlan')

            # 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.')
                raise UserNotAuthorizedError(None)

            # Valid env ID
            if not is_valid_int_greater_zero_param(id_env):
                self.log.error(
                    u'The id_env parameter is not a valid value: %s.', id_env)
                raise InvalidValueError(None, 'env_id', id_env)

            # Valid num Vlan
            if not is_valid_int_greater_zero_param(num_vlan):
                self.log.error(
                    u'The num_vlan parameter is not a valid value: %s.',
                    num_vlan)
                raise InvalidValueError(None, 'num_vlan', id_env)
            else:
                num_vlan = int(num_vlan)

            if is_valid_int_greater_zero_param(id_vlan):
                vlan_to_edit = Vlan().get_by_pk(id_vlan)
                if vlan_to_edit.num_vlan == num_vlan:
                    return self.response(
                        dumps_networkapi({'has_numbers_availables': True}))

            environment = Ambiente().get_by_pk(id_env)
            vlan = Vlan()
            vlan.ambiente = environment

            # Check if environment has min/max num_vlan value or use the value
            # that 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 = MIN_VLAN_NUMBER_01
                max_num_01 = MAX_VLAN_NUMBER_01
                min_num_02 = MIN_VLAN_NUMBER_02
                max_num_02 = MAX_VLAN_NUMBER_02

            has_numbers_availables = False
            availables_numbers = vlan.calculate_vlan_number(
                min_num_01, max_num_01, True)
            if num_vlan not in availables_numbers:
                availables_numbers = vlan.calculate_vlan_number(
                    min_num_02, max_num_02, True)
                if num_vlan in availables_numbers:
                    has_numbers_availables = True
            else:
                has_numbers_availables = True

            if Vlan.objects.filter(num_vlan=num_vlan, ambiente=environment):
                has_numbers_availables = True

            return self.response(
                dumps_networkapi(
                    {'has_numbers_availables': has_numbers_availables}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
    def handle_delete(self, request, user, *args, **kwargs):
        """Handles DELETE requests to remove VLAN by ID.

        URLs: /vlan/<id_vlan>/remove/
        """

        self.log.info('Remove VLAN by ID')
        CODE_MESSAGE_VLAN_ERROR = 369

        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
            vlan_id = kwargs.get('id_vlan')

            # 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)

            # Existing VLAN ID
            vlan = Vlan().get_by_pk(vlan_id)

            # Check permission group equipments
            equips_from_ipv4 = Equipamento.objects.filter(
                ipequipamento__ip__networkipv4__vlan=vlan_id, equipamentoambiente__is_router=1).distinct()
            equips_from_ipv6 = Equipamento.objects.filter(
                ipv6equipament__ip__networkipv6__vlan=vlan_id, equipamentoambiente__is_router=1).distinct()
            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()

            with distributedlock(LOCK_VLAN % vlan_id):

                # Business Rules

                if vlan.ativada:
                    network_errors = []

                    for net4 in vlan.networkipv4_set.all():

                        if net4.active:
                            try:
                                command = settings.NETWORKIPV4_REMOVE % int(
                                    net4.id)

                                code, stdout, stderr = exec_script(command)
                                if code == 0:
                                    net4.deactivate(user, True)
                                else:
                                    network_errors.append(str(net4.id))
                            except Exception, e:
                                network_errors.append(str(net4.id))
                                pass

                    for net6 in vlan.networkipv6_set.all():

                        if net6.active:
                            try:
                                command = settings.NETWORKIPV6_REMOVE % int(
                                    net6.id)
                                code, stdout, stderr = exec_script(command)
                                if code == 0:
                                    net6.deactivate(user, True)
                                else:
                                    network_errors.append(str(net6.id))
                            except Exception, e:
                                network_errors.append(str(net6.id))
                                pass

                    if network_errors:
                        raise VlanNetworkError(
                            None, message=', '.join(network_errors))

                else:
예제 #35
0
    def handle_post(self, request, user, *args, **kwargs):
        '''Treat POST requests to edit a vlan 

        URL: vlan/edit/
        '''

        try:

            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')
            id_vlan = vlan_map.get('vlan_id')

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

            # 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)

            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()
            vlan = vlan.get_by_pk(id_vlan)

            with distributedlock(LOCK_VLAN % id_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
                    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
                    vlan.get_vlan_by_acl_v6(acl_file_v6)

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

                change_name = False
                change_number_environment = False

                redes4 = vlan.networkipv4_set.all()
                redes6 = vlan.networkipv6_set.all()

                listaIpsv4 = []
                listaIpsv6 = []

                listaEquips4 = []
                listaEquips6 = []

                for rede in redes4:
                    for ip in rede.ip_set.all():
                        listaIpsv4.append(ip)

                for rede in redes6:
                    for ip in rede.ipv6_set.all():
                        listaIpsv6.append(ip)

                for ip in listaIpsv4:
                    for ipequip in ip.ipequipamento_set.all():
                        listaEquips4.append(ipequip.equipamento)

                for ip in listaIpsv6:
                    for ipequip in ip.ipv6equipament_set.all():
                        listaEquips6.append(ipequip.equipamento)

                listaDeIps4DoEquip = []
                listaDeIps6DoEquip = []
                listaDeVlansDoEquip = []

                for equip in listaEquips4:
                    for ipequip in equip.ipequipamento_set.all():
                        ip_aux = ipequip.ip
                        if ip_aux not in listaDeIps4DoEquip:
                            listaDeIps4DoEquip.append(ip_aux)

                for equip in listaEquips6:
                    for ipequip in equip.ipv6equipament_set.all():
                        ip_aux = ipequip.ip
                        if ip_aux not in listaDeIps4DoEquip:
                            listaDeIps6DoEquip.append(ip_aux)

                for ip in listaDeIps4DoEquip:
                    vlan_aux = ip.networkipv4.vlan
                    if vlan_aux not in listaDeVlansDoEquip:
                        listaDeVlansDoEquip.append(vlan_aux)

                for ip in listaDeIps6DoEquip:
                    vlan_aux = ip.networkipv6.vlan
                    if vlan_aux not in listaDeVlansDoEquip:
                        listaDeVlansDoEquip.append(vlan_aux)

                if vlan.nome != name:
                    change_name = True
                    vlan.nome = name
                if int(vlan.num_vlan) != int(number) or int(vlan.ambiente.id) != int(environment_id):
                    change_number_environment = True
                    vlan.num_vlan = number
                    vlan.ambiente = ambiente

                vlan.acl_file_name = acl_file
                vlan.acl_file_name_v6 = acl_file_v6
                vlan.descricao = description

                vlan_id_cache = [id_vlan]
                # Delete vlan's cache
                destroy_cache_function(vlan_id_cache)

                # Delete equipment's cache
                equip_id_list = []

                for netv4 in vlan.networkipv4_set.all():
                    for ip in netv4.ip_set.all():
                        for ip_equip in ip.ipequipamento_set.all():
                            equip_id_list.append(ip_equip.equipamento_id)

                for netv6 in vlan.networkipv6_set.all():
                    for ip in netv6.ipv6_set.all():
                        for ip_equip in ip.ipv6equipament_set.all():
                            equip_id_list.append(ip_equip.equipamento_id)

                destroy_cache_function(equip_id_list, True)

                vlan.edit_vlan(user, change_name, change_number_environment)
                # Return XML

                return self.response(dumps_networkapi({}))

        except VlanACLDuplicatedError, e:
            return self.response_error(311, acl_file)
예제 #36
0
    def add_remove_check_list_vlan_trunk(self, user, networkapi_map, vlan_id, operation):

        equipment_map = networkapi_map.get('equipamento')
        if equipment_map is None:
            return self.response_error(105)

        try:
            name = equipment_map.get('nome')
            if name is None or name == '':
                self.log.error(u'Parameter nome is invalid. Value: %s.', name)
                raise InvalidValueError(None, 'nome', name)

            interface_name = equipment_map.get('nome_interface')
            if interface_name is None or interface_name == '':
                self.log.error(
                    u'Parameter nome_interface is invalid. Value: %s.', interface_name)
                raise InvalidValueError(None, 'nome_interface', interface_name)

            if operation != 'list':
                vlan = Vlan().get_by_pk(vlan_id)

            # Check existence
            equipment = Equipamento().get_by_name(name)

            equip_permission = AdminPermission.EQUIP_UPDATE_CONFIG_OPERATION
            admin_permission = AdminPermission.WRITE_OPERATION
            if operation in ['check', 'list']:
                equip_permission = AdminPermission.EQUIP_READ_OPERATION
                admin_permission = AdminPermission.READ_OPERATION

            if not has_perm(user,
                            AdminPermission.VLAN_ALTER_SCRIPT,
                            admin_permission,
                            None,
                            equipment.id,
                            equip_permission):
                return self.not_authorized()

            interface = Interface.get_by_interface_equipment(
                interface_name, equipment.id)

            if interface.ligacao_front is None:
                return self.response_error(139)

            protected = None
            if operation not in ['check', 'list']:
                protected = 0

            try:
                switch_interface = interface.get_switch_interface_from_host_interface(
                    protected)
            except InterfaceNotFoundError:
                return self.response_error(144)

            if not has_perm(user,
                            AdminPermission.VLAN_ALTER_SCRIPT,
                            admin_permission,
                            None,
                            switch_interface.equipamento_id,
                            equip_permission):
                return self.not_authorized()

            # configurador -T snmp_vlans_trunk -i <nomequip> -A “'int=<interface> add=<numvlan>'”
            # configurador -T snmp_vlans_trunk -i <nomequip> -A “'int=<interface> del=<numvlan>'”
            # configurador -T snmp_vlans_trunk -i <nomequip> -A “'int=<interface> check=<numvlan>'"
            # configurador -T snmp_vlans_trunk -i <nomequip> -A
            # “'int=<interface> list'"
            command = 'configurador -T snmp_vlans_trunk -i %s -A "\'int=%s %s' % (switch_interface.equipamento.nome,
                                                                                  switch_interface.interface,
                                                                                  operation)
            if operation != 'list':
                command = command + '=%d' % vlan.num_vlan

            command = command + '\'"'

            code, stdout, stderr = exec_script(command)
            if code == 0:
                map = dict()
                success_map = dict()
                success_map['codigo'] = '%04d' % code
                success_map['descricao'] = {'stdout': stdout, 'stderr': stderr}
                map['sucesso'] = success_map

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

        except EquipamentoNotFoundError:
            return self.response_error(117, name)
        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
    def handle_delete(self, request, user, *args, **kwargs):
        """Treat requests DELETE to deallocate all relationships between Vlan.

        URL: vlan/<id_vlan>/deallocate/
        """

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

        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.')
                raise UserNotAuthorizedError(None)

            # Load URL param
            id_vlan = kwargs.get('id_vlan')

            # Valid vlan id
            if not is_valid_int_greater_zero_param(id_vlan):
                self.log.error(
                    u'The id_vlan parameter is not a valid value: %s.', 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)

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

            # Delete equipment's cache
            equip_id_list = []

            for netv4 in vlan.networkipv4_set.all():
                for ipv4 in netv4.ip_set.all():

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

                    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_ipv4_string(ipv4)
                        vlan_name = vlan.nome
                        network_ip = mount_ipv4_string(netv4)

                        raise IpCantRemoveFromServerPool({'ip': ip_formated, 'vlan_name': vlan_name, 'network_ip': network_ip, 'server_pool_identifiers': server_pool_identifiers},
                            "Não foi possível excluir a vlan %s pois ela possui a rede %s e essa rede possui o ip %s contido nela, e esse ip esta sendo usado nos Server Pools (id:identifier) %s" %
                            (vlan_name, network_ip, ip_formated, server_pool_identifiers))


                    for ip_equip in ipv4.ipequipamento_set.all():
                        equip_id_list.append(ip_equip.equipamento_id)

            for netv6 in vlan.networkipv6_set.all():
                for ip in netv6.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)
                        vlan_name = vlan.nome
                        network_ip = mount_ipv6_string(netv6)

                        raise IpCantRemoveFromServerPool({'ip': ip_formated, 'vlan_name': vlan_name, 'network_ip': network_ip, 'server_pool_identifiers': server_pool_identifiers},
                            "Não foi possível excluir a vlan %s pois ela possui a rede %s e essa rede possui o ip %s contido nela, e esse ip esta sendo usado nos Server Pools (id:identifier) %s" %
                            (vlan_name, network_ip, ip_formated, server_pool_identifiers))

                    for ip_equip in ip.ipv6equipament_set.all():
                        equip_id_list.append(ip_equip.equipamento_id)

            destroy_cache_function(equip_id_list, True)

            with distributedlock(LOCK_VLAN % id_vlan):

                # Remove Vlan
                vlan.delete(user)

                return self.response(dumps_networkapi({}))

        except IpCantRemoveFromServerPool, e:
            return self.response_error(387, e.cause.get('vlan_name'), e.cause.get('network_ip'), e.cause.get('ip'), e.cause.get('server_pool_identifiers'))
예제 #38
0
    def handle_post(self, request, user, *args, **kwargs):
        '''Treat POST requests to Create ACL

        URL: vlan/create/acl/
        '''
        self.log.info('Create ACL Vlan')

        try:
            is_suggest_acl_name = False
            # 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, _ = loads(request.raw_post_data,
                               ["searchable_columns", "asorting_cols"])

            # XML data format
            networkapi_map = xml_map.get('networkapi')
            self.validate_networkapi_map(networkapi_map)

            vlan_map = networkapi_map.get('vlan')
            self.validate_vlan_map(vlan_map)

            id_vlan = vlan_map.get('id_vlan')
            network_type = vlan_map.get('network_type')

            self.validate_id_vlan(id_vlan)

            self.validate_ip_version(network_type)

            vlan = Vlan().get_by_pk(id_vlan)

            environment = get_environment_map(vlan.ambiente)

            if network_type == NETWORK_TYPES.v4:
                if not vlan.acl_file_name:
                    is_suggest_acl_name = True
                    vlan.acl_file_name = self.__create_suggest_acl_name(vlan)

                acl_name = vlan.acl_file_name
            else:
                if not vlan.acl_file_name_v6:
                    is_suggest_acl_name = True
                    vlan.acl_file_name_v6 = self.__create_suggest_acl_name(
                        vlan)

                acl_name = vlan.acl_file_name_v6

            self.validate_duplicate_acl(acl_name, environment, network_type,
                                        user)

            if is_suggest_acl_name:
                vlan.save()

            createAclCvs(acl_name, environment, network_type, user)

            # Send to Queue
            queue_manager = QueueManager()

            serializer = VlanSerializer(vlan)
            data_to_queue = serializer.data
            data_to_queue.update({'description': queue_keys.VLAN_CREATE_ACL})
            queue_manager.append({
                'action': queue_keys.VLAN_CREATE_ACL,
                'kind': queue_keys.VLAN_KEY,
                'data': data_to_queue
            })

            queue_manager.send()

            return self.response(
                dumps_networkapi({'vlan': model_to_dict(vlan)}))

        except InvalidValueError, e:
            return self.response_error(self.CODE_MESSAGE_INVALID_PARAM,
                                       e.param, e.value)
    def handle_post(self, request, user, *args, **kwargs):
        '''Treat POST requests to Create ACL

        URL: vlan/create/acl/
        '''
        self.log.info('Create ACL Vlan')

        try:
            is_suggest_acl_name = False
            # 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, _ = loads(
                request.raw_post_data, ["searchable_columns", "asorting_cols"])

            # XML data format
            networkapi_map = xml_map.get('networkapi')
            self.validate_networkapi_map(networkapi_map)

            vlan_map = networkapi_map.get('vlan')
            self.validate_vlan_map(vlan_map)

            id_vlan = vlan_map.get('id_vlan')
            network_type = vlan_map.get('network_type')

            self.validate_id_vlan(id_vlan)

            self.validate_ip_version(network_type)

            vlan = Vlan().get_by_pk(id_vlan)

            environment = get_environment_map(vlan.ambiente)

            if network_type == NETWORK_TYPES.v4:
                if not vlan.acl_file_name:
                    is_suggest_acl_name = True
                    vlan.acl_file_name = self.__create_suggest_acl_name(vlan)

                acl_name = vlan.acl_file_name
            else:
                if not vlan.acl_file_name_v6:
                    is_suggest_acl_name = True
                    vlan.acl_file_name_v6 = self.__create_suggest_acl_name(
                        vlan)

                acl_name = vlan.acl_file_name_v6

            self.validate_duplicate_acl(
                acl_name, environment, network_type, user)

            if is_suggest_acl_name:
                vlan.save()

            createAclCvs(acl_name, environment, network_type, user)

            # Send to Queue
            queue_manager = QueueManager()

            serializer = VlanSerializer(vlan)
            data_to_queue = serializer.data
            data_to_queue.update({'description': queue_keys.VLAN_CREATE_ACL})
            queue_manager.append({'action': queue_keys.VLAN_CREATE_ACL,'kind': queue_keys.VLAN_KEY,'data': data_to_queue})

            queue_manager.send()

            return self.response(dumps_networkapi({'vlan': model_to_dict(vlan)}))

        except InvalidValueError, e:
            return self.response_error(self.CODE_MESSAGE_INVALID_PARAM, e.param, e.value)
    def handle_post(self, request, user, *args, **kwargs):
        """Handles POST requests to create new VLAN without add NetworkIPv4.

        URLs: /vlan/no-network/
        """

        self.log.info('Create new VLAN without add NetworkIPv4')

        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)
            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 = vlan_map.get('environment_id')
            name = vlan_map.get('name')
            description = vlan_map.get('description')
            vrf = vlan_map.get('vrf')

            # Name must NOT be none and 50 is the maxsize
            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 description is invalid. Value: %s.',
                               description)
                raise InvalidValueError(None, 'description', description)

            # 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)

            # Environment
            try:

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

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

            except AmbienteNotFoundError, e:
                self.log.error(u'The environment parameter does not exist.')
                return self.response_error(112)

            # Business Rules

            # 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

            #To avoid allocation same vlan number twice for different environments in same equipments
            #Lock all environments related to this environment when allocating vlan number
            #select all equipments from this environment that are not part of a filter
            # and them selects all environments from all these equipments and lock them out
            filtered_equipment_type_ids = list()

            env_filter = None
            try:
                env_filter = env.filter.id
            except:
                pass

            for fet in FilterEquipType.objects.filter(filter=env_filter):
                filtered_equipment_type_ids.append(fet.equiptype.id)

            filtered_environment_equips = Equipamento.objects.filter(
                equipamentoambiente__ambiente=env).exclude(
                    tipo_equipamento__in=filtered_equipment_type_ids)

            #select all environments from the equips that were not filtered
            locks_list = list()
            environments_list = Ambiente.objects.filter(
                equipamentoambiente__equipamento__in=filtered_environment_equips
            ).distinct().order_by('id')
            for environment in environments_list:
                lock = distributedlock(LOCK_ENVIRONMENT % environment.id)
                lock.__enter__()
                locks_list.append(lock)

            # Persist
            try:
                vlan.create_new(user, min_num_01, max_num_01, min_num_02,
                                max_num_02)
            except Exception, e:
                #release all the locks if failed
                for lock in locks_list:
                    lock.__exit__('', '', '')
                raise e
    def handle_post(self, request, user, *args, **kwargs):
        """Handles POST requests to create new VLAN without add NetworkIPv4.

        URLs: /vlan/no-network/
        """

        self.log.info('Create new VLAN without add NetworkIPv4')

        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)
            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 = vlan_map.get('environment_id')
            name = vlan_map.get('name')
            description = vlan_map.get('description')
            vrf = vlan_map.get('vrf')

            # Name must NOT be none and 50 is the maxsize
            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 description is invalid. Value: %s.', description)
                raise InvalidValueError(None, 'description', description)
                
            # 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)

            # Environment
            try:

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

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

            except AmbienteNotFoundError, e:
                self.log.error(u'The environment parameter does not exist.')
                return self.response_error(112)

            # Business Rules

            # 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
                            )

            vlan_map = dict()
            vlan_map['vlan'] = model_to_dict(vlan)

            # Return XML
            return self.response(dumps_networkapi(vlan_map))
    def handle_get(self, request, user, *args, **kwargs):
        """Treat GET requests to check if a vlan need confimation to insert

        URL: vlan/confirm/
        """

        try:

            # Get XML data
            ip_version = kwargs.get("ip_version")

            if ip_version == "None":
                is_number = True
                number = kwargs.get("number")
                id_environment = kwargs.get("id_environment")
            else:
                network = kwargs.get("number")
                network = network.replace("net_replace", "/")
                id_vlan = kwargs.get("id_environment")
                if ip_version == "1":
                    version = "v6"
                else:
                    version = "v4"
                is_number = False

            # 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()

            if is_number:
                # Valid number

                if not is_valid_int_greater_zero_param(id_environment):
                    self.log.error(u"Parameter id_environment is invalid. Value: %s.", id_environment)
                    raise InvalidValueError(None, "id_environment", id_environment)

                ambiente = Ambiente.get_by_pk(id_environment)

                equips = list()
                envs = list()
                envs_aux = list()

                for env in ambiente.equipamentoambiente_set.all():
                    equips.append(env.equipamento)

                for equip in equips:
                    for env in equip.equipamentoambiente_set.all():
                        if not env.ambiente_id in envs_aux:
                            envs.append(env.ambiente)
                            envs_aux.append(env.ambiente_id)

                # Valid number
                map = dict()
                map["needs_confirmation"] = True

                for env in envs:
                    for vlan in env.vlan_set.all():
                        if int(vlan.num_vlan) == int(number):
                            if (
                                ambiente.filter_id == None
                                or vlan.ambiente.filter_id == None
                                or int(vlan.ambiente.filter_id) != int(ambiente.filter_id)
                            ):
                                map["needs_confirmation"] = False
                            else:
                                map["needs_confirmation"] = True
                                break
            else:
                # Valid subnet

                if not is_valid_int_greater_zero_param(id_vlan):
                    self.log.error(u"Parameter id_vlan is invalid. Value: %s.", id_vlan)
                    raise InvalidValueError(None, "id_vlan", id_vlan)

                # Get all vlans environments from equipments of the current
                # environment
                vlan = Vlan()
                vlan = vlan.get_by_pk(id_vlan)
                ambiente = vlan.ambiente

                equips = list()
                envs = list()
                envs_aux = list()

                for env in ambiente.equipamentoambiente_set.all():
                    equips.append(env.equipamento)

                for equip in equips:
                    for env in equip.equipamentoambiente_set.all():
                        if not env.ambiente_id in envs_aux:
                            envs.append(env.ambiente)
                            envs_aux.append(env.ambiente_id)

                # Check subnet's
                network = str(network)
                prefix = split(network, "/")
                net_explode = prefix[0]

                if version == IP_VERSION.IPv4[0]:
                    expl = split(net_explode, ".")
                else:
                    expl = split(net_explode, ":")

                expl.append(str(prefix[1]))

                ids_exclude = []
                ids_all = []

                network_ip_verify = IPNetwork(network)
                for env in envs:
                    for vlan_obj in env.vlan_set.all():
                        ids_all.append(vlan_obj.id)
                        is_subnet = verify_subnet(vlan_obj, network_ip_verify, version)

                        if not is_subnet:
                            ids_exclude.append(vlan_obj.id)
                        else:
                            if (
                                ambiente.filter_id == None
                                or vlan_obj.ambiente.filter_id == None
                                or int(vlan_obj.ambiente.filter_id) != int(ambiente.filter_id)
                            ):
                                pass
                            else:
                                ids_exclude.append(vlan_obj.id)

                                # Valid number
                map = dict()
                map["needs_confirmation"] = True

                # Ignore actual vlan
                if envs != [] and long(id_vlan) not in ids_exclude:
                    ids_exclude.append(id_vlan)

                # Check if have duplicated vlan's with same net range in an
                # environment with shared equipment
                if len(ids_all) != len(ids_exclude):
                    map["needs_confirmation"] = False
                else:
                    map["needs_confirmation"] = True

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

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
예제 #43
0
    def handle_put(self, request, user, *args, **kwargs):
        """Handles PUT requests to create Network and Vlan.

        URL: network/create/
        """

        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')
            network_map = networkapi_map.get('network')
            ids = network_map.get('ids')
            id_vlan = network_map.get('id_vlan')

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

            vlan = Vlan()
            vlan = vlan.get_by_pk(id_vlan)

            # Check permission group equipments
            equips_from_ipv4 = Equipamento.objects.filter(
                ipequipamento__ip__networkipv4__vlan=id_vlan, equipamentoambiente__is_router=1).distinct()
            equips_from_ipv6 = Equipamento.objects.filter(
                ipv6equipament__ip__networkipv6__vlan=id_vlan, equipamentoambiente__is_router=1).distinct()
            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()

            with distributedlock(LOCK_VLAN % id_vlan):
                if vlan.ativada == 0:
                    # Make command - VLAN'
                    vlan_command = VLAN_CREATE % int(id_vlan)

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

                    # code = 0 means OK
                    if code == 0:
                        vlan.activate(user)
                    else:
                        return self.response_error(2, stdout + stderr)

                # if 'ids' is a list
                if isinstance(ids, list):
                    for id in ids:
                        code, stdout, stderr = self.activate_network(user, id)
                else:
                    code, stdout, stderr = self.activate_network(user, ids)

                if code != 0:
                    return self.response_error(2, stdout + stderr)

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

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)