Ejemplo n.º 1
0
def _load_template_file(equipment, template_type):
    """Load template file with specific type related to equipment

    Args: equipment: Equipamento object
    template_type: Type of template to be loaded

    Returns: template string
    """

    try:
        equipment_template = (EquipamentoRoteiro.search(
            None, equipment.id, template_type)).uniqueResult()
    except:
        log.error('Template type %s not found.' % template_type)
        raise exceptions.NetworkTemplateException()

    filename_in = NETWORK_CONFIG_TEMPLATE_PATH + \
        '/' + equipment_template.roteiro.roteiro

    # Read contents from file
    try:
        file_handle = open(filename_in, 'r')
        template_file = Template(file_handle.read())
        file_handle.close()
    except IOError, e:
        log.error('Error opening template file for read: %s' % filename_in)
        raise e
Ejemplo n.º 2
0
def _load_template_file(equipment, template_type):
    """Load template file with specific type related to equipment

    Args: equipment: Equipamento object
    template_type: Type of template to be loaded

    Returns: template string
    """

    try:
        equipment_template = (EquipamentoRoteiro.search(
            None, equipment.id, template_type)).uniqueResult()
    except:
        log.error('Template type %s not found.' % template_type)
        raise exceptions.NetworkTemplateException()

    filename_in = NETWORK_CONFIG_TEMPLATE_PATH + \
        '/' + equipment_template.roteiro.roteiro

    # Read contents from file
    try:
        file_handle = open(filename_in, 'r')
        template_file = Template(file_handle.read())
        file_handle.close()
    except IOError, e:
        log.error('Error opening template file for read: %s' % filename_in)
        raise e
    def test_deploy_networkipv6_configuration_with_inactive_vlan(self):
        self.networkv6.vlan.ativada = False

        self.mock_ip_get_by_blocks_and_net(
            Ipv6(block1='fff',
                 block2='fff',
                 block3='fff',
                 block4='fff',
                 block5='fff',
                 block6='fff',
                 block7='fff',
                 block8='fff'))
        self.mock_find_equipamento_ipv6([Ipv6Equipament()])
        self.mock_find_roteiro(
            EquipamentoRoteiro(roteiro=Roteiro(roteiro='roteiro')))
        self.mock_template_file_read('script content')
        deploy_config_mock = self.mock_deploy_config('config_deployed')
        network_activation_mock = self.mock_networkv6_activation()
        vlan_activation_mock = self.mock_vlan_activation()

        response = deploy_networkIPv6_configuration(self.user, self.networkv6,
                                                    self.equipment_list)

        self.assertTrue(deploy_config_mock.called)
        network_activation_mock.assert_called_with(self.user)
        vlan_activation_mock.assert_called_with(self.user)
        self.assertEquals({1: 'config_deployed'}, response)
Ejemplo n.º 4
0
def _load_template_file(equipment_id, template_type):

    try:
        INTERFACE_CONFIG_TEMPLATE_PATH = get_variable("interface_config_template_path")
    except ObjectDoesNotExist:
        raise var_exceptions.VariableDoesNotExistException(
            "Erro buscando a variável INTERFACE_CONFIG<TOAPPLY,TEMPLATE,FILES>_PATH."
        )

    try:
        equipment_template = (EquipamentoRoteiro.search(None, equipment_id, template_type)).uniqueResult()
    except:
        log.error("Template type %s not found. Equip: %s" % (template_type, equipment_id))
        raise exceptions.InterfaceTemplateException()

    filename_in = INTERFACE_CONFIG_TEMPLATE_PATH + equipment_template.roteiro.roteiro

    # Read contents from file
    try:
        file_handle = open(filename_in, "r")
        template_file = Template(file_handle.read())
        file_handle.close()
    except IOError, e:
        log.error("Error opening template file for read: %s. Equip: %s" % (filename_in, equipment_id))
        raise e
Ejemplo n.º 5
0
def _load_template_file(equipment_id, template_type):
    log.info("_load_template_file")

    try:
        INTERFACE_CONFIG_TEMPLATE_PATH = get_variable(
            'interface_config_template_path')
    except ObjectDoesNotExist:
        raise var_exceptions.VariableDoesNotExistException(
            'Erro buscando a variável INTERFACE_CONFIG'
            '<TOAPPLY,TEMPLATE,FILES>_PATH.')

    try:
        equipment_template = (EquipamentoRoteiro.search(
            None, equipment_id, template_type)).uniqueResult()
    except:
        log.error('Template type %s not found. Equip: %s' %
                  (template_type, equipment_id))
        raise exceptions.InterfaceTemplateException()

    filename_in = INTERFACE_CONFIG_TEMPLATE_PATH + \
        equipment_template.roteiro.roteiro

    # Read contents from file
    try:
        file_handle = open(filename_in, 'r')
        template_file = Template(file_handle.read())
        file_handle.close()
    except IOError, e:
        log.error('Error opening template file for read: %s. Equip: %s' %
                  (filename_in, equipment_id))
        raise 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_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)
Ejemplo n.º 8
0
    def handle_get(self, request, user, *args, **kwargs):
        '''Trata as requisições de GET para listar Roteiros.

        URLs: roteiro/$
              roteiro/tiporoteiro/<id_tipo_roteiro>/
              roteiro/equipamento/<id_equip>/
        '''

        try:
            map_list = []

            equipment_id = kwargs.get('id_equip')
            if equipment_id is None:
                if not has_perm(user, AdminPermission.SCRIPT_MANAGEMENT, AdminPermission.READ_OPERATION):
                    return self.not_authorized()

                scripts = Roteiro.search(kwargs.get('id_tipo_roteiro'))
                for script in scripts:
                    script_map = dict()
                    script_map['id'] = script.id
                    script_map['nome'] = script.roteiro
                    script_map['descricao'] = script.descricao
                    script_map['id_tipo_roteiro'] = script.tipo_roteiro_id

                    map_list.append(script_map)

            else:
                if not has_perm(user,
                                AdminPermission.EQUIPMENT_MANAGEMENT,
                                AdminPermission.READ_OPERATION,
                                None,
                                equipment_id,
                                AdminPermission.EQUIP_READ_OPERATION):
                    return self.not_authorized()

                equipment_scripts = EquipamentoRoteiro.search(
                    None, equipment_id)
                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

                    map_list.append(script_map)

            return self.response(dumps_networkapi({'roteiro': map_list}))

        except EquipamentoNotFoundError:
            return self.response_error(117, equipment_id)
        except (RoteiroError, GrupoError, EquipamentoError):
            return self.response_error(1)
    def handle_get(self, request, user, *args, **kwargs):
        """Treat requests GET to list all Equipment Script.

        URL: equipmentscript/all
        """
        try:
            self.log.info('GET to list all Equipment Script')

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

            map_list = []
            for equipment_script in EquipamentoRoteiro.search(
                    user.grupos.all()):
                equip_map = dict()
                equip_map['id'] = equipment_script.equipamento.id
                equip_map['nome'] = equipment_script.equipamento.nome
                equip_map[
                    'id_tipo_equipamento'] = equipment_script.equipamento.tipo_equipamento.id
                equip_map[
                    'nome_tipo_equipamento'] = equipment_script.equipamento.tipo_equipamento.tipo_equipamento
                equip_map['id_modelo'] = equipment_script.equipamento.modelo.id
                equip_map[
                    'nome_modelo'] = equipment_script.equipamento.modelo.nome
                equip_map[
                    'id_marca'] = equipment_script.equipamento.modelo.marca.id
                equip_map[
                    'nome_marca'] = equipment_script.equipamento.modelo.marca.nome

                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

                equip_script_map = dict()
                equip_script_map['equipamento'] = equip_map
                equip_script_map['roteiro'] = script_map

                if equip_script_map not in map_list:
                    map_list.append(equip_script_map)

            return self.response(
                dumps_networkapi({'equipamento_roteiro': map_list}))

        except UserNotAuthorizedError:
            return self.not_authorized()
        except EquipamentoError:
            return self.response_error(1)
    def handle_get(self, request, user, *args, **kwargs):
        '''Trata as requisições de GET para listar Roteiros.

        URLs: roteiro/$
              roteiro/tiporoteiro/<id_tipo_roteiro>/
              roteiro/equipamento/<id_equip>/
        '''

        try:
            map_list = []

            equipment_id = kwargs.get('id_equip')
            if equipment_id is None:
                if not has_perm(user, AdminPermission.SCRIPT_MANAGEMENT, AdminPermission.READ_OPERATION):
                    return self.not_authorized()

                scripts = Roteiro.search(kwargs.get('id_tipo_roteiro'))
                for script in scripts:
                    script_map = dict()
                    script_map['id'] = script.id
                    script_map['nome'] = script.roteiro
                    script_map['descricao'] = script.descricao
                    script_map['id_tipo_roteiro'] = script.tipo_roteiro_id

                    map_list.append(script_map)

            else:
                if not has_perm(user,
                                AdminPermission.EQUIPMENT_MANAGEMENT,
                                AdminPermission.READ_OPERATION,
                                None,
                                equipment_id,
                                AdminPermission.EQUIP_READ_OPERATION):
                    return self.not_authorized()

                equipment_scripts = EquipamentoRoteiro.search(
                    None, equipment_id)
                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

                    map_list.append(script_map)

            return self.response(dumps_networkapi({'roteiro': map_list}))

        except EquipamentoNotFoundError:
            return self.response_error(117, equipment_id)
        except (RoteiroError, GrupoError, EquipamentoError):
            return self.response_error(1)
    def handle_get(self, request, user, *args, **kwargs):
        """Treat requests GET to list all Equipment Script.

        URL: equipmentscript/all
        """
        try:
            self.log.info("GET to list all Equipment Script")

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

            map_list = []
            for equipment_script in EquipamentoRoteiro.search(user.grupos.all()):
                equip_map = dict()
                equip_map['id'] = equipment_script.equipamento.id
                equip_map['nome'] = equipment_script.equipamento.nome
                equip_map[
                    'id_tipo_equipamento'] = equipment_script.equipamento.tipo_equipamento.id
                equip_map[
                    'nome_tipo_equipamento'] = equipment_script.equipamento.tipo_equipamento.tipo_equipamento
                equip_map['id_modelo'] = equipment_script.equipamento.modelo.id
                equip_map[
                    'nome_modelo'] = equipment_script.equipamento.modelo.nome
                equip_map[
                    'id_marca'] = equipment_script.equipamento.modelo.marca.id
                equip_map[
                    'nome_marca'] = equipment_script.equipamento.modelo.marca.nome

                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

                equip_script_map = dict()
                equip_script_map['equipamento'] = equip_map
                equip_script_map['roteiro'] = script_map

                if equip_script_map not in map_list:
                    map_list.append(equip_script_map)

            return self.response(dumps_networkapi({'equipamento_roteiro': map_list}))

        except UserNotAuthorizedError:
            return self.not_authorized()
        except EquipamentoError:
            return self.response_error(1)
Ejemplo n.º 12
0
def buscar_roteiro(id_sw, tipo):

    roteiros = EquipamentoRoteiro.search(None, id_sw)
    for rot in roteiros:
        if (rot.roteiro.tipo_roteiro.tipo == tipo):
            roteiro_eq = rot.roteiro.roteiro
    roteiro_eq = roteiro_eq.lower()
    if '.txt' not in roteiro_eq:
        roteiro_eq = roteiro_eq + '.txt'

    return roteiro_eq
def buscar_roteiro(id_sw, tipo):

    roteiros = EquipamentoRoteiro.search(None, id_sw)
    for rot in roteiros:
        if (rot.roteiro.tipo_roteiro.tipo==tipo): 
            roteiro_eq = rot.roteiro.roteiro
    roteiro_eq = roteiro_eq.lower()
    if not '.txt' in roteiro_eq:
        roteiro_eq=roteiro_eq+".txt"
        
    return roteiro_eq 
    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)
Ejemplo n.º 16
0
def _load_template_file(equipment_id, template_type):
    try:
        equipment_template = (EquipamentoRoteiro.search(None, equipment_id, template_type)).uniqueResult()
    except:
        log.error("Template type %s not found." % template_type)
        raise exceptions.InterfaceTemplateException()

    filename_in = INTERFACE_CONFIG_TEMPLATE_PATH+"/"+equipment_template.roteiro.roteiro

    # Read contents from file
    try:
        file_handle = open(filename_in, 'r')
        template_file = Template ( file_handle.read() )
        file_handle.close()
    except IOError, e:
        log.error("Error opening template file for read: %s" % filename_in)
        raise e
    def test_deploy_networkipv4_configuration_with_active_vlan(self):
        self.networkv4.vlan.ativada = True

        ipv4 = Ip(oct1=192, oct2=168, oct3=0, oct4=0)
        self.mock_ip_get_by_octets(ipv4)
        self.mock_find_equipamento_ip([IpEquipamento()])
        self.mock_dhcp_relay_find([DHCPRelayIPv4(ipv4=ipv4)])
        self.mock_find_roteiro(
            EquipamentoRoteiro(roteiro=Roteiro(roteiro='roteiro')))
        self.mock_template_file_read('script content')
        deploy_config_mock = self.mock_deploy_config('config_deployed')
        network_activation_mock = self.mock_network_activation()
        vlan_activation_mock = self.mock_vlan_activation()

        response = deploy_networkIPv4_configuration(self.user, self.networkv4,
                                                    self.equipment_list)

        self.assertTrue(deploy_config_mock.called)
        network_activation_mock.assert_called_with(self.user)
        self.assertFalse(vlan_activation_mock.called)
        self.assertEquals({1: 'config_deployed'}, response)
Ejemplo n.º 18
0
    def handle_put(self, request, user, *args, **kwargs):
        """Treat requests PUT to edit Script.

        URL: script/<id_script>/
        """
        try:

            self.log.info("Edit Script")

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

            id_script = kwargs.get('id_script')

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

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

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

            # Get XML data
            script = script_map.get('script')
            id_script_type = script_map.get('id_script_type')
            models = script_map.get('model')
            description = script_map.get('description')

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

            # Valid Script
            if not is_valid_string_minsize(
                    script, 3) or not is_valid_string_maxsize(script, 40):
                self.log.error(u'Parameter script is invalid. Value: %s',
                               script)
                raise InvalidValueError(None, 'script', script)

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

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

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

            # Find Script Type by ID to check if it exist
            script_type = TipoRoteiro.get_by_pk(id_script_type)

            models_old = []
            scr_models = ModeloRoteiro.objects.all().filter(roteiro__id=scr.id)
            for i in scr_models:
                models_old.append(int(i.modelo.id))

            if models is not None and type(models) is not list:
                var = int(models)
                models = []
                models.append(var)
            else:
                models = [int(x) for x in models]

            desassociar = set(models_old) - set(models)
            for i in desassociar:
                scr_model = ModeloRoteiro()
                scr_model.remover(user, int(i), int(scr.id))
            associar = set(models) - set(models_old)
            for i in associar:
                scr_models = ModeloRoteiro()
                scr_models.roteiro = scr
                scr_models.modelo = Modelo.get_by_pk(i)
                scr_models.create(user)

            #verificar se há equipamento daquele modelo que não está associado a um roteiro
            for ids in models:
                equipamentos = Equipamento.objects.filter(modelo__id=int(ids))
                for equip in equipamentos:
                    try:
                        equip_roteiro = EquipamentoRoteiro.objects.filter(
                            equipamento__id=equip.id,
                            roteiro__tipo_roteiro__id=scr.tipo_roteiro.id
                        ).uniqueResult()
                        equip_roteiro.id
                    except:
                        equip_rot = EquipamentoRoteiro()
                        equip_rot.equipamento = equip
                        equip_rot.roteiro = scr
                        equip_rot.create(user)
                        pass

            with distributedlock(LOCK_SCRIPT % id_script):

                try:
                    if not scr.roteiro.lower() == script.lower(
                    ) and not scr.tipo_roteiro.id == id_script_type:
                        Roteiro.get_by_name_script(script, id_script_type)
                        raise RoteiroNameDuplicatedError(
                            None,
                            u'Já existe um roteiro com o nome %s com tipo de roteiro %s.'
                            % (script, script_type.tipo))
                except RoteiroNotFoundError:
                    pass

                # set variables
                scr.roteiro = script
                scr.tipo_roteiro = script_type
                scr.descricao = description

                try:
                    # update Script
                    scr.save()
                except Exception, e:
                    self.log.error(u'Failed to update the Script.')
                    raise RoteiroError(e, u'Failed to update the Script.')

                return self.response(dumps_networkapi({}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
Ejemplo n.º 19
0
class ScriptAddResource(RestResource):

    log = logging.getLogger('ScriptAddResource')

    def handle_post(self, request, user, *args, **kwargs):
        """Treat requests POST to add Script.

        URL: script/
        """

        try:

            self.log.info("Add Script")

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

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

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

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

            # Get XML data
            script = script_map.get('script')
            id_script_type = script_map.get('id_script_type')
            model = script_map.get('model')
            description = script_map.get('description')

            # Valid Script
            if not is_valid_string_minsize(
                    script, 3) or not is_valid_string_maxsize(script, 40):
                self.log.error(u'Parameter script is invalid. Value: %s',
                               script)
                raise InvalidValueError(None, 'script', script)

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

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

            # Find Script Type by ID to check if it exist
            script_type = TipoRoteiro.get_by_pk(id_script_type)

            try:
                Roteiro.get_by_name_script(script, id_script_type)
                raise RoteiroNameDuplicatedError(
                    None,
                    u'Já existe um roteiro com o nome %s com tipo de roteiro %s.'
                    % (script, script_type.tipo))
            except RoteiroNotFoundError:
                pass

            scr = Roteiro()

            # set variables
            scr.roteiro = script
            scr.tipo_roteiro = script_type
            scr.descricao = description

            modelo_list = []

            try:
                # save Script
                scr.save()
            except Exception, e:
                self.log.error(u'Failed to save the Script.')
                raise RoteiroError(e, u'Failed to save the Script.')

            #associar o modelo ao roteiro
            try:
                if type(model) is unicode:
                    item = model
                    model = []
                    model.append(item)
                for ids in model:
                    modelos = ModeloRoteiro()
                    modelos.roteiro = scr
                    modelo = Modelo().get_by_pk(int(ids))
                    modelos.modelo = modelo
                    modelos.create(user)
                    modelo_list.append(modelos.modelo)
            except Exception, e:
                raise RoteiroError(e, u"Failed to save modelo_roteiro.")

            #verificar se há equipamento daquele modelo que não está associado a um roteiro
            for ids in modelo_list:
                equipamentos = Equipamento.objects.filter(modelo__id=ids.id)
                for equip in equipamentos:
                    equip_roteiro = EquipamentoRoteiro.objects.filter(
                        equipamento=equip.id)
                    for rot in equip_roteiro:
                        if not rot.roteiro.tipo_roteiro == scr.tipo_roteiro:
                            try:
                                equip_roteiro = EquipamentoRoteiro()
                                equip_roteiro.equipamento = equip
                                equip_roteiro.roteiro = scr
                                equip_roteiro.create(user)
                            except:
                                pass

            script_map = dict()
            script_map['script'] = model_to_dict(
                scr, exclude=["roteiro", "tipo_roteiro", "descricao"])

            return self.response(dumps_networkapi(script_map))
    def handle_post(self, request, user, *args, **kwargs):
        """Treat requests POST to add Equipment Script.

        URL: equipmentscript/
        """

        try:

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

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

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

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

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

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

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

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

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

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

            equip_script = EquipamentoRoteiro()

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

            # save Equipment Type
            equip_script.create(user)

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

            return self.response(dumps_networkapi(networkapi_map))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
    def handle_put(self, request, user, *args, **kwargs):
        """Treat requests PUT to edit Script.

        URL: script/<id_script>/
        """
        try:

            self.log.info("Edit Script")

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

            id_script = kwargs.get("id_script")

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

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

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

            # Get XML data
            script = script_map.get("script")
            id_script_type = script_map.get("id_script_type")
            models = script_map.get("model")
            description = script_map.get("description")

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

            # Valid Script
            if not is_valid_string_minsize(script, 3) or not is_valid_string_maxsize(script, 40):
                self.log.error(u"Parameter script is invalid. Value: %s", script)
                raise InvalidValueError(None, "script", script)

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

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

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

            # Find Script Type by ID to check if it exist
            script_type = TipoRoteiro.get_by_pk(id_script_type)

            models_old = []
            scr_models = ModeloRoteiro.objects.all().filter(roteiro__id=scr.id)
            for i in scr_models:
                models_old.append(int(i.modelo.id))

            if models is not None and type(models) is not list:
                var = int(models)
                models = []
                models.append(var)
            else:
                models = [int(x) for x in models]

            desassociar = set(models_old) - set(models)
            for i in desassociar:
                scr_model = ModeloRoteiro()
                scr_model.remover(user, int(i), int(scr.id))
            associar = set(models) - set(models_old)
            for i in associar:
                scr_models = ModeloRoteiro()
                scr_models.roteiro = scr
                scr_models.modelo = Modelo.get_by_pk(i)
                scr_models.create(user)

            # verificar se há equipamento daquele modelo que não está associado a um roteiro
            for ids in models:
                equipamentos = Equipamento.objects.filter(modelo__id=int(ids))
                for equip in equipamentos:
                    try:
                        equip_roteiro = EquipamentoRoteiro.objects.filter(
                            equipamento__id=equip.id, roteiro__tipo_roteiro__id=scr.tipo_roteiro.id
                        ).uniqueResult()
                        equip_roteiro.id
                    except:
                        equip_rot = EquipamentoRoteiro()
                        equip_rot.equipamento = equip
                        equip_rot.roteiro = scr
                        equip_rot.create(user)
                        pass

            with distributedlock(LOCK_SCRIPT % id_script):

                try:
                    if not scr.roteiro.lower() == script.lower() and not scr.tipo_roteiro.id == id_script_type:
                        Roteiro.get_by_name_script(script, id_script_type)
                        raise RoteiroNameDuplicatedError(
                            None,
                            u"Já existe um roteiro com o nome %s com tipo de roteiro %s." % (script, script_type.tipo),
                        )
                except RoteiroNotFoundError:
                    pass

                # set variables
                scr.roteiro = script
                scr.tipo_roteiro = script_type
                scr.descricao = description

                try:
                    # update Script
                    scr.save()
                except Exception, e:
                    self.log.error(u"Failed to update the Script.")
                    raise RoteiroError(e, u"Failed to update the Script.")

                return self.response(dumps_networkapi({}))

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

        URL: equipmentscript/
        """

        try:

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

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

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

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

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

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

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

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

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

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

            equip_script = EquipamentoRoteiro()

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

            # save Equipment Type
            equip_script.create(user)

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

            return self.response(dumps_networkapi(networkapi_map))

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