def _validate_prefix_by_net_type(self, prefix, network_type):

        if is_valid_int_param(prefix):
            if network_type == IP_VERSION.IPv4[0]:
                if int(prefix) not in range(33):
                    self.log.error(
                        u'The prefix parameter is invalid value: %s.', prefix)
                    raise InvalidValueError(None, 'prefix', prefix)
            elif network_type == IP_VERSION.IPv6[0]:
                if int(prefix) not in range(129):
                    self.log.error(
                        u'The prefix parameter is invalid value: %s.', prefix)
                    raise InvalidValueError(None, 'prefix', prefix)
Пример #2
0
    def handle_post(self, request, user, *args, **kwargs):
        """Handles POST requests to edit an IP.

        URL: ipv4/edit/
        """

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

        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
            id_ip = ip_map.get('id_ip')
            description = ip_map.get('descricao')
            ip4 = ip_map.get('ip4')

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

            if not is_valid_string_maxsize(ip4, 15):
                self.log.error(u'Parameter ip4 is invalid. Value: %s.', ip4)
                raise InvalidValueError(None, 'ip4', description)

            # Valid description
            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):
                raise UserNotAuthorizedError(
                    None, u'User does not have permission to perform the operation.')

            # Business Rules

            # New IP

            ip = Ip()

            ip = ip.get_by_pk(id_ip)

            with distributedlock(LOCK_IPV4 % id_ip):

                # se Houver erro no ip informado para retorna-lo na mensagem
                ip_error = ip4

                # verificação se foi passado algo errado no ip
                ip4 = ip4.split('.')
                for oct in ip4:
                    if not is_valid_int_param(oct):
                        raise InvalidValueError(None, 'ip4', ip_error)

                # Ip passado de forma invalida
                if len(ip4) is not 4:
                    raise IndexError

                ip.descricao = description
                ip.oct1 = ip4[0]
                ip.oct2 = ip4[1]
                ip.oct3 = ip4[2]
                ip.oct4 = ip4[3]

                # Persist
                ip.edit_ipv4(user)

                return self.response(dumps_networkapi({}))

        except UserNotAuthorizedError:
            return self.not_authorized()
        except IndexError:
            msg = 'Invalid IP %s' % ip_error
            return self.response_error(150, msg)
        except IpNotFoundError, e:
            return self.response_error(150, e.message)
    def handle_post(self, request, user, *args, **kwargs):
        """
        Handles POST requests to list all the VIPs related to IPv4 id.

        URL: vip/ipv4/all/
        """

        try:

            # Commons Validations

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

            # 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:
                return self.response_error(3, u'There is no value to the networkapi tag of XML request.')
            vip_map = networkapi_map.get('vip')
            if vip_map is None:
                return self.response_error(3, u'There is no value to the vip tag of XML request.')

            # Get XML data
            ip_str = str(vip_map['ipv4'])
            all_prop = str(vip_map['all_prop'])

            # Valid IPv4
            if not is_valid_ip(ip_str):
                self.log.error(
                    u'Parameter ipv4 is invalid. Value: %s.', ip_str)
                raise InvalidValueError(None, 'ipv4', ip_str)

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

            # Find IPv4 by octs
            octs = ip_str.split('.')

            if len(octs) != 4:
                self.log.error(
                    u'Parameter ipv4 is invalid. Value: %s.', ip_str)
                raise InvalidValueError(None, 'ipv4', ip_str)

            ipv4 = Ip().get_by_octs(octs[0], octs[1], octs[2], octs[3])

            # Business Rules
            list_ips = []
            for ip in ipv4:

                ips_map = dict()
                ips_map = model_to_dict(ip)

                # Find all VIPs related to ipv4
                if all_prop == 1:
                    ips_map["vips"] = ip.requisicaovips_set.all().values()
                else:
                    vips = ip.requisicaovips_set.all().values_list(
                        'id', flat=True)
                    ips_map["vips"] = [int(item) for item in vips]

                list_ips.append(ips_map)

            # Return XML
            vips_map = dict()
            vips_map['ips'] = list_ips

            return self.response(dumps_networkapi(vips_map))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
Пример #4
0
    def handle_post(self, request, user, *args, **kwargs):
        '''Handles POST requests to add an IP and associate it to an equipment.

        URL: ipv4/save/
        '''

        self.log.info('Add an IP 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_ipv4_id = ip_map.get('id_net')
            description = ip_map.get('descricao')
            ip4 = ip_map.get('ip4')

            # 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_ipv4_id):
                self.log.error(
                    u'Parameter network_ipv4_id is invalid. Value: %s.',
                    network_ipv4_id)
                raise InvalidValueError(None, 'network_ipv4_id',
                                        network_ipv4_id)

            # Valid ip size
            if not is_valid_string_maxsize(ip4, 15):
                self.log.error(u'Parameter ip4 is invalid. Value: %s.', ip4)
                raise InvalidValueError(None, 'ip4', ip4)

            # Description can NOT be greater than 100
            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
            ip = Ip()

            net = NetworkIPv4.get_by_pk(network_ipv4_id)

            with distributedlock(LOCK_NETWORK_IPV4 % network_ipv4_id):

                # se Houver erro no ip informado para retorna-lo na mensagem
                ip_error = ip4

                # verificação se foi passado algo errado no ip
                ip4 = ip4.split(".")
                for oct in ip4:
                    if not is_valid_int_param(oct):
                        raise InvalidValueError(None, 'ip4', ip_error)
                        #raise IndexError

                # Ip passado de forma invalida
                if len(ip4) is not 4:
                    raise IndexError

                ip.descricao = description
                ip.oct1 = ip4[0]
                ip.oct2 = ip4[1]
                ip.oct3 = ip4[2]
                ip.oct4 = ip4[3]

                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
                ip.save_ipv4(equip_id, user, net)

                list_ip = []
                lequips = []

                if ip.id is None:
                    ip = Ip.get_by_octs_and_net(ip.oct1, ip.oct2, ip.oct3,
                                                ip.oct4, net.id)

                equips = IpEquipamento.list_by_ip(ip.id)
                ip_maps = dict()
                ip_maps['id'] = ip.id
                ip_maps['oct1'] = ip.oct1
                ip_maps['oct2'] = ip.oct2
                ip_maps['oct3'] = ip.oct3
                ip_maps['oct4'] = ip.oct4
                ip_maps['descricao'] = ip.descricao

                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['ip'] = 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 edit an IP.

        URL: ipv4/edit/
        """

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

        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
            id_ip = ip_map.get('id_ip')
            description = ip_map.get('descricao')
            ip4 = ip_map.get('ip4')

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

            if not is_valid_string_maxsize(ip4, 15):
                self.log.error(u'Parameter ip4 is invalid. Value: %s.', ip4)
                raise InvalidValueError(None, 'ip4', description)

            # Valid description
            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):
                raise UserNotAuthorizedError(
                    None,
                    u'User does not have permission to perform the operation.')

            # Business Rules

            # New IP

            ip = Ip()

            ip = ip.get_by_pk(id_ip)

            with distributedlock(LOCK_IPV4 % id_ip):

                # se Houver erro no ip informado para retorna-lo na mensagem
                ip_error = ip4

                # verificação se foi passado algo errado no ip
                ip4 = ip4.split('.')
                for oct in ip4:
                    if not is_valid_int_param(oct):
                        raise InvalidValueError(None, 'ip4', ip_error)

                # Ip passado de forma invalida
                if len(ip4) is not 4:
                    raise IndexError

                ip.descricao = description
                ip.oct1 = ip4[0]
                ip.oct2 = ip4[1]
                ip.oct3 = ip4[2]
                ip.oct4 = ip4[3]

                # Persist
                ip.edit_ipv4(user)

                return self.response(dumps_networkapi({}))

        except UserNotAuthorizedError:
            return self.not_authorized()
        except IndexError:
            msg = 'Invalid IP %s' % ip_error
            return self.response_error(150, msg)
        except IpNotFoundError, e:
            return self.response_error(150, e.message)
    def handle_post(self, request, user, *args, **kwargs):
        '''Handles POST requests to add an IP and associate it to an equipment.

        URL: ipv4/save/
        '''

        self.log.info('Add an IP 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_ipv4_id = ip_map.get('id_net')
            description = ip_map.get('descricao')
            ip4 = ip_map.get('ip4')

            # 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_ipv4_id):
                self.log.error(
                    u'Parameter network_ipv4_id is invalid. Value: %s.', network_ipv4_id)
                raise InvalidValueError(
                    None, 'network_ipv4_id', network_ipv4_id)

            # Valid ip size
            if not is_valid_string_maxsize(ip4, 15):
                self.log.error(u'Parameter ip4 is invalid. Value: %s.', ip4)
                raise InvalidValueError(None, 'ip4', ip4)

            # Description can NOT be greater than 100
            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
            ip = Ip()

            net = NetworkIPv4.get_by_pk(network_ipv4_id)

            with distributedlock(LOCK_NETWORK_IPV4 % network_ipv4_id):

                # se Houver erro no ip informado para retorna-lo na mensagem
                ip_error = ip4

                # verificação se foi passado algo errado no ip
                ip4 = ip4.split(".")
                for oct in ip4:
                    if not is_valid_int_param(oct):
                        raise InvalidValueError(None, 'ip4', ip_error)
                        #raise IndexError

                # Ip passado de forma invalida
                if len(ip4) is not 4:
                    raise IndexError

                ip.descricao = description
                ip.oct1 = ip4[0]
                ip.oct2 = ip4[1]
                ip.oct3 = ip4[2]
                ip.oct4 = ip4[3]

                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
                ip.save_ipv4(equip_id, user, net)

                list_ip = []
                lequips = []

                if ip.id is None:
                    ip = Ip.get_by_octs_and_net(
                        ip.oct1, ip.oct2, ip.oct3, ip.oct4, net.id)

                equips = IpEquipamento.list_by_ip(ip.id)
                ip_maps = dict()
                ip_maps['id'] = ip.id
                ip_maps['oct1'] = ip.oct1
                ip_maps['oct2'] = ip.oct2
                ip_maps['oct3'] = ip.oct3
                ip_maps['oct4'] = ip.oct4
                ip_maps['descricao'] = ip.descricao

                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['ip'] = 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 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)
Пример #8
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)