def handle_delete(self, request, user, *args, **kwargs):
        """Trata as requisições de DELETE para remover uma associação entre um Equipamento e um Grupo.

        URL:  /equipamentogrupo/equipamento/<id_equip>/egrupo/<id_egrupo>/
        """
        try:

            equip_id = kwargs.get('id_equip')
            if not is_valid_int_greater_zero_param(equip_id):
                self.log.error(
                    u'The equip_id parameter is not a valid value: %s.',
                    equip_id)
                raise InvalidValueError(None, 'equip_id', equip_id)

            egroup_id = kwargs.get('id_egrupo')
            if not is_valid_int_greater_zero_param(egroup_id):
                self.log.error(
                    u'The egroup_id parameter is not a valid value: %s.',
                    egroup_id)
                raise InvalidValueError(None, 'egroup_id', egroup_id)

            Equipamento.get_by_pk(equip_id)
            EGrupo.get_by_pk(egroup_id)

            if not has_perm(user, AdminPermission.EQUIPMENT_MANAGEMENT,
                            AdminPermission.WRITE_OPERATION, None, equip_id,
                            AdminPermission.EQUIP_WRITE_OPERATION):
                return self.not_authorized()

            with distributedlock(LOCK_EQUIPMENT_GROUP % egroup_id):

                EquipamentoGrupo.remove(user, equip_id, egroup_id)
                return self.response(dumps_networkapi({}))
        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
예제 #2
0
def save_rack(rack_dict):

    rack = Rack()

    rack.nome = rack_dict.get('name')
    rack.numero = rack_dict.get('number')
    rack.mac_sw1 = rack_dict.get('sw1_mac')
    rack.mac_sw2 = rack_dict.get('sw2_mac')
    rack.mac_ilo = rack_dict.get('sw3_mac')
    id_sw1 = rack_dict.get('sw1_id')
    id_sw2 = rack_dict.get('sw2_id')
    id_sw3 = rack_dict.get('sw3_id')

    if not rack.nome:
        raise exceptions.InvalidInputException("O nome do Rack não foi informado.")
    if Rack.objects.filter(nome__iexact=rack.nome):
        raise exceptions.RackNameDuplicatedError()
    if Rack.objects.filter(numero__iexact=rack.numero):
        raise exceptions.RackNumberDuplicatedValueError()

    if not id_sw1:
        raise exceptions.InvalidInputException("O Leaf de id %s não existe." % id_sw1)
    if not id_sw2:
        raise exceptions.InvalidInputException("O Leaf de id %s não existe." % id_sw2)
    if not id_sw3:
        raise exceptions.InvalidInputException("O OOB de id %s não existe." % id_sw3)

    rack.id_sw1 = Equipamento.get_by_pk(int(id_sw1))
    rack.id_sw2 = Equipamento.get_by_pk(int(id_sw2))
    rack.id_ilo = Equipamento.get_by_pk(int(id_sw3))

    rack.save()
    return rack
예제 #3
0
    def handle_delete(self, request, user, *args, **kwargs):
        """Treat DELETE requests to remove IP and Equipment relationship.

        URL: ip/<id_ip>/equipamento/<id_equipamento>/$
        """
        try:

            ip_id = kwargs.get('id_ip')
            equip_id = kwargs.get('id_equipamento')

            if not is_valid_int_greater_zero_param(ip_id):
                self.log.error(
                    u'The ip_id parameter is not a valid value: %s.', ip_id)
                raise InvalidValueError(None, 'ip_id', ip_id)

            if not is_valid_int_greater_zero_param(equip_id):
                self.log.error(
                    u'The equip_id parameter is not a valid value: %s.', equip_id)
                raise InvalidValueError(None, 'equip_id', equip_id)

            Ip.get_by_pk(ip_id)
            Equipamento.get_by_pk(equip_id)

            with distributedlock(LOCK_IP_EQUIPMENT % (ip_id, equip_id)):

                ipv4 = Ip.get_by_pk(ip_id)
                equipament = Equipamento.get_by_pk(equip_id)

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

                # delete equipment's cache
                destroy_cache_function([equip_id], True)

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

                if server_pool_member_list.count() != 0:
                    # IP associated with Server Pool

                    server_pool_name_list = set()

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

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

                    raise IpCantRemoveFromServerPool({'ip': mount_ipv4_string(ipv4), 'equip_name': equipament.nome, 'server_pool_identifiers': server_pool_identifiers},
                                                     'Ipv4 não pode ser disassociado do equipamento %s porque ele está sendo utilizando nos Server Pools (id:identifier) %s' % (equipament.nome, server_pool_identifiers))

                remove_ip_equipment(ip_id, equip_id, user)

                return self.response(dumps_networkapi({}))

        except IpCantRemoveFromServerPool, e:
            return self.response_error(385, e.cause.get('ip'), e.cause.get('equip_name'), e.cause.get('server_pool_identifiers'))
    def handle_delete(self, request, user, *args, **kwargs):
        """Trata uma requisição DELETE para excluir uma informação de acesso a equipamento

        URL: /equipamentoacesso/id_equipamento/id_tipo_acesso/

        """

        # Verifica acesso e obtém dados do request
        try:
            # Obtém argumentos passados na URL
            id_equipamento = kwargs.get('id_equipamento')

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

            id_tipo_acesso = kwargs.get('id_tipo_acesso')

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

            Equipamento.get_by_pk(id_equipamento)

            TipoAcesso.get_by_pk(id_tipo_acesso)

            # Após obtenção do id_equipamento podemos verificar a permissão
            if not has_perm(user, AdminPermission.EQUIPMENT_MANAGEMENT,
                            AdminPermission.WRITE_OPERATION, None,
                            id_equipamento,
                            AdminPermission.EQUIP_WRITE_OPERATION):
                return self.not_authorized()

            with distributedlock(LOCK_EQUIPMENT_ACCESS % id_tipo_acesso):

                # Remove a informação de acesso a equipamento
                EquipamentoAcesso.remove(user, id_equipamento, id_tipo_acesso)

                # Retorna response vazio em caso de sucesso
                return self.response(dumps_networkapi({}))
        except InvalidValueError as e:
            return self.response_error(269, e.param, e.value)
        except EquipamentoNotFoundError:
            return self.response_error(117, id_equipamento)
        except AccessTypeNotFoundError:
            return self.response_error(171, id_tipo_acesso)
        except EquipamentoAcesso.DoesNotExist:
            return self.response_error(209, id_equipamento, id_tipo_acesso)
        except (EquipamentoError, GrupoError):
            return self.response_error(1)
    def handle_get(self, request, user, *args, **kwargs):
        """Treat requests GET to list all the Script by Equipment.

        URL: script/equipment/<id_equipment>
        """
        try:

            self.log.info("GET to list all the Script by Equipment")

            id_equipment = kwargs.get('id_equipment')

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

            # Find Equipment by ID to check if it exist
            Equipamento.get_by_pk(id_equipment)

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

            script_list = []
            equipment_scripts = EquipamentoRoteiro.search(None, id_equipment)
            for equipment_script in equipment_scripts:
                script_map = dict()
                script_map['id'] = equipment_script.roteiro.id
                script_map['nome'] = equipment_script.roteiro.roteiro
                script_map['descricao'] = equipment_script.roteiro.descricao
                script_map[
                    'id_tipo_roteiro'] = equipment_script.roteiro.tipo_roteiro.id
                script_map[
                    'nome_tipo_roteiro'] = equipment_script.roteiro.tipo_roteiro.tipo
                script_map[
                    'descricao_tipo_roteiro'] = equipment_script.roteiro.tipo_roteiro.descricao

                script_list.append(script_map)

            return self.response(dumps_networkapi({'script': script_list}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
예제 #6
0
def save_rack(user, rack_dict):

    rack = Rack()

    rack.numero = rack_dict.get('number')
    rack.mac_sw1 = rack_dict.get('sw1_mac')
    rack.mac_sw2 = rack_dict.get('sw2_mac')
    rack.mac_ilo = rack_dict.get('sw3_mac')
    id_sw1 = rack_dict.get('sw1_id')
    id_sw2 = rack_dict.get('sw2_id')
    id_sw3 = rack_dict.get('sw3_id')

    if not rack_dict.get('name'):
        raise exceptions.InvalidInputException(
            "O nome do Rack não foi informado.")
    elif rack_dict.get('name') is not 0:
        rack.nome = rack_dict.get('name')
    try:
        Rack.objects.get(numero__iexact=rack.numero)
        raise exceptions.RackNumberDuplicatedValueError()
    except ObjectDoesNotExist:
        pass
    try:
        Rack.objects.get(nome__iexact=rack.nome)
        raise exceptions.RackNameDuplicatedError()
    except ObjectDoesNotExist:
        pass

    if id_sw1 is not None:
        try:
            rack.id_sw1 = Equipamento.get_by_pk(int(id_sw1))
        except:
            raise exceptions.InvalidInputException(
                "O Leaf de id %s não existe." % id_sw1)
    if id_sw2 is not None:
        try:
            rack.id_sw2 = Equipamento.get_by_pk(int(id_sw2))
        except:
            raise exceptions.InvalidInputException(
                "O Leaf de id %s não existe." % id_sw2)
    if id_sw3 is not None:
        try:
            rack.id_ilo = Equipamento.get_by_pk(int(id_sw3))
        except:
            raise exceptions.InvalidInputException(
                "O OOB de id %s não existe." % id_sw3)

    rack.save(user)
    return rack
    def handle_get(self, request, user, *args, **kwargs):
        """Treat requests GET to list all the Script by Equipment.

        URL: script/equipment/<id_equipment>
        """
        try:

            self.log.info("GET to list all the Script by Equipment")

            id_equipment = kwargs.get("id_equipment")

            # Valid ID Equipment
            if not is_valid_int_greater_zero_param(id_equipment):
                self.log.error(u"The id_equipment parameter is not a valid value: %s.", id_equipment)
                raise InvalidValueError(None, "id_equipment", id_equipment)

            # Find Equipment by ID to check if it exist
            Equipamento.get_by_pk(id_equipment)

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

            script_list = []
            equipment_scripts = EquipamentoRoteiro.search(None, id_equipment)
            for equipment_script in equipment_scripts:
                script_map = dict()
                script_map["id"] = equipment_script.roteiro.id
                script_map["nome"] = equipment_script.roteiro.roteiro
                script_map["descricao"] = equipment_script.roteiro.descricao
                script_map["id_tipo_roteiro"] = equipment_script.roteiro.tipo_roteiro.id
                script_map["nome_tipo_roteiro"] = equipment_script.roteiro.tipo_roteiro.tipo
                script_map["descricao_tipo_roteiro"] = equipment_script.roteiro.tipo_roteiro.descricao

                script_list.append(script_map)

            return self.response(dumps_networkapi({"script": script_list}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
    def handle_delete(self, request, user, *args, **kwargs):
        """Trata uma requisição DELETE para excluir uma informação de acesso a equipamento

        URL: /equipamentoacesso/id_equipamento/id_tipo_acesso/ 

        """

        # Verifica acesso e obtém dados do request
        try:
            # Obtém argumentos passados na URL
            id_equipamento = kwargs.get('id_equipamento')

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

            id_tipo_acesso = kwargs.get('id_tipo_acesso')

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

            Equipamento.get_by_pk(id_equipamento)

            TipoAcesso.get_by_pk(id_tipo_acesso)

            # Após obtenção do id_equipamento podemos verificar a permissão
            if not has_perm(user,
                            AdminPermission.EQUIPMENT_MANAGEMENT,
                            AdminPermission.WRITE_OPERATION,
                            None,
                            id_equipamento,
                            AdminPermission.EQUIP_WRITE_OPERATION):
                return self.not_authorized()

            with distributedlock(LOCK_EQUIPMENT_ACCESS % id_tipo_acesso):

                # Remove a informação de acesso a equipamento
                EquipamentoAcesso.remove(user, id_equipamento, id_tipo_acesso)

                # Retorna response vazio em caso de sucesso
                return self.response(dumps_networkapi({}))
        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
예제 #9
0
def generate_and_deploy_channel_config_sync(user, id_channel):

    if not is_valid_int_greater_zero_param(id_channel):
        raise exceptions.InvalidIdInterfaceException()

    channel = PortChannel.get_by_pk(id_channel)

    interfaces = channel.list_interfaces()

    #group interfaces by equipment
    equipment_interfaces = dict()
    for interface in interfaces:
        if interface.equipamento.id not in equipment_interfaces:
            equipment_interfaces[interface.equipamento.id] = []
        equipment_interfaces[interface.equipamento.id].append(interface)

    files_to_deploy = {}
    for equipment_id in equipment_interfaces.keys():
        grouped_interfaces = equipment_interfaces[equipment_id]
        file_to_deploy = _generate_config_file(grouped_interfaces)
        files_to_deploy[equipment_id] = file_to_deploy

    #TODO Deploy config file
    #make separate threads
    for equipment_id in files_to_deploy.keys():
        lockvar = LOCK_INTERFACE_DEPLOY_CONFIG % (equipment_id)
        equipamento = Equipamento.get_by_pk(equipment_id)
        status_deploy = deploy_config_in_equipment_synchronous(files_to_deploy[equipment_id], equipamento, lockvar)

    return status_deploy
예제 #10
0
def deploy_config_in_equipment_synchronous(rel_filename, equipment, lockvar, tftpserver=None, equipment_access=None):
	'''Apply configuration file on equipment

	Args:
		rel_filename: relative file path from TFTPBOOT_FILES_PATH to apply in equipment
		equipment: networkapi.equipamento.Equipamento() or Equipamento().id
		lockvar: distributed lock variable to use when applying config to equipment
		equipment_access: networkapi.equipamento.EquipamentoAcesso() to use
		tftpserver: source TFTP server address

	Returns:
		equipment output

	Raises:
	'''

	#validate filename
	path = os.path.abspath(TFTPBOOT_FILES_PATH+rel_filename)
	if not path.startswith(TFTPBOOT_FILES_PATH):
		raise exceptions.InvalidFilenameException(rel_filename)

	if type(equipment) is int:
		equipment = Equipamento.get_by_pk(equipment)
	elif type(equipment) is Equipamento:
		pass
	else:
		log.error("Invalid data for equipment")
		raise api_exceptions.NetworkAPIException()

	with distributedlock(lockvar):
		return __applyConfig(equipment, rel_filename, equipment_access, tftpserver)
예제 #11
0
def generate_and_deploy_channel_config_sync(user, id_channel):

    if not is_valid_int_greater_zero_param(id_channel):
        raise exceptions.InvalidIdInterfaceException()

    channel = PortChannel.get_by_pk(id_channel)

    interfaces = channel.list_interfaces()

    # group interfaces by equipment
    equipment_interfaces = dict()
    for interface in interfaces:
        if interface.equipamento.id not in equipment_interfaces:
            equipment_interfaces[interface.equipamento.id] = []
        equipment_interfaces[interface.equipamento.id].append(interface)

    files_to_deploy = {}
    for equipment_id in equipment_interfaces.keys():
        grouped_interfaces = equipment_interfaces[equipment_id]
        file_to_deploy = _generate_config_file(grouped_interfaces)
        files_to_deploy[equipment_id] = file_to_deploy

    # TODO Deploy config file
    # make separate threads
    for equipment_id in files_to_deploy.keys():
        lockvar = LOCK_INTERFACE_DEPLOY_CONFIG % (equipment_id)
        equipamento = Equipamento.get_by_pk(equipment_id)
        status_deploy = deploy_config_in_equipment_synchronous(
            files_to_deploy[equipment_id], equipamento, lockvar)

    return status_deploy
예제 #12
0
def has_perm(user, perm_function, perm_oper, egroup_id=None, equip_id=None, equip_oper=None):
    '''
    @raise EGrupoNotFoundError: Grupo do equipamento nao cadastrado.

    @raise EquipamentoNotFoundError: Equipamento nao cadastrado.

    @raise GrupoError: Falha ao pesquisar os direitos do grupo-equipamento, ou as permissões administrativas, ou o grupo do equipamento.

    @raise EquipamentoError: Falha ao pesquisar o equipamento.
    '''
    if user is None:
        return False

    egroups = None
    if egroup_id is not None:
        egroup = EGrupo.get_by_pk(egroup_id)
        egroups = [egroup]
    elif equip_id is not None:
        equip = Equipamento.get_by_pk(equip_id, 'grupos')
        egroups = equip.grupos.all()
        if len(egroups) == 0:
            return False

    ugroups = user.grupos.all()
    for ugroup in ugroups:
        try:
            # perm = PermissaoAdministrativa().get_permission(perm_function, ugroup, perm_oper)
            PermissaoAdministrativa().get_permission(perm_function, ugroup, perm_oper)
            if (egroups is None) or (_has_equip_perm(ugroup, egroups, equip_oper)):
                return True
        except PermissaoAdministrativaNotFoundError:
            continue
    return False
예제 #13
0
def has_perm(user, perm_function, perm_oper, egroup_id=None, equip_id=None, equip_oper=None):
    """
    @raise EGrupoNotFoundError: Grupo do equipamento nao cadastrado.

    @raise EquipamentoNotFoundError: Equipamento nao cadastrado.

    @raise GrupoError: Falha ao pesquisar os direitos do grupo-equipamento, ou as permissões administrativas, ou o grupo do equipamento.

    @raise EquipamentoError: Falha ao pesquisar o equipamento.
    """
    if user is None:
        return False

    egroups = None
    if egroup_id is not None:
        egroup = EGrupo.get_by_pk(egroup_id)
        egroups = [egroup]
    elif equip_id is not None:
        equip = Equipamento.get_by_pk(equip_id, 'grupos')
        egroups = equip.grupos.all()
        if len(egroups) == 0:
            return False

    ugroups = user.grupos.all()
    for ugroup in ugroups:
        try:
            # perm = PermissaoAdministrativa().get_permission(perm_function, ugroup, perm_oper)
            PermissaoAdministrativa().get_permission(perm_function, ugroup, perm_oper)
            if (egroups is None) or (_has_equip_perm(ugroup, egroups, equip_oper)):
                return True
        except PermissaoAdministrativaNotFoundError:
            continue
    return False
    def handle_delete(self, request, user, *args, **kwargs):
        """Treat requests DELETE to remove Equipment Script.

        URL: equipmentscript/<id_equipment>/<id_script>/
        """
        try:
            self.log.info("Remove Equipment Script")

            id_equipment = kwargs.get('id_equipment')
            id_script = kwargs.get('id_script')

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

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

            # Find Equipment by ID to check if it exist
            Equipamento.get_by_pk(id_equipment)

            # Find Script by ID to check if it exist
            Roteiro.get_by_pk(id_script)

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

            with distributedlock(LOCK_EQUIPMENT_SCRIPT % id_script):

                EquipamentoRoteiro.remove(user, id_equipment, id_script)
                return self.response(dumps_networkapi({}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
    def handle_delete(self, request, user, *args, **kwargs):
        """Treat requests DELETE to remove Equipment Script.

        URL: equipmentscript/<id_equipment>/<id_script>/
        """
        try:
            self.log.info("Remove Equipment Script")

            id_equipment = kwargs.get("id_equipment")
            id_script = kwargs.get("id_script")

            # Valid ID Equipment
            if not is_valid_int_greater_zero_param(id_equipment):
                self.log.error(u"The id_equipment parameter is not a valid value: %s.", id_equipment)
                raise InvalidValueError(None, "id_equipment", id_equipment)

            # Valid ID Script
            if not is_valid_int_greater_zero_param(id_script):
                self.log.error(u"The id_script parameter is not a valid value: %s.", id_script)
                raise InvalidValueError(None, "id_script", id_script)

            # Find Equipment by ID to check if it exist
            Equipamento.get_by_pk(id_equipment)

            # Find Script by ID to check if it exist
            Roteiro.get_by_pk(id_script)

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

            with distributedlock(LOCK_EQUIPMENT_SCRIPT % id_script):

                EquipamentoRoteiro.remove(user, id_equipment, id_script)
                return self.response(dumps_networkapi({}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
    def handle_get(self, request, user, *args, **kwargs):
        """Treat requests GET to list all Environments.

        URL: /ambiente/equip/id_equip
        """

        try:

            # Commons Validations

            # User permission

            if not has_perm(user, AdminPermission.ENVIRONMENT_MANAGEMENT, AdminPermission.READ_OPERATION):
                return self.not_authorized()
            if not has_perm(user, AdminPermission.EQUIPMENT_MANAGEMENT, AdminPermission.READ_OPERATION):
                return self.not_authorized()

            id_equip = kwargs.get('id_equip')

            if not is_valid_int_greater_zero_param(id_equip):
                raise InvalidValueError(None, 'id_equip', id_equip)

            # Business Rules
            equip = Equipamento.get_by_pk(id_equip)
            environments_list = EquipamentoAmbiente.get_by_equipment(equip.id)

            # Get all environments in DB
            lists_aux = []
            for environment in environments_list:
                env = Ambiente.get_by_pk(environment.ambiente.id)
                env_map = model_to_dict(env)
                env_map['grupo_l3_name'] = env.grupo_l3.nome
                env_map['ambiente_logico_name'] = env.ambiente_logico.nome
                env_map['divisao_dc_name'] = env.divisao_dc.nome
                env_map['is_router'] = environment.is_router

                try:
                    env_map['range'] = str(
                        env.min_num_vlan_1) + ' - ' + str(env.max_num_vlan_1)
                    if env.min_num_vlan_1 != env.min_num_vlan_2:
                        env_map['range'] = env_map[
                            'range'] + '; ' + str(env.min_num_vlan_2) + ' - ' + str(env.max_num_vlan_2)
                except:
                    env_map['range'] = 'Nao definido'

                if env.filter is not None:
                    env_map['filter_name'] = env.filter.name

                lists_aux.append(env_map)
            # Return XML
            environment_list = dict()
            environment_list['ambiente'] = lists_aux
            return self.response(dumps_networkapi(environment_list))

        except InvalidValueError, e:
            self.log.error(
                u'Parameter %s is invalid. Value: %s.', e.param, e.value)
            return self.response_error(269, e.param, e.value)
예제 #17
0
def save_rack(rack_dict):

    rack = Rack()

    rack.nome = rack_dict.get('name')
    rack.numero = rack_dict.get('number')
    rack.mac_sw1 = rack_dict.get('sw1_mac')
    rack.mac_sw2 = rack_dict.get('sw2_mac')
    rack.mac_ilo = rack_dict.get('sw3_mac')
    id_sw1 = rack_dict.get('sw1_id')
    id_sw2 = rack_dict.get('sw2_id')
    id_sw3 = rack_dict.get('sw3_id')

    if not rack.nome:
        raise exceptions.InvalidInputException(
            "O nome do Rack não foi informado.")
    if Rack.objects.filter(nome__iexact=rack.nome):
        raise exceptions.RackNameDuplicatedError()
    if Rack.objects.filter(numero__iexact=rack.numero):
        raise exceptions.RackNumberDuplicatedValueError()

    if not id_sw1:
        raise exceptions.InvalidInputException("O Leaf de id %s não existe." %
                                               id_sw1)
    if not id_sw2:
        raise exceptions.InvalidInputException("O Leaf de id %s não existe." %
                                               id_sw2)
    if not id_sw3:
        raise exceptions.InvalidInputException("O OOB de id %s não existe." %
                                               id_sw3)

    rack.id_sw1 = Equipamento.get_by_pk(int(id_sw1))
    rack.id_sw2 = Equipamento.get_by_pk(int(id_sw2))
    rack.id_ilo = Equipamento.get_by_pk(int(id_sw3))

    rack.save()
    return rack
    def handle_delete(self, request, user, *args, **kwargs):
        """Trata as requisições de DELETE para remover uma associação entre um Equipamento e um Grupo.

        URL:  /equipamentogrupo/equipamento/<id_equip>/egrupo/<id_egrupo>/
        """
        try:

            equip_id = kwargs.get('id_equip')
            if not is_valid_int_greater_zero_param(equip_id):
                self.log.error(
                    u'The equip_id parameter is not a valid value: %s.', equip_id)
                raise InvalidValueError(None, 'equip_id', equip_id)

            egroup_id = kwargs.get('id_egrupo')
            if not is_valid_int_greater_zero_param(egroup_id):
                self.log.error(
                    u'The egroup_id parameter is not a valid value: %s.', egroup_id)
                raise InvalidValueError(None, 'egroup_id', egroup_id)

            Equipamento.get_by_pk(equip_id)
            EGrupo.get_by_pk(egroup_id)

            if not has_perm(user,
                            AdminPermission.EQUIPMENT_MANAGEMENT,
                            AdminPermission.WRITE_OPERATION,
                            None,
                            equip_id,
                            AdminPermission.EQUIP_WRITE_OPERATION):
                return self.not_authorized()

            with distributedlock(LOCK_EQUIPMENT_GROUP % egroup_id):

                EquipamentoGrupo.remove(user, equip_id, egroup_id)
                return self.response(dumps_networkapi({}))
        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
    def handle_get(self, request, user, *args, **kwargs):
        """Trata as requisições de GET para listar todos os grupos de equipamento de um determindo equipamento.

        URL: egrupo/equip/id_equip
        """
        try:

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

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

            id_equip = kwargs.get('id_equip')

            if not is_valid_int_greater_zero_param(id_equip):
                raise InvalidValueError(None, 'id_equip', id_equip)

            equip = Equipamento.get_by_pk(id_equip)

            egroups = EquipamentoGrupo.get_by_equipment(equip.id)

            group_list = []
            map_list = []

            for egroup in egroups:
                group_list.append(EGrupo.get_by_pk(egroup.egrupo.id))

            for egroup in group_list:
                egroup_map = dict()
                egroup_map['id'] = egroup.id
                egroup_map['nome'] = egroup.nome
                map_list.append(egroup_map)

            network_map = dict()

            network_map['grupo'] = map_list

            return self.response(dumps_networkapi(network_map))

        except InvalidValueError, e:
            self.log.error(u'Parameter %s is invalid. Value: %s.', e.param,
                           e.value)
            return self.response_error(269, e.param, e.value)
    def handle_get(self, request, user, *args, **kwargs):
        '''Trata as requisições de GET para listar todos os grupos de equipamento de um determindo equipamento.

        URL: egrupo/equip/id_equip
        '''
        try:

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

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

            id_equip = kwargs.get('id_equip')

            if not is_valid_int_greater_zero_param(id_equip):
                raise InvalidValueError(None, 'id_equip', id_equip)

            equip = Equipamento.get_by_pk(id_equip)

            egroups = EquipamentoGrupo.get_by_equipment(equip.id)

            group_list = []
            map_list = []

            for egroup in egroups:
                group_list.append(EGrupo.get_by_pk(egroup.egrupo.id))

            for egroup in group_list:
                egroup_map = dict()
                egroup_map['id'] = egroup.id
                egroup_map['nome'] = egroup.nome
                map_list.append(egroup_map)

            network_map = dict()

            network_map['grupo'] = map_list

            return self.response(dumps_networkapi(network_map))

        except InvalidValueError, e:
            self.log.error(
                u'Parameter %s is invalid. Value: %s.', e.param, e.value)
            return self.response_error(269, e.param, e.value)
예제 #21
0
    def create(self, authenticated_user):
        """Add new interface

        @param authenticated_user: User Authentication
        @return: Interface instance

        @raise EquipamentoNotFoundError: Equipment doesn't exist
        @raise EquipamentoError: Failed to find equipment
        @raise FrontLinkNotFoundError: FrontEnd interface doesn't exist
        @raise BackLinkNotFoundError: BackEnd interface doesn't exist
        @raise InterfaceForEquipmentDuplicatedError: An interface with the same name on the same
        equipment already exists
        @raise InterfaceError: Failed to add new interface
        """

        # Valid equipment
        self.equipamento = Equipamento.get_by_pk(self.equipamento.id)

        marca = self.equipamento.modelo.marca.id if self.equipamento.tipo_equipamento.id != 2 else 0

        if marca == 0:
            regex = '^([a-zA-Z0-9-_/ ]+(:)?){1,6}$'
        elif marca == 2:
            regex = '^(Int)\s[0-9]+$'
        elif marca == 3:
            regex = '^(Fa|Gi|Te|Serial|Eth|mgmt)\s?[0-9]+(/[0-9]+(/[0-9]+)?)?$'
        elif marca == 4:
            regex = '^(interface)\s[0-9a-zA-Z]+(/[0-9a-zA-Z])+([0-9a-zA-Z-.]+)?$'
        elif marca == 5:
            regex = '^(eth)[0-9]+(/[0-9]+)?$'
        else:
            regex = ''

        # Checks if name is valid according to the brand
        if not is_valid_regex(self.interface, regex):
            raise InvalidValueError(None, 'nome', self.interface)

        # Check front end interface existence
        if self.ligacao_front is not None:
            try:
                self.ligacao_front = Interface.get_by_pk(self.ligacao_front.id)
            except InterfaceNotFoundError, e:
                raise FrontLinkNotFoundError(
                    e, u'Frontend interface does not exist')
예제 #22
0
    def create(self, authenticated_user):
        """Add new interface

        @return: Interface instance

        @raise EquipamentoNotFoundError: Equipment doesn't exist
        @raise EquipamentoError: Failed to find equipment 
        @raise FrontLinkNotFoundError: FrontEnd interface doesn't exist
        @raise BackLinkNotFoundError: BackEnd interface doesn't exist
        @raise InterfaceForEquipmentDuplicatedError: An interface with the same name on the same equipment already exists
        @raise InterfaceError: Failed to add new interface
        """

        # Valid equipment
        self.equipamento = Equipamento.get_by_pk(self.equipamento.id)

        marca = self.equipamento.modelo.marca.id if self.equipamento.tipo_equipamento.id != 2 else 0

        if marca == 0:
            regex = "^([a-zA-Z0-9-_/ ]+(:)?){1,6}$"
        elif marca == 2:
            regex = "^(Int)\s[0-9]+$"
        elif marca == 3:
            regex = "^(Fa|Gi|Te|Serial|Eth|mgmt)\s?[0-9]+(/[0-9]+(/[0-9]+)?)?$"
        elif marca == 4:
            regex = "^(interface)\s[0-9a-zA-Z]+(/[0-9a-zA-Z])+([0-9a-zA-Z-.]+)?$"
        elif marca == 5:
            regex = "^(eth)[0-9]+(/[0-9]+)?$"
        elif marca == 8:
            regex = "^[0-9]+$"
        else:
            regex = ""

        # Checks if name is valid according to the brand
        if not is_valid_regex(self.interface, regex):
            raise InvalidValueError(None, 'nome', self.interface)

        # Check front end interface existence
        if self.ligacao_front is not None:
            try:
                self.ligacao_front = Interface.get_by_pk(self.ligacao_front.id)
            except InterfaceNotFoundError, e:
                raise FrontLinkNotFoundError(
                    e, u'Frontend interface does not exist')
예제 #23
0
def deploy_config_in_equipment_synchronous(rel_filename,
                                           equipment,
                                           lockvar,
                                           tftpserver=None,
                                           equipment_access=None):
    """Apply configuration file on equipment

    Args:
            rel_filename: relative file path from TFTPBOOT_FILES_PATH to apply
                          in equipment
            equipment: networkapi.equipamento.Equipamento() or Equipamento().id
            lockvar: distributed lock variable to use when applying config to
                     equipment
            equipment_access: networkapi.equipamento.EquipamentoAcesso() to use
            tftpserver: source TFTP server address

    Returns:
            equipment output

    Raises:
    """

    # validate filename
    path = os.path.abspath(TFTPBOOT_FILES_PATH + rel_filename)
    if not path.startswith(TFTPBOOT_FILES_PATH):
        raise exceptions.InvalidFilenameException(rel_filename)

    if type(equipment) is int:
        equipment = Equipamento.get_by_pk(equipment)
    elif type(equipment) is Equipamento:
        pass
    else:
        log.error('Invalid data for equipment')
        raise api_exceptions.NetworkAPIException()

    if equipment.maintenance:
        raise AllEquipmentsAreInMaintenanceException()

    with distributedlock(lockvar):
        return _applyconfig(equipment, rel_filename, equipment_access,
                            tftpserver)
    def handle_get(self, request, user, *args, **kwargs):
        '''Trata as requisições de GET remover a associação entre um grupo de equipamento e um equipamento.

        URL: egrupo/equipamento/id_equip/egrupo/id_egrupo/
        '''
        try:

            id_equip = kwargs.get('id_equipamento')
            id_egrupo = kwargs.get('id_egrupo')

            if not is_valid_int_greater_zero_param(id_egrupo):
                raise InvalidValueError(None, 'id_egrupo', id_egrupo)

            if not is_valid_int_greater_zero_param(id_equip):
                raise InvalidValueError(None, 'id_equip', id_equip)

            equip = Equipamento.get_by_pk(id_equip)
            EGrupo.get_by_pk(id_egrupo)

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

            with distributedlock(LOCK_EQUIPMENT_GROUP % id_egrupo):

                EquipamentoGrupo.remove(user, equip.id, id_egrupo)

                return self.response(dumps_networkapi({}))

        except InvalidValueError, e:
            self.log.error(
                u'Parameter %s is invalid. Value: %s.', e.param, e.value)
            return self.response_error(269, e.param, e.value)
예제 #25
0
def get_poolmember_state(servers_pools):
    """
    Return Pool Members State
    """
    load_balance = {}

    for server_pool in servers_pools:

        pools_members = []

        server_pool_members = ServerPoolMember.objects.filter(
            server_pool=server_pool)
        for pool_member in server_pool_members:
            if pool_member.ipv6 is None:
                ip = pool_member.ip.ip_formated
            else:
                ip = pool_member.ipv6.ip_formated

            pools_members.append({
                'id': pool_member.id,
                'ip': ip,
                'port': pool_member.port_real,
                'member_status': pool_member.member_status
            })

        if pools_members:

            # pool_name = server_pool.identifier
            pool_id = server_pool.id

            equips = EquipamentoAmbiente.objects.filter(
                ambiente__id=server_pool.environment.id,
                equipamento__tipo_equipamento__tipo_equipamento=u'Balanceador')

            equipment_list = [e.equipamento for e in equips]
            if all_equipments_are_in_maintenance(equipment_list):
                raise AllEquipmentsAreInMaintenanceException()

            for e in equips:
                eqpt_id = str(e.equipamento.id)
                equipment_access = EquipamentoAcesso.search(
                    equipamento=e.equipamento.id,
                    protocolo="https"
                ).uniqueResult()
                equipment = Equipamento.get_by_pk(e.equipamento.id)

                plugin = PluginFactory.factory(equipment)

                if not load_balance.get(eqpt_id):

                    load_balance[eqpt_id] = {
                        'plugin': plugin,
                        'fqdn': equipment_access.fqdn,
                        'user': equipment_access.user,
                        'password': equipment_access.password,
                        'pools': [],
                    }

                load_balance[eqpt_id]['pools'].append({
                    'id': server_pool.id,
                    'nome': server_pool.identifier,
                    'pools_members': pools_members
                })

    for lb in load_balance:
        ps = {}
        status = {}
        # call plugin to get state member
        states = load_balance[lb]['plugin'].getStateMember(load_balance[lb])

        for idx, state in enumerate(states):
            pool_id = load_balance[lb]['pools'][idx]['id']
            if not ps.get(pool_id):
                ps[pool_id] = {}
                status[pool_id] = {}

            # populate variable for to verify diff states
            for idx_m, st in enumerate(state):
                member_id = load_balance[lb]['pools'][idx]['pools_members'][idx_m]['id']
                if not ps[pool_id].get(member_id):
                    ps[pool_id][member_id] = []

                ps[pool_id][member_id].append(st)
                status[pool_id][member_id] = st

    # Verify diff state of pool member in eqpts
    for idx in ps:
        for idx_m in ps[idx]:
            if len(set(ps[idx][idx_m])) > 1:
                msg = 'There are states differents in equipments.'
                log.error(msg)
                raise exceptions.DiffStatesEquipament(msg)

    return status
    def handle_get(self, request, user, *args, **kwargs):
        """Handles GET requests to list all real related equipment.

        URLs: equipamento/get_real_related/<id_equip>
        """

        try:

            # 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.')
                return self.not_authorized()

            id_equip = kwargs.get('id_equip')

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

            equipment = Equipamento.get_by_pk(id_equip)

            map_dicts = []

            # IPV4
            for ip_equip in equipment.ipequipamento_set.all():
                vip_dict = dict()

                ip = ip_equip.ip

                for server_pool_member in ip.serverpoolmember_set.all():
                    server_pool_id = server_pool_member.server_pool_id
                    vip_port_to_pool = VipPortToPool.objects.filter(
                        server_pool__id=server_pool_id)

                    for vptp in vip_port_to_pool:
                        vip = RequisicaoVips.get_by_pk(
                            vptp.requisicao_vip.id)

                        if vip.id not in vip_dict:
                            vip_dict = {str(vip.id): list()}

                        host_name = vip.variables_to_map()['host']

                        map_dicts.append({'server_pool_member_id': server_pool_member.id,
                                          'id_vip': vip.id,
                                          'host_name': host_name,
                                          'port_vip': vptp.port_vip,
                                          'port_real': server_pool_member.port_real,
                                          'ip': mount_ipv4_string(ip)})

            # IPV6
            for ip_equip in equipment.ipv6equipament_set.all():
                vip_dict = dict()

                ip = ip_equip.ip

                for server_pool_member in ip.serverpoolmember_set.all():
                    server_pool_id = server_pool_member.server_pool_id
                    vip_port_to_pool = VipPortToPool.objects.filter(
                        server_pool__id=server_pool_id)

                    for vptp in vip_port_to_pool:
                        vip = RequisicaoVips.get_by_pk(
                            vptp.requisicao_vip.id)

                        if vip.id not in vip_dict:
                            vip_dict = {str(vip.id): list()}

                        host_name = vip.variables_to_map()['host']

                        map_dicts.append({'server_pool_member_id': server_pool_member.id,
                                          'id_vip': vip.id,
                                          'host_name': host_name,
                                          'port_vip': vptp.port_vip,
                                          'port_real': server_pool_member.port_real,
                                          'ip': mount_ipv6_string(ip)})

            vip_map = dict()
            vip_map["vips"] = map_dicts
            vip_map["equip_name"] = equipment.nome

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

        except EquipamentoNotFoundError, e:
            return self.response_error(117, id_equip)
예제 #27
0
def set_poolmember_state(pools):
    """
    Set Pool Members state

    """

    try:
        load_balance = {}

        for pool in pools:

            pools_members = []

            q_filters = []
            for pool_member in pool['server_pool_members']:

                port_real = pool_member['port_real']

                if pool_member['ipv6'] is None:
                    ip = pool_member['ip']['ip_formated']

                    ip_ft = '.'.join(str(x) for x in [
                        pool_member['ip']['oct1'],
                        pool_member['ip']['oct2'],
                        pool_member['ip']['oct3'],
                        pool_member['ip']['oct4']])

                    if ip != ip_ft:
                        raise exceptions.InvalidIpNotExist()

                    q_filters.append({
                        'ip__oct1': pool_member['ip']['oct1'],
                        'ip__oct2': pool_member['ip']['oct2'],
                        'ip__oct3': pool_member['ip']['oct3'],
                        'ip__oct4': pool_member['ip']['oct4'],
                        'port_real': port_real
                    })
                else:
                    ip = pool_member['ipv6']['ip_formated']

                    ip_ft = '.'.join(str(x) for x in [
                        pool_member['ipv6']['block1'],
                        pool_member['ipv6']['block2'],
                        pool_member['ipv6']['block3'],
                        pool_member['ipv6']['block4'],
                        pool_member['ipv6']['block5'],
                        pool_member['ipv6']['block6'],
                        pool_member['ipv6']['block7'],
                        pool_member['ipv6']['block8']])

                    if ip != ip_ft:
                        raise exceptions.InvalidIpNotExist()

                    q_filters.append({
                        'ipv6__block1': pool_member['ipv6']['block1'],
                        'ipv6__block2': pool_member['ipv6']['block2'],
                        'ipv6__block3': pool_member['ipv6']['block3'],
                        'ipv6__block4': pool_member['ipv6']['block4'],
                        'ipv6__block5': pool_member['ipv6']['block5'],
                        'ipv6__block6': pool_member['ipv6']['block6'],
                        'ipv6__block7': pool_member['ipv6']['block7'],
                        'ipv6__block8': pool_member['ipv6']['block8'],
                        'port_real': port_real
                    })

                pools_members.append({
                    'id': pool_member['id'],
                    'ip': ip,
                    'port': port_real,
                    'member_status': pool_member['member_status']
                })

            server_pool_members = ServerPoolMember.objects.filter(
                reduce(lambda x, y: x | y, [Q(**q_filter) for q_filter in q_filters]), server_pool=pool['server_pool']['id'])
            if len(server_pool_members) != len(pools_members):
                raise exceptions.PoolmemberNotExist()

            pool_name = pool['server_pool']['identifier']
            server_pools = ServerPool.objects.filter(identifier=pool_name)
            if not server_pools:
                raise exceptions.PoolNotExist()

            equips = EquipamentoAmbiente.objects.filter(
                ambiente__id=pool['server_pool']['environment']['id'],
                equipamento__tipo_equipamento__tipo_equipamento=u'Balanceador')

            equipment_list = [e.equipamento for e in equips]
            if all_equipments_are_in_maintenance(equipment_list):
                raise AllEquipmentsAreInMaintenanceException()

            for e in equips:
                eqpt_id = str(e.equipamento.id)
                equipment_access = EquipamentoAcesso.search(
                    equipamento=e.equipamento.id,
                    protocolo="https"
                ).uniqueResult()
                equipment = Equipamento.get_by_pk(e.equipamento.id)

                plugin = PluginFactory.factory(equipment)

                if not load_balance.get(eqpt_id):

                    load_balance[eqpt_id] = {
                        'plugin': plugin,
                        'fqdn': equipment_access.fqdn,
                        'user': equipment_access.user,
                        'password': equipment_access.password,
                        'pools': [],
                    }

                load_balance[eqpt_id]['pools'].append({
                    'id': pool['server_pool']['id'],
                    'nome': pool_name,
                    'pools_members': pools_members
                })

        for lb in load_balance:
            load_balance[lb]['plugin'].setStateMember(load_balance[lb])
        return {}

    except Exception, exception:
        log.error(exception)
        raise exception
예제 #28
0
    def handle_get(self, request, user, *args, **kwargs):
        """Handles GET requests to get a ipv6.

        URLs: ipv6/get/id_ip6
        """

        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_ip = kwargs.get('id_ipv6')

            if not is_valid_int_greater_zero_param(id_ip):
                raise InvalidValueError(None, 'id_ip', id_ip)

            # Business Rules

            ip = Ipv6()

            ip = ip.get_by_pk(id_ip)

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

            try:

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

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

            network_map = dict()

            list_ips = []
            lequips = []

            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)

            list_ips

            network_map['ips'] = list_ips

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

        except InvalidValueError, e:
            self.log.error(
                u'Parameter %s is invalid. Value: %s.', e.param, e.value)
            return self.response_error(269, e.param, e.value)
예제 #29
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_get(self, request, user, *args, **kwargs):
        """Handles GET requests to get a ipv4.

        URLs: ip/get/id_ip
        """

        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_ip = kwargs.get('id_ip')

            if not is_valid_int_greater_zero_param(id_ip):
                raise InvalidValueError(None, 'id_ip', id_ip)

            # Business Rules

            ip = Ip()

            ip = ip.get_by_pk(id_ip)

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

            try:

                EquipIps = []
                equipsIp = IpEquipamento.list_by_ip(ip.id)
                for eIp in equipsIp:
                    EquipIps.append(eIp)
                mapa[ip.id] = EquipIps
                # lista.append(mapa)

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

            network_map = dict()

            list_ips = []
            lequips = []

            lequips = []
            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
            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)

            list_ips

            network_map['ips'] = list_ips

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

        except InvalidValueError, e:
            self.log.error(
                u'Parameter %s is invalid. Value: %s.', e.param, e.value)
            return self.response_error(269, e.param, e.value)
    def handle_delete(self, request, user, *args, **kwargs):
        """Treat Delete requests to remove related Equipment and  Environment

        URL: equipment/<id_equip>/environment/<id_amb>/
        """

        self.log.info('Remove EquipmentEnvironment by id')

        try:

            # Business Validations

            id_equipment = kwargs.get('id_equipment')
            id_environment = kwargs.get('id_environment')

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

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

            # Find Equipment by ID to check if it exist
            Equipamento.get_by_pk(id_equipment)

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

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

            with distributedlock(LOCK_EQUIPMENT_ENVIRONMENT % id_environment):
                '''
                equip_env = EquipamentoAmbiente().get_by_equipment_environment(
                    id_equipment, id_environment)

                is_error = False
                ipv4_error = ""
                ipv6_error = ""

                for ipequip in equip_env.equipamento.ipequipamento_set.all():

                    if ipequip.ip.networkipv4.vlan.ambiente.id == int(id_environment):
                        try:
                            ip = ipequip.ip
                            ipequip.remove(user, ip.id, ipequip.equipamento.id)
                        except IpCantBeRemovedFromVip, e:
                            is_error = True
                            ipv4_error += " %s.%s.%s.%s - Vip %s ," % (
                                ip.oct1, ip.oct2, ip.oct3, ip.oct4, e.cause)

                for ipequip in equip_env.equipamento.ipv6equipament_set.all():

                    if ipequip.ip.networkipv6.vlan.ambiente.id == int(id_environment):
                        try:
                            ip = ipequip.ip
                            ipequip.remove(user, ip.id, ipequip.equipamento.id)
                        except IpCantBeRemovedFromVip, e:
                            is_error = True
                            ipv6_error += " %s:%s:%s:%s:%s:%s:%s:%s - Vip %s ," % (
                                ip.block1, ip.block2, ip.block3, ip.block4, ip.block5, ip.block6, ip.block7, ip.block8, e.cause)

                if is_error:
                    return self.response_error(336, environment.show_environment(), ipv4_error, ipv6_error)

                # Remove Equipment - Environment
                '''
                EquipamentoAmbiente.remove(user, id_equipment, id_environment)

                return self.response(dumps_networkapi({}))

        except EquipamentoNotFoundError, e:
            return self.response_error(117, id_equipment)
    def handle_post(self, request, user, *args, **kwargs):
        '''Handles POST requests to associate and IP to an equipment.

        URL: ipv4/assoc/
        '''

        self.log.info('Associate Ip 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_ipv4_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_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)

            # 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 = NetworkIPv4.get_by_pk(network_ipv4_id)

            with distributedlock(LOCK_NETWORK_IPV4 % network_ipv4_id):

                # Get ip
                ip = Ip.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)

                                #Equipment type should be in both filters
                                if equip.tipo_equipamento not in tp_equip_list_one or equip.tipo_equipamento not in tp_equip_list_two:
                                    flag_vlan_error = True

                                    #Out of band network is never trunked, it is only in mgmt interface
                                    # allow it - not a good thing to to, but is very specific
                                    if vlan.ambiente.divisao_dc.nome == 'OOB-CM' or vlan_atual.ambiente.divisao_dc.nome == 'OOB-CM':
                                        flag_vlan_error = False
                                        

                            ## 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 = IpEquipamento()
                        ipEquip.get_by_ip_equipment(ip.id, equip_id)

                        # Ip %s.%s.%s.%s already has association with
                        # Equipament %s.' % (self.oct1, self.oct2, self.oct3,
                        # self.oct4,equipment_id)
                        raise IpEquipmentAlreadyAssociation(None, u'Ip %s.%s.%s.%s already has association with Equipament %s.' % (
                            ip.oct1, ip.oct2, ip.oct3, ip.oct4, equip_id))
                    except IpEquipmentNotFoundError, e:
                        pass

                    equipment = Equipamento().get_by_pk(equip_id)
                    ip_equipment = IpEquipamento()
                    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 IpEquipamento related to this equipment
                    ip_equips = IpEquipamento.objects.filter(
                        equipamento=equip_id)

                    for ip_test in [ip_equip.ip for ip_equip in ip_equips]:
                        if ip_test.networkipv4.oct1 == ip.networkipv4.oct1 and \
                                ip_test.networkipv4.oct2 == ip.networkipv4.oct2 and \
                                ip_test.networkipv4.oct3 == ip.networkipv4.oct3 and \
                                ip_test.networkipv4.oct4 == ip.networkipv4.oct4 and \
                                ip_test.networkipv4.block == ip.networkipv4.block and \
                                ip_test.networkipv4 != ip.networkipv4:

                            # Filter testing
                            if ip_test.networkipv4.vlan.ambiente.filter is None or ip.networkipv4.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.networkipv4.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.networkipv4.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 ##

                    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)

                        # Delete vlan's cache
                        destroy_cache_function([net.vlan_id])
                    except EquipamentoAmbienteDuplicatedError, e:
                        # If already exists, OK !
                        pass

                except IpRangeAlreadyAssociation, e:
                    raise IpRangeAlreadyAssociation(None, e.message)
    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)
예제 #34
0
    def handle_delete(self, request, user, *args, **kwargs):
        '''Treat DELETE requests to remove IP and Equipment relationship.

        URL: ip/<id_ip>/equipamento/<id_equipamento>/$
        '''
        try:

            ip_id = kwargs.get('id_ip')
            equip_id = kwargs.get('id_equipamento')

            if not is_valid_int_greater_zero_param(ip_id):
                self.log.error(
                    u'The ip_id parameter is not a valid value: %s.', ip_id)
                raise InvalidValueError(None, 'ip_id', ip_id)

            if not is_valid_int_greater_zero_param(equip_id):
                self.log.error(
                    u'The equip_id parameter is not a valid value: %s.',
                    equip_id)
                raise InvalidValueError(None, 'equip_id', equip_id)

            Ip.get_by_pk(ip_id)
            Equipamento.get_by_pk(equip_id)

            with distributedlock(LOCK_IP_EQUIPMENT % (ip_id, equip_id)):

                ipv4 = Ip.get_by_pk(ip_id)
                equipament = Equipamento.get_by_pk(equip_id)

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

                # delete equipment's cache
                destroy_cache_function([equip_id], True)

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

                if server_pool_member_list.count() != 0:
                    # IP associated with Server Pool

                    server_pool_name_list = set()

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

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

                    raise IpCantRemoveFromServerPool(
                        {
                            'ip': mount_ipv4_string(ipv4),
                            'equip_name': equipament.nome,
                            'server_pool_identifiers': server_pool_identifiers
                        },
                        "Ipv4 não pode ser disassociado do equipamento %s porque ele está sendo utilizando nos Server Pools (id:identifier) %s"
                        % (equipament.nome, server_pool_identifiers))

                remove_ip_equipment(ip_id, equip_id, user)

                return self.response(dumps_networkapi({}))

        except IpCantRemoveFromServerPool, e:
            return self.response_error(385, e.cause.get('ip'),
                                       e.cause.get('equip_name'),
                                       e.cause.get('server_pool_identifiers'))
    def handle_post(self, request, user, *args, **kwargs):
        """Treat requests POST to add Equipment Script.

        URL: equipmentscript/
        """

        try:

            self.log.info('Add Equipment Script')

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

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

            # Get XML data
            id_equipment = equipment_script_map.get('id_equipment')
            id_script = equipment_script_map.get('id_script')

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

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

            # Find Equipment by ID to check if it exist
            equipment = Equipamento.get_by_pk(id_equipment)

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

            # Find Script by ID to check if it exist
            script = Roteiro.get_by_pk(id_script)

            equip_script = EquipamentoRoteiro()

            # set variables
            equip_script.equipamento = equipment
            equip_script.roteiro = script

            # save Equipment Type
            equip_script.create(user)

            equip_script_map = dict()
            equip_script_map['id'] = equip_script.id
            networkapi_map = dict()
            networkapi_map['equipamento_roteiro'] = equip_script_map

            return self.response(dumps_networkapi(networkapi_map))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
예제 #36
0
    def handle_post(self, request, user, *args, **kwargs):
        """Trata as requisições de POST para criar uma nova interface para o equipamento

        URL: /interface/

        """
        # Obtém dados do request e verifica acesso
        try:

            # Obtém os dados do xml do request
            xml_map, attrs_map = loads(request.raw_post_data)

            # Obtém o mapa correspondente ao root node do mapa do XML
            # (networkapi)
            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is None:
                return self.response_error(
                    3,
                    u'Não existe valor para a tag networkapi do XML de requisição.'
                )

            # Verifica a existência do node "interface"
            interface_map = networkapi_map.get('interface')
            if interface_map is None:
                return self.response_error(
                    3,
                    u'Não existe valor para a tag interface do XML de requisição.'
                )

            # Valid id_equipamento value
            id_equipamento = interface_map.get('id_equipamento')
            if not is_valid_int_greater_zero_param(id_equipamento):
                self.log.error(
                    u'Parameter id_equipamento is invalid. Value: %s',
                    id_equipamento)
                raise InvalidValueError(None, 'id_equipamento', id_equipamento)
            else:
                id_equipamento = int(id_equipamento)

            # Check existence
            Equipamento.get_by_pk(id_equipamento)

            # Verify permission
            if not has_perm(user, AdminPermission.EQUIPMENT_MANAGEMENT,
                            AdminPermission.WRITE_OPERATION, None,
                            id_equipamento,
                            AdminPermission.EQUIP_WRITE_OPERATION):
                return self.not_authorized()

            # Valid name value
            nome = interface_map.get('nome')
            if not is_valid_string_minsize(
                    nome, 1) or not is_valid_string_maxsize(nome, 20):
                self.log.error(u'Parameter nome is invalid. Value: %s', nome)
                raise InvalidValueError(None, 'nome', nome)

            # Valid protegida value
            protegida = interface_map.get('protegida')
            if not is_valid_boolean_param(protegida):
                self.log.error(u'Parameter protegida is invalid. Value: %s',
                               protegida)
                raise InvalidValueError(None, 'protegida', protegida)
            else:
                protegida = convert_string_or_int_to_boolean(protegida)

            # Valid descricao value
            descricao = interface_map.get('descricao')
            if descricao is not None:
                if not is_valid_string_minsize(
                        descricao, 3) or not is_valid_string_maxsize(
                            descricao, 200):
                    self.log.error(
                        u'Parameter descricao is invalid. Value: %s',
                        descricao)
                    raise InvalidValueError(None, 'descricao', descricao)

            # Valid "id_ligacao_front" value
            id_ligacao_front = interface_map.get('id_ligacao_front')
            if id_ligacao_front is not None:
                if not is_valid_int_greater_zero_param(id_ligacao_front):
                    self.log.error(
                        u'The id_ligacao_front parameter is not a valid value: %s.',
                        id_ligacao_front)
                    raise InvalidValueError(None, 'id_ligacao_front',
                                            id_ligacao_front)
                else:
                    id_ligacao_front = int(id_ligacao_front)
                    ligacao_front = Interface(id=id_ligacao_front)
            else:
                ligacao_front = None

            # Valid "id_ligacao_back" value
            id_ligacao_back = interface_map.get('id_ligacao_back')
            if id_ligacao_back is not None:
                if not is_valid_int_greater_zero_param(id_ligacao_back):
                    self.log.error(
                        u'The id_ligacao_back parameter is not a valid value: %s.',
                        id_ligacao_back)
                    raise InvalidValueError(None, 'id_ligacao_back',
                                            id_ligacao_back)
                else:
                    id_ligacao_back = int(id_ligacao_back)
                    ligacao_back = Interface(id=id_ligacao_back)
            else:
                ligacao_back = None

            tipo_interface = interface_map.get('tipo')
            if tipo_interface is None:
                tipo_interface = 'Access'
            tipo_interface = TipoInterface.get_by_name(tipo_interface)

            vlan = interface_map.get('vlan')

            # Cria a interface conforme dados recebidos no XML
            interface = Interface(interface=nome,
                                  protegida=protegida,
                                  descricao=descricao,
                                  ligacao_front=ligacao_front,
                                  ligacao_back=ligacao_back,
                                  equipamento=Equipamento(id=id_equipamento),
                                  tipo=tipo_interface,
                                  vlan_nativa=vlan)

            interface.create(user)

            networkapi_map = dict()
            interface_map = dict()

            interface_map['id'] = interface.id
            networkapi_map['interface'] = interface_map

            return self.response(dumps_networkapi(networkapi_map))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
    def handle_get(self, request, user, *args, **kwargs):
        """Handles GET requests to list all network IPv4 by network ipv4 id.

        URLs: ip/id_network_ipv4/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

            NetworkIPv4.get_by_pk(id_network)

            ips = Ip.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 = IpEquipamento.list_by_ip(ip.id)
                    for eIp in equipsIp:
                        EquipIps.append(eIp)
                    mapa[ip.id] = EquipIps
                    # lista.append(mapa)

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

            network_map = dict()

            list_ips = []

            for ip in ips:
                lequips = []
                ip_maps = dict()
                ip_maps = model_to_dict(ip)

                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

            # Return XML
            return self.response(dumps_networkapi(network_map))
    def handle_post(self, request, user, *args, **kwargs):
        """Treat requests POST to edit Rack.

        URL: rack/edit/
        """

        try:

            self.log.info("Edit Rack")

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

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

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

            # Get XML data
            id_rack = rack_map.get('id_rack')
            number = rack_map.get('number')
            name = rack_map.get('name')
            mac_address_sw1 = rack_map.get('mac_address_sw1')
            mac_address_sw2 = rack_map.get('mac_address_sw2')
            mac_address_ilo = rack_map.get('mac_address_ilo')
            id_sw1 = rack_map.get('id_sw1')
            id_sw2 = rack_map.get('id_sw2')
            id_ilo = rack_map.get('id_ilo')

            racks = Rack()

            with distributedlock(LOCK_RACK % id_rack):
                racks.__dict__.update(id=id_rack, nome=name, numero=number, mac_sw1=mac_address_sw1, mac_sw2=mac_address_sw2, mac_ilo=mac_address_ilo)
                if not id_sw1==None:
                    id_sw1 = int(id_sw1)
                    racks.id_sw1 = Equipamento.get_by_pk(id_sw1)

                if not id_sw2==None:
                    id_sw2 = int(id_sw2)
                    racks.id_sw2 = Equipamento.get_by_pk(id_sw2)

                if not id_ilo==None:
                    id_ilo = int(id_ilo)
                    racks.id_ilo = Equipamento.get_by_pk(id_ilo)

                # save 
                racks.save()

                rack_map = dict()
                rack_map['rack'] = model_to_dict(racks)

            return self.response(dumps_networkapi(rack_map))

        except InvalidValueError, e:
            return self.response_error(369, e.param, e.value)
예제 #39
0
def delete_real_pool(request):
    """
    delete real pool in eqpt
    """
    pools = request.DATA.get("pools", [])

    load_balance = {}

    for pool in pools:

        pools_members = []
        for pool_member in pool['server_pool_members']:
            if pool_member['ipv6'] is None:
                ip = pool_member['ip']['ip_formated']
            else:
                ip = pool_member['ipv6']['ip_formated']

            pools_members.append({
                'id': pool_member['id'],
                'ip': ip,
                'port': pool_member['port_real'],
                'member_status': pool_member['member_status'],
                'limit': pool_member['limit'],
                'priority': pool_member['priority'],
                'weight': pool_member['weight']
            })

        equips = EquipamentoAmbiente.objects.filter(
            ambiente__id=pool['server_pool']['environment']['id'],
            equipamento__tipo_equipamento__tipo_equipamento=u'Balanceador')

        equipment_list = [e.equipamento for e in equips]
        if all_equipments_are_in_maintenance(equipment_list):
            raise AllEquipmentsAreInMaintenanceException()

        for e in equips:
            eqpt_id = str(e.equipamento.id)
            equipment_access = EquipamentoAcesso.search(
                equipamento=e.equipamento.id,
                protocolo="https"
            ).uniqueResult()
            equipment = Equipamento.get_by_pk(e.equipamento.id)

            plugin = PluginFactory.factory(equipment)

            if not load_balance.get(eqpt_id):

                load_balance[eqpt_id] = {
                    'plugin': plugin,
                    'fqdn': equipment_access.fqdn,
                    'user': equipment_access.user,
                    'password': equipment_access.password,
                    'pools': [],
                }

            load_balance[eqpt_id]['pools'].append({
                'id': pool['server_pool']['id'],
                'nome': pool['server_pool']['identifier'],
                'lb_method': pool['server_pool']['lb_method'],
                'healthcheck': pool['server_pool']['healthcheck'],
                'action': pool['server_pool']['servicedownaction']['name'],
                'pools_members': pools_members
            })

    for lb in load_balance:
        load_balance[lb]['plugin'].deletePool(load_balance[lb])

    ids = [pool['server_pool']['id'] for pool in pools]
    ServerPool.objects.filter(id__in=ids).update(pool_created=False)

    return {}
예제 #40
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)
예제 #41
0
def update_real_pool(request):
    """
    - update real pool in eqpt
    - update data pool in db
    """
    pools = request.DATA.get("pools", [])
    load_balance = {}

    # valid data for save in DB and apply in eqpt
    ps, sp = valid_to_save_reals_v2(pools)

    for pool in pools:

        ids = [p['id'] for p in pool['server_pool_members'] if p['id']]
        db_members = ServerPoolMember.objects.filter(id__in=ids)
        db_members_remove = ServerPoolMember.objects.filter(server_pool__id=pool['server_pool']['id']).exclude(id__in=ids)
        db_members_id = [str(s.id) for s in db_members]

        pools_members = list()
        for pool_member in pool['server_pool_members']:

            if not pool_member['ipv6']:
                ip = pool_member['ip']['ip_formated']
            else:
                ip = pool_member['ipv6']['ip_formated']

            if pool_member['id']:
                member = db_members[db_members_id.index(str(pool_member['id']))]
                if not member.ipv6:
                    ip_db = member.ip.ip_formated
                else:
                    ip_db = member.ipv6.ip_formated

                if member.port_real == pool_member['port_real'] and ip_db == ip:
                    pools_members.append({
                        'id': pool_member['id'],
                        'ip': ip,
                        'port': pool_member['port_real'],
                        'limit': pool_member['limit'],
                        'priority': pool_member['priority'],
                        'weight': pool_member['weight'],
                    })
                else:
                    pools_members.append({
                        'id': None,
                        'ip': ip_db,
                        'port': member.port_real,
                        'remove': 1
                    })
                    pools_members.append({
                        'id': pool_member['id'],
                        'ip': ip,
                        'port': pool_member['port_real'],
                        'limit': pool_member['limit'],
                        'priority': pool_member['priority'],
                        'weight': pool_member['weight'],
                        'new': 1
                    })
            else:
                pools_members.append({
                    'id': None,
                    'ip': ip,
                    'port': pool_member['port_real'],
                    'limit': pool_member['limit'],
                    'priority': pool_member['priority'],
                    'weight': pool_member['weight'],
                    'new': 1
                })

        # members to remove
        for member in db_members_remove:
            if not member.ipv6:
                ip_db = member.ip.ip_formated
            else:
                ip_db = member.ipv6.ip_formated
            pools_members.append({
                'id': member.id,
                'ip': ip_db,
                'port': member.port_real,
                'remove': 1
            })

        # get eqpts associate with pool
        equips = EquipamentoAmbiente.objects.filter(
            ambiente__id=pool['server_pool']['environment']['id'],
            equipamento__tipo_equipamento__tipo_equipamento=u'Balanceador')

        equipment_list = [e.equipamento for e in equips]
        if all_equipments_are_in_maintenance(equipment_list):
            raise AllEquipmentsAreInMaintenanceException()

        for e in equips:
            eqpt_id = str(e.equipamento.id)
            equipment_access = EquipamentoAcesso.search(
                equipamento=e.equipamento.id,
                protocolo="https"
            ).uniqueResult()
            equipment = Equipamento.get_by_pk(e.equipamento.id)

            plugin = PluginFactory.factory(equipment)

            if not load_balance.get(eqpt_id):

                load_balance[eqpt_id] = {
                    'plugin': plugin,
                    'fqdn': equipment_access.fqdn,
                    'user': equipment_access.user,
                    'password': equipment_access.password,
                    'pools': [],
                }

            load_balance[eqpt_id]['pools'].append({
                'id': pool['server_pool']['id'],
                'nome': pool['server_pool']['identifier'],
                'lb_method': pool['server_pool']['lb_method'],
                'healthcheck': pool['server_pool']['healthcheck'],
                'action': pool['server_pool']['servicedownaction']['name'],
                'pools_members': pools_members
            })

    # get ids from pools created
    names = [sp[p].id for idx, p in enumerate(ps) if sp[p].pool_created]
    environments = [sp[p].id for idx, p in enumerate(ps) if sp[p].pool_created]

    # call plugin to change in load balance
    for lb in load_balance:
        lbe = [l for l in load_balance[lb]['pools'] if l['id'] in names if l['id'] in environments]

        if len(lbe) > 0:
            json = load_balance[lb]
            json['pools'] = lbe
            json['plugin'].updatePool(json)

    # save pool in DB
    for idx in sp:
        idx = str(idx)
        sp[idx].identifier = ps[idx]['server_pool']['identifier']
        sp[idx].environment = Ambiente.objects.get(
            id=ps[idx]['server_pool']['environment']['id'])
        sp[idx].default_limit = ps[idx]['server_pool']['default_limit']
        sp[idx].default_port = ps[idx]['server_pool']['default_port']
        sp[idx].lb_method = ps[idx]['server_pool']['lb_method']
        sp[idx].servicedownaction = OptionPool.objects.get(
            id=ps[idx]['server_pool']['servicedownaction']['id'])
        is_healthcheck_valid(ps[idx]['server_pool']['healthcheck'])
        ps[idx]['server_pool']['healthcheck'] = ps[idx]['server_pool']['healthcheck']
        sp[idx].healthcheck = get_or_create_healthcheck(
            request.user,
            ps[idx]['server_pool']['healthcheck']['healthcheck_expect'],
            ps[idx]['server_pool']['healthcheck']['healthcheck_type'],
            ps[idx]['server_pool']['healthcheck']['healthcheck_request'],
            ps[idx]['server_pool']['healthcheck']['destination'],
            ps[idx]['server_pool']['healthcheck']['identifier'])

        sp[idx].save()

    members_id = [p['id'] for p in pool['server_pool_members'] for pool in pools if p['id']]
    pms = ServerPoolMember.objects.filter(id__in=members_id)
    pms_delete = ServerPoolMember.objects.exclude(id__in=members_id).filter(server_pool__id__in=[pool['server_pool']['id'] for pool in pools])

    members = dict()
    for pool in pools:
        for member in pool['server_pool_members']:
            if member['id']:
                members[str(member['id'])] = member

    # update pool members

    log.info(pools)
    for pm in pms:
        if members.get(str(pm.id)):
            pm.port_real = members.get(str(pm.id))['port_real']
            pm.priority = members.get(str(pm.id))['priority']
            pm.weight = members.get(str(pm.id))['weight']
            pm.limit = members.get(str(pm.id))['limit']
            pm.save()

    # delete pool members
    for pm in pms_delete:
        pm.delete()

    # create new pool members
    members = [p for p in pool['server_pool_members'] for pool in pools if not p['id']]
    for member in members:
        pm = ServerPoolMember()
        pm.server_pool_id = member['server_pool']['id']
        pm.limit = member['limit']
        if member['ip']:
            pm.ip_id = member['ip']['id']
        if member['ipv6']:
            pm.ipv6_id = member['ipv6']['id']
        pm.identifier = member['identifier']
        pm.weight = member['weight']
        pm.priority = member['priority']
        pm.port_real = member['port_real']

        pm.save()

    # Save reals
    # save_server_pool_member(request.user, sp, list_server_pool_member)

    return {}
예제 #42
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):
        """Treat requests POST to add Equipment Script.

        URL: equipmentscript/
        """

        try:

            self.log.info('Add Equipment Script')

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

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

            # Get XML data
            id_equipment = equipment_script_map.get('id_equipment')
            id_script = equipment_script_map.get('id_script')

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

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

            # Find Equipment by ID to check if it exist
            equipment = Equipamento.get_by_pk(id_equipment)

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

            # Find Script by ID to check if it exist
            script = Roteiro.get_by_pk(id_script)

            equip_script = EquipamentoRoteiro()

            # set variables
            equip_script.equipamento = equipment
            equip_script.roteiro = script

            # save Equipment Type
            equip_script.create(user)

            equip_script_map = dict()
            equip_script_map['id'] = equip_script.id
            networkapi_map = dict()
            networkapi_map['equipamento_roteiro'] = equip_script_map

            return self.response(dumps_networkapi(networkapi_map))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
    def handle_get(self, request, user, *args, **kwargs):
        """Handles GET requests to list all real related equipment.

        URLs: equipamento/get_real_related/<id_equip>
        """

        try:

            # 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.')
                return self.not_authorized()

            id_equip = kwargs.get('id_equip')

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

            equipment = Equipamento.get_by_pk(id_equip)

            map_dicts = []

            # IPV4
            for ip_equip in equipment.ipequipamento_set.all():
                vip_dict = dict()

                ip = ip_equip.ip

                for server_pool_member in ip.serverpoolmember_set.all():
                    server_pool_id = server_pool_member.server_pool_id
                    vip_port_to_pool = VipPortToPool.objects.filter(
                        server_pool__id=server_pool_id)

                    for vptp in vip_port_to_pool:
                        vip = RequisicaoVips.get_by_pk(
                            vptp.requisicao_vip.id)

                        if vip.id not in vip_dict:
                            vip_dict = {str(vip.id): list()}

                        host_name = vip.variables_to_map()['host']

                        map_dicts.append({'server_pool_member_id': server_pool_member.id,
                                          'id_vip': vip.id,
                                          'host_name': host_name,
                                          'port_vip': vptp.port_vip,
                                          'port_real': server_pool_member.port_real,
                                          'ip': mount_ipv4_string(ip)})

            # IPV6
            for ip_equip in equipment.ipv6equipament_set.all():
                vip_dict = dict()

                ip = ip_equip.ip

                for server_pool_member in ip.serverpoolmember_set.all():
                    server_pool_id = server_pool_member.server_pool_id
                    vip_port_to_pool = VipPortToPool.objects.filter(
                        server_pool__id=server_pool_id)

                    for vptp in vip_port_to_pool:
                        vip = RequisicaoVips.get_by_pk(
                            vptp.requisicao_vip.id)

                        if vip.id not in vip_dict:
                            vip_dict = {str(vip.id): list()}

                        host_name = vip.variables_to_map()['host']

                        map_dicts.append({'server_pool_member_id': server_pool_member.id,
                                          'id_vip': vip.id,
                                          'host_name': host_name,
                                          'port_vip': vptp.port_vip,
                                          'port_real': server_pool_member.port_real,
                                          'ip': mount_ipv6_string(ip)})

            vip_map = dict()
            vip_map["vips"] = map_dicts
            vip_map["equip_name"] = equipment.nome

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

        except EquipamentoNotFoundError, e:
            return self.response_error(117, id_equip)
    def handle_post(self, request, user, *args, **kwargs):
        """Treat requests POST to edit Rack.

        URL: rack/edit/
        """

        try:

            self.log.info("Edit Rack")

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

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

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

            # Get XML data
            id_rack = rack_map.get('id_rack')
            number = rack_map.get('number')
            name = rack_map.get('name')
            mac_address_sw1 = rack_map.get('mac_address_sw1')
            mac_address_sw2 = rack_map.get('mac_address_sw2')
            mac_address_ilo = rack_map.get('mac_address_ilo')
            id_sw1 = rack_map.get('id_sw1')
            id_sw2 = rack_map.get('id_sw2')
            id_ilo = rack_map.get('id_ilo')

            racks = Rack()

            with distributedlock(LOCK_RACK % id_rack):
                racks.__dict__.update(id=id_rack,
                                      nome=name,
                                      numero=number,
                                      mac_sw1=mac_address_sw1,
                                      mac_sw2=mac_address_sw2,
                                      mac_ilo=mac_address_ilo)
                if not id_sw1 == None:
                    id_sw1 = int(id_sw1)
                    racks.id_sw1 = Equipamento.get_by_pk(id_sw1)

                if not id_sw2 == None:
                    id_sw2 = int(id_sw2)
                    racks.id_sw2 = Equipamento.get_by_pk(id_sw2)

                if not id_ilo == None:
                    id_ilo = int(id_ilo)
                    racks.id_ilo = Equipamento.get_by_pk(id_ilo)

                # save
                racks.save()

                rack_map = dict()
                rack_map['rack'] = model_to_dict(racks)

            return self.response(dumps_networkapi(rack_map))

        except InvalidValueError, e:
            return self.response_error(369, e.param, e.value)
    def handle_post(self, request, user, *args, **kwargs):
        """Trata uma requisicao POST para editar um equipamento.

        URL: equipmento/edit/
        """
        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)
            equip_map = networkapi_map.get('equipamento')
            if equip_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 = equip_map.get('id_equip')
            id_modelo = equip_map.get('id_modelo')
            nome = equip_map.get('nome')
            id_tipo_equipamento = equip_map.get('id_tipo_equipamento')
            maintenance = equip_map.get('maintenance')

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

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

            # Valid nome
            if not is_valid_string_minsize(
                    nome, 3) or not is_valid_string_maxsize(
                        nome, 80) or not is_valid_regex(nome, '^[A-Z0-9-_]+$'):
                self.log.error(u'Parameter nome is invalid. Value: %s', nome)
                raise InvalidValueError(None, 'nome', nome)

            # Business Rules

            # New equipment
            equip = Equipamento()
            equip = equip.get_by_pk(equip_id)

            # maintenance is a new feature. Check existing value if not defined in request
            # Old calls does not send this field
            if maintenance is None:
                maintenance = equip.maintenance
            if not is_valid_boolean_param(maintenance):
                self.log.error(
                    u'The maintenance parameter is not a valid value: %s.',
                    maintenance)
                raise InvalidValueError(None, 'maintenance', maintenance)

            if maintenance in ['1', 'True', True]:
                maintenance = True
            else:
                maintenance = False

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

            with distributedlock(LOCK_EQUIPMENT % equip_id):
                tipo_equip = TipoEquipamento.get_by_pk(id_tipo_equipamento)

                if equip.tipo_equipamento != tipo_equip:
                    # Environments with filters using current equip type, with
                    # equipment associated
                    envs = [
                        eq_env.ambiente.id
                        for eq_env in equip.equipamentoambiente_set.filter(
                            ambiente__filter__filterequiptype__equiptype=equip.
                            tipo_equipamento)
                    ]

                    # Filters case 1 and 2

                    filters_ok = True

                    # Networks in environments with same ip range
                    nets_same_range = NetworkIPv4.objects.filter(
                        vlan__ambiente__in=envs).values(
                            'oct1', 'oct2', 'oct3', 'oct4', 'block').annotate(
                                count=Count('id')).filter(count__gt=1)

                    if len(nets_same_range) > 0:
                        for net_gp in nets_same_range:
                            nets_current_range = NetworkIPv4.objects.filter(
                                vlan__ambiente__in=envs,
                                oct1=net_gp['oct1'],
                                oct2=net_gp['oct2'],
                                oct3=net_gp['oct3'],
                                oct4=net_gp['oct4'],
                                block=net_gp['block'])
                            filters_of_envs = [
                                net.vlan.ambiente.filter.id
                                for net in nets_current_range
                            ]
                            for fil_ in filters_of_envs:
                                if TipoEquipamento.objects.filter(
                                        id=id_tipo_equipamento,
                                        filterequiptype__filter=fil_).count(
                                        ) == 0:
                                    filters_ok = False
                                    break

                            if not filters_ok:
                                raise EquipTypeCantBeChangedError(
                                    None,
                                    'O tipo de equipamento não pode ser modificado pois existe um filtro em uso que não possui o novo tipo de equipamento informado.'
                                )

                    # Networks ipv6 in environments with same ipv6 range
                    nets_v6_same_range = NetworkIPv6.objects.filter(
                        vlan__ambiente__in=envs).values(
                            'block1', 'block2', 'block3', 'block4', 'block5',
                            'block6', 'block7', 'block8', 'block').annotate(
                                count=Count('id')).filter(count__gt=1)

                    if len(nets_v6_same_range) > 0:
                        for net_gp in nets_v6_same_range:
                            nets_current_range = NetworkIPv6.objects.filter(
                                vlan__ambiente__in=envs,
                                block1=net_gp['block1'],
                                block2=net_gp['block2'],
                                block3=net_gp['block3'],
                                block4=net_gp['block4'],
                                block5=net_gp['block5'],
                                block6=net_gp['block6'],
                                block7=net_gp['block7'],
                                block8=net_gp['block8'],
                                block=net_gp['block'])
                            filters_of_envs = [
                                net.vlan.ambiente.filter.id
                                for net in nets_current_range
                            ]
                            for fil_ in filters_of_envs:
                                if TipoEquipamento.objects.filter(
                                        id=id_tipo_equipamento,
                                        filterequiptype__filter=fil_).count(
                                        ) == 0:
                                    filters_ok = False
                                    break

                            if not filters_ok:
                                raise EquipTypeCantBeChangedError(
                                    None,
                                    'O tipo de equipamento não pode ser modificado pois existe um filtro em uso que não possui o novo tipo de equipamento informado.'
                                )

                    # Filters case 1 and 2 end

                    # Filter case 3

                    # Get vlans with same number
                    vlans_same_number = Vlan.objects.filter(
                        ambiente__in=envs).values('num_vlan').annotate(
                            count=Count('id')).filter(count__gt=1)

                    if len(vlans_same_number) > 0:
                        for vlan_gp in vlans_same_number:
                            vlans_current_number = Vlan.objects.filter(
                                ambiente__in=envs,
                                num_vlan=vlan_gp['num_vlan'])
                            filters_of_envs = [
                                vlan.ambiente.filter.id
                                for vlan in vlans_current_number
                            ]
                            for fil_ in filters_of_envs:
                                if TipoEquipamento.objects.filter(
                                        id=id_tipo_equipamento,
                                        filterequiptype__filter=fil_).count(
                                        ) == 0:
                                    filters_ok = False
                                    break

                            if not filters_ok:
                                raise EquipTypeCantBeChangedError(
                                    None,
                                    'O tipo de equipamento não pode ser modificado pois existe um filtro em uso que não possui o novo tipo de equipamento informado.'
                                )

                    # Filter case 3 end

                    # Test all vip requests if equip.tipo_equipamento is
                    # balancing

                    if equip.tipo_equipamento == TipoEquipamento.get_tipo_balanceador(
                    ):
                        vips = RequisicaoVips.objects.all()
                        vip_ips = []
                        vip_ipsv6 = []
                        for vip in vips:
                            if vip.vip_criado:
                                if vip.ip is not None:
                                    if vip.ip.ipequipamento_set.filter(
                                            equipamento=equip.id).count() > 0:
                                        raise EquipTypeCantBeChangedError(
                                            None,
                                            'O tipo de equipamento não pode ser modificado pois este equipamento é o balanceador associado com o vip criado %s.'
                                            % vip.id)
                                if vip.ipv6 is not None:
                                    if vip.ipv6.ipv6equipament_set.filter(
                                            equipamento=equip.id).count() > 0:
                                        raise EquipTypeCantBeChangedError(
                                            None,
                                            'O tipo de equipamento não pode ser modificado pois este equipamento é o balanceador associado com o vip criado %s.'
                                            % vip.id)

                            else:
                                if vip.ip is not None:
                                    vip_ips.append(vip.ip.id)
                                if vip.ipv6 is not None:
                                    vip_ipsv6.append(vip.ipv6.id)

                        nets_using_balancer_in_vips_ = [
                            ip_.networkipv4
                            for ip_ in Ip.objects.filter(id__in=vip_ips)
                        ]
                        nets_using_balancer_in_vips = [
                            ip_.networkipv4 for ip_ in Ip.objects.filter(
                                networkipv4__in=nets_using_balancer_in_vips_,
                                ipequipamento__equipamento=equip.id)
                        ]
                        nets_v6_using_balancer_in_vips_ = [
                            ip_.networkipv6
                            for ip_ in Ipv6.objects.filter(id__in=vip_ipsv6)
                        ]
                        nets_v6_using_balancer_in_vips = [
                            ip_.networkipv6 for ip_ in Ipv6.objects.filter(
                                networkipv6__in=nets_v6_using_balancer_in_vips_,
                                ipv6equipament__equipamento=equip.id)
                        ]

                        for net in nets_using_balancer_in_vips:
                            net_str = str(net.oct1) + '.' + str(net.oct2) + '.' + \
                                str(net.oct3) + '.' + str(net.oct4) + \
                                '/' + str(net.block)
                            if IpEquipamento.objects.filter(
                                    ip__networkipv4=net,
                                    equipamento__tipo_equipamento=TipoEquipamento
                                    .get_tipo_balanceador()).exclude(
                                        equipamento=equip).count() == 0:
                                raise EquipTypeCantBeChangedError(
                                    None,
                                    'O tipo de equipamento não pode ser modificado pois este equipamento é o único balanceador disponível na rede %s da vlan %s.'
                                    % (net_str, net.vlan.nome))

                        for net in nets_v6_using_balancer_in_vips:
                            net_str = str(net.block1) + ':' + str(
                                net.block2
                            ) + ':' + str(net.block3) + ':' + str(
                                net.block4) + ':' + str(
                                    net.block5) + ':' + str(
                                        net.block6) + ':' + str(
                                            net.block7) + ':' + str(
                                                net.block8) + '/' + str(
                                                    net.block)
                            if Ipv6Equipament.objects.filter(
                                    ip__networkipv6=net,
                                    equipamento__tipo_equipamento=TipoEquipamento
                                    .get_tipo_balanceador()).exclude(
                                        equipamento=equip).count() == 0:
                                raise EquipTypeCantBeChangedError(
                                    None,
                                    'O tipo de equipamento não pode ser modificado pois este equipamento é o único balanceador disponível na rede %s da vlan %s.'
                                    % (net_str, net.vlan.nome))

                ip_equipamento_list = IpEquipamento.objects.filter(
                    equipamento=equip_id)
                ip6_equipamento_list = Ipv6Equipament.objects.filter(
                    equipamento=equip_id)

                # Delete vlan's cache
                key_list = []
                for eq in ip_equipamento_list:
                    vlan = eq.ip.networkipv4.vlan
                    vlan_id = vlan.id
                    key_list.append(vlan_id)

                for eq in ip6_equipamento_list:
                    vlan = eq.ip.networkipv6.vlan
                    vlan_id = vlan.id
                    key_list.append(vlan_id)

                destroy_cache_function(key_list)

                # Delete equipment's cache
                destroy_cache_function([equip_id], True)

                modelo = Modelo.get_by_pk(id_modelo)
                equip.edit(user, nome, tipo_equip, modelo, maintenance)

                return self.response(dumps_networkapi({}))

        except EquipTypeCantBeChangedError, e:
            return self.response_error(150, e.message)
예제 #47
0
    def handle_delete(self, request, user, *args, **kwargs):
        """Treat Delete requests to remove related Equipment and  Environment

        URL: equipment/<id_equip>/environment/<id_amb>/
        """

        self.log.info('Remove EquipmentEnvironment by id')

        try:

            # Business Validations

            id_equipment = kwargs.get('id_equipment')
            id_environment = kwargs.get('id_environment')

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

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

            # Find Equipment by ID to check if it exist
            Equipamento.get_by_pk(id_equipment)

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

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

            with distributedlock(LOCK_EQUIPMENT_ENVIRONMENT % id_environment):
                """
                equip_env = EquipamentoAmbiente().get_by_equipment_environment(
                    id_equipment, id_environment)

                is_error = False
                ipv4_error = ""
                ipv6_error = ""

                for ipequip in equip_env.equipamento.ipequipamento_set.all():

                    if ipequip.ip.networkipv4.vlan.ambiente.id == int(id_environment):
                        try:
                            ip = ipequip.ip
                            ipequip.remove(user, ip.id, ipequip.equipamento.id)
                        except IpCantBeRemovedFromVip, e:
                            is_error = True
                            ipv4_error += " %s.%s.%s.%s - Vip %s ," % (
                                ip.oct1, ip.oct2, ip.oct3, ip.oct4, e.cause)

                for ipequip in equip_env.equipamento.ipv6equipament_set.all():

                    if ipequip.ip.networkipv6.vlan.ambiente.id == int(id_environment):
                        try:
                            ip = ipequip.ip
                            ipequip.remove(user, ip.id, ipequip.equipamento.id)
                        except IpCantBeRemovedFromVip, e:
                            is_error = True
                            ipv6_error += " %s:%s:%s:%s:%s:%s:%s:%s - Vip %s ," % (
                                ip.block1, ip.block2, ip.block3, ip.block4, ip.block5, ip.block6, ip.block7, ip.block8, e.cause)

                if is_error:
                    return self.response_error(336, environment.show_environment(), ipv4_error, ipv6_error)

                # Remove Equipment - Environment
                """
                EquipamentoAmbiente.remove(user, id_equipment, id_environment)

                return self.response(dumps_networkapi({}))

        except EquipamentoNotFoundError, e:
            return self.response_error(117, id_equipment)
예제 #48
0
    def handle_get(self, request, user, *args, **kwargs):
        """Handles GET requests to list all network IPv4 by network ipv4 id.

        URLs: ip/id_network_ipv4/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

            NetworkIPv4.get_by_pk(id_network)

            ips = Ip.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 = IpEquipamento.list_by_ip(ip.id)
                    for eIp in equipsIp:
                        EquipIps.append(eIp)
                    mapa[ip.id] = EquipIps
                    # lista.append(mapa)

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

            network_map = dict()

            list_ips = []

            for ip in ips:
                lequips = []
                ip_maps = dict()
                ip_maps = model_to_dict(ip)

                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

            # Return XML
            return self.response(dumps_networkapi(network_map))
예제 #49
0
    def create_v4(self, route_map):

        self.equipment = Equipamento.get_by_pk(route_map.get('equipment'))
        self.route_map = RouteMap.get_by_pk(route_map.get('route_map'))
        self.save()
    def handle_post(self, request, user, *args, **kwargs):
        """Trata uma requisicao POST para editar um equipamento.

        URL: equipmento/edit/
        """

        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)
            equip_map = networkapi_map.get('equipamento')
            if equip_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 = equip_map.get('id_equip')
            id_modelo = equip_map.get('id_modelo')
            nome = equip_map.get('nome')
            id_tipo_equipamento = equip_map.get('id_tipo_equipamento')
            maintenance = equip_map.get('maintenance')

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

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

            # Valid nome
            if not is_valid_string_minsize(nome, 3) or not is_valid_string_maxsize(nome, 80) or not is_valid_regex(nome, "^[A-Z0-9-_]+$"):
                self.log.error(u'Parameter nome is invalid. Value: %s', nome)
                raise InvalidValueError(None, 'nome', nome)


            # Business Rules

            # New equipment
            equip = Equipamento()
            equip = equip.get_by_pk(equip_id)

            #maintenance is a new feature. Check existing value if not defined in request
            #Old calls does not send this field
            if maintenance is None:
                maintenance = equip.maintenance
            if not is_valid_boolean_param(maintenance):
                self.log.error(u'The maintenance parameter is not a valid value: %s.', maintenance)
                raise InvalidValueError(None, 'maintenance', maintenance)

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

            with distributedlock(LOCK_EQUIPMENT % equip_id):
                tipo_equip = TipoEquipamento.get_by_pk(id_tipo_equipamento)

                if equip.tipo_equipamento != tipo_equip:
                    # Environments with filters using current equip type, with
                    # equipment associated
                    envs = [eq_env.ambiente.id for eq_env in equip.equipamentoambiente_set.filter(
                        ambiente__filter__filterequiptype__equiptype=equip.tipo_equipamento)]

                    # Filters case 1 and 2

                    filters_ok = True

                    # Networks in environments with same ip range
                    nets_same_range = NetworkIPv4.objects.filter(vlan__ambiente__in=envs).values(
                        'oct1', 'oct2', 'oct3', 'oct4', 'block').annotate(count=Count('id')).filter(count__gt=1)

                    if len(nets_same_range) > 0:
                        for net_gp in nets_same_range:
                            nets_current_range = NetworkIPv4.objects.filter(vlan__ambiente__in=envs, oct1=net_gp[
                                                                            'oct1'], oct2=net_gp['oct2'], oct3=net_gp['oct3'], oct4=net_gp['oct4'], block=net_gp['block'])
                            filters_of_envs = [
                                net.vlan.ambiente.filter.id for net in nets_current_range]
                            for fil_ in filters_of_envs:
                                if TipoEquipamento.objects.filter(id=id_tipo_equipamento, filterequiptype__filter=fil_).count() == 0:
                                    filters_ok = False
                                    break

                            if not filters_ok:
                                raise EquipTypeCantBeChangedError(
                                    None, 'O tipo de equipamento não pode ser modificado pois existe um filtro em uso que não possui o novo tipo de equipamento informado.')

                    # Networks ipv6 in environments with same ipv6 range
                    nets_v6_same_range = NetworkIPv6.objects.filter(vlan__ambiente__in=envs).values(
                        'block1', 'block2', 'block3', 'block4', 'block5', 'block6', 'block7', 'block8', 'block').annotate(count=Count('id')).filter(count__gt=1)

                    if len(nets_v6_same_range) > 0:
                        for net_gp in nets_v6_same_range:
                            nets_current_range = NetworkIPv6.objects.filter(vlan__ambiente__in=envs, block1=net_gp['block1'], block2=net_gp['block2'], block3=net_gp[
                                                                            'block3'], block4=net_gp['block4'], block5=net_gp['block5'], block6=net_gp['block6'], block7=net_gp['block7'], block8=net_gp['block8'], block=net_gp['block'])
                            filters_of_envs = [
                                net.vlan.ambiente.filter.id for net in nets_current_range]
                            for fil_ in filters_of_envs:
                                if TipoEquipamento.objects.filter(id=id_tipo_equipamento, filterequiptype__filter=fil_).count() == 0:
                                    filters_ok = False
                                    break

                            if not filters_ok:
                                raise EquipTypeCantBeChangedError(
                                    None, 'O tipo de equipamento não pode ser modificado pois existe um filtro em uso que não possui o novo tipo de equipamento informado.')

                    # Filters case 1 and 2 end

                    # Filter case 3

                    # Get vlans with same number
                    vlans_same_number = Vlan.objects.filter(ambiente__in=envs).values(
                        'num_vlan').annotate(count=Count('id')).filter(count__gt=1)

                    if len(vlans_same_number) > 0:
                        for vlan_gp in vlans_same_number:
                            vlans_current_number = Vlan.objects.filter(
                                ambiente__in=envs, num_vlan=vlan_gp['num_vlan'])
                            filters_of_envs = [
                                vlan.ambiente.filter.id for vlan in vlans_current_number]
                            for fil_ in filters_of_envs:
                                if TipoEquipamento.objects.filter(id=id_tipo_equipamento, filterequiptype__filter=fil_).count() == 0:
                                    filters_ok = False
                                    break

                            if not filters_ok:
                                raise EquipTypeCantBeChangedError(
                                    None, 'O tipo de equipamento não pode ser modificado pois existe um filtro em uso que não possui o novo tipo de equipamento informado.')

                    # Filter case 3 end

                    # Test all vip requests if equip.tipo_equipamento is
                    # balancing

                    if equip.tipo_equipamento == TipoEquipamento.get_tipo_balanceador():
                        vips = RequisicaoVips.objects.all()
                        vip_ips = []
                        vip_ipsv6 = []
                        for vip in vips:
                            if vip.vip_criado:
                                if vip.ip is not None:
                                    if vip.ip.ipequipamento_set.filter(equipamento=equip.id).count() > 0:
                                        raise EquipTypeCantBeChangedError(
                                            None, 'O tipo de equipamento não pode ser modificado pois este equipamento é o balanceador associado com o vip criado %s.' % vip.id)
                                if vip.ipv6 is not None:
                                    if vip.ipv6.ipv6equipament_set.filter(equipamento=equip.id).count() > 0:
                                        raise EquipTypeCantBeChangedError(
                                            None, 'O tipo de equipamento não pode ser modificado pois este equipamento é o balanceador associado com o vip criado %s.' % vip.id)

                            else:
                                if vip.ip is not None:
                                    vip_ips.append(vip.ip.id)
                                if vip.ipv6 is not None:
                                    vip_ipsv6.append(vip.ipv6.id)

                        nets_using_balancer_in_vips_ = [
                            ip_.networkipv4 for ip_ in Ip.objects.filter(id__in=vip_ips)]
                        nets_using_balancer_in_vips = [ip_.networkipv4 for ip_ in Ip.objects.filter(
                            networkipv4__in=nets_using_balancer_in_vips_, ipequipamento__equipamento=equip.id)]
                        nets_v6_using_balancer_in_vips_ = [
                            ip_.networkipv6 for ip_ in Ipv6.objects.filter(id__in=vip_ipsv6)]
                        nets_v6_using_balancer_in_vips = [ip_.networkipv6 for ip_ in Ipv6.objects.filter(
                            networkipv6__in=nets_v6_using_balancer_in_vips_, ipv6equipament__equipamento=equip.id)]

                        for net in nets_using_balancer_in_vips:
                            net_str = str(net.oct1) + '.' + str(net.oct2) + '.' + \
                                str(net.oct3) + '.' + str(net.oct4) + \
                                '/' + str(net.block)
                            if IpEquipamento.objects.filter(ip__networkipv4=net, equipamento__tipo_equipamento=TipoEquipamento.get_tipo_balanceador()).exclude(equipamento=equip).count() == 0:
                                raise EquipTypeCantBeChangedError(
                                    None, 'O tipo de equipamento não pode ser modificado pois este equipamento é o único balanceador disponível na rede %s da vlan %s.' % (net_str, net.vlan.nome))

                        for net in nets_v6_using_balancer_in_vips:
                            net_str = str(net.block1) + ':' + str(net.block2) + ':' + str(net.block3) + ':' + str(net.block4) + ':' + str(
                                net.block5) + ':' + str(net.block6) + ':' + str(net.block7) + ':' + str(net.block8) + '/' + str(net.block)
                            if Ipv6Equipament.objects.filter(ip__networkipv6=net, equipamento__tipo_equipamento=TipoEquipamento.get_tipo_balanceador()).exclude(equipamento=equip).count() == 0:
                                raise EquipTypeCantBeChangedError(
                                    None, 'O tipo de equipamento não pode ser modificado pois este equipamento é o único balanceador disponível na rede %s da vlan %s.' % (net_str, net.vlan.nome))

                ip_equipamento_list = IpEquipamento.objects.filter(
                    equipamento=equip_id)
                ip6_equipamento_list = Ipv6Equipament.objects.filter(
                    equipamento=equip_id)

                # Delete vlan's cache
                key_list = []
                for eq in ip_equipamento_list:
                    vlan = eq.ip.networkipv4.vlan
                    vlan_id = vlan.id
                    key_list.append(vlan_id)

                for eq in ip6_equipamento_list:
                    vlan = eq.ip.networkipv6.vlan
                    vlan_id = vlan.id
                    key_list.append(vlan_id)

                destroy_cache_function(key_list)

                # Delete equipment's cache
                destroy_cache_function([equip_id], True)

                modelo = Modelo.get_by_pk(id_modelo)
                equip.edit(user, nome, tipo_equip, modelo)

                return self.response(dumps_networkapi({}))

        except EquipTypeCantBeChangedError, e:
            return self.response_error(150, e.message)
    def handle_post(self, request, user, *args, **kwargs):
        """Trata as requisições de POST para criar uma nova interface para o equipamento

        URL: /interface/ 

        """
        # Obtém dados do request e verifica acesso
        try:

            # Obtém os dados do xml do request
            xml_map, attrs_map = loads(request.raw_post_data)

            # Obtém o mapa correspondente ao root node do mapa do XML
            # (networkapi)
            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is None:
                return self.response_error(3, u'Não existe valor para a tag networkapi do XML de requisição.')

            # Verifica a existência do node "interface"
            interface_map = networkapi_map.get('interface')
            if interface_map is None:
                return self.response_error(3, u'Não existe valor para a tag interface do XML de requisição.')

            # Valid id_equipamento value
            id_equipamento = interface_map.get('id_equipamento')
            if not is_valid_int_greater_zero_param(id_equipamento):
                self.log.error(
                    u'Parameter id_equipamento is invalid. Value: %s', id_equipamento)
                raise InvalidValueError(None, 'id_equipamento', id_equipamento)
            else:
                id_equipamento = int(id_equipamento)

            # Check existence
            Equipamento.get_by_pk(id_equipamento)

            # Verify permission
            if not has_perm(user, AdminPermission.EQUIPMENT_MANAGEMENT, AdminPermission.WRITE_OPERATION, None,
                            id_equipamento, AdminPermission.EQUIP_WRITE_OPERATION):
                return self.not_authorized()

            # Valid name value
            nome = interface_map.get('nome')
            if not is_valid_string_minsize(nome, 1) or not is_valid_string_maxsize(nome, 20):
                self.log.error(u'Parameter nome is invalid. Value: %s', nome)
                raise InvalidValueError(None, 'nome', nome)

            # Valid protegida value
            protegida = interface_map.get('protegida')
            if not is_valid_boolean_param(protegida):
                self.log.error(
                    u'Parameter protegida is invalid. Value: %s', protegida)
                raise InvalidValueError(None, 'protegida', protegida)
            else:
                protegida = convert_string_or_int_to_boolean(protegida)

            # Valid descricao value
            descricao = interface_map.get('descricao')
            if descricao is not None:
                if not is_valid_string_minsize(descricao, 3) or not is_valid_string_maxsize(descricao, 200):
                    self.log.error(
                        u'Parameter descricao is invalid. Value: %s', descricao)
                    raise InvalidValueError(None, 'descricao', descricao)

            # Valid "id_ligacao_front" value
            id_ligacao_front = interface_map.get('id_ligacao_front')
            if id_ligacao_front is not None:
                if not is_valid_int_greater_zero_param(id_ligacao_front):
                    self.log.error(
                        u'The id_ligacao_front parameter is not a valid value: %s.', id_ligacao_front)
                    raise InvalidValueError(
                        None, 'id_ligacao_front', id_ligacao_front)
                else:
                    id_ligacao_front = int(id_ligacao_front)
                    ligacao_front = Interface(id=id_ligacao_front)
            else:
                ligacao_front = None

            # Valid "id_ligacao_back" value
            id_ligacao_back = interface_map.get('id_ligacao_back')
            if id_ligacao_back is not None:
                if not is_valid_int_greater_zero_param(id_ligacao_back):
                    self.log.error(
                        u'The id_ligacao_back parameter is not a valid value: %s.', id_ligacao_back)
                    raise InvalidValueError(
                        None, 'id_ligacao_back', id_ligacao_back)
                else:
                    id_ligacao_back = int(id_ligacao_back)
                    ligacao_back = Interface(id=id_ligacao_back)
            else:
                ligacao_back = None

            tipo_interface = interface_map.get('tipo')
            if tipo_interface == None:
                tipo_interface = "Access"
            tipo_interface = TipoInterface.get_by_name(tipo_interface)

            vlan = interface_map.get('vlan')

            # Cria a interface conforme dados recebidos no XML
            interface = Interface(
                interface=nome,
                protegida=protegida,
                descricao=descricao,
                ligacao_front=ligacao_front,
                ligacao_back=ligacao_back,
                equipamento=Equipamento(id=id_equipamento),
                tipo=tipo_interface,
                vlan_nativa=vlan
            )

            interface.create(user)

            networkapi_map = dict()
            interface_map = dict()

            interface_map['id'] = interface.id
            networkapi_map['interface'] = interface_map

            return self.response(dumps_networkapi(networkapi_map))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
    def handle_get(self, request, user, *args, **kwargs):
        """Handles GET requests to get a ipv4 and ipv6 of determined Equip.

        URLs: ip/getbyequip/id_equip
        """

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

            if not has_perm(user, AdminPermission.EQUIPMENT_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_equip = kwargs.get('id_equip')

            if not is_valid_int_greater_zero_param(id_equip):
                raise InvalidValueError(None, 'id_equip', id_equip)

            # Business Rules
            listadeIps6 = []
            listaDeIps4 = []

            equip = Equipamento.get_by_pk(id_equip)

            ipEquip = IpEquipamento()
            ips = ipEquip.list_by_equip(equip.id)

            for ip4 in ips:
                listaDeIps4.append(Ip.get_by_pk(ip4.ip.id))

            ips = Ipv6Equipament.list_by_equip(equip.id)

            for ip6 in ips:
                listadeIps6.append(Ipv6.get_by_pk(ip6.ip.id))

            network_map = dict()

            list_ips = []
            list_ip4 = []
            list_ip6 = []

            dict_ips = dict()
            ip4_maps = dict()
            ip6_maps = dict()

            for ip4 in listaDeIps4:

                ip4_maps['id'] = ip4.id
                ip4_maps['oct1'] = ip4.oct1
                ip4_maps['oct2'] = ip4.oct2
                ip4_maps['oct3'] = ip4.oct3
                ip4_maps['oct4'] = ip4.oct4
                ip4_maps['descricao'] = ip4.descricao
                ip4_maps['id_rede'] = ip4.networkipv4_id
                list_ip4.append(ip4_maps)
                ip4_maps = dict()

            for ip6 in listadeIps6:

                ip6_maps['id'] = ip6.id
                ip6_maps['block1'] = ip6.block1
                ip6_maps['block2'] = ip6.block2
                ip6_maps['block3'] = ip6.block3
                ip6_maps['block4'] = ip6.block4
                ip6_maps['block5'] = ip6.block5
                ip6_maps['block6'] = ip6.block6
                ip6_maps['block7'] = ip6.block7
                ip6_maps['block8'] = ip6.block8
                ip6_maps['descricao'] = ip6.description
                ip6_maps['id_rede'] = ip6.networkipv6_id
                list_ip6.append(ip6_maps)
                ip6_maps = dict()

            dict_ips['ipv4'] = list_ip4
            dict_ips['ipv6'] = list_ip6
            list_ips.append(dict_ips)

            network_map['ips'] = list_ips

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

        except InvalidValueError, e:
            self.log.error(
                u'Parameter %s is invalid. Value: %s.', e.param, e.value)
            return self.response_error(269, e.param, e.value)
예제 #53
0
    def handle_get(self, request, user, *args, **kwargs):
        """Handles GET requests to get a ipv4 and ipv6 of determined Equip.

        URLs: ip/getbyequip/id_equip
        """

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

            if not has_perm(user, AdminPermission.EQUIPMENT_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_equip = kwargs.get('id_equip')

            if not is_valid_int_greater_zero_param(id_equip):
                raise InvalidValueError(None, 'id_equip', id_equip)

            # Business Rules
            listadeIps6 = []
            listaDeIps4 = []

            equip = Equipamento.get_by_pk(id_equip)

            ipEquip = IpEquipamento()
            ips = ipEquip.list_by_equip(equip.id)

            for ip4 in ips:
                listaDeIps4.append(Ip.get_by_pk(ip4.ip.id))

            ips = Ipv6Equipament.list_by_equip(equip.id)

            for ip6 in ips:
                listadeIps6.append(Ipv6.get_by_pk(ip6.ip.id))

            network_map = dict()

            list_ips = []
            list_ip4 = []
            list_ip6 = []

            dict_ips = dict()
            ip4_maps = dict()
            ip6_maps = dict()

            for ip4 in listaDeIps4:

                ip4_maps['id'] = ip4.id
                ip4_maps['oct1'] = ip4.oct1
                ip4_maps['oct2'] = ip4.oct2
                ip4_maps['oct3'] = ip4.oct3
                ip4_maps['oct4'] = ip4.oct4
                ip4_maps['descricao'] = ip4.descricao
                ip4_maps['id_rede'] = ip4.networkipv4_id
                list_ip4.append(ip4_maps)
                ip4_maps = dict()

            for ip6 in listadeIps6:

                ip6_maps['id'] = ip6.id
                ip6_maps['block1'] = ip6.block1
                ip6_maps['block2'] = ip6.block2
                ip6_maps['block3'] = ip6.block3
                ip6_maps['block4'] = ip6.block4
                ip6_maps['block5'] = ip6.block5
                ip6_maps['block6'] = ip6.block6
                ip6_maps['block7'] = ip6.block7
                ip6_maps['block8'] = ip6.block8
                ip6_maps['descricao'] = ip6.description
                ip6_maps['id_rede'] = ip6.networkipv6_id
                list_ip6.append(ip6_maps)
                ip6_maps = dict()

            dict_ips['ipv4'] = list_ip4
            dict_ips['ipv6'] = list_ip6
            list_ips.append(dict_ips)

            network_map['ips'] = list_ips

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

        except InvalidValueError, e:
            self.log.error(u'Parameter %s is invalid. Value: %s.', e.param,
                           e.value)
            return self.response_error(269, e.param, e.value)
    def handle_get(self, request, user, *args, **kwargs):
        """Treat requests GET to list all Environments.

        URL: /ambiente/equip/id_equip
        """

        try:

            # Commons Validations

            # User permission

            if not has_perm(user, AdminPermission.ENVIRONMENT_MANAGEMENT,
                            AdminPermission.READ_OPERATION):
                return self.not_authorized()
            if not has_perm(user, AdminPermission.EQUIPMENT_MANAGEMENT,
                            AdminPermission.READ_OPERATION):
                return self.not_authorized()

            id_equip = kwargs.get('id_equip')

            if not is_valid_int_greater_zero_param(id_equip):
                raise InvalidValueError(None, 'id_equip', id_equip)

            # Business Rules
            equip = Equipamento.get_by_pk(id_equip)
            environments_list = EquipamentoAmbiente.get_by_equipment(equip.id)

            # Get all environments in DB
            lists_aux = []
            for environment in environments_list:
                env = Ambiente.get_by_pk(environment.ambiente.id)
                env_map = model_to_dict(env)
                env_map["grupo_l3_name"] = env.grupo_l3.nome
                env_map["ambiente_logico_name"] = env.ambiente_logico.nome
                env_map["divisao_dc_name"] = env.divisao_dc.nome
                env_map["is_router"] = environment.is_router

                try:
                    env_map['range'] = str(env.min_num_vlan_1) + " - " + str(
                        env.max_num_vlan_1)
                    if env.min_num_vlan_1 != env.min_num_vlan_2:
                        env_map['range'] = env_map['range'] + "; " + str(
                            env.min_num_vlan_2) + " - " + str(
                                env.max_num_vlan_2)
                except:
                    env_map['range'] = "Nao definido"

                if env.filter is not None:
                    env_map["filter_name"] = env.filter.name

                lists_aux.append(env_map)
            # Return XML
            environment_list = dict()
            environment_list["ambiente"] = lists_aux
            return self.response(dumps_networkapi(environment_list))

        except InvalidValueError, e:
            self.log.error(u'Parameter %s is invalid. Value: %s.', e.param,
                           e.value)
            return self.response_error(269, e.param, e.value)