Пример #1
0
def networkIPv6_deploy(request, network_id):
    '''Deploy network L3 configuration in the environment routers for network ipv6

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

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

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

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

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

		if len(DHCPRelayIPv6.objects.filter(ipv6=ipv6, networkipv6=networkipv6)) > 0:
			raise exceptions.DHCPRelayAlreadyExistsError(ipv6_id, networkipv6_id)
		
		self.ipv6 = ipv6
		self.networkipv6 = networkipv6
Пример #3
0
def networksIPv6_by_pk(request, network_id):
    """
    Lists network ipv6.
    """
    try:

        networkipv6_obj = NetworkIPv6.get_by_pk(network_id)

        serializer_options = NetworkIPv6Serializer(networkipv6_obj, many=False)

        return Response(serializer_options.data)
    except NetworkIPv6NotFoundError, exception:
        raise exceptions.InvalidNetworkIDException()
Пример #4
0
def networksIPv6_by_pk(request, network_id):
    '''Lists network ipv6
    '''
    try:

        networkIPv6_obj = NetworkIPv6.get_by_pk(network_id)

        serializer_options = NetworkIPv6Serializer(
            networkIPv6_obj,
            many=False
        )

        return Response(serializer_options.data)
    except NetworkIPv6NotFoundError, exception:
        raise exceptions.InvalidNetworkIDException()
Пример #5
0
    def activate_network(self, user, id):
        # id => ex: '55-v4' or '55-v6'
        value = id.split('-')

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        return code, stdout, stderr
    def deactivate_network(self, user, id):

        id_network, network_type = self.get_id_and_net_type(id)

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

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

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

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

            command = NETWORKIPV4_REMOVE % int(id_network)

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

            net = NetworkIPv6.get_by_pk(id_network)

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

            command = NETWORKIPV6_REMOVE % int(id_network)

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

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

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

        try:

            # Commons Validations

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

            # Business Validations

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

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

            # Business Rules

            network = NetworkIPv6.get_by_pk(id_network)

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

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

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

        id_network, network_type = self.get_id_and_net_type(id)

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

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

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

                command = NETWORKIPV4_REMOVE % int(id_network)

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

                command = NETWORKIPV6_REMOVE % int(id_network)

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

        return code, stdout, stderr
    def deactivate_network(self, user, id):

        id_network, network_type = self.get_id_and_net_type(id)

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

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

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

                command = NETWORKIPV4_REMOVE % int(id_network)

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

                command = NETWORKIPV6_REMOVE % int(id_network)

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

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

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

        try:

            # Commons Validations

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

            # Business Validations

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

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

            # Business Rules

            network = NetworkIPv6.get_by_pk(id_network)

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

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

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
Пример #12
0
def networkIPv6_deploy(request, network_id):
    """Deploy network L3 configuration in the environment routers for network ipv6

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

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

    equipment_list = []

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

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

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

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

    if all_equipments_are_in_maintenance(equipment_list):
        raise AllEquipmentsAreInMaintenanceException()

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

        return Response(returned_data)

    except Exception, exception:
        log.error(exception)
        raise api_exceptions.NetworkAPIException()
Пример #13
0
    def handle_post(self, request, user, *args, **kwargs):
        """Handles POST requests to add an IP6 and associate it to an equipment.

        URL: ipv6/save/
        """

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

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

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

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

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

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

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

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

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

            # Business Rules

            # New IP
            ipv6 = Ipv6()

            net = NetworkIPv6.get_by_pk(network_ipv6_id)

            with distributedlock(LOCK_NETWORK_IPV6 % network_ipv6_id):

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

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

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

                equip = Equipamento.get_by_pk(equip_id)

                listaVlansDoEquip = []

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

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

                vlan_atual = net.vlan

                ambiente_aux = None
                vlan_aux = None

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

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

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

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

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

                            ## Filter case 3 - end ##

                            if flag_vlan_error:

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

                ipv6.save_ipv6(equip_id, user, net)

                list_ip = []
                lequips = list()

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

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

                list_id_equip = []

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

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

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

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

                return self.response(dumps_networkapi(network_map))

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

        URL: ipv6/save/
        '''

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

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

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

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

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

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

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

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

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

            # Business Rules

            # New IP
            ipv6 = Ipv6()

            net = NetworkIPv6.get_by_pk(network_ipv6_id)

            with distributedlock(LOCK_NETWORK_IPV6 % network_ipv6_id):

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

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

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

                equip = Equipamento.get_by_pk(equip_id)

                listaVlansDoEquip = []

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

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

                vlan_atual = net.vlan

                ambiente_aux = None
                vlan_aux = None

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

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

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

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

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

                            ## Filter case 3 - end ##

                            if flag_vlan_error:

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

                ipv6.save_ipv6(equip_id, user, net)

                list_ip = []
                lequips = list()

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

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

                list_id_equip = []

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

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

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

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

                return self.response(dumps_networkapi(network_map))

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

        URL: ipv6/assoc/
        '''

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

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

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

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

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

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

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

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

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

            # Business Rules

            # Get net
            net = NetworkIPv6.get_by_pk(network_ipv6_id)

            with distributedlock(LOCK_NETWORK_IPV6 % network_ipv6_id):

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

                listaVlansDoEquip = []

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

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

                vlan_atual = net.vlan
                vlan_aux = None
                ambiente_aux = None

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

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

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

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

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

                            ## Filter case 3 - end ##

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

                # Persist
                try:

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

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

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

                    ip_equipment.equipamento = equipment

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

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

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

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

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

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

                    ## Filter case 2 - end ##

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

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

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

                except IpRangeAlreadyAssociation, e:
                    raise IpRangeAlreadyAssociation(None, e.message)
Пример #16
0
    def handle_post(self, request, user, *args, **kwargs):
        """Handles POST requests to edit an Network.

        URL: network/edit/
        """

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

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

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

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

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

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

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

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

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

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

            # Business Rules

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

            # New network_tyoe

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

                with distributedlock(LOCK_NETWORK_IPV4 % id_network):

                    if id_env_vip is not None:

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

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

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

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

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

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

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

                with distributedlock(LOCK_NETWORK_IPV6 % id_network):

                    if id_env_vip is not None:

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

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

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

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

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

                    net.edit_network_ipv6(user, id_net_type, id_env_vip)

            # Delete vlan's cache
            # destroy_cache_function()

            return self.response(dumps_networkapi({}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
    def handle_post(self, request, user, *args, **kwargs):
        '''Handles POST requests to associate and IPv6 to an equipment.

        URL: ipv6/assoc/
        '''

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

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

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

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

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

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

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

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

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

            # Business Rules

            # Get net
            net = NetworkIPv6.get_by_pk(network_ipv6_id)

            with distributedlock(LOCK_NETWORK_IPV6 % network_ipv6_id):

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

                listaVlansDoEquip = []

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

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

                vlan_atual = net.vlan
                vlan_aux = None
                ambiente_aux = None

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

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

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

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

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

                            ## Filter case 3 - end ##

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

                # Persist
                try:

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

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

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

                    ip_equipment.equipamento = equipment

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

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

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

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

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

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

                    ## Filter case 2 - end ##

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

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

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

                except IpRangeAlreadyAssociation, e:
                    raise IpRangeAlreadyAssociation(None, e.message)
    def handle_get(self, request, user, *args, **kwargs):
        """Handles GET requests to list all network IPv6 by network ipv6 id.

        URLs: ip/id_network_ipv6/id_rede 
         """

        try:
            # Commons Validations

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

            # Business Validations

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

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

            # Business Rules

            NetworkIPv6.get_by_pk(id_network)

            ips = Ipv6.list_by_network(id_network)

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

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

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

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

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

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

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

            network_map['ips'] = list_ips

            network_map
            # Return XML
            return self.response(dumps_networkapi(network_map))
Пример #19
0
    def handle_get(self, request, user, *args, **kwargs):
        """Handles GET requests to list all network IPv6 by network ipv6 id.

        URLs: ip/id_network_ipv6/id_rede
         """

        try:
            # Commons Validations

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

            # Business Validations

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

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

            # Business Rules

            NetworkIPv6.get_by_pk(id_network)

            ips = Ipv6.list_by_network(id_network)

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

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

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

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

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

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

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

            network_map['ips'] = list_ips

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

        URL: network/edit/
        '''

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

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

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

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

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

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

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

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

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

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

            # Business Rules

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

            # New network_tyoe

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

                with distributedlock(LOCK_NETWORK_IPV4 % id_network):

                    if id_env_vip is not None:

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

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

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

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

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

                    net.edit_network_ipv4(user, id_net_type, id_env_vip)

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

                with distributedlock(LOCK_NETWORK_IPV6 % id_network):

                    if id_env_vip is not None:

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

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

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

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

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

                    net.edit_network_ipv6(user, id_net_type, id_env_vip)

            # Delete vlan's cache
            # destroy_cache_function()

            return self.response(dumps_networkapi({}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
Пример #21
0
def networkIPv6_deploy(request, network_id):
    """Deploy network L3 configuration in the environment routers for network ipv6

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

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

    equipment_list = []

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

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

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

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

    if all_equipments_are_in_maintenance(equipment_list):
        raise AllEquipmentsAreInMaintenanceException()

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

        return Response(returned_data)

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