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)
Exemple #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
Exemple #3
0
def update_rack(rack_id, rack):

    try:
        rack_obj = Rack()
        rack_obj = rack_obj.get_rack(idt=rack_id)

        rack_obj.nome = rack.get("name")
        rack_obj.numero = rack.get("number")
        rack_obj.mac_sw1 = rack.get("mac_sw1")
        rack_obj.mac_sw2 = rack.get("mac_sw2")
        rack_obj.mac_ilo = rack.get("mac_ilo")
        rack_obj.id_sw1 = Equipamento().get_by_pk(int(rack.get("id_sw1")))
        rack_obj.id_sw2 = Equipamento().get_by_pk(int(rack.get("id_sw2")))
        rack_obj.id_ilo = Equipamento().get_by_pk(int(rack.get("id_ilo")))
        rack_obj.dcroom = DatacenterRooms().get_dcrooms(idt=rack.get('fabric_id')) if rack.get('fabric_id') \
            else None

        rack_obj.save()

        return rack_obj

    except (exceptions.RackNumberDuplicatedValueError,
            exceptions.RackNameDuplicatedError,
            exceptions.InvalidInputException) as e:
        log.exception(e)
        raise Exception(e)
    except Exception, e:
        log.exception(e)
        raise Exception(e)
    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'))
Exemple #5
0
def create_equipment(equipment, user):
    """Create equipment"""

    equipment_obj = Equipamento()

    equipment_obj.create_v3(equipment)

    return equipment_obj
    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)
Exemple #7
0
def create_equipment(equipments, user):
    """Create equipment"""

    response = list()

    try:
        for equipment in equipments:
            equipment_obj = Equipamento()
            equipment_obj.create_v4(equipment)
            response.append({'id': equipment_obj.id})
    except EquipamentoError, e:
        raise ValidationAPIException(e.message)
Exemple #8
0
def create_equipment(equipments, user):
    """Create equipment"""

    response = list()

    try:
        for equipment in equipments:
            equipment_obj = Equipamento()
            equipment_obj.create_v3(equipment)
            response.append({'id': equipment_obj.id})
    except EquipamentoError, e:
        raise ValidationAPIException(e.message)
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_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)
Exemple #13
0
    def test_check_available_ip(self):
        ip_equipamento = IpEquipamento(equipamento=Equipamento(
            tipo_equipamento=TipoEquipamento(id=1,
                                             tipo_equipamento='balanceador')))
        network = self.mock_network(ip_equipamento)

        self.mock_user_has_permission(True)
        self.mock_get_vip_environment_by_pk(
            self.mock_vip_environment(1, 'production env', networks=[network]))
        self.mock_network_get_available_ip(IPv4Address('192.168.1.1'))
        self.mock_get_tipo_balanceador(
            TipoEquipamento(id=1, tipo_equipamento='balanceador'))
        ip_save_mock = self.mock_ip_save()

        response = self.client.post('/ip/availableip4/vip/1/',
                                    XML % 1,
                                    content_type='text/xml')

        print(response)
        xml_map = self.parse_response(response)
        self.assertEquals('192',
                          xml_map.get('networkapi').get('ip').get('oct1'))
        self.assertEquals('168',
                          xml_map.get('networkapi').get('ip').get('oct2'))
        self.assertEquals('1', xml_map.get('networkapi').get('ip').get('oct3'))
        self.assertEquals('1', xml_map.get('networkapi').get('ip').get('oct4'))
        self.assertEquals(200, response.status_code)
        self.assertTrue(ip_save_mock.called)
Exemple #14
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 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
Exemple #16
0
def get_equipment_by_id(equipment_id):
    """Get equipment by id"""

    try:
        equipment = Equipamento().get_by_pk(equipment_id)
    except EquipamentoNotFoundError, e:
        raise ObjectDoesNotExistException(e.message)
Exemple #17
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
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
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)
Exemple #20
0
    def get(self, request, *args, **kwargs):
        try:

            env_id = kwargs.get('env_id')

            data = dict()

            if env_id:
                log.info('Get Routers by environment.')

                routers_list = []
                rot_do_ambiente = facade.get_routers_by_environment(
                    int(env_id))
                for r in rot_do_ambiente:
                    router_id = r.equipamento.id
                    router = Equipamento().get_by_pk(router_id)
                    routers_list.append(facade.get_equipment_map(router))

                data['routers'] = routers_list

            return CustomResponse(data,
                                  status=status.HTTP_200_OK,
                                  request=request)

        except ObjectDoesNotExist, exception:
            log.error(exception)
            raise api_exceptions.ObjectDoesNotExistException(
                'Equipment Does Not Exist')
def aplicar(rack):

    path_config = settings.PATH_TO_CONFIG +'*'+rack.nome+'*'
    arquivos = glob.glob(path_config)

    #Get all files and search for equipments of the rack
    for var in arquivos: 
        name_equipaments = var.split('/')[-1][:-4]      
        for nome in name_equipaments:
            #Check if file is config relative to this rack
            if rack.nome in nome:
                #Apply config only in spines. Leaves already have all necessary config in startup
                if "ADD" in nome:
                    #Check if equipment in under maintenance. If so, does not aplly on it
                    try:
                        equip = Equipamento.get_by_name(nome)
                        if not equip.maintenance:
                            (erro, result) = commands.getstatusoutput("/usr/bin/backuper -T acl -b %s -e -i %s -w 300" % (var, nome))
                            if erro:
                                raise RackAplError(None, None, "Falha ao aplicar as configuracoes: %s" %(result))
                    except RackAplError, e:
                        raise e
                    except:
                        #Error equipment not found, do nothing
                        pass
    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)
Exemple #23
0
    def post(self, *args, **kwargs):
        try:
            log.info('RACK deploy.')

            rack_id = kwargs.get('rack_id')
            rack = facade.get_by_pk(rack_id)

            try:
                PATH_TO_ADD_CONFIG = get_variable('path_to_add_config')
                REL_PATH_TO_ADD_CONFIG = get_variable('rel_path_to_add_config')
            except ObjectDoesNotExist:
                raise var_exceptions.VariableDoesNotExistException("Erro buscando a variável PATH_TO_ADD_CONFIG ou "
                                                                   "REL_PATH_TO_ADD_CONFIG.")

            path_config = PATH_TO_ADD_CONFIG + '*' + rack.nome + '*'
            arquivos = glob.glob(path_config)

            # Get all files and search for equipments of the rack
            for var in arquivos:
                filename_equipments = var.split('/')[-1]
                rel_filename = REL_PATH_TO_ADD_CONFIG + filename_equipments
                log.debug("rel_filename: %s" % rel_filename)
                # Check if file is config relative to this rack
                if rack.nome in filename_equipments:
                    # Apply config only in spines. Leaves already have all necessary config in startup
                    if "ADD" in filename_equipments:
                        # Check if equipment in under maintenance. If so, does not aplly on it
                        equipment_name = filename_equipments.split('-ADD-')[0]
                        log.debug("equipment_name: %s" % equipment_name)
                        try:
                            equip = Equipamento.get_by_name(equipment_name)
                            if not equip.maintenance:
                                lockvar = LOCK_EQUIPMENT_DEPLOY_CONFIG_USERSCRIPT % (equip.id)
                                output = deploy_facade.deploy_config_in_equipment_synchronous(rel_filename, equip, lockvar)

                                log.debug("equipment output: %s" % (output))
                        except Exception as e:
                            log.exception(e)
                            raise exceptions.RackAplError(e)
            # SEPARAR AQUI!

            datas = dict()
            success_map = dict()

            success_map['rack_conf'] = True
            datas['sucesso'] = success_map

            return Response(datas, status=status.HTTP_201_CREATED)

        except exceptions.RackNumberNotFoundError as e:
            log.exception(e)
            raise exceptions.NetworkAPIException(e)
        except var_exceptions.VariableDoesNotExistException as e:
            log.error(e)
            raise api_exceptions.NetworkAPIException(
                'Erro buscando a variável PATH_TO_ADD_CONFIG ou REL_PATH_TO_ADD_CONFIG. Erro: %s' % e)
        except Exception as e:
            log.exception(e)
            raise api_exceptions.NetworkAPIException(e)
    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)
Exemple #26
0
def save_rack_dc(rack_dict):

    rack = Rack()

    rack.nome = rack_dict.get('name')
    rack.numero = rack_dict.get('number')
    rack.mac_sw1 = rack_dict.get('mac_sw1')
    rack.mac_sw2 = rack_dict.get('mac_sw2')
    rack.mac_ilo = rack_dict.get('mac_ilo')
    rack.id_sw1 = Equipamento().get_by_pk(rack_dict.get('id_sw1'))
    rack.id_sw2 = Equipamento().get_by_pk(rack_dict.get('id_sw2'))
    rack.id_sw3 = Equipamento().get_by_pk(rack_dict.get('id_ilo'))
    rack.dcroom = DatacenterRooms().get_dcrooms(
        idt=rack_dict.get('fabric_id')) if rack_dict.get('fabric_id') else None

    if not rack.nome:
        raise exceptions.InvalidInputException(
            "O nome do Rack não foi informado.")

    rack.save_rack()
    return rack
 def create_pool_member(self):
     pool = self.create_server_pool_model()
     member = ServerPoolMember(server_pool=pool,
                               identifier='member_1',
                               ip=self.create_ipv4(),
                               priority=1,
                               weight=0,
                               limit=pool.default_limit,
                               port_real=8080)
     member.equipment = Equipamento(
         id=1, nome="l-59c0df40-624d-4174-ad7e-a67e54bb3ced")
     return member
Exemple #28
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)
Exemple #31
0
def get_id_ip(real):
    """
        Get real id_ip by octs/block and equipment
    """
    equip = Equipamento().get_by_name(real['real_name'])

    # Check ip type
    if is_valid_ipv4(real['real_ip']) is True:
        oct = real['real_ip'].split('.')
        ip = Ip().get_by_octs_equipment(
            oct[0], oct[1], oct[2], oct[3], equip.id)
    else:
        block = real['real_ip'].split(':')
        ip = Ipv6().get_by_blocks_equipment(block[0], block[1], block[2], block[
            3], block[4], block[5], block[6], block[7], equip.id)

    return ip.id
    def handle_get(self, request, user, *args, **kwargs):
        """Trata as requisições de GET para consulta de um ambiente.

        Consulta o ambiente de um IP associado a um Equipamento.

        URL: /ambiente/equipamento/<nome_equip>/ip/<x1>.<x2>.<x3>.<x4>/
        """
        equipment_name = kwargs.get('nome_equip')
        oct1 = kwargs.get('x1')
        oct2 = kwargs.get('x2')
        oct3 = kwargs.get('x3')
        oct4 = kwargs.get('x4')

        if equipment_name is None or oct1 is None or oct2 is None or oct3 is None or oct4 is None:
            return super(AmbienteEquipamentoResource,
                         self).handle_get(request, user, *args, **kwargs)

        self.log.debug('nome_equip = %s', equipment_name)
        self.log.debug('x1 = %s', oct1)
        self.log.debug('x2 = %s', oct2)
        self.log.debug('x3 = %s', oct3)
        self.log.debug('x4 = %s', oct4)

        try:
            equip = Equipamento().get_by_name(equipment_name)

            if not has_perm(user, AdminPermission.ENVIRONMENT_MANAGEMENT,
                            AdminPermission.READ_OPERATION, None, equip.id,
                            AdminPermission.EQUIP_READ_OPERATION):
                return self.not_authorized()

            ip = Ip().get_by_octs_equipment(oct1, oct2, oct3, oct4, equip.id)

            environment_map = get_environment_map(ip.vlan.ambiente)
            map = dict()
            map['ambiente'] = environment_map

            return self.response(dumps_networkapi(map))

        except EquipamentoNotFoundError:
            return self.response_error(117, equipment_name)
        except IpNotFoundError:
            return self.response_error(
                118, oct1 + '.' + oct2 + '.' + oct3 + '.' + oct4, equip.id)
        except (IpError, EquipamentoError, GrupoError):
            return self.response_error(1)
Exemple #33
0
    def post(self, *args, **kwargs):
        try:
            log.info('RACK deploy.')

            rack_id = kwargs.get('rack_id')
            rack = facade.get_by_pk(rack_id)

            try:
                PATH_TO_ADD_CONFIG = get_variable('path_to_add_config')
                REL_PATH_TO_ADD_CONFIG = get_variable('rel_path_to_add_config')
            except ObjectDoesNotExist:
                raise var_exceptions.VariableDoesNotExistException(
                    "Erro buscando a variável PATH_TO_ADD_CONFIG ou "
                    "REL_PATH_TO_ADD_CONFIG.")

            path_config = PATH_TO_ADD_CONFIG + '*' + rack.nome + '*'
            arquivos = glob.glob(path_config)

            # Get all files and search for equipments of the rack
            for var in arquivos:
                filename_equipments = var.split('/')[-1]
                rel_filename = "../../" + REL_PATH_TO_ADD_CONFIG + filename_equipments
                log.debug("rel_filename: %s" % rel_filename)
                # Check if file is config relative to this rack
                if rack.nome in filename_equipments:
                    # Apply config only in spines. Leaves already have all necessary config in startup
                    if "ADD" in filename_equipments:
                        # Check if equipment in under maintenance. If so, does not aplly on it
                        equipment_name = filename_equipments.split('-ADD-')[0]
                        log.debug("equipment_name: %s" % equipment_name)
                        try:
                            equip = Equipamento.get_by_name(equipment_name)
                            if not equip.maintenance:
                                (erro, result) = commands.getstatusoutput(
                                    "/usr/bin/backuper -T acl -b %s -e -i %s -w "
                                    "300" % (rel_filename, equipment_name))
                                log.debug("erro: %s, result: %s" %
                                          (str(erro), str(result)))
                                if erro:
                                    raise exceptions.RackAplError()
                        except exceptions.RackAplError, e:
                            raise e
                        except:
                            # Error equipment not found, do nothing
                            pass
    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')
Exemple #35
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')
    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 inserir_equip(user, variablestochangecore, rede_id):
    
    ip = Ip()    
    ip.descricao = None
    ip.oct1, ip.oct2, ip.oct3, ip.oct4 = str(variablestochangecore["IPCORE"]).split('.')
    equip = Equipamento.get_by_name(variablestochangecore["EQUIP_NAME"])
    rede = NetworkIPv4.get_by_pk(rede_id)
    ip.save_ipv4(equip.id, user, rede)

    if ip.id is None:
        raise RackAplError (None, None, "Erro ao inserir os equipamentos")

    # Delete vlan's cache
    destroy_cache_function([rede.vlan_id])
    list_id_equip = []
    list_id_equip.append(equip.id)
    destroy_cache_function(list_id_equip, True)

    return 0
Exemple #38
0
    def post(self, *args, **kwargs):
        try:
            log.info('RACK deploy.')

            rack_id = kwargs.get('rack_id')
            rack = facade.get_by_pk(rack_id)

            try:
                PATH_TO_ADD_CONFIG = get_variable('path_to_add_config')
                REL_PATH_TO_ADD_CONFIG = get_variable('rel_path_to_add_config')
            except ObjectDoesNotExist:
                raise var_exceptions.VariableDoesNotExistException("Erro buscando a variável PATH_TO_ADD_CONFIG ou "
                                                                   "REL_PATH_TO_ADD_CONFIG.")

            path_config = PATH_TO_ADD_CONFIG + '*' + rack.nome + '*'
            arquivos = glob.glob(path_config)

            # Get all files and search for equipments of the rack
            for var in arquivos:
                filename_equipments = var.split('/')[-1]
                rel_filename = "../../" + REL_PATH_TO_ADD_CONFIG + filename_equipments
                log.debug("rel_filename: %s" % rel_filename)
                # Check if file is config relative to this rack
                if rack.nome in filename_equipments:
                    # Apply config only in spines. Leaves already have all necessary config in startup
                    if "ADD" in filename_equipments:
                        # Check if equipment in under maintenance. If so, does not aplly on it
                        equipment_name = filename_equipments.split('-ADD-')[0]
                        log.debug("equipment_name: %s" % equipment_name)
                        try:
                            equip = Equipamento.get_by_name(equipment_name)
                            if not equip.maintenance:
                                (erro, result) = commands.getstatusoutput("/usr/bin/backuper -T acl -b %s -e -i %s -w "
                                                                          "300" % (rel_filename, equipment_name))
                                log.debug("erro: %s, result: %s" % (str(erro), str(result)))
                                if erro:
                                    raise exceptions.RackAplError()
                        except exceptions.RackAplError, e:
                            raise e
                        except:
                            # Error equipment not found, do nothing
                            pass
Exemple #39
0
def inserir_equip(user, variablestochangecore, rede_id):

    ip = Ip()
    ip.descricao = None
    ip.oct1, ip.oct2, ip.oct3, ip.oct4 = str(
        variablestochangecore['IPCORE']).split('.')
    equip = Equipamento.get_by_name(variablestochangecore['EQUIP_NAME'])
    rede = NetworkIPv4.get_by_pk(rede_id)
    ip.save_ipv4(equip.id, user, rede)

    if ip.id is None:
        raise RackAplError(None, None, 'Erro ao inserir os equipamentos')

    # Delete vlan's cache
    destroy_cache_function([rede.vlan_id])
    list_id_equip = []
    list_id_equip.append(equip.id)
    destroy_cache_function(list_id_equip, True)

    return 0
Exemple #40
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)
Exemple #41
0
    def test_add_network_given_successfully(self):
        self.mock_get_network_type_by_pk(TipoRede(id=1))
        self.mock_get_vip_environment_by_pk(EnvironmentVip(id=1))
        add_network_mock = self.mock_add_network_ipv4(self.get_vlan_map())
        self.mock_get_equipamento_ambiente(
            EquipamentoAmbiente(equipamento=Equipamento(id=1)))
        self.mock_get_first_available_ip("192.168.10.18")
        self.mock_ip_save()
        self.mock_ip_equipamento_create()

        response = self.client.post("/network/ipv4/add/",
                                    XML.format(cidr='24',
                                               vlan=1,
                                               vip_env=1,
                                               net_type=1),
                                    content_type="text/xml")

        xml_map = self.parse_response(response)
        self.assertIsNotNone(xml_map.get('networkapi').get('vlan'))
        self.assertEquals(200, response.status_code)
        self.assertTrue(add_network_mock.called)
Exemple #42
0
    def test_add_network_given_no_first_ip_available(self):
        self.mock_get_network_type_by_pk(TipoRede(id=1))
        self.mock_get_vip_environment_by_pk(EnvironmentVip(id=1))
        add_network_mock = self.mock_add_network_ipv4({'vlan': {}})
        self.mock_get_equipamento_ambiente(
            EquipamentoAmbiente(equipamento=Equipamento(id=1)))
        self.mock_get_first_available_ip(
            IpNotAvailableError('Endereço IP não dispoínvel'))

        response = self.client.post("/network/ipv4/add/",
                                    XML.format(cidr='24',
                                               vlan=1,
                                               vip_env=1,
                                               net_type=1),
                                    content_type="text/xml")

        xml_map = self.parse_response(response)
        self.assertEquals(
            "Causa: Endereço IP não dispoínvel, Mensagem: None",
            xml_map.get('networkapi').get('erro').get('descricao'))
        self.assertEquals(500, response.status_code)
        self.assertTrue(add_network_mock.called)
    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)
    def setUp(self):
        self.user = Usuario()
        self.equipment_list = [Equipamento(id=1, nome='router')]
        self.ambiente = Ambiente()
        self.vlan = Vlan(id=1, ambiente=self.ambiente)
        self.networkv4 = NetworkIPv4(id=1,
                                     vlan=self.vlan,
                                     oct1=192,
                                     oct2=168,
                                     oct3=0,
                                     oct4=0,
                                     mask_oct1=255,
                                     mask_oct2=255,
                                     mask_oct3=255,
                                     mask_oct4=0)

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

        self.mock_distributed_lock()
        self.mock_transaction()
Exemple #45
0
    def insert_equipment_group(self, equip_id, group_id, user):

        equipment_group = EquipamentoGrupo()
        equipment_group.egrupo = EGrupo()
        equipment_group.egrupo.id = group_id
        equipment_group.equipamento = Equipamento()
        equipment_group.equipamento.id = equip_id

        try:
            equipment_group.create(user)

            equipment_group_map = dict()
            equipment_group_map['id'] = equipment_group.id
            map = dict()
            map['equipamento_grupo'] = equipment_group_map

            return self.response(dumps_networkapi(map))

        except EGrupoNotFoundError:
            return self.response_error(102)
        except EquipamentoGrupoDuplicatedError:
            return self.response_error(146)
        except (EquipamentoError, GrupoError):
            return self.response_error(1)
Exemple #46
0
    def test_check_available_ip_given_no_load_balancer_equipment_available_on_network(
            self):
        ip_equipamento = IpEquipamento(equipamento=Equipamento(
            tipo_equipamento=TipoEquipamento(id=2, tipo_equipamento='router')))
        network = self.mock_network(ip_equipamento)

        self.mock_user_has_permission(True)
        self.mock_get_vip_environment_by_pk(
            self.mock_vip_environment(1, 'production env', networks=[network]))
        self.mock_network_get_available_ip(IPv4Address('192.168.1.1'))
        self.mock_get_tipo_balanceador(
            TipoEquipamento(id=1, tipo_equipamento='balanceador'))

        response = self.client.post('/ip/availableip4/vip/1/',
                                    XML % 1,
                                    content_type='text/xml')

        xml_map = self.parse_response(response)
        self.assertEquals(
            'Não há ipv4 disponivel para as redes associdas com o Ambiente '
            'Vip: production env - production env - production env, pois não existe '
            'equipamentos do Tipo Balanceador nessas redes.',
            xml_map.get('networkapi').get('erro').get('descricao'))
        self.assertEquals(500, response.status_code)
    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 __post_virtual_group_equipment(self, equipment_maps, vip_maps, user, resp_equipment_maps, vip_equipment_ip_map):
        try:
            for equipment_map in equipment_maps:
                equipment_prefixo = equipment_map.get('prefixo')
                if equipment_prefixo is None:
                    return self.response_error(105)

                name = Equipamento.get_next_name_by_prefix(equipment_prefixo)
                equipment_map['nome'] = name

                response = insert_equipment(equipment_map, user)
                if response[0] == 0:
                    equip_id = response[2].id

                    ip_map = equipment_map.get('ip')
                    if ip_map is None:
                        return self.response_error(3, u'Não existe valor para a tag ip do equipamento %s do XML de requisição.' % equipment_map.get('nome'))

                    ip_map['id_equipamento'] = equip_id

                    response_ip = insert_ip(ip_map, user)
                    if response_ip[0] == 0:

                        # Insere um IP para cada VIP e o relacionamento dele
                        # com equipamento
                        resp_vip_maps = []
                        for vip_map in vip_maps:
                            ip_vip_map = vip_map.get('ip_real', dict())
                            ip_vip_map['id_equipamento'] = equip_id

                            response_ip_vip = insert_ip(ip_vip_map, user)
                            if (response_ip_vip[0] == 0):
                                resp_vip_maps.append({'id': vip_map.get('id'),
                                                      'ip': response_ip_vip[1]})

                                ip = str(response_ip_vip[1].get('oct1')) + '.' + str(response_ip_vip[1].get('oct2')) + '.' + str(
                                    response_ip_vip[1].get('oct3')) + '.' + str(response_ip_vip[1].get('oct4'))

                                equipment_ip_map = {
                                    'ip': ip, 'nome_equipamento': equipment_map.get('nome')}

                                equipment_ip_maps = vip_equipment_ip_map.get(
                                    vip_map.get('id'))
                                if equipment_ip_maps is None:
                                    equipment_ip_maps = [equipment_ip_map]
                                else:
                                    equipment_ip_maps.append(equipment_ip_map)

                                vip_equipment_ip_map[
                                    vip_map.get('id')] = equipment_ip_maps
                            else:
                                return self.__treat_response_error(response_ip_vip)

                        resp_equipment_maps.append({'id': equip_id,
                                                    'nome': name,
                                                    'ip': response_ip[1],
                                                    'vips': {'vip': resp_vip_maps}})

                    else:
                        return self.__treat_response_error(response_ip)
                else:
                    return self.__treat_response_error(response)

        except InvalidGroupToEquipmentTypeError:
            return self.response_error(107)
        except TipoEquipamentoNotFoundError:
            return self.response_error(100)
        except ModeloNotFoundError:
            return self.response_error(101)
        except EquipamentoNameDuplicatedError:
            return self.response_error(149)
        except EGrupoNotFoundError:
            return self.response_error(102)

        return
Exemple #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 __post_virtual_group_vip(self, vip_maps, user, vip_equipment_ip_map, resp_vip_maps):
        try:
            for vip_map in vip_maps:
                resp_vip_map = dict()

                vip_id = vip_map.get('id')

                resp_vip_map['id'] = vip_id

                id_vip_request_map = vip_map.get('requisicao_vip')

                ip_map = vip_map.get('ip')

                # Somente insere o IP do VIP se a requisição de VIP ainda não foi criada
                # (id_vip_request_map is None).

                if (ip_map is not None) and (id_vip_request_map is None):

                    # Insere o IP do VIP e o associa aos balanceadores

                    balanceadores_map = vip_map.get('balanceadores')
                    if balanceadores_map is None:
                        return self.response_error(3, u'Não existe valor para a tag balanceadors do vip %s do XML de requisição.' % vip_id)

                    equipments_ids = balanceadores_map.get('id_equipamento')
                    if len(equipments_ids) == 0:
                        return self.response_error(3, u'Não existe valor para a tag id_equipamento do vip %s do XML de requisição.' % vip_id)

                    # Insere um IP e o relacionamento dele com o primeiro
                    # balanceador
                    equip_id = equipments_ids[0]
                    ip_map['id_equipamento'] = equip_id
                    response_ip = insert_ip(ip_map, user)
                    if response_ip[0] != 0:
                        return self.__treat_response_error(response_ip)

                    # Insere o relacionamento entre o IP e os demais
                    # balanceadores
                    for equip_id in equipments_ids[1:len(equipments_ids)]:
                        insert_ip_equipment(
                            response_ip[1].get('id'), equip_id, user)

                    resp_vip_map['ip'] = response_ip[1]

                    vip_map['id_ip'] = response_ip[1].get('id')

                # Constroe o reals

                # Obtem os reals já criados e que foram enviados no XML de
                # requisição
                reals_map = vip_map.get('reals')
                if reals_map is not None:
                    real_maps = reals_map.get('real', [])
                else:
                    real_maps = []

                # Adiciona os novos reals para os equipamentos criados
                equipment_ip_maps = vip_equipment_ip_map.get(vip_id)
                if equipment_ip_maps is not None:
                    for equipment_ip_map in equipment_ip_maps:
                        real_name = equipment_ip_map.get(
                            'nome_equipamento')  # + sufix
                        real_ip = equipment_ip_map.get('ip')
                        real_maps.append(
                            {'real_name': real_name, 'real_ip': real_ip})

                vip_map['reals'] = {'real': real_maps}

                reals_priority_map = vip_map.get('reals_prioritys')
                if reals_priority_map is not None:
                    reals_priority_map = reals_priority_map.get(
                        'reals_priority')
                    if reals_priority_map is None:
                        reals_priority_map = ['0' for __real in real_maps]
                else:
                    reals_priority_map = ['0' for __real in real_maps]

                vip_map['reals_prioritys'] = {
                    'reals_priority': reals_priority_map}

                reals_weight_map = vip_map.get('reals_weights')
                if reals_weight_map is not None:
                    reals_weight_map = reals_weight_map.get('reals_weight')
                    if reals_weight_map is None:
                        reals_weight_map = ['0' for __real in real_maps]
                else:
                    reals_weight_map = ['0' for __real in real_maps]

                vip_map['reals_weights'] = {'reals_weight': reals_weight_map}

                # Valid real names and real ips of real server
                if vip_map.get('reals') is not None:

                    evip = EnvironmentVip.get_by_values(
                        vip_map.get('finalidade'), vip_map.get('cliente'), vip_map.get('ambiente'))

                    for real in vip_map.get('reals').get('real'):
                        ip_aux_error = real.get('real_ip')
                        equip_id = real.get('real_name')
                        if equip_id is not None:
                            equip = Equipamento.get_by_name(equip_id)
                        else:
                            self.log.error(
                                u'The real_name parameter is not a valid value: None.')
                            raise InvalidValueError(None, 'real_name', 'None')

                        # Valid Real
                        RequisicaoVips.valid_real_server(
                            ip_aux_error, equip, evip, False)

                        vip_map, code = RequisicaoVips().valid_values_reals_priority(
                            vip_map)
                        if code is not None:
                            return self.response_error(code)

                        vip_map, code = RequisicaoVips().valid_values_reals_weight(
                            vip_map)
                        if code is not None:
                            return self.response_error(code)

                # Insere ou atualiza a requisição de VIP
                if (id_vip_request_map is not None):

                    resp_vip_map['requisicao_vip'] = id_vip_request_map

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

                    vip_request = RequisicaoVips.get_by_pk(
                        id_vip_request_map.get('id'))

                    vip_map['id_ip'] = vip_request.ip_id
                    if vip_request.validado:
                        vip_map['validado'] = '1'
                    else:
                        vip_map['validado'] = '0'
                    if vip_request.vip_criado:
                        vip_map['vip_criado'] = '1'
                    else:
                        vip_map['vip_criado'] = '0'

                    response_vip = update_vip_request(
                        vip_request.id, vip_map, user)
                    if (response_vip != 0):
                        return self.response_error(response_vip)

                else:
                    """This condition is used to attend a requisite from 'Orquestra', 
                       because in some points the VIP doesn't have cache option and 
                       the value can be 'None'"""
                    if vip_map['cache'] is None:
                        vip_map['cache'] = "(nenhum)"

                    response_vip = insert_vip_request(vip_map, user)
                    if (response_vip[0] != 0):
                        if response_vip[0] not in (275, 276, 277):
                            return self.__treat_response_error(response_vip)
                        else:
                            return self.__treat_response_error([response_vip[0]])

                    resp_vip_map['requisicao_vip'] = {'id': response_vip[1].id}

                resp_vip_maps.append(resp_vip_map)

        except EnvironmentVipNotFoundError:
            return self.response_error(316, vip_map['finalidade'], vip_map['cliente'], vip_map['ambiente'])
        except RequisicaoVipsNotFoundError:
            return self.response_error(152)
        except HealthcheckExpectNotFoundError:
            return self.response_error(124)
        except InvalidFinalidadeValueError:
            return self.response_error(125)
        except InvalidClienteValueError:
            return self.response_error(126)
        except InvalidAmbienteValueError:
            return self.response_error(127)
        except InvalidCacheValueError:
            return self.response_error(128)
        except InvalidMetodoBalValueError:
            return self.response_error(131)
        except InvalidPersistenciaValueError:
            return self.response_error(132)
        except InvalidHealthcheckTypeValueError:
            return self.response_error(133)
        except InvalidHealthcheckValueError:
            return self.response_error(134)
        except InvalidTimeoutValueError:
            return self.response_error(135)
        except InvalidHostNameError:
            return self.response_error(136)
        except InvalidMaxConValueError:
            return self.response_error(137)
        except InvalidBalAtivoValueError:
            return self.response_error(129)
        except InvalidTransbordoValueError, t:
            transbordo = 'nulo'
            if t.message is not None:
                transbordo = t.message
            return self.response_error(130, transbordo)
    def handle_put(self, request, user, *args, **kwargs):
        """
        Handles PUT requests to change the VIP's real server.

        URL: vip/real/edit
        """

        self.log.info("Change VIP's real server")

        try:

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

            # Commons Validations

            # Load XML data
            xml_map, attrs_map = loads(
                request.raw_post_data, ['real', 'reals_weight', 'reals_priority'])

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

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

            # Get XML data
            vip_id = vip_map.get('vip_id')
            alter_priority = vip_map.get('alter_priority')

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

            # Valid Alter Priority
            if not is_valid_int_greater_equal_zero_param(alter_priority):
                alter_priority = 0

            # Existing Vip ID
            vip = RequisicaoVips.get_by_pk(vip_id)

            # Clone vip
            vip_old = clone(vip)

            server_pools = ServerPool.objects.filter(vipporttopool__requisicao_vip=vip)
            server_pools_old = []
            server_pools_members_old = []
            for sp in server_pools:
                server_pools_old.append(sp)
                for spm in sp.serverpoolmember_set.all():
                    server_pools_members_old.append(spm)

            # Get variables
            variables_map = vip.variables_to_map()

            # Valid variables
            vip.set_variables(variables_map)

            # Get balancing method
            vip_map['metodo_bal'] = str(
                variables_map.get('metodo_bal')).upper()

            with distributedlock(LOCK_VIP % vip_id):

                # Valid real names and real ips of real server
                if vip_map.get('reals') is not None:

                    evip = EnvironmentVip.get_by_values(variables_map.get(
                        'finalidade'), variables_map.get('cliente'), variables_map.get('ambiente'))

                    for real in vip_map.get('reals').get('real'):
                        ip_aux_error = real.get('real_ip')
                        equip_aux_error = real.get('real_name')
                        if equip_aux_error is not None:
                            equip = Equipamento.get_by_name(equip_aux_error)
                        else:
                            self.log.error(
                                u'The real_name parameter is not a valid value: None.')
                            raise InvalidValueError(None, 'real_name', 'None')

                        # Valid Real
                        RequisicaoVips.valid_real_server(
                            ip_aux_error, equip, evip, False)

                    # Valid reals_prioritys
                    vip_map, code = vip.valid_values_reals_priority(vip_map)
                    if code is not None:
                        return self.response_error(329)

                    # Valid reals_weight
                    vip_map, code = vip.valid_values_reals_weight(vip_map)
                    if code is not None:
                        return self.response_error(330)

                # Get variables
                variables_map = vip.variables_to_map()

                vip_port_list, reals_list, reals_priority, reals_weight = vip.get_vips_and_reals(
                    vip.id)

                if reals_list:
                    variables_map['reals'] = {'real': reals_list}
                    variables_map['reals_prioritys'] = {
                        'reals_priority': reals_priority}
                    variables_map['reals_weights'] = {
                        'reals_weight': reals_weight}

                variables_map['portas_servicos'] = {'porta': vip_port_list}

                # clone variables_map
                variables_map_old = clone(variables_map)

                # Valid ports
                variables_map, code = vip.valid_values_ports(variables_map)
                if code is not None:
                    return self.response_error(331)

                """ OLD CALLS - Deprecated """
                vip_ports_pool = VipPortToPool.objects.filter(
                    requisicao_vip=vip)

                reals = vip_map.get('reals')

                new_call = True
                if reals and 'port_real' not in reals['real'][0]:
                    new_call = False
                    reals_prioritys = vip_map.get('reals_prioritys')
                    reals_weights = dict()
                    if 'reals_weights' in vip_map:
                        reals_weights = vip_map.get('reals_weights')

                    reals_aux = dict()
                    reals_prioritys_aux = dict()
                    reals_weight_aux = dict()

                    reals_aux['real'] = list()
                    reals_prioritys_aux['reals_priority'] = list()
                    reals_weight_aux['reals_weight'] = list()

                    repeat = (
                        len(vip_ports_pool) * len(reals['real'])) / len(reals['real'])
                    execute_list = list()

                    for x in range(repeat):
                        execute_list.append((x + 1) * len(reals['real']))

                    for i in range(len(reals['real'])):
                        for vippp in vip_ports_pool:

                            reals_prioritys_aux['reals_priority'].append(
                                reals_prioritys['reals_priority'][i])
                            if 'reals_weight' in reals_weights:
                                reals_weight_aux['reals_weight'].append(
                                    reals_weights['reals_weight'][i])
                            server_pool = ServerPool.objects.get(
                                vipporttopool__id=vippp.id, vipporttopool__requisicao_vip=vip)

                            if 'id_ip' not in reals['real'][i]:
                                id_ip = get_id_ip(reals['real'][i])
                            else:
                                id_ip = reals['real'][i]['id_ip']

                            reals_aux['real'].append({'id_ip': id_ip, 'port_real': server_pool.default_port, 'real_name': reals[
                                                     'real'][i]['real_name'], 'port_vip': vippp.port_vip, u'real_ip': reals['real'][i]['real_ip']})

                        vip_map['reals_prioritys'] = reals_prioritys_aux
                        vip_map['reals_weights'] = reals_weight_aux
                        vip_map['reals'] = reals_aux

                """ OLD CALLS - END """

                # Check diff reals (reals_to_add, reals_to_rem, reals_to_stay)
                reals_to_add, reals_to_rem, reals_to_stay = diff_reals(
                    variables_map, vip_map)

                reals_final = dict()
                reals_final['reals'] = list()
                reals_final['priorities'] = list()
                reals_final['weights'] = list()

                reals_error = list()
                removes = True
                error = False

                ##############################################
                #        NOT MODIFIED - reals_to_stay        #
                ##############################################
                for i in range(len(reals_to_stay['reals'])):

                    real, priority, weight, id_ip, port_vip, port_real, new_call = get_variables(
                        reals_to_stay, i, new_call)

                    # Check ip type
                    if is_valid_ipv4(real.get('real_ip')) == True:
                        ip_type = IP_VERSION.IPv4[1]
                        ip = Ip().get_by_pk(id_ip)
                    else:
                        ip_type = IP_VERSION.IPv6[1]
                        ip = Ipv6().get_by_pk(id_ip)

                    reals_final['reals'].append(reals_to_stay['reals'][i])
                    reals_final['priorities'].append(
                        reals_to_stay['priorities'][i])
                    if reals_to_stay['weighted']:
                        reals_final['weights'].append(
                            reals_to_stay['weights'][i])

                        server_pool = ServerPool.objects.get(
                            vipporttopool__port_vip=port_vip, vipporttopool__requisicao_vip=vip)
                        if ip_type == IP_VERSION.IPv4[1]:
                            server_pool_member = ServerPoolMember.objects.get(server_pool=server_pool,
                                                                              port_real=port_real,
                                                                              ip=id_ip)
                        else:
                            server_pool_member = ServerPoolMember.objects.get(server_pool=server_pool,
                                                                              port_real=port_real,
                                                                              ipv6=id_ip)
                    server_pool_member.priority = priority
                    server_pool_member.weight = weight
                    server_pool_member.save(user, commit=True)

                #############################################
                #          ADD REALS - reals_to_add         #
                #############################################
                for i in range(len(reals_to_add['reals'])):

                    real, priority, weight, id_ip, port_vip, port_real, new_call = get_variables(
                        reals_to_add, i, new_call)

                    if len(real.get('real_ip').split('.')) <= 1:
                        ip_type = IP_VERSION.IPv6[1]
                        ip = Ipv6().get_by_pk(id_ip)
                        if new_call:
                            command = VIP_REALS_v6_CREATE % (
                                vip.id, id_ip, port_real, port_vip)
                        else:
                            command = VIP_REAL_v6_CREATE % (
                                vip.id, real.get('real_name'), real.get('real_ip'))
                    else:
                        ip_type = IP_VERSION.IPv4[1]
                        ip = Ip().get_by_pk(id_ip)
                        if new_call:
                            command = VIP_REALS_v4_CREATE % (
                                vip.id, id_ip, port_real, port_vip)
                        else:
                            command = VIP_REAL_v4_CREATE % (
                                vip.id, real.get('real_name'), real.get('real_ip'))

                    self.log.info(
                        '------------------- ADD ----------------------')
                    self.log.info(
                        'Insert ServerPoolMember before execute script')

                    add_reals_before_script(
                        port_vip, vip, ip, ip_type, priority, weight, port_real, user)

                    self.log.info('The insert has completed successfully')

                    # if new_call or (i + 1) in execute_list:

                    self.log.info('Execute script: %s' % command)

                    code, stdout, stderr = exec_script(command)

                    self.log.info(
                        'Script was executed and returned code %s' % code)

                    if code != 0:
                        removes = False
                        error = True
                        reals_error.append(real)

                        self.log.info(
                            'Remove ServerPoolMember after execute script if code != 0')
                        remove_reals_after_script(
                            port_vip, ip_type, vip, port_real, priority, weight, id_ip, user)
                        self.log.info('The remove has completed successfully')

                    else:
                        reals_final['reals'].append(real)
                        reals_final['priorities'].append(
                            reals_to_add['priorities'][i])
                        if reals_to_add['weighted']:
                            reals_final['weights'].append(
                                reals_to_add['weights'][i])

                    self.log.info(
                        '----------------- ADD END --------------------')

                ##########################################
                #       REMOVE REALS - reals_to_rem      #
                ##########################################
                if removes:
                    for i in range(len(reals_to_rem['reals'])):

                        real, priority, weight, id_ip, port_vip, port_real, new_call = get_variables(
                            reals_to_rem, i, new_call)

                        if len(real.get('real_ip').split('.')) <= 1:
                            ip_type = IP_VERSION.IPv6[1]
                            if new_call:
                                command = VIP_REALS_v6_REMOVE % (
                                    vip.id, id_ip, port_real, port_vip)
                            else:
                                command = VIP_REAL_v6_REMOVE % (
                                    vip.id, real.get('real_name'), real.get('real_ip'))
                        else:
                            ip_type = IP_VERSION.IPv4[1]
                            if new_call:
                                command = VIP_REALS_v4_REMOVE % (
                                    vip.id, id_ip, port_real, port_vip)
                            else:
                                command = VIP_REAL_v4_REMOVE % (
                                    vip.id, real.get('real_name'), real.get('real_ip'))

                        self.log.info(
                            '------------------ REMOVE --------------------')
                        self.log.info('Execute script: %s' % command)

                        code, stdout, stderr = exec_script(command)

                        self.log.info(
                            'script was executed and returned code %s' % code)

                        if code != 0:
                            error = True
                            reals_error.append(real)
                            reals_final['reals'].append(real)
                            reals_final['priorities'].append(
                                reals_to_rem['priorities'][i])
                            if reals_to_rem['weighted']:
                                reals_final['weights'].append(
                                    reals_to_rem['weights'][i])
                        else:

                            self.log.info(
                                'Remove ServerPoolMember after execute script')
                            remove_reals_after_script(
                                port_vip, ip_type, vip, port_real, priority, weight, id_ip, user)
                            self.log.info(
                                'The remove has completed successfully')

                        self.log.info(
                            '---------------- REMOVE END ------------------')

                else:
                    for i in range(len(reals_to_rem['reals'])):
                        real = reals_to_rem['reals'][i]
                        reals_final['reals'].append(real)
                        reals_final['priorities'].append(
                            reals_to_rem['priorities'][i])
                        if reals_to_add['weighted']:
                            reals_final['weights'].append(
                                reals_to_rem['weights'][i])

                variables_map['reals'] = dict()
                variables_map['reals_prioritys'] = dict()
                variables_map['reals_weights'] = dict()

                if len(reals_final['reals']) > 0:
                    variables_map['reals']['real'] = reals_final['reals']
                    variables_map['reals_prioritys'][
                        'reals_priority'] = reals_final['priorities']
                    if reals_final['weights'] is not None:
                        variables_map['reals_weights'][
                            'reals_weight'] = reals_final['weights']
                else:
                    variables_map.pop('reals')
                    variables_map.pop('reals_prioritys')
                    variables_map.pop('reals_weights')

                # set variables
                vip.set_variables(variables_map)

                try:
                    # If Priority changed
                    if int(alter_priority) != 0:
                        # gerador_vips -i <ID_REQUISICAO> --priority
                        command = 'gerador_vips -i %d --priority' % vip.id

                        # Logging
                        self.log.info(
                            '---------------- ALTER PRIORITY ------------------')
                        self.log.info('Command: ' + command)

                        # Execute script
                        code, stdout, stderr = exec_script(command)
                        self.log.info('Code returned: ' + str(code))
                        self.log.info('Stdout: ' + stdout)
                        self.log.info(
                            '-------------- ALTER PRIORITY END ----------------')

                        # Script returned error while executing, rollback the
                        # changes in database
                        if code != 0:
                            self.log.info('Code != 0, rollback changes')
                            vip_old.save(user, commit=True)
                            for sp in server_pools_old:
                                sp.save(user, commit=True)
                            for spm in server_pools_members_old:
                                spm.save(user, commit=True)

                            return self.response_error(2, stdout + stderr)

                except Exception, e:
                    if isinstance(e, IntegrityError):
                        # Duplicate value for Port Vip, Port Real and IP
                        self.log.error(u'Failed to update the request vip.')
                        return self.response_error(353)
                    else:
                        self.log.error(u'Failed to update the request vip.')
                        raise RequisicaoVipsError(
                            e, u'Failed to update the request vip')

                if error:
                    # build return message
                    vip_list = ''
                    ip_list = ''

                    for real in reals_error:
                        vip_list = vip_list + real['real_name'] + ', '
                        ip_list = ip_list + real['real_ip'] + ', '

                    return self.response_error(333, vip_list[:-2], ip_list[:-2])
                else:
                    return self.response(dumps_networkapi({}))

        except XMLError, x:
            self.log.error(u'Error reading the XML request.')
            return self.response_error(3, x)
Exemple #52
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
Exemple #53
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
Exemple #54
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 {}
    def handle_put(self, request, user, *args, **kwargs):
        """Treat  requests PUT change limit connections to VIP.

        URLs: /vip/<id_vip>/maxcon/<maxcon>/
        """

        self.log.info("Change limit connections to VIP")

        try:

            vip_id = kwargs.get('id_vip')
            maxcon = kwargs.get('maxcon')

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

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

            # Valid Maxcon
            if not is_valid_int_greater_equal_zero_param(maxcon):
                self.log.error(
                    u'The maxcon parameter is not a valid value: %s.', maxcon)
                raise InvalidValueError(None)

            # Existing Vip ID
            vip = RequisicaoVips.get_by_pk(vip_id)

            with distributedlock(LOCK_VIP % vip_id):

                vip_old = clone(vip)
                server_pools = ServerPool.objects.filter(vipporttopool__requisicao_vip=vip)
                server_pools_old = []
                server_pools_members_old = []
                for sp in server_pools:
                    server_pools_old.append(sp)
                    for spm in sp.serverpoolmember_set.all():
                        server_pools_members_old.append(spm)

                # Vip must be created
                if not vip.vip_criado:
                    self.log.error(
                        u'Maxcon can not be changed because VIP has not yet been created.')
                    raise RequestVipsNotBeenCreatedError(None)

                # Vip equipments permission
                if vip.ip is not None:
                    for ip_equipment in vip.ip.ipequipamento_set.all():
                        if not has_perm(user, AdminPermission.VIP_ALTER_SCRIPT, AdminPermission.WRITE_OPERATION, None, ip_equipment.equipamento_id, AdminPermission.EQUIP_UPDATE_CONFIG_OPERATION):
                            self.log.error(
                                u'Groups of equipment registered with the IP of the  VIP request  is not allowed of acess.')
                            raise EquipmentGroupsNotAuthorizedError(None)

                if vip.ipv6 is not None:
                    for ip_equipment in vip.ipv6.ipv6equipament_set.all():
                        if not has_perm(user, AdminPermission.VIP_ALTER_SCRIPT, AdminPermission.WRITE_OPERATION, None, ip_equipment.equipamento_id, AdminPermission.EQUIP_UPDATE_CONFIG_OPERATION):
                            self.log.error(
                                u'Groups of equipment registered with the IP of the  VIP request  is not allowed of acess.')
                            raise EquipmentGroupsNotAuthorizedError(None)

                # Get variables
                variables_map = vip.variables_to_map()

                # Valid variables
                vip.set_variables(variables_map)

                # Valid real names and real ips of real server
                if variables_map.get('reals') is not None:

                    evip = EnvironmentVip.get_by_values(variables_map.get(
                        'finalidade'), variables_map.get('cliente'), variables_map.get('ambiente'))

                    for real in variables_map.get('reals').get('real'):
                        ip_aux_error = real.get('real_ip')
                        equip_aux_error = real.get('real_name')
                        equip = Equipamento.get_by_name(equip_aux_error)

                        # Valid Real
                        RequisicaoVips.valid_real_server(
                            ip_aux_error, equip, evip)

                    # Valid reals_prioritys
                    variables_map, code = vip.valid_values_reals_priority(
                        variables_map)
                    if code is not None:
                        return self.response_error(329)

                    # Valid reals_weight
                    variables_map, code = vip.valid_values_reals_weight(
                        variables_map)
                    if code is not None:
                        return self.response_error(330)

                    # Valid ports
                    variables_map, code = vip.valid_values_ports(variables_map)
                    if code is not None:
                        return self.response_error(331)

                variables_map['maxcon'] = maxcon

                vip.set_variables(variables_map)

                vip.save(user, commit=True)

                #update server pool limits table
                #Fix #27
                server_pools = ServerPool.objects.filter(vipporttopool__requisicao_vip=vip)

                for sp in server_pools:
                    #If exists pool member, change default maxconn of pool and members
                    if(len(sp.serverpoolmember_set.all()) > 0):
                        #if(old_maxconn != sp.default_limit and sp.pool_created):
                        sp.default_limit = maxcon
                        sp.save(user, commit=True)
                        for serverpoolmember in sp.serverpoolmember_set.all():
                            serverpoolmember.limit = maxcon
                            serverpoolmember.save(user, commit=True)

                # gerador_vips -i <ID_REQUISICAO> --maxconn
                command = 'gerador_vips -i %d --maxconn' % vip.id
                code, stdout, stderr = exec_script(command)

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

                    map = dict()
                    map['sucesso'] = success_map
                    return self.response(dumps_networkapi(map))
                else:
                    #TODO Check if is needed to update pool members separately
                    vip_old.save(user, commit=True)
                    for sp in server_pools_old:
                        sp.save(user, commit=True)
                    for spm in server_pools_members_old:
                        spm.save(user, commit=True)
                    return self.response_error(2, stdout + stderr)

        except XMLError, x:
            self.log.error(u'Error reading the XML request.')
            return self.response_error(3, x)
    def handle_post(self, request, user, *args, **kwargs):
        """Handles POST requests to list all equip scripts by equipment name.

        URLs: equipamentoroteiro/name/
        """

        try:

            # Commons Validations

            # User permission
            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

            # 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_script_map = networkapi_map.get('equipamento_roteiro')
            if equip_script_map is None:
                msg = u'There is no value to the equipamento_roteiro tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)

            # Get XML data
            name = equip_script_map.get('name')

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

            # Equipment
            try:

                # Find equipment by name to check if it exist
                equip = Equipamento.get_by_name(name)

            except EquipamentoNotFoundError, e:
                return self.response_error(117, name)

            # Business Rules

            # List access related with equip
            equip_script_list = equip.equipamentoroteiro_set.all()
            # Permissions
            equip_script_list = equip_script_list.filter(equipamento__grupos__direitosgrupoequipamento__ugrupo__in=user.grupos.all(
            ), equipamento__grupos__direitosgrupoequipamento__escrita='1')

            map_dicts = []
            for equip_script in equip_script_list:
                es_map = dict()
                es_map['id'] = equip_script.id
                es_map['roteiro_id'] = equip_script.roteiro.id
                es_map['roteiro_name'] = equip_script.roteiro.roteiro
                es_map['roteiro_desc'] = equip_script.roteiro.descricao
                es_map[
                    'tipo_roteiro_id'] = equip_script.roteiro.tipo_roteiro.id
                es_map[
                    'tipo_roteiro_name'] = equip_script.roteiro.tipo_roteiro.tipo
                es_map[
                    'tipo_roteiro_desc'] = equip_script.roteiro.tipo_roteiro.descricao
                map_dicts.append(es_map)

            equip_map = dict()
            equip_map['id'] = equip.id
            equip_map['name'] = equip.nome

            equip_script_map = dict()
            equip_script_map['equipamento_roteiro'] = map_dicts
            equip_script_map['equipamento'] = equip_map

            # Return XML
            return self.response(dumps_networkapi(equip_script_map))
    def handle_post(self, request, user, *args, **kwargs):
        """Handles POST requests to valid Real server.

        URL: vip/real/valid/
        """
        self.log.info('Valid Real Server')

        try:

            # Business Validations

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

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

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

            # Get XML data
            ip = real_map.get('ip')
            name = real_map.get('name_equipment')
            id_evip = real_map.get('id_environment_vip')
            valid = real_map.get('valid')

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

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

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

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

            # Valid Equipment
            equip = Equipamento.get_by_name(name)

            # Valid EnvironmentVip
            evip = EnvironmentVip.get_by_pk(id_evip)

            version = ''
            if is_valid_ipv4(ip):
                version = IP_VERSION.IPv4[1]

            elif is_valid_ipv6(ip):
                version = IP_VERSION.IPv6[1]

            ip, equip, evip = RequisicaoVips.valid_real_server(
                ip, equip, evip, valid)

            real_dict = {}
            ip_dict = model_to_dict(ip)
            ip_dict['version'] = version

            real_dict['ip'] = ip_dict
            real_dict['equipment'] = model_to_dict(equip)
            real_dict['environmentvip'] = model_to_dict(evip)

            return self.response(dumps_networkapi({'real': real_dict}))

        except XMLError, x:
            self.log.error(u'Error reading the XML request.')
            return self.response_error(3, x)
Exemple #58
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 {}
    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)