Ejemplo n.º 1
0
    def _dissociate_interfaces_from_channel(self, ids_list, ids_interface):

        ids_list = [int(y) for y in ids_list]

        if type(ids_interface) is list:

            ids_interface = [int(x) for x in ids_interface]
            dissociate = set(ids_list) - set(ids_interface)
            for item in dissociate:
                item = Interface.get_by_pk(int(item))
                item.channel = None
                item.save()
        else:
            if ids_interface is not None:
                ids_interface = int(ids_interface)

                if ids_interface is not None:
                    for item in ids_list:
                        item = Interface.get_by_pk(int(item))
                        item.channel = None
                        item.save()
                else:
                    for item in ids_list:
                        if not item == ids_interface:
                            item = Interface.get_by_pk(int(item))
                            item.channel = None
                            item.save()
Ejemplo n.º 2
0
def create_interface(interface):

    try:
        interface_obj = Interface()
        interface_obj.create_v3(interface)
    except models.InterfaceError, e:
        raise ValidationAPIException(e.message)
Ejemplo n.º 3
0
def verificar_nome_channel(nome, interfaces):

    interface = Interface()

    channels = PortChannel.objects.filter(nome=nome)
    channels_id = []
    for ch in channels:
        channels_id.append(int(ch.id))
    if channels_id:
        for var in interfaces:
            if not var == "" and not var == None:
                interface_id = int(var)
        interface_id = interface.get_by_pk(interface_id)
        equip_id = interface_id.equipamento.id
        equip_interfaces = interface.search(equip_id)
        for i in equip_interfaces:
            try:
                sw = i.get_switch_and_router_interface_from_host_interface(i.protegida)
            except:
                sw = None
                pass
            if sw is not None:
                if sw.channel is not None:
                    if sw.channel.id in channels_id:
                        raise exceptions.InterfaceException(u"O nome do port channel ja foi utilizado no equipamento")
Ejemplo n.º 4
0
def available_channel_number(channel_name, interface_ids):
    log.info("available channel")

    interface_obj = Interface()

    for interface_id in interface_ids:

        interface = interface_obj.get_by_pk(interface_id)

        if not interface:
            raise Exception("Do not exist interface with id: %s" %
                            interface_id)

        equipment_id = interface.equipamento.id

        if not interface.ligacao_front:
            raise Exception("Interface is not connected.")

        front_equipment_id = interface.ligacao_front.equipamento.id

        if Interface.objects.filter(equipamento=equipment_id,
                                    channel__nome=channel_name):
            raise Exception("Channel name already exist on the equipment: %s" %
                            channel_name)
        if Interface.objects.filter(equipamento=front_equipment_id,
                                    channel__nome=channel_name):
            raise Exception("Channel name already exist on the equipment: %s" %
                            channel_name)
Ejemplo n.º 5
0
def create_interface(interface):

    try:
        interface_obj = Interface()
        interface_obj.create_v3(interface)
    except models.InterfaceError, e:
        raise ValidationAPIException(e.message)
    def handle_get(self, request, user, *args, **kwargs):

        try:



            self.log.info("INTERFACE")

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

            # Get XML data
            equip_id = kwargs.get('id_equipamento')


            interface = Interface()
            equip_interface = interface.search(equip_id)
            interface_list = []
            
            for var in equip_interface:
                try:
                    interface_list.append(get_new_interface_map(var.get_switch_and_router_interface_from_host_interface(None)))
                except:
                    pass

            if len(interface_list)==0:
                raise InterfaceNotFoundError(None, 'Erro: O servidor deve estar conectado aos uplinks')

            return self.response(dumps_networkapi({'map': interface_list}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
Ejemplo n.º 7
0
def verificar_nome_channel(nome, interfaces):
    log.info("verificar_nome_channel")

    interface = Interface()

    channels = PortChannel.objects.filter(nome=nome)
    channels_id = []
    for ch in channels:
        channels_id.append(int(ch.id))
    if channels_id:
        for var in interfaces:
            if not var == '' and var is not None:
                interface_id = int(var)
        interface_id = interface.get_by_pk(interface_id)
        equip_id = interface_id.equipamento.id
        equip_interfaces = interface.search(equip_id)
        for i in equip_interfaces:
            try:
                sw = i.get_switch_and_router_interface_from_host_interface(
                    i.protegida)
            except:
                sw = None
                pass
            if sw is not None:
                if sw.channel is not None:
                    if sw.channel.id in channels_id:
                        raise exceptions.InterfaceException(
                            u'O nome do port channel ja foi '
                            'utilizado no equipamento')
    def handle_post(self, request, user, *args, **kwargs):
        """Treat requests POST to add Rack.

        URL: interface/associar-ambiente/
        """
        try:
            self.log.info('Associa interface aos ambientes')

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

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

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

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

            # Get XML data
            env = interface_map.get('ambiente')
            interface = interface_map.get('interface')

            amb_int = EnvironmentInterface()
            interfaces = Interface()
            amb = Ambiente()

            amb_int.interface = interfaces.get_by_pk(int(interface))
            amb_int.ambiente = amb.get_by_pk(int(env))

            amb_int.create(user)

            amb_int_map = dict()
            amb_int_map['interface_ambiente'] = amb_int

            return self.response(dumps_networkapi(amb_int_map))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
Ejemplo n.º 9
0
    def delete(self, channel_id):
        """ tries to delete a channel and update equipments interfaces """

        try:
            interface = Interface.get_by_pk(int(channel_id))

            try:
                interface.channel.id
                channel = interface.channel
            except AtributeError:
                channel = interface.ligacao_front.channel

            try:
                interfaces = Interface.objects.all().filter(
                    channel__id=channel.id)
            except Exception as err:
                return {"error": str(err)}

            iface_type = TipoInterface.get_by_name('access')
            equip_dict = self._get_equipment_dict(interfaces)

            self._update_equipments(equip_dict, iface_type, self.user, channel)
            channel.delete(self.user)

            return {"channel": channel.id}

        except (InterfaceException, InvalidKeyException,
                InterfaceTemplateException) as err:
            return {"error": str(err)}
Ejemplo n.º 10
0
    def search_interface_of_equipment(self, equipment_id, is_new):
        """Obtém as interfaces do equipamento"""

        # Efetua a consulta das interfaces do equipamento
        results = Interface.search(equipment_id)

        if results.count() > 0:
            # Monta lista com dados retornados
            map_list = []
            for item in results:
                if is_new:
                    map_list.append(self.get_new_interface_map(item))
                else:
                    map_list.append(self.get_interface_map(item))

            # Gera response (XML) com resultados
            if is_new:
                return self.response(dumps_networkapi({'interfaces':
                                                       map_list}))
            else:
                return self.response(dumps_networkapi({'interface': map_list}))

        else:
            # Gera response (XML) para resultado vazio
            return self.response(dumps_networkapi({}))
Ejemplo n.º 11
0
def get_core_name(rack):

    name_core1 = None
    name_core2 = None

    try:
        interfaces2 = Interface.search(rack.id_ilo.id)
        for interface2 in interfaces2:
            try:
                sw = interface2.get_switch_and_router_interface_from_host_interface(
                    None)

                if sw.equipamento.nome.split('-')[0] == 'OOB':
                    if sw.equipamento.nome.split('-')[2] == '01':
                        name_core1 = sw.equipamento.nome
                    elif sw.equipamento.nome.split('-')[2] == '02':
                        name_core2 = sw.equipamento.nome

            except InterfaceNotFoundError:
                next

    except e:
        raise RackAplError(
            None, rack.nome,
            'Erro ao buscar os nomes do Core associado ao Switch de gerencia %s'
            % rack.id_ilo.id)

    return name_core1, name_core2
Ejemplo n.º 12
0
 def _dissociate_interfaces_from_channel(self, ids_list, ids_interface):
     ids_interface = [int(x) for x in ids_interface]
     dissociate = set(ids_list) - set(ids_interface)
     for item in dissociate:
         item = Interface.get_by_pk(int(item))
         item.channel = None
         item.save()
    def handle_post(self, request, user, *args, **kwargs):
        """Treat requests POST to add Rack.

        URL: interface/associar-ambiente/
        """
        try:
            self.log.info("Associa interface aos ambientes")

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

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

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

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

            # Get XML data
            env = interface_map.get('ambiente')
            interface = interface_map.get('interface')

            amb_int = EnvironmentInterface()
            interfaces = Interface()
            amb = Ambiente()

            amb_int.interface = interfaces.get_by_pk(int(interface))
            amb_int.ambiente = amb.get_by_pk(int(env))

            amb_int.create(user)

            amb_int_map = dict()
            amb_int_map['interface_ambiente'] = amb_int

            return self.response(dumps_networkapi(amb_int_map))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
Ejemplo n.º 14
0
    def delete(self, request, *args, **kwargs):
        """URL: api/interface/disconnect/(?P<id_interface_1>\d+)/(?P<id_interface_2>\d+)/"""

        try:
            log.info('API_Disconnect')

            data = dict()

            id_interface_1 = kwargs.get('id_interface_1')
            id_interface_2 = kwargs.get('id_interface_2')

            interface_1 = Interface.get_by_pk(int(id_interface_1))
            interface_2 = Interface.get_by_pk(int(id_interface_2))

            with distributedlock(LOCK_INTERFACE % id_interface_1):

                if interface_1.channel or interface_2.channel:
                    raise exceptions.InterfaceException(
                        'Interface está em um Port Channel')

                if interface_1.ligacao_front_id == interface_2.id:
                    interface_1.ligacao_front = None
                    if interface_2.ligacao_front_id == interface_1.id:
                        interface_2.ligacao_front = None
                    else:
                        interface_2.ligacao_back = None
                elif interface_1.ligacao_back_id == interface_2.id:
                    interface_1.ligacao_back = None
                    if interface_2.ligacao_back_id == interface_1.id:
                        interface_2.ligacao_back = None
                    else:
                        interface_2.ligacao_front = None
                elif not interface_1.ligacao_front_id and not interface_1.ligacao_back_id:
                    raise exceptions.InterfaceException(
                        'Interface id %s não connectada' % interface_1)

                interface_1.save()
                interface_2.save()

            return Response(data, status=status.HTTP_200_OK)

        except exceptions.InterfaceException, exception:
            raise exception
Ejemplo n.º 15
0
    def delete(self, request, *args, **kwargs):
        """URL: api/interface/disconnect/(?P<id_interface_1>\d+)/(?P<id_interface_2>\d+)/"""

        try:
            log.info('API_Disconnect')

            data = dict()

            id_interface_1 = kwargs.get('id_interface_1')
            id_interface_2 = kwargs.get('id_interface_2')

            interface_1 = Interface.get_by_pk(int(id_interface_1))
            interface_2 = Interface.get_by_pk(int(id_interface_2))

            with distributedlock(LOCK_INTERFACE % id_interface_1):

                if interface_1.channel or interface_2.channel:
                    raise exceptions.InterfaceException(
                        'Interface está em um Port Channel')

                if interface_1.ligacao_front_id == interface_2.id:
                    interface_1.ligacao_front = None
                    if interface_2.ligacao_front_id == interface_1.id:
                        interface_2.ligacao_front = None
                    else:
                        interface_2.ligacao_back = None
                elif interface_1.ligacao_back_id == interface_2.id:
                    interface_1.ligacao_back = None
                    if interface_2.ligacao_back_id == interface_1.id:
                        interface_2.ligacao_back = None
                    else:
                        interface_2.ligacao_front = None
                elif not interface_1.ligacao_front_id and not interface_1.ligacao_back_id:
                    raise exceptions.InterfaceException(
                        'Interface id %s não connectada' % interface_1)

                interface_1.save()
                interface_2.save()

            return Response(data, status=status.HTTP_200_OK)

        except exceptions.InterfaceException, exception:
            raise exception
Ejemplo n.º 16
0
    def _update_interfaces_from_http_put(self, ids_interface, int_type,
                                         vlan_nativa, envs_vlans):

        # update interfaces
        if type(ids_interface) is not list:
            i = ids_interface
            ids_interface = []
            ids_interface.append(i)

        ifaces_on_channel = []
        for iface_id in ids_interface:

            iface = Interface.get_by_pk(int(iface_id))

            self._update_interfaces_from_a_channel(iface, vlan_nativa,
                                                   ifaces_on_channel,
                                                   int_type)

            interface_sw = Interface.get_by_pk(int(iface))
            interface_server = Interface.get_by_pk(
                interface_sw.ligacao_front.id)

            front = None
            if interface_server.ligacao_front.id is not None:
                front = interface_server.ligacao_front.id

            back = None
            if interface_server.ligacao_back.id is not None:
                back = interface_server.ligacao_back.id

            Interface.update(
                user,
                interface_server.id,
                interface=interface_server.interface,
                protegida=interface_server.protegida,
                descricao=interface_server.descricao,
                ligacao_front_id=front,
                ligacao_back_id=back,
                tipo=int_type,
                vlan_nativa=int(vlan_nativa)
            )
Ejemplo n.º 17
0
    def handle_get(self, request, user, *args, **kwargs):

        try:

            self.log.info("INTERFACE")

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

            # Get XML data
            equip_id = kwargs.get('id_equipamento')

            interface = Interface()
            equip_interface = interface.search(equip_id)
            interface_list = []

            for var in equip_interface:
                try:
                    interface_list.append(
                        get_new_interface_map(
                            var.
                            get_switch_and_router_interface_from_host_interface(
                                None)))
                except:
                    pass

            if len(interface_list) == 0:
                raise InterfaceNotFoundError(
                    None, 'Erro: O servidor deve estar conectado aos uplinks')

            return self.response(dumps_networkapi({'map': interface_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 interface

        URL: /interface/<id_interface>/ 

        """
        # Get request data and check permission
        try:
            # Valid Interface ID
            id_interface = kwargs.get("id_interface")
            if not is_valid_int_greater_zero_param(id_interface):
                self.log.error(u"The id_interface parameter is not a valid value: %s.", id_interface)
                raise InvalidValueError(None, "id_interface", id_interface)

            # Get interface and equipment to check permission
            interface = Interface.get_by_pk(id_interface)
            id_equipamento = interface.equipamento_id

            # Check permission
            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_INTERFACE % id_interface):

                # Remove interface
                Interface.remove(user, id_interface)

                return self.response(dumps_networkapi({}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
Ejemplo n.º 19
0
def available_channel_number(channel_name, interface_ids):
    log.info("available channel")

    interface_obj = Interface()

    for interface_id in interface_ids:

        interface = interface_obj.get_by_pk(interface_id)

        if not interface:
            raise Exception("Do not exist interface with id: %s" % interface_id)

        equipment_id = interface.equipamento.id

        if not interface.ligacao_front:
            raise Exception("Interface is not connected.")

        front_equipment_id = interface.ligacao_front.equipamento.id

        if Interface.objects.filter(equipamento=equipment_id, channel__nome=channel_name):
            raise Exception("Channel name already exist on the equipment: %s" % channel_name)
        if Interface.objects.filter(equipamento=front_equipment_id, channel__nome=channel_name):
            raise Exception("Channel name already exist on the equipment: %s" % channel_name)
Ejemplo n.º 20
0
    def handle_delete(self, request, user, *args, **kwargs):
        """Trata uma requisição DELETE para excluir uma interface

        URL: /interface/<id_interface>/

        """
        # Get request data and check permission
        try:
            # Valid Interface ID
            id_interface = kwargs.get('id_interface')
            if not is_valid_int_greater_zero_param(id_interface):
                self.log.error(
                    u'The id_interface parameter is not a valid value: %s.', id_interface)
                raise InvalidValueError(None, 'id_interface', id_interface)

            # Get interface and equipment to check permission
            interface = Interface.get_by_pk(id_interface)
            id_equipamento = interface.equipamento_id

            # Check permission
            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_INTERFACE % id_interface):

                # Remove interface
                Interface.remove(user, id_interface)

                return self.response(dumps_networkapi({}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
Ejemplo n.º 21
0
    def _update_interfaces_from_a_channel(self, iface, vlan_nativa,
                                          ifaces_on_channel, int_type):

        try:
            sw_router = iface.get_switch_and_router_interface_from_host_interface(
                iface.protegida)
        except:
            raise InterfaceError('Interface not connected')

        if sw_router.channel is not None:
            raise InterfaceError('Interface %s is already a Channel' %
                                 sw_router.interface)

        if not sw_router.equipamento.id in ifaces_on_channel:
            ifaces_on_channel.append(int(sw_router.equipamento.id))

            if len(ifaces_on_channel) > 2:
                raise InterfaceError('More than one equipment selected')

        ligacao_front_id = None
        if sw_router.ligacao_front is not None:
            ligacao_front_id = sw_router.ligacao_front.id

        ligacao_back_id = None
        if sw_router.ligacao_back is not None:
            ligacao_back_id = sw_router.ligacao_back.id

        Interface.update(user,
                         sw_router.id,
                         interface=sw_router.interface,
                         protegida=sw_router.protegida,
                         descricao=sw_router.descricao,
                         ligacao_front_id=ligacao_front_id,
                         ligacao_back_id=ligacao_back_id,
                         tipo=int_type,
                         vlan_nativa=vlan_nativa,
                         channel=self.channel)
Ejemplo n.º 22
0
def generate_and_deploy_interface_config_sync(user, id_interface):

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

    interface = Interface.get_by_pk(id_interface)
    interfaces = [interface]

    file_to_deploy = _generate_config_file(interfaces)

    #TODO Deploy config file
    lockvar = LOCK_INTERFACE_DEPLOY_CONFIG % (interface.equipamento.id)
    status_deploy = deploy_config_in_equipment_synchronous(file_to_deploy, interface.equipamento, lockvar)

    return status_deploy
Ejemplo n.º 23
0
def generate_and_deploy_interface_config_sync(user, id_interface):

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

    interface = Interface.get_by_pk(id_interface)
    interfaces = [interface]

    file_to_deploy = _generate_config_file(interfaces)

    # TODO Deploy config file
    lockvar = LOCK_INTERFACE_DEPLOY_CONFIG % (interface.equipamento.id)
    status_deploy = deploy_config_in_equipment_synchronous(
        file_to_deploy, interface.equipamento, lockvar)

    return status_deploy
    def search_interface_by_name_and_equipment(self, equipment_id, interface_name, is_new):
        """Obtém a interface do equipamento e retorna todas as interfaces ligadas no front e no back. """

        interface = Interface.get_by_interface_equipment(interface_name, equipment_id)
        interfaces = interface.search_front_back_interfaces()

        map_list = []
        for interface in interfaces:
            if is_new:
                map_list.append(self.get_new_interface_map(interface))
            else:
                map_list.append(self.get_interface_map(interface))

        if is_new:
            return self.response(dumps_networkapi({"interfaces": map_list}))
        else:
            return self.response(dumps_networkapi({"interface": map_list}))
Ejemplo n.º 25
0
    def search_interface_by_name_and_equipment(self, equipment_id, interface_name, is_new):
        '''Obtém a interface do equipamento e retorna todas as interfaces ligadas no front e no back. '''

        interface = Interface.get_by_interface_equipment(
            interface_name, equipment_id)
        interfaces = interface.search_front_back_interfaces()

        map_list = []
        for interface in interfaces:
            if is_new:
                map_list.append(self.get_new_interface_map(interface))
            else:
                map_list.append(self.get_interface_map(interface))

        if is_new:
            return self.response(dumps_networkapi({'interfaces': map_list}))
        else:
            return self.response(dumps_networkapi({'interface': map_list}))
Ejemplo n.º 26
0
    def create(self, data):
        """ Creates a new Port Channel """

        try:
            interfaces = data.get('interfaces')
            nome = data.get('nome')
            lacp = data.get('lacp')
            int_type = data.get('int_type')
            vlan_nativa = data.get('vlan')
            envs_vlans = data.get('envs')

            api_interface_facade.verificar_vlan_nativa(vlan_nativa)

            # Checks if Port Channel name already exists on equipment
            interfaces = str(interfaces).split('-')
            api_interface_facade.check_channel_name_on_equipment(
                nome, interfaces)

            self.channel = PortChannel()
            self.channel.nome = str(nome)
            self.channel.lacp = convert_string_or_int_to_boolean(lacp)
            self.channel.create(user)

            int_type = TipoInterface.get_by_name(str(int_type))

            ifaces_on_channel = []
            for interface in interfaces:

                if interface:
                    iface = Interface.get_by_pk(int(interface))

                    self._update_interfaces_from_a_channel(
                        iface, vlan_nativa, ifaces_on_channel, int_type)

                    if 'trunk' in int_type.tipo:
                        self._create_ifaces_on_trunks(sw_router, envs_vlans)

        except Exception as err:
            return {"error": str(err)}

        return {'port_channel': self.channel}
def get_core_name(rack):

    name_core1 = None
    name_core2 = None

    try:
        interfaces2 = Interface.search(rack.id_ilo.id)
        for interface2 in interfaces2:
            try:
                sw = interface2.get_switch_and_router_interface_from_host_interface(None)

                if sw.equipamento.nome.split('-')[0]=='OOB':
                    if sw.equipamento.nome.split('-')[2]=='01':
                        name_core1 = sw.equipamento.nome
                    elif sw.equipamento.nome.split('-')[2]=='02':
                        name_core2 = sw.equipamento.nome

            except InterfaceNotFoundError:
                next

    except e:
        raise RackAplError(None,rack.nome,"Erro ao buscar os nomes do Core associado ao Switch de gerencia %s" % rack.id_ilo.id)

    return name_core1, name_core2
    def search_interface_of_equipment(self, equipment_id, is_new):
        '''Obtém as interfaces do equipamento'''

        # Efetua a consulta das interfaces do equipamento
        results = Interface.search(equipment_id)

        if results.count() > 0:
            # Monta lista com dados retornados
            map_list = []
            for item in results:
                if is_new:
                    map_list.append(self.get_new_interface_map(item))
                else:
                    map_list.append(self.get_interface_map(item))

            # Gera response (XML) com resultados
            if is_new:
                return self.response(dumps_networkapi({'interfaces': map_list}))
            else:
                return self.response(dumps_networkapi({'interface': map_list}))

        else:
            # Gera response (XML) para resultado vazio
            return self.response(dumps_networkapi({}))
    def handle_delete(self, request, user, *args, **kwargs):
        """Treat DELETE requests to remove the connection of two interfaces by front or back

        URL: interface/<id_interface>/<back_or_front>/
        """

        try:

            self.log.info("Disconnect")

            # Valid Interface ID
            id_interface = kwargs.get('id_interface')
            if not is_valid_int_greater_zero_param(id_interface):
                self.log.error(
                    u'The id_interface parameter is not a valid value: %s.', id_interface)
                raise InvalidValueError(None, 'id_interface', id_interface)

            # Valid back or front param
            back_or_front = kwargs.get('back_or_front')
            if not is_valid_zero_one_param(back_or_front):
                self.log.error(
                    u'The back_or_front parameter is not a valid value: %s.', back_or_front)
                raise InvalidValueError(None, 'back_or_front', back_or_front)
            else:
                back_or_front = int(back_or_front)

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

            # Checks if interface exists in database
            interface_1 = Interface.get_by_pk(id_interface)

            with distributedlock(LOCK_INTERFACE % id_interface):

                # Is valid back or front connection
                if back_or_front:
                    try:
                        interface_2 = Interface.get_by_pk(
                            interface_1.ligacao_front_id)
                    except InterfaceNotFoundError:
                        raise InterfaceInvalidBackFrontError(
                            None, "Interface two has no connection with front of Interface one")
                else:
                    try:
                        interface_2 = Interface.get_by_pk(
                            interface_1.ligacao_back_id)
                    except InterfaceNotFoundError:
                        raise InterfaceInvalidBackFrontError(
                            None, "Interface two has no connection with back of Interface one")

                if interface_2.ligacao_front_id == interface_1.id:
                    back_or_front_2 = 1
                elif interface_2.ligacao_back_id == interface_1.id:
                    back_or_front_2 = 0
                else:
                    raise InterfaceInvalidBackFrontError(
                        None, "Interface one has no connection with front or back of Interface two")

                # Business Rules

                # Remove Interface one connection
                if back_or_front:
                    interface_1.ligacao_front = None
                else:
                    interface_1.ligacao_back = None

                # Remove Interface two connection
                if back_or_front_2:
                    interface_2.ligacao_front = None
                else:
                    interface_2.ligacao_back = None

                # Save
                interface_1.save()
                interface_2.save()

            #sai do channel
            if interface_1.channel is not None:
                self.log.info("channel")

                id_channel = interface_1.channel.id
                interface_1.channel = None
                interface_1.save()

                interfaces = Interface.objects.all().filter(channel__id=id_channel)
                if not len(interfaces) > 0:
                    self.log.info("len "+str(len(interfaces)))

                    PortChannel.delete()

            # Return None for success
            return self.response(dumps_networkapi({}))

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

        URL: channel/editar/
        """
        try:
            self.log.info("Editar Channel")

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

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

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

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

            # Get XML data
            id_channel = channel_map.get('id_channel')
            nome = channel_map.get('nome')
            lacp = channel_map.get('lacp')
            int_type = channel_map.get('int_type')
            vlan = channel_map.get('vlan')
            envs = channel_map.get('envs')
            ids_interface = channel_map.get('ids_interface')


            if ids_interface is None:
                raise InterfaceError("Nenhuma interface selecionada")

            if vlan is not None:
                if int(vlan) < 1 or int(vlan) > 4096:
                    raise InvalidValueError(None, "Vlan" , vlan)
                if int(vlan) < 1 or 3967 < int(vlan) < 4048 or int(vlan)==4096:
                    raise InvalidValueError(None, "Vlan Nativa" ,"Range reservado: 3968-4047;4094.")

            port_channel = PortChannel()
            interface = Interface()
            amb = Ambiente()
            cont = []

            #buscar interfaces do channel
            interfaces = Interface.objects.all().filter(channel__id=id_channel)
            ids_list = []
            for i in interfaces:
                ids_list.append(i.id)

            ids_list = [ int(y) for y in ids_list ]
            if type(ids_interface) is list:
                ids_interface = [ int(x) for x in ids_interface ]
                desassociar = set(ids_list) - set(ids_interface)
                for item in desassociar:
                    item = interface.get_by_pk(int(item))
                    item.channel = None
                    item.save(user)
            else:
                if ids_interface is not None:
                    ids_interface = int(ids_interface)
                    if ids_interface is not None:
                        for item in ids_list:
                            item = interface.get_by_pk(int(item))
                            item.channel = None
                            item.save(user)
                    else:
                        for item in ids_list:
                            if not item== ids_interface:
                                item = interface.get_by_pk(int(item))
                                item.channel = None
                                item.save(user)




            #update channel
            port_channel = port_channel.get_by_pk(id_channel)
            port_channel.nome = str(nome)
            port_channel.lacp = convert_string_or_int_to_boolean(lacp)
            port_channel.save(user)

            int_type = TipoInterface.get_by_name(str(int_type))

            #update interfaces
            if type(ids_interface) is list:
                for var in ids_interface:
                    alterar_interface(var, interface, port_channel, int_type, vlan, user, envs, amb)
            else:
                var = ids_interface
                alterar_interface(var, interface, port_channel, int_type, vlan, user, envs, amb)


            port_channel_map = dict()
            port_channel_map['port_channel'] = port_channel

            return self.response(dumps_networkapi({'port_channel': port_channel_map}))

        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 um port channel
            URL: /channel/delete/<channel_name>/<interface_id>
        """
        try:
            self.log.info("Delete Channel")

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

            interface_id = kwargs.get('channel_name')
            interface = Interface.get_by_pk(int(interface_id))
            equip_list = []

            try:
                interface.channel.id
                channel = interface.channel
            except:
                channel = interface.ligacao_front.channel
                pass
            try:
                interfaces = Interface.objects.all().filter(channel__id=channel.id)
            except:
                return self.response(dumps_networkapi({}))

            for i in interfaces:
                equip_list.append(i.equipamento.id)
            equip_list = set(equip_list)
            equip_dict = dict()
            for e in equip_list:
                equip_dict[str(e)] = interfaces.filter(equipamento__id=e)

            tipo = TipoInterface()
            tipo = tipo.get_by_name("access")

            for e in equip_dict:
                for i in equip_dict.get(e):
                    try:
                        front = i.ligacao_front.id
                    except:
                        front = None
                        pass
                    try:
                        back = i.ligacao_back.id
                    except:
                        back = None
                        pass
                    i.update(user,
                                  i.id,
                                  interface=i.interface,
                                  protegida=i.protegida,
                                  descricao=i.descricao,
                                  ligacao_front_id=front,
                                  ligacao_back_id=back,
                                  tipo=tipo,
                                  vlan_nativa="1")

                status = api_interface_facade.delete_channel(user, e, equip_dict.get(e), channel)

            channel.delete(user)

            return self.response(dumps_networkapi({}))

        except api_interface_exceptions.InterfaceException, e:
            return api_interface_exceptions.InterfaceException(e)
Ejemplo n.º 32
0
    def handle_post(self, request, user, *args, **kwargs):
        """Treat requests POST to add Rack.
        URL: channel/inserir/
        """
        try:
            self.log.info('Inserir novo Channel')

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

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

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

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

            # Get XML data
            interfaces = channel_map.get('interfaces')
            nome = channel_map.get('nome')
            lacp = channel_map.get('lacp')
            int_type = channel_map.get('int_type')
            vlan_nativa = channel_map.get('vlan')
            envs_vlans = channel_map.get('envs')

            port_channel = PortChannel()
            interface = Interface()
            amb = Ambiente()
            cont = []

            api_interface_facade.verificar_vlan_nativa(vlan_nativa)

            # verifica se o nome do port channel já existe no equipamento
            interfaces = str(interfaces).split('-')
            api_interface_facade.verificar_nome_channel(nome, interfaces)

            # cria o port channel
            port_channel.nome = str(nome)
            port_channel.lacp = convert_string_or_int_to_boolean(lacp)
            port_channel.create(user)

            int_type = TipoInterface.get_by_name(str(int_type))

            for var in interfaces:
                if not var == '' and not var is None:
                    interf = interface.get_by_pk(int(var))

                    try:
                        sw_router = interf.get_switch_and_router_interface_from_host_interface(
                            interf.protegida)
                    except:
                        raise InterfaceError('Interface não conectada')

                    if sw_router.channel is not None:
                        raise InterfaceError(
                            'Interface %s já está em um Channel' % sw_router.interface)

                    if cont is []:
                        cont.append(int(sw_router.equipamento.id))
                    elif not sw_router.equipamento.id in cont:
                        cont.append(int(sw_router.equipamento.id))
                        if len(cont) > 2:
                            raise InterfaceError(
                                'Mais de dois equipamentos foram selecionados')

                    if sw_router.ligacao_front is not None:
                        ligacao_front_id = sw_router.ligacao_front.id
                    else:
                        ligacao_front_id = None
                    if sw_router.ligacao_back is not None:
                        ligacao_back_id = sw_router.ligacao_back.id
                    else:
                        ligacao_back_id = None

                    Interface.update(user,
                                     sw_router.id,
                                     interface=sw_router.interface,
                                     protegida=sw_router.protegida,
                                     descricao=sw_router.descricao,
                                     ligacao_front_id=ligacao_front_id,
                                     ligacao_back_id=ligacao_back_id,
                                     tipo=int_type,
                                     vlan_nativa=vlan_nativa,
                                     channel=port_channel)

                    if 'trunk' in int_type.tipo:
                        interface_list = EnvironmentInterface.objects.all().filter(interface=sw_router.id)
                        for int_env in interface_list:
                            int_env.delete()
                        if type(envs_vlans) is not list:
                            d = envs_vlans
                            envs_vlans = []
                            envs_vlans.append(d)
                        for i in envs_vlans:
                            amb = amb.get_by_pk(int(i.get('env')))
                            amb_int = EnvironmentInterface()
                            amb_int.interface = sw_router
                            amb_int.ambiente = amb
                            try:
                                range_vlans = i.get('vlans')
                            except:
                                range_vlans = None
                                pass
                            if range_vlans:
                                api_interface_facade.verificar_vlan_range(
                                    amb, range_vlans)
                                amb_int.vlans = range_vlans
                            amb_int.create(user)

            port_channel_map = dict()
            port_channel_map['port_channel'] = port_channel

            return self.response(dumps_networkapi({'port_channel': port_channel_map}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
Ejemplo n.º 33
0
def remove_link(interfaces):

    interface_list = list()

    for i in interfaces:
        try:
            interface_obj = Interface.objects.get(id=int(i))
            interface_list.append(interface_obj)
        except ObjectDoesNotExistException, e:
            raise ObjectDoesNotExistException(e.detail)
        except Exception, e:
            raise NetworkAPIException(str(e))

    try:
        link = Interface()
        link.disconnecting_interfaces(interface_list)
    except models.InterfaceError, e:
        raise ValidationAPIException(e.message)
    except ObjectDoesNotExistException, e:
        raise ObjectDoesNotExistException(e.detail)
    except InvalidValueError, e:
        raise ValidationAPIException(e)
    except ValidationAPIException, e:
        raise ValidationAPIException(e.detail)
    except Exception, e:
        raise NetworkAPIException(str(e))


def link_interface(interfaces):
Ejemplo n.º 34
0
    def add_remove_check_list_vlan_trunk(self, user, networkapi_map, vlan_id, operation):

        equipment_map = networkapi_map.get('equipamento')
        if equipment_map is None:
            return self.response_error(105)

        try:
            name = equipment_map.get('nome')
            if name is None or name == '':
                self.log.error(u'Parameter nome is invalid. Value: %s.', name)
                raise InvalidValueError(None, 'nome', name)

            interface_name = equipment_map.get('nome_interface')
            if interface_name is None or interface_name == '':
                self.log.error(
                    u'Parameter nome_interface is invalid. Value: %s.', interface_name)
                raise InvalidValueError(None, 'nome_interface', interface_name)

            if operation != 'list':
                vlan = Vlan().get_by_pk(vlan_id)

            # Check existence
            equipment = Equipamento().get_by_name(name)

            equip_permission = AdminPermission.EQUIP_UPDATE_CONFIG_OPERATION
            admin_permission = AdminPermission.WRITE_OPERATION
            if operation in ['check', 'list']:
                equip_permission = AdminPermission.EQUIP_READ_OPERATION
                admin_permission = AdminPermission.READ_OPERATION

            if not has_perm(user,
                            AdminPermission.VLAN_ALTER_SCRIPT,
                            admin_permission,
                            None,
                            equipment.id,
                            equip_permission):
                return self.not_authorized()

            interface = Interface.get_by_interface_equipment(
                interface_name, equipment.id)

            if interface.ligacao_front is None:
                return self.response_error(139)

            protected = None
            if operation not in ['check', 'list']:
                protected = 0

            try:
                switch_interface = interface.get_switch_interface_from_host_interface(
                    protected)
            except InterfaceNotFoundError:
                return self.response_error(144)

            if not has_perm(user,
                            AdminPermission.VLAN_ALTER_SCRIPT,
                            admin_permission,
                            None,
                            switch_interface.equipamento_id,
                            equip_permission):
                return self.not_authorized()

            # configurador -T snmp_vlans_trunk -i <nomequip> -A “'int=<interface> add=<numvlan>'”
            # configurador -T snmp_vlans_trunk -i <nomequip> -A “'int=<interface> del=<numvlan>'”
            # configurador -T snmp_vlans_trunk -i <nomequip> -A “'int=<interface> check=<numvlan>'"
            # configurador -T snmp_vlans_trunk -i <nomequip> -A
            # “'int=<interface> list'"
            command = 'configurador -T snmp_vlans_trunk -i %s -A "\'int=%s %s' % (switch_interface.equipamento.nome,
                                                                                  switch_interface.interface,
                                                                                  operation)
            if operation != 'list':
                command = command + '=%d' % vlan.num_vlan

            command = command + '\'"'

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

                return self.response(dumps_networkapi(map))
            else:
                return self.response_error(2, stdout + stderr)

        except EquipamentoNotFoundError:
            return self.response_error(117, name)
        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
    def handle_put(self, request, user, *args, **kwargs):
        """Trata uma requisição PUT para alterar informações de uma interface.

        URL: /interface/<id_interface>/
        """

        # Get request data and check permission
        try:
            # Valid Interface ID
            id_interface = kwargs.get('id_interface')
            if not is_valid_int_greater_zero_param(id_interface):
                self.log.error(
                    u'The id_interface parameter is not a valid value: %s.', id_interface)
                raise InvalidValueError(None, 'id_interface', id_interface)

            # Get interface and equipment to check permission
            interface = Interface.get_by_pk(id_interface)
            id_equipamento = interface.equipamento_id

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

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

            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is None:
                return self.response_error(3, u'There is no networkapi tag in XML request.')

            interface_map = networkapi_map.get('interface')
            if interface_map is None:
                return self.response_error(3, u'There is no interface tag in XML request.')

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

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

            tipo = interface_map.get('tipo')
            tipo = TipoInterface.get_by_name(tipo)

            vlan = interface_map.get('vlan')

            with distributedlock(LOCK_INTERFACE % id_interface):

                # Update interface
                Interface.update(user,
                                 id_interface,
                                 interface=nome,
                                 protegida=protegida,
                                 descricao=descricao,
                                 ligacao_front_id=id_ligacao_front,
                                 ligacao_back_id=id_ligacao_back,
                                 tipo=tipo,
                                 vlan_nativa=vlan)

                return self.response(dumps_networkapi({}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
Ejemplo n.º 36
0
    def handle_get(self, request, user, *args, **kwargs):
        """Treat GET requests to list interface by ID or by channel

        URL: interface/<id_interface>/get/
             interface/get-by-channel/<channel_name>/equip-name/
             interface/get/<channel_name>/<id_equip>
        """

        try:

            self.log.info('GET Interface')

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

            # Get id_interface param
            interface = kwargs.get('id_interface')
            channel = kwargs.get('channel_name')
            equipamento = kwargs.get('id_equipamento')
            equip_name = kwargs.get('equip_name')

            equipInterface_list = []
            interface_list = []

            # Valid Interface ID
            if interface is not None:
                if not is_valid_int_greater_zero_param(interface):
                    self.log.error(
                        u'The id_interface parameter is not a valid value: %s.',
                        interface)
                    raise InvalidValueError(None, 'id_interface', interface)
                id_interface = interface
                # Checks if interface exists in database
                interface = Interface.get_by_pk(id_interface)
                int_map = get_new_interface_map(interface)
                # Return interface map
                return self.response(dumps_networkapi({'interface': int_map}))

            if channel:
                if equip_name:
                    get_channel = Interface.objects.filter(channel__id=channel)
                    channel_id = get_channel[
                        0].channel.id if get_channel else ""
                    interfaces = Interface.objects.filter(
                        channel__id=channel_id) if channel_id else []
                    for i in interfaces:
                        equipInterface_list.append(get_new_interface_map(i))
                    return self.response(
                        dumps_networkapi({'interfaces': equipInterface_list}))
                if equipamento is not None:
                    interfaces = Interface.objects.all().filter(
                        channel__nome=channel)
                    for interf in interfaces:
                        if interf.equipamento.id == int(equipamento):
                            int_server = interf.get_server_switch_or_router_interface_from_host_interface(
                            )
                            equipamento = int_server.equipamento.id
                    interfaces_equip = Interface.objects.all().filter(
                        equipamento__id=int(equipamento))
                    for interf in interfaces_equip:
                        try:
                            i = interf.get_switch_and_router_interface_from_host_interface(
                            )
                            interface_list.append(get_new_interface_map(i))
                        except:
                            pass
                    return self.response(
                        dumps_networkapi({'interfaces': interface_list}))

            return self.response(dumps_networkapi({}))

        except UserNotAuthorizedError:
            return self.not_authorized()
        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 Rack.
        URL: channel/inserir/
        """
        try:
            self.log.info("Inserir novo Channel")

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

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

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

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

            # Get XML data
            interfaces = channel_map.get('interfaces')
            nome = channel_map.get('nome')
            lacp = channel_map.get('lacp')
            int_type = channel_map.get('int_type')
            vlans = channel_map.get('vlan')
            envs = channel_map.get('envs')

            port_channel = PortChannel()
            interface = Interface()
            amb = Ambiente()

            cont = []

            interfaces = str(interfaces).split('-')
            interface_id = None

            # verifica a vlan_nativa
            vlan = vlans.get('vlan_nativa')
            if vlan is not None:
                if int(vlan) < 1 or int(vlan) > 4096:
                    raise InvalidValueError(None, "Vlan Nativa", "Range valido: 1 - 4096.")
                if int(vlan) < 1 or 3967 < int(vlan) < 4048 or int(vlan)==4096:
                    raise InvalidValueError(None, "Vlan Nativa" ,"Range reservado: 3968-4047;4094.")

            # verifica se o nome do port channel já existe no equipamento
            channels = PortChannel.objects.filter(nome=nome)
            channels_id = []
            for ch in channels:
                channels_id.append(int(ch.id))
            if channels_id:
                for var in interfaces:
                    if not var=="" and not var==None:
                        interface_id = int(var)
                interface_id = interface.get_by_pk(interface_id)
                equip_id = interface_id.equipamento.id
                equip_interfaces = interface.search(equip_id)
                for i in equip_interfaces:
                    try:
                        sw = i.get_switch_and_router_interface_from_host_interface(i.protegida)
                    except:
                        sw = None
                        pass
                    if sw.channel is not None:
                        if sw.channel.id in channels_id:
                            raise InterfaceError("O nome do port channel ja foi utilizado no equipamento")

            #cria o port channel
            port_channel.nome = str(nome)
            port_channel.lacp = convert_string_or_int_to_boolean(lacp)
            port_channel.create(user)

            int_type = TipoInterface.get_by_name(str(int_type))

            for var in interfaces:
                if not var=="" and not var==None:
                    interf = interface.get_by_pk(int(var))

                    try:
                        sw_router = interf.get_switch_and_router_interface_from_host_interface(interf.protegida)
                    except:
                        raise InterfaceError("Interface não conectada")

                    if sw_router.channel is not None:
                        raise InterfaceError("Interface %s já está em um Channel" % sw_router.interface)

                    if cont is []:
                        cont.append(int(sw_router.equipamento.id))
                    elif not sw_router.equipamento.id in cont:
                        cont.append(int(sw_router.equipamento.id))
                        if len(cont) > 2:
                            raise InterfaceError("Mais de dois equipamentos foram selecionados")

                    if sw_router.ligacao_front is not None:
                        ligacao_front_id = sw_router.ligacao_front.id
                    else:
                        ligacao_front_id = None
                    if sw_router.ligacao_back is not None:
                        ligacao_back_id = sw_router.ligacao_back.id
                    else:
                        ligacao_back_id = None

                    Interface.update(user,
                                     sw_router.id,
                                     interface=sw_router.interface,
                                     protegida=sw_router.protegida,
                                     descricao=sw_router.descricao,
                                     ligacao_front_id=ligacao_front_id,
                                     ligacao_back_id=ligacao_back_id,
                                     tipo=int_type,
                                     vlan_nativa=vlans.get('vlan_nativa'),
                                     channel=port_channel)

                    if "trunk" in int_type.tipo:
                        interface_list = EnvironmentInterface.objects.all().filter(interface=sw_router.id)
                        for int_env in interface_list:
                            int_env.delete()
                        if envs is not None:
                            amb = amb.get_by_pk(int(envs))
                            amb_int = EnvironmentInterface()
                            amb_int.interface = sw_router
                            amb_int.ambiente = amb
                            try:
                                range_vlans = vlans.get('range')
                            except:
                                range_vlans = None
                                pass
                            if range_vlans:
                                api_interface_facade.verificar_vlan_range(amb, range_vlans)
                                amb_int.vlans = range_vlans
                            amb_int.create(user)

            port_channel_map = dict()
            port_channel_map['port_channel'] = port_channel

            return self.response(dumps_networkapi({'port_channel': port_channel_map}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
Ejemplo n.º 38
0
def gera_config(rack):

    id_core1 = None
    id_core2 = None
    name_sp1 = None
    name_sp2 = None
    name_sp3 = None
    name_sp4 = None
    name_core1 = None
    name_core2 = None
    int_sp1 = None
    int_sp2 = None
    int_sp3 = None
    int_sp4 = None
    int_lf1_sp1 = None
    int_lf1_sp2 = None
    int_lf2_sp3 = None
    int_lf2_sp4 = None
    int_oob_mgmtlf1 = None
    int_oob_mgmtlf2 = None
    int_oob_core1 = None
    int_oob_core2 = None
    int_core1_oob = None
    int_core2_oob = None
    prefix_spine = 'SPN'
    prefix_oob = 'OOB'

    # Equipamentos
    num_rack = rack.numero
    try:
        id_lf1 = rack.id_sw1.id
        name_lf1 = rack.id_sw1.nome
        id_lf2 = rack.id_sw2.id
        name_lf2 = rack.id_sw2.nome
        id_oob = rack.id_ilo.id
        name_oob = rack.id_ilo.nome
    except:
        raise RackConfigError(None, rack.nome, 'Erro: Rack incompleto.')

    # Interface leaf01
    try:
        interfaces = Interface.search(id_lf1)
        for interface in interfaces:
            try:
                sw = interface.get_switch_and_router_interface_from_host_interface(
                    None)
                if sw.equipamento.nome.split('-')[0] == prefix_spine:
                    if sw.equipamento.nome.split('-')[2] == '01' or sw.equipamento.nome.split('-')[2] == '1':
                        int_lf1_sp1 = interface.interface
                        name_sp1 = sw.equipamento.nome
                        id_sp1 = sw.equipamento.id
                        int_sp1 = sw.interface
                    elif sw.equipamento.nome.split('-')[2] == '02' or sw.equipamento.nome.split('-')[2] == '2':
                        int_lf1_sp2 = interface.interface
                        name_sp2 = sw.equipamento.nome
                        id_sp2 = sw.equipamento.id
                        int_sp2 = sw.interface
                elif sw.equipamento.nome.split('-')[0] == prefix_oob:
                    int_oob_mgmtlf1 = sw.interface
            except:
                pass
    except InterfaceNotFoundError:
        raise RackConfigError(
            None, rack.nome, 'Erro ao buscar as interfaces associadas ao Leaf 01.')

    if int_sp1 is None or int_sp2 is None or int_oob_mgmtlf1 is None:
        raise RackConfigError(
            None, rack.nome, 'Erro: As interfaces do Leaf01 nao foram cadastradas.')

    # Interface leaf02
    try:
        interfaces1 = Interface.search(id_lf2)
        for interface1 in interfaces1:
            try:
                sw = interface1.get_switch_and_router_interface_from_host_interface(
                    None)
                if sw.equipamento.nome.split('-')[0] == prefix_spine:
                    if sw.equipamento.nome.split('-')[2] == '03' or sw.equipamento.nome.split('-')[2] == '3':
                        int_lf2_sp3 = interface1.interface
                        name_sp3 = sw.equipamento.nome
                        id_sp3 = sw.equipamento.id
                        int_sp3 = sw.interface
                    elif sw.equipamento.nome.split('-')[2] == '04' or sw.equipamento.nome.split('-')[2] == '4':
                        int_lf2_sp4 = interface1.interface
                        name_sp4 = sw.equipamento.nome
                        id_sp4 = sw.equipamento.id
                        int_sp4 = sw.interface
                elif sw.equipamento.nome.split('-')[0] == prefix_oob:
                    int_oob_mgmtlf2 = sw.interface
            except:
                pass
    except InterfaceNotFoundError:
        raise RackConfigError(
            None, rack.nome, 'Erro ao buscar as interfaces associadas ao Leaf 02.')

    if int_sp3 is None or int_sp4 is None or int_oob_mgmtlf2 is None:
        raise RackConfigError(
            None, rack.nome, 'Erro: As interfaces do Leaf02 nao foram cadastradas.')

    # Interface OOB
    try:
        interfaces2 = Interface.search(id_oob)
        for interface2 in interfaces2:
            try:
                sw = interface2.get_switch_and_router_interface_from_host_interface(
                    None)
                if sw.equipamento.nome.split('-')[0] == prefix_oob:
                    if sw.equipamento.nome.split('-')[2] == '01' or sw.equipamento.nome.split('-')[2] == '1':
                        int_oob_core1 = interface2.interface
                        name_core1 = sw.equipamento.nome
                        int_core1_oob = sw.interface
                        id_core1 = sw.equipamento.id
                    elif sw.equipamento.nome.split('-')[2] == '02' or sw.equipamento.nome.split('-')[2] == '2':
                        int_oob_core2 = interface2.interface
                        name_core2 = sw.equipamento.nome
                        int_core2_oob = sw.interface
                        id_core2 = sw.equipamento.id
            except:
                pass
    except InterfaceNotFoundError:
        raise RackConfigError(
            None, rack.nome, 'Erro ao buscar as interfaces associadas ao Switch de gerencia.')

    if int_oob_core1 is None or int_core1_oob is None or int_oob_core2 is None or int_core2_oob is None:
        raise RackConfigError(
            None, rack.nome, 'Erro: As interfaces do Switch de gerencia nao foram cadastradas.')

    # Roteiro LF01
    try:
        FILEINLF1 = buscar_roteiro(id_lf1, 'CONFIGURACAO')
    except:
        raise RackConfigError(
            None, rack.nome, 'Erro ao buscar o roteiro do Leaf 01.')

    # Roteiro LF02
    try:
        FILEINLF2 = buscar_roteiro(id_lf2, 'CONFIGURACAO')
    except:
        raise RackConfigError(
            None, rack.nome, 'Erro ao buscar o roteiro do Leaf 02.')

    # Roteiro SPN01
    try:
        FILEINSP1 = buscar_roteiro(id_sp1, 'CONFIGURACAO')
    except:
        raise RackConfigError(
            None, rack.nome, 'Erro ao buscar o roteiro do Spine 01.')

    # Roteiro SPN02
    try:
        FILEINSP2 = buscar_roteiro(id_sp2, 'CONFIGURACAO')
    except:
        raise RackConfigError(
            None, rack.nome, 'Erro ao buscar o roteiro do Spine 02.')

    # Roteiro SPN03
    try:
        FILEINSP3 = buscar_roteiro(id_sp3, 'CONFIGURACAO')
    except:
        raise RackConfigError(
            None, rack.nome, 'Erro ao buscar o roteiro do Spine 03.')

    # Roteiro SPN04
    try:
        FILEINSP4 = buscar_roteiro(id_sp4, 'CONFIGURACAO')
    except:
        raise RackConfigError(
            None, rack.nome, 'Erro ao buscar o roteiro do Spine 04.')

    # Roteiro Core 01
    try:
        FILEINCR1 = buscar_roteiro(id_core1, 'CONFIGURACAO')
    except:
        raise RackConfigError(
            None, rack.nome, 'Erro ao buscar o roteiro do Core 01.')

    # Roteiro Core 02
    try:
        FILEINCR2 = buscar_roteiro(id_core2, 'CONFIGURACAO')
    except:
        raise RackConfigError(
            None, rack.nome, 'Erro ao buscar o roteiro do Core 02.')

    # Roteiro OOB
    try:
        FILEINOOB = buscar_roteiro(id_oob, 'CONFIGURACAO')
    except:
        raise RackConfigError(
            None, rack.nome, 'Erro ao buscar o roteiro do switch de gerencia.')

    # Ip LF01
    try:
        ip_mgmtlf1 = buscar_ip(id_lf1)
    except:
        raise RackConfigError(
            None, rack.nome, 'Erro ao buscar o ip de gerencia do leaf 01.')

    # Ip LF02
    try:
        ip_mgmtlf2 = buscar_ip(id_lf2)
    except:
        raise RackConfigError(
            None, rack.nome, 'Erro ao buscar o ip de gerencia do leaf 02.')

    # Ip OOB
    try:
        ip_mgmtoob = buscar_ip(id_oob)
    except:
        raise RackConfigError(
            None, rack.nome, 'Erro ao buscar o ip de gerencia do oob.')

    try:
        NETWORKAPI_USE_FOREMAN = int(get_variable('use_foreman'))
        NETWORKAPI_FOREMAN_URL = get_variable('foreman_url')
        NETWORKAPI_FOREMAN_USERNAME = get_variable('foreman_username')
        NETWORKAPI_FOREMAN_PASSWORD = get_variable('foreman_password')
        FOREMAN_HOSTS_ENVIRONMENT_ID = get_variable(
            'foreman_hosts_environment_id')
    except ObjectDoesNotExist:
        raise var_exceptions.VariableDoesNotExistException(
            'Erro buscando as variáveis relativas ao Foreman.')

    # begin - Create Foreman entries for rack switches
    if NETWORKAPI_USE_FOREMAN:
        foreman = Foreman(NETWORKAPI_FOREMAN_URL, (NETWORKAPI_FOREMAN_USERNAME,
                                                   NETWORKAPI_FOREMAN_PASSWORD), api_version=2)

        # for each switch, check the switch ip against foreman know networks, finds foreman hostgroup
        # based on model and brand and inserts the host in foreman
        # if host already exists, delete and recreate with new information
        for [switch, mac] in [[rack.id_sw1, rack.mac_sw1], [rack.id_sw2, rack.mac_sw2], [rack.id_ilo, rack.mac_ilo]]:
            # Get all foremand subnets and compare with the IP address of the
            # switches until find it
            if mac is None:
                raise RackConfigError(
                    None, rack.nome, ('Could not create entry for %s. There is no mac address.' % (switch.nome)))

            ip = buscar_ip(switch.id)
            if ip is None:
                raise RackConfigError(
                    None, rack.nome, ('Could not create entry for %s. There is no management IP.' % (switch.nome)))

            switch_cadastrado = 0
            for subnet in foreman.subnets.index()['results']:
                network = IPNetwork(ip + '/' + subnet['mask']).network
                # check if switches ip network is the same as
                # subnet['subnet']['network'] e subnet['subnet']['mask']
                if network.__str__() == subnet['network']:
                    subnet_id = subnet['id']
                    hosts = foreman.hosts.index(search=switch.nome)['results']
                    if len(hosts) == 1:
                        foreman.hosts.destroy(id=hosts[0]['id'])
                    elif len(hosts) > 1:
                        raise RackConfigError(
                            None, rack.nome, ('Could not create entry for %s. There are multiple entries with the sam name.' % (switch.nome)))

                    # Lookup foreman hostgroup
                    # By definition, hostgroup should be Marca+"_"+Modelo
                    hostgroup_name = switch.modelo.marca.nome + '_' + switch.modelo.nome
                    hostgroups = foreman.hostgroups.index(
                        search=hostgroup_name)
                    if len(hostgroups['results']) == 0:
                        raise RackConfigError(None, rack.nome, 'Could not create entry for %s. Could not find hostgroup %s in foreman.' % (
                            switch.nome, hostgroup_name))
                    elif len(hostgroups['results']) > 1:
                        raise RackConfigError(None, rack.nome, 'Could not create entry for %s. Multiple hostgroups %s found in Foreman.' % (
                            switch.nome, hostgroup_name))
                    else:
                        hostgroup_id = hostgroups['results'][0]['id']

                    host = foreman.hosts.create(host={'name': switch.nome, 'ip': ip, 'mac': mac, 'environment_id': FOREMAN_HOSTS_ENVIRONMENT_ID,
                                                      'hostgroup_id': hostgroup_id, 'subnet_id': subnet_id, 'build': 'true', 'overwrite': 'true'})
                    switch_cadastrado = 1

            if not switch_cadastrado:
                raise RackConfigError(None, rack.nome, "Unknown error. Could not create entry for %s in foreman." % (switch.nome))
    #end - Create Foreman entries for rack switches
    var1 = autoprovision_splf(num_rack, FILEINLF1, FILEINLF2, FILEINSP1, FILEINSP2, FILEINSP3, FILEINSP4,
                              name_lf1, name_lf2, name_oob, name_sp1, name_sp2, name_sp3, name_sp4,
                              ip_mgmtlf1, ip_mgmtlf2,
                              int_oob_mgmtlf1, int_oob_mgmtlf2, int_sp1, int_sp2, int_sp3, int_sp4, int_lf1_sp1,
                              int_lf1_sp2, int_lf2_sp3, int_lf2_sp4)

    var2 = autoprovision_coreoob(num_rack, FILEINCR1, FILEINCR2, FILEINOOB,
                                 name_core1, name_core2, name_oob, name_lf1, name_lf2,
                                 ip_mgmtoob, int_oob_core1, int_oob_core2, int_core1_oob, int_core2_oob )


    if var1 and var2:
        return True

    return False
    def handle_get(self, request, user, *args, **kwargs):
        """Treat GET requests to list interface by ID or by channel

        URL: interface/<id_interface>/get/
             interface/get-by-channel/<channel_name>/
             interface/get/<channel_name>/<id_equip>
        """

        try:

            self.log.info("GET Interface")

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

            # Get id_interface param
            interface = kwargs.get('id_interface')
            channel = kwargs.get('channel_name')
            equipamento = kwargs.get('id_equipamento')

            equipInterface_list = []
            interface_list = []

            # Valid Interface ID
            if interface is not None:
                if not is_valid_int_greater_zero_param(interface):
                    self.log.error(u'The id_interface parameter is not a valid value: %s.', interface)
                    raise InvalidValueError(None, 'id_interface', interface)
                id_interface = interface
                # Checks if interface exists in database
                interface = Interface.get_by_pk(id_interface)
                int_map = get_new_interface_map(interface)
                # Return interface map
                return self.response(dumps_networkapi({'interface': int_map}))

            if channel is not None:
                if equipamento is None:
                    interfaces = Interface.objects.all().filter(channel__nome=channel)
                    for interf in interfaces:
                        equipInterface_list.append(get_new_interface_map(interf))
                    return self.response(dumps_networkapi({'interfaces': equipInterface_list}))
                else:
                    interfaces = Interface.objects.all().filter(channel__nome=channel)
                    for interf in interfaces:
                        if interf.equipamento.id==int(equipamento):
                            int_server = interf.get_server_switch_or_router_interface_from_host_interface()
                            equipamento = int_server.equipamento.id
                    interfaces_equip = Interface.objects.all().filter(equipamento__id=int(equipamento))
                    for interf in interfaces_equip:
                        try:
                            i = interf.get_switch_and_router_interface_from_host_interface()
                            interface_list.append(get_new_interface_map(i))
                        except:
                            pass
                    return self.response(dumps_networkapi({'interfaces': interface_list}))

            return self.response(dumps_networkapi({}))


        except UserNotAuthorizedError:
            return self.not_authorized()
        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
Ejemplo n.º 40
0
    def handle_put(self, request, user, *args, **kwargs):
        """Trata uma requisição PUT para alterar informações de uma interface.

        URL: /interface/<id_interface>/
        """

        # Get request data and check permission
        try:
            # Valid Interface ID
            id_interface = kwargs.get('id_interface')
            if not is_valid_int_greater_zero_param(id_interface):
                self.log.error(
                    u'The id_interface parameter is not a valid value: %s.',
                    id_interface)
                raise InvalidValueError(None, 'id_interface', id_interface)

            # Get interface and equipment to check permission
            interface = Interface.get_by_pk(id_interface)
            id_equipamento = interface.equipamento_id

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

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

            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is None:
                return self.response_error(
                    3, u'There is no networkapi tag in XML request.')

            interface_map = networkapi_map.get('interface')
            if interface_map is None:
                return self.response_error(
                    3, u'There is no interface tag in XML request.')

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

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

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

            vlan = interface_map.get('vlan')
            with distributedlock(LOCK_INTERFACE % id_interface):

                # Update interface
                Interface.update(user,
                                 id_interface,
                                 interface=nome,
                                 protegida=protegida,
                                 descricao=descricao,
                                 ligacao_front_id=id_ligacao_front,
                                 ligacao_back_id=id_ligacao_back,
                                 tipo=tipo,
                                 vlan_nativa=vlan)

                return self.response(dumps_networkapi({}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
Ejemplo n.º 41
0
    def handle_put(self, request, user, *args, **kwargs):
        """Treat requests POST to add Rack.

        URL: channel/editar/
        """
        try:
            self.log.info('Editar Channel')

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

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

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

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

            # Get XML data
            id_channel = channel_map.get('id_channel')
            nome = channel_map.get('nome')
            if not is_valid_int_greater_zero_param(nome):
                raise InvalidValueError(
                    None, 'Numero do Channel', 'Deve ser um numero inteiro.')
            lacp = channel_map.get('lacp')
            int_type = channel_map.get('int_type')
            vlan_nativa = channel_map.get('vlan')
            envs_vlans = channel_map.get('envs')
            ids_interface = channel_map.get('ids_interface')
            if ids_interface is None:
                raise InterfaceError('Nenhuma interface selecionada')

            if type(ids_interface) == list:
                interfaces_list = ids_interface
            else:
                interfaces_list = str(ids_interface).split('-')

            port_channel = PortChannel()
            interface = Interface()
            amb = Ambiente()

            api_interface_facade.verificar_vlan_nativa(vlan_nativa)

            # verifica se o nome do port channel já existe no equipamento
            channel = port_channel.get_by_pk(int(id_channel))
            if not nome == channel.nome:
                api_interface_facade.verificar_nome_channel(
                    nome, interfaces_list)

            # buscar interfaces do channel
            interfaces = Interface.objects.all().filter(channel__id=id_channel)
            ids_list = []
            for i in interfaces:
                ids_list.append(i.id)

            ids_list = [int(y) for y in ids_list]
            if type(ids_interface) is list:
                ids_interface = [int(x) for x in ids_interface]
                desassociar = set(ids_list) - set(ids_interface)
                for item in desassociar:
                    item = interface.get_by_pk(int(item))
                    item.channel = None
                    item.save()
            else:
                if ids_interface is not None:
                    ids_interface = int(ids_interface)
                    if ids_interface is not None:
                        for item in ids_list:
                            item = interface.get_by_pk(int(item))
                            item.channel = None
                            item.save()
                    else:
                        for item in ids_list:
                            if not item == ids_interface:
                                item = interface.get_by_pk(int(item))
                                item.channel = None
                                item.save()

            # update channel
            channel.nome = str(nome)
            channel.lacp = convert_string_or_int_to_boolean(lacp)
            channel.save()

            int_type = TipoInterface.get_by_name(str(int_type))

            # update interfaces
            if type(ids_interface) is not list:
                i = ids_interface
                ids_interface = []
                ids_interface.append(i)
            for var in ids_interface:
                alterar_interface(var, interface, channel,
                                  int_type, vlan_nativa, user, envs_vlans, amb)
                interface = Interface()
                server_obj = Interface()
                interface_sw = interface.get_by_pk(int(var))
                interface_server = server_obj.get_by_pk(
                    interface_sw.ligacao_front.id)
                try:
                    front = interface_server.ligacao_front.id
                except:
                    front = None
                    pass
                try:
                    back = interface_server.ligacao_back.id
                except:
                    back = None
                    pass
                server_obj.update(user,
                                  interface_server.id,
                                  interface=interface_server.interface,
                                  protegida=interface_server.protegida,
                                  descricao=interface_server.descricao,
                                  ligacao_front_id=front,
                                  ligacao_back_id=back,
                                  tipo=int_type,
                                  vlan_nativa=int(vlan_nativa))

            port_channel_map = dict()
            port_channel_map['port_channel'] = port_channel

            return self.response(dumps_networkapi({'port_channel': port_channel_map}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
Ejemplo n.º 42
0
    def handle_delete(self, request, user, *args, **kwargs):
        """Trata uma requisição DELETE para excluir um port channel
            URL: /channel/delete/<channel_name>/<interface_id>
        """
        try:
            self.log.info('Delete Channel')

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

            interface_id = kwargs.get('channel_name')
            interface = Interface.get_by_pk(int(interface_id))
            equip_list = []

            try:
                interface.channel.id
                channel = interface.channel
            except:
                channel = interface.ligacao_front.channel
                pass
            try:
                interfaces = Interface.objects.all().filter(channel__id=channel.id)
            except:
                return self.response(dumps_networkapi({}))

            for i in interfaces:
                equip_list.append(i.equipamento.id)
            equip_list = set(equip_list)
            equip_dict = dict()
            for e in equip_list:
                equip_dict[str(e)] = interfaces.filter(equipamento__id=e)

            tipo = TipoInterface()
            tipo = tipo.get_by_name('access')

            for e in equip_dict:
                for i in equip_dict.get(e):
                    try:
                        front = i.ligacao_front.id
                    except:
                        front = None
                        pass
                    try:
                        back = i.ligacao_back.id
                    except:
                        back = None
                        pass
                    i.update(user,
                             i.id,
                             interface=i.interface,
                             protegida=i.protegida,
                             descricao=i.descricao,
                             ligacao_front_id=front,
                             ligacao_back_id=back,
                             tipo=tipo,
                             vlan_nativa='1')

                status = api_interface_facade.delete_channel(
                    user, e, equip_dict.get(e), channel)

            channel.delete(user)

            return self.response(dumps_networkapi({}))

        except api_interface_exceptions.InterfaceException, e:
            return self.response_error(410, e)
Ejemplo n.º 43
0
def gerar_arquivo_config(ids):
    log.debug("gerar_arquivo_config")

    for id in ids:
        rack = Rack().get_rack(idt=id)
        equips = list()
        lf1 = dict()
        lf2 = dict()
        oob = dict()

        # Equipamentos
        try:
            nome_rack = rack.nome.upper()
            lf1["sw"] = 1
            lf1["id"] = rack.id_sw1.id
            lf1["nome"] = rack.id_sw1.nome
            lf1["mac"] = rack.mac_sw1
            lf1["marca"] = rack.id_sw1.modelo.marca.nome
            lf1["modelo"] = rack.id_sw1.modelo.nome
            equips.append(lf1)
            lf2["sw"] = 2
            lf2["id"] = rack.id_sw2.id
            lf2["nome"] = rack.id_sw2.nome
            lf2["mac"] = rack.mac_sw2
            lf2["marca"] = rack.id_sw2.modelo.marca.nome
            lf2["modelo"] = rack.id_sw2.modelo.nome
            equips.append(lf2)
            oob["sw"] = 3
            oob["id"] = rack.id_ilo.id
            oob["nome"] = rack.id_ilo.nome
            oob["mac"] = rack.mac_ilo
            oob["marca"] = rack.id_ilo.modelo.marca.nome
            oob["modelo"] = rack.id_ilo.modelo.nome
            equips.append(oob)
            dcname = rack.dcroom.dc.dcname
        except:
            raise Exception(
                "Erro: Informações incompletas. Verifique o cadastro do Datacenter, do Fabric e do Rack"
            )

        dcsigla = "".join([c[0] for c in dcname.split(" ")
                           ]) if len(dcname.split(" ")) >= 2 else dcname[:3]
        prefixspn = "SPN"
        prefixlf = "LF-"
        prefixoob = "OOB"

        # Interface e Roteiro
        for equip in equips:
            try:
                interfaces = Interface.search(equip.get("id"))
                equip["interfaces"] = list()
                for interface in interfaces:
                    dic = dict()
                    try:
                        sw = interface.get_switch_and_router_interface_from_host_interface(
                            None)
                        if sw.equipamento.nome[:3] in [
                                prefixlf, prefixoob, prefixspn
                        ]:
                            dic["nome"] = sw.equipamento.nome
                            dic["id"] = sw.equipamento.id
                            dic["ip_mngt"] = _buscar_ip(sw.equipamento.id)
                            dic["interface"] = sw.interface
                            dic["eq_interface"] = interface.interface
                            dic["roteiro"] = _buscar_roteiro(
                                sw.equipamento.id, "CONFIGURACAO")
                            equip["interfaces"].append(dic)
                    except:
                        pass
            except:
                raise Exception(
                    "Erro ao buscar o roteiro de configuracao ou as interfaces associadas ao equipamento: "
                    "%s." % equip.get("nome"))
            try:
                equip["roteiro"] = _buscar_roteiro(equip.get("id"),
                                                   "CONFIGURACAO")
                equip["ip_mngt"] = _buscar_ip(equip.get("id"))
            except:
                raise Exception(
                    "Erro ao buscar os roteiros do equipamento: %s" %
                    equip.get("nome"))

        autoprovision.autoprovision_splf(rack, equips)
        autoprovision.autoprovision_coreoob(rack, equips)

    return True
Ejemplo n.º 44
0
def remove_link(interfaces):

    interface_list = list()

    for i in interfaces:
        try:
            interface_obj = Interface.objects.get(id=int(i))
            interface_list.append(interface_obj)
        except ObjectDoesNotExistException, e:
            raise ObjectDoesNotExistException(e.detail)
        except Exception, e:
            raise NetworkAPIException(str(e))

    try:
        link = Interface()
        link.disconnecting_interfaces(interface_list)
    except models.InterfaceError, e:
        raise ValidationAPIException(e.message)
    except ObjectDoesNotExistException, e:
        raise ObjectDoesNotExistException(e.detail)
    except InvalidValueError, e:
        raise ValidationAPIException(e)
    except ValidationAPIException, e:
        raise ValidationAPIException(e.detail)
    except Exception, e:
        raise NetworkAPIException(str(e))


def link_interface(interfaces):
Ejemplo n.º 45
0
    def handle_get(self, request, user, *args, **kwargs):
        """Handles GET requests to find all Racks

        URLs: /rack/find/
        """

        self.log.info('Get Rack by equipment id')

        try:

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

            # Get XML data
            equip_id = kwargs.get('equip_id')
            equip_id = int(equip_id)
            rack_map = []
            interface = Interface()

            try:
                racks = Rack.objects.filter(id_sw1__id=equip_id)
                for cont in racks:
                    rack_map.append(model_to_dict(cont))
                    return self.response(dumps_networkapi({'rack': rack_map}))
            except:
                pass

            try:
                racks = Rack.objects.filter(id_sw2__id=equip_id)
                for cont in racks:
                    rack_map.append(model_to_dict(cont))
                    return self.response(dumps_networkapi({'rack': rack_map}))
            except:
                pass

            try:
                racks = Rack.objects.filter(id_ilo__id=equip_id)
                for cont in racks:
                    rack_map.append(model_to_dict(cont))
                    return self.response(dumps_networkapi({'rack': rack_map}))
            except:
                pass

            try:
                interfaces = interface.search(equip_id)
                for interf in interfaces:
                    sw_router = interf.get_switch_and_router_interface_from_host_interface(
                        interf.protegida)
                    try:
                        racks = Rack.objects.filter(
                            id_sw1__id=sw_router.equipamento.id)
                        for cont in racks:
                            rack_map.append(model_to_dict(cont))
                            return self.response(dumps_networkapi({'rack': rack_map}))
                    except:
                        pass
                    try:
                        racks = Rack.objects.filter(
                            id_sw2__id=sw_router.equipamento.id)
                        for cont in racks:
                            rack_map.append(model_to_dict(cont))
                            return self.response(dumps_networkapi({'rack': rack_map}))
                    except:
                        pass
                    try:
                        racks = Rack.objects.filter(
                            id_ilo__id=sw_router.equipamento.id)
                        for cont in racks:
                            rack_map.append(model_to_dict(cont))
                            return self.response(dumps_networkapi({'rack': rack_map}))
                    except:
                        pass
            except:
                pass

            return self.response(dumps_networkapi({'rack': rack_map}))

        except UserNotAuthorizedError:
            return self.not_authorized()

        except RackError:
            return self.response_error(1)

        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 Rack.

        URL: channel/inserir/
        """
        try:
            self.log.info("Inserir novo Channel")

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

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

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

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

            # Get XML data
            interfaces = channel_map.get('interfaces')
            nome = channel_map.get('nome')
            lacp = channel_map.get('lacp')
            int_type = channel_map.get('int_type')
            vlan = channel_map.get('vlan')
            envs = channel_map.get('envs')
            port_channel = PortChannel()
            interface = Interface()
            amb = Ambiente()

            cont = []

            port_channel.nome = str(nome)
            port_channel.lacp = convert_string_or_int_to_boolean(lacp)
            port_channel.create(user)

            interfaces = str(interfaces).split('-')

            int_type = TipoInterface.get_by_name(str(int_type))
            for var in interfaces:
                if not var=="" and not var==None:
                    interf = interface.get_by_pk(int(var))
                    try:
                        sw_router = interf.get_switch_and_router_interface_from_host_interface(interf.protegida)
                    except:
                        raise InterfaceError("Interface não conectada")

                    if sw_router.channel is not None:
                        raise InterfaceError("Interface %s já está em um Channel" % sw_router.interface)

                    for i in interface.search(sw_router.equipamento.id):
                        if i.channel is not None:
                            raise InterfaceError("Equipamento %s já possui um Channel" % sw_router.equipamento.nome)

                    if cont is []:
                        cont.append(int(sw_router.equipamento.id))
                    elif not sw_router.equipamento.id in cont:
                        cont.append(int(sw_router.equipamento.id))
                        if len(cont) > 2:
                            raise InterfaceError("Mais de dois equipamentos foram selecionados")

                    if sw_router.ligacao_front is not None:
                        ligacao_front_id = sw_router.ligacao_front.id
                    else:
                        ligacao_front_id = None
                    if sw_router.ligacao_back is not None:
                        ligacao_back_id = sw_router.ligacao_back.id
                    else:
                        ligacao_back_id = None

                    Interface.update(user,
                                     sw_router.id,
                                     interface=sw_router.interface,
                                     protegida=sw_router.protegida,
                                     descricao=sw_router.descricao,
                                     ligacao_front_id=ligacao_front_id,
                                     ligacao_back_id=ligacao_back_id,
                                     tipo=int_type,
                                     vlan_nativa=vlan,
                                     channel=port_channel)

                    if "trunk" in int_type.tipo:
                        interface_list = EnvironmentInterface.objects.all().filter(interface=sw_router.id)
                        for int_env in interface_list:
                            int_env.delete(user)
                        if envs is not None:
                            if not type(envs)==unicode:
                                for env in envs:
                                    amb_int = EnvironmentInterface()
                                    amb_int.interface = sw_router
                                    amb_int.ambiente = amb.get_by_pk(int(env))
                                    amb_int.create(user)
                            else:
                                amb_int = EnvironmentInterface()
                                amb_int.interface = sw_router
                                amb_int.ambiente = amb.get_by_pk(int(envs))
                                amb_int.create(user)

            port_channel_map = dict()
            port_channel_map['port_channel'] = port_channel

            return self.response(dumps_networkapi({'port_channel': port_channel_map}))

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

    id_core1=None
    id_core2=None
    name_sp1=None
    name_sp2=None   
    name_sp3=None   
    name_sp4=None   
    name_core1=None
    name_core2=None
    int_sp1=None
    int_sp2=None   
    int_sp3=None   
    int_sp4=None   
    int_lf1_sp1=None   
    int_lf1_sp2=None   
    int_lf2_sp3=None   
    int_lf2_sp4=None
    int_oob_mgmtlf1=None
    int_oob_mgmtlf2=None
    int_oob_core1=None  
    int_oob_core2=None  
    int_core1_oob=None  
    int_core2_oob=None  


    #Equipamentos
    num_rack = rack.numero
    try:
        id_lf1 = rack.id_sw1.id
        name_lf1 = rack.id_sw1.nome
        id_lf2 = rack.id_sw2.id
        name_lf2 = rack.id_sw2.nome
        id_oob = rack.id_ilo.id
        name_oob = rack.id_ilo.nome
    except:
        raise RackConfigError(None,rack.nome,"Erro: Rack incompleto.")


    #Interface leaf01
    try:
        interfaces = Interface.search(id_lf1)
        for interface in interfaces:
            try: 
                sw = interface.get_switch_and_router_interface_from_host_interface(None)
                if sw.equipamento.nome.split('-')[2]=='01' or sw.equipamento.nome.split('-')[2]=='1': 
                    int_lf1_sp1 = interface.interface
                    name_sp1 = sw.equipamento.nome
                    id_sp1 = sw.equipamento.id
                    int_sp1 =  sw.interface
                elif sw.equipamento.nome.split('-')[2]=='02' or sw.equipamento.nome.split('-')[2]=='2':
                    int_lf1_sp2 = interface.interface
                    name_sp2 = sw.equipamento.nome
                    id_sp2 = sw.equipamento.id
                    int_sp2 =  sw.interface 
                elif sw.equipamento.nome.split('-')[0]=='OOB':
                    int_oob_mgmtlf1 = sw.interface
            except:
                pass
    except InterfaceNotFoundError:
        raise RackConfigError(None,rack.nome,"Erro ao buscar as interfaces associadas ao Leaf 01.")

    if int_sp1==None or int_sp2==None or int_oob_mgmtlf1==None:
        raise RackConfigError(None,rack.nome,"Erro: As interfaces do Leaf01 nao foram cadastradas.")  

    #Interface leaf02
    try:
        interfaces1 = Interface.search(id_lf2)
        for interface1 in interfaces1:
            try:
                sw = interface1.get_switch_and_router_interface_from_host_interface(None)
                if sw.equipamento.nome.split('-')[2]=='03' or sw.equipamento.nome.split('-')[2]=='3':
                    int_lf2_sp3 = interface1.interface
                    name_sp3 = sw.equipamento.nome
                    id_sp3 = sw.equipamento.id
                    int_sp3 =  sw.interface
                elif sw.equipamento.nome.split('-')[2]=='04' or sw.equipamento.nome.split('-')[2]=='4':
                    int_lf2_sp4 = interface1.interface
                    name_sp4 = sw.equipamento.nome
                    id_sp4 = sw.equipamento.id
                    int_sp4 =  sw.interface
                elif sw.equipamento.nome.split('-')[0]=='OOB':
                    int_oob_mgmtlf2 = sw.interface
            except:
                pass
    except InterfaceNotFoundError:
        raise RackConfigError(None,rack.nome,"Erro ao buscar as interfaces associadas ao Leaf 02.")

    if int_sp3==None or int_sp4==None or int_oob_mgmtlf2==None:
        raise RackConfigError(None,rack.nome,"Erro: As interfaces do Leaf02 nao foram cadastradas.")

    #Interface OOB
    try:
        interfaces2 = Interface.search(id_oob)
        for interface2 in interfaces2:
            try:
                sw = interface2.get_switch_and_router_interface_from_host_interface(None)
                if sw.equipamento.nome.split('-')[0]=='OOB':
                    if sw.equipamento.nome.split('-')[2]=='01' or sw.equipamento.nome.split('-')[2]=='1':
                        int_oob_core1 = interface2.interface
                        name_core1 = sw.equipamento.nome
                        int_core1_oob =  sw.interface
                        id_core1 = sw.equipamento.id
                    elif sw.equipamento.nome.split('-')[2]=='02' or sw.equipamento.nome.split('-')[2]=='2':
                        int_oob_core2 = interface2.interface
                        name_core2 = sw.equipamento.nome
                        int_core2_oob =  sw.interface
                        id_core2 = sw.equipamento.id
            except:
                pass 
    except InterfaceNotFoundError:
        raise RackConfigError(None,rack.nome,"Erro ao buscar as interfaces associadas ao Switch de gerencia.")

    if int_oob_core1==None or int_core1_oob==None or int_oob_core2==None or int_core2_oob==None:
        raise RackConfigError(None,rack.nome,"Erro: As interfaces do Switch de gerencia nao foram cadastradas.")

    #Roteiro LF01
    try:
        FILEINLF1 = buscar_roteiro(id_lf1, "CONFIGURACAO")
    except:
        raise RackConfigError(None,rack.nome,"Erro ao buscar o roteiro do Leaf 01.")

   #Roteiro LF02
    try:
        FILEINLF2 = buscar_roteiro(id_lf2, "CONFIGURACAO")    
    except:
        raise RackConfigError(None,rack.nome,"Erro ao buscar o roteiro do Leaf 02.")

    #Roteiro SPN01
    try:
        FILEINSP1 = buscar_roteiro(id_sp1, "CONFIGURACAO")    
    except:
        raise RackConfigError(None,rack.nome,"Erro ao buscar o roteiro do Spine 01.")

    #Roteiro SPN02
    try:
        FILEINSP2 = buscar_roteiro(id_sp2, "CONFIGURACAO")    
    except:
        raise RackConfigError(None,rack.nome,"Erro ao buscar o roteiro do Spine 02.")

    #Roteiro SPN03
    try:
        FILEINSP3 = buscar_roteiro(id_sp3, "CONFIGURACAO")    
    except:
        raise RackConfigError(None,rack.nome,"Erro ao buscar o roteiro do Spine 03.")

    #Roteiro SPN04
    try:
        FILEINSP4 = buscar_roteiro(id_sp4, "CONFIGURACAO")    
    except:
        raise RackConfigError(None,rack.nome,"Erro ao buscar o roteiro do Spine 04.")

    #Roteiro Core 01
    try:
        FILEINCR1 = buscar_roteiro(id_core1, "CONFIGURACAO")    
    except:
        raise RackConfigError(None,rack.nome,"Erro ao buscar o roteiro do Core 01.")

    #Roteiro Core 02
    try:
        FILEINCR2 = buscar_roteiro(id_core2, "CONFIGURACAO")    
    except:
        raise RackConfigError(None,rack.nome,"Erro ao buscar o roteiro do Core 02.")

    #Roteiro OOB
    try:
        FILEINOOB = buscar_roteiro(id_oob, "CONFIGURACAO")    
    except:
        raise RackConfigError(None,rack.nome,"Erro ao buscar o roteiro do switch de gerencia.")

    #Ip LF01
    try:
        ip_mgmtlf1 = buscar_ip(id_lf1)
    except:
        raise RackConfigError(None,rack.nome,"Erro ao buscar o ip de gerencia do leaf 01.")

    #Ip LF02
    try:
        ip_mgmtlf2 = buscar_ip(id_lf2)
    except:
        raise RackConfigError(None,rack.nome,"Erro ao buscar o ip de gerencia do leaf 02.")

    #Ip OOB
    try:
        ip_mgmtoob = buscar_ip(id_oob)
    except:
        raise RackConfigError(None,rack.nome,"Erro ao buscar o ip de gerencia do oob.")

    try:
        NETWORKAPI_USE_FOREMAN = int(get_variable("use_foreman"))
        NETWORKAPI_FOREMAN_URL = get_variable("foreman_url")
        NETWORKAPI_FOREMAN_USERNAME = get_variable("foreman_username")
        NETWORKAPI_FOREMAN_PASSWORD = get_variable("foreman_password")
        FOREMAN_HOSTS_ENVIRONMENT_ID = get_variable("foreman_hosts_environment_id")
    except ObjectDoesNotExist:
        raise var_exceptions.VariableDoesNotExistException("Erro buscando as variáveis relativas ao Foreman.")

    #begin - Create Foreman entries for rack switches
    if NETWORKAPI_USE_FOREMAN:
        foreman = Foreman(NETWORKAPI_FOREMAN_URL, (NETWORKAPI_FOREMAN_USERNAME, NETWORKAPI_FOREMAN_PASSWORD), api_version=2)

        #for each switch, check the switch ip against foreman know networks, finds foreman hostgroup
        # based on model and brand and inserts the host in foreman
        # if host already exists, delete and recreate with new information
        for [switch, mac] in [[rack.id_sw1, rack.mac_sw1], [rack.id_sw2, rack.mac_sw2], [rack.id_ilo, rack.mac_ilo]]:
            #Get all foremand subnets and compare with the IP address of the switches until find it
            if mac == None:
                raise RackConfigError(None, rack.nome, ("Could not create entry for %s. There is no mac address." % (switch.nome)))

            ip = buscar_ip(switch.id)
            switch_cadastrado=0
            for subnet in foreman.subnets.index()['results']:
                network = IPNetwork(ip+'/'+subnet['mask']).network
                #check if switches ip network is the same as subnet['subnet']['network'] e subnet['subnet']['mask']
                if network.__str__() == subnet['network']:
                    subnet_id = subnet['id']
                    hosts = foreman.hosts.index(search=switch.nome)['results']
                    if len(hosts) == 1:
                        foreman.hosts.destroy(id=hosts[0]['id'])
                    elif len(hosts) > 1:
                        raise RackConfigError(None, rack.nome, ("Could not create entry for %s. There are multiple entries with the sam name." % (switch.nome)))

                    #Lookup foreman hostgroup
                    #By definition, hostgroup should be Marca+"_"+Modelo
                    hostgroup_name = switch.modelo.marca.nome+"_"+switch.modelo.nome
                    hostgroups = foreman.hostgroups.index(search=hostgroup_name)
                    if len(hostgroups['results']) == 0:
                        raise RackConfigError(None, rack.nome, "Could not create entry for %s. Could not find hostgroup %s in foreman." % (switch.nome, hostgroup_name))
                    elif len(hostgroups['results'])>1:
                        raise RackConfigError(None, rack.nome, "Could not create entry for %s. Multiple hostgroups %s found in Foreman." % (switch.nome, hostgroup_name))
                    else:
                        hostgroup_id = hostgroups['results'][0]['id']

                    host = foreman.hosts.create(host={'name': switch.nome, 'ip': ip, 'mac': mac, 'environment_id': FOREMAN_HOSTS_ENVIRONMENT_ID, 'hostgroup_id': hostgroup_id, 'subnet_id': subnet_id, 'build': 'true', 'overwrite': 'true'})
                    switch_cadastrado=1
                    
            if not switch_cadastrado:
                raise RackConfigError(None, rack.nome, "Unknown error. Could not create entry for %s in foreman." % (switch.nome))
    #end - Create Foreman entries for rack switches
    var1 = autoprovision_splf(num_rack, FILEINLF1, FILEINLF2, FILEINSP1, FILEINSP2, FILEINSP3, FILEINSP4, name_lf1, name_lf2, name_oob, name_sp1, name_sp2, name_sp3, name_sp4, ip_mgmtlf1, ip_mgmtlf2, int_oob_mgmtlf1, int_oob_mgmtlf2, int_sp1, int_sp2, int_sp3, int_sp4, int_lf1_sp1, int_lf1_sp2, int_lf2_sp3, int_lf2_sp4)

    var2 = autoprovision_coreoob(num_rack, FILEINCR1, FILEINCR2, FILEINOOB, name_core1, name_core2, name_oob, name_lf1, name_lf2, ip_mgmtoob, int_oob_core1, int_oob_core2, int_core1_oob, int_core2_oob )

    if var1 and var2:
        return True

    return False
    def handle_put(self, request, user, *args, **kwargs):
        """Treat requests POST to add Rack.

        URL: channel/editar/
        """
        try:
            self.log.info("Editar Channel")

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

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

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

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

            # Get XML data
            id_channel = channel_map.get('id_channel')
            nome = channel_map.get('nome')
            if not is_valid_int_greater_zero_param(nome):
                raise InvalidValueError(None, "Numero do Channel", "Deve ser um numero inteiro.")
            lacp = channel_map.get('lacp')
            int_type = channel_map.get('int_type')
            vlans = channel_map.get('vlan')
            envs = channel_map.get('envs')
            ids_interface = channel_map.get('ids_interface')


            if ids_interface is None:
                raise InterfaceError("Nenhuma interface selecionada")

            # verifica a vlan_nativa
            vlan = vlans.get('vlan_nativa')
            if vlan is not None:
                if int(vlan) < 1 or int(vlan) > 4096:
                    raise InvalidValueError(None, "Vlan Nativa", "Range valido: 1 - 4096.")
                if int(vlan) < 1 or 3967 < int(vlan) < 4048 or int(vlan)==4096:
                    raise InvalidValueError(None, "Vlan Nativa" ,"Range reservado: 3968-4047;4094.")

            port_channel = PortChannel()
            interface = Interface()
            amb = Ambiente()

            # verifica se o nome do port channel está sendo usado no equipamento
            channels = PortChannel.objects.filter(nome=nome)
            channels_id = []
            for ch in channels:
                channels_id.append(int(ch.id))
            if len(channels_id)>1:
                if type(ids_interface) is list:
                    for var in ids_interface:
                        if not var=="" and not var==None:
                            interface_id = int(var)
                else:
                    interface_id = int(ids_interface)
                interface_id = interface.get_by_pk(interface_id)
                equip_id = interface_id.equipamento.id
                equip_interfaces = interface.search(equip_id)
                for i in equip_interfaces:
                    try:
                        sw = i.get_switch_and_router_interface_from_host_interface(i.protegida)
                    except:
                        sw = None
                        pass
                    if sw is not None:
                        if sw.channel is not None:
                            if sw.channel.id in channels_id and sw.channel.id is not id_channel:
                                raise InterfaceError("O nome do port channel ja foi utilizado no equipamento")

            #buscar interfaces do channel
            interfaces = Interface.objects.all().filter(channel__id=id_channel)
            ids_list = []
            for i in interfaces:
                ids_list.append(i.id)

            ids_list = [ int(y) for y in ids_list ]
            if type(ids_interface) is list:
                ids_interface = [ int(x) for x in ids_interface ]
                desassociar = set(ids_list) - set(ids_interface)
                for item in desassociar:
                    item = interface.get_by_pk(int(item))
                    item.channel = None
                    item.save()
            else:
                if ids_interface is not None:
                    ids_interface = int(ids_interface)
                    if ids_interface is not None:
                        for item in ids_list:
                            item = interface.get_by_pk(int(item))
                            item.channel = None
                            item.save()
                    else:
                        for item in ids_list:
                            if not item== ids_interface:
                                item = interface.get_by_pk(int(item))
                                item.channel = None
                                item.save()


            #update channel
            port_channel = port_channel.get_by_pk(id_channel)
            port_channel.nome = str(nome)
            port_channel.lacp = convert_string_or_int_to_boolean(lacp)
            port_channel.save()

            int_type = TipoInterface.get_by_name(str(int_type))

            #update interfaces
            if type(ids_interface) is not list:
                i = ids_interface
                ids_interface = []
                ids_interface.append(i)
            for var in ids_interface:
                alterar_interface(var, interface, port_channel, int_type, vlans, user, envs, amb)
                interface = Interface()
                server_obj = Interface()
                interface_sw = interface.get_by_pk(int(var))
                interface_server = server_obj.get_by_pk(interface_sw.ligacao_front.id)
                try:
                    front = interface_server.ligacao_front.id
                except:
                    front = None
                    pass
                try:
                    back = interface_server.ligacao_back.id
                except:
                    back = None
                    pass
                server_obj.update(user,
                                  interface_server.id,
                                  interface=interface_server.interface,
                                  protegida=interface_server.protegida,
                                  descricao=interface_server.descricao,
                                  ligacao_front_id=front,
                                  ligacao_back_id=back,
                                  tipo=int_type,
                                  vlan_nativa=int(vlan))

            port_channel_map = dict()
            port_channel_map['port_channel'] = port_channel

            return self.response(dumps_networkapi({'port_channel': port_channel_map}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
    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)
Ejemplo n.º 50
0
    def handle_delete(self, request, user, *args, **kwargs):
        """Treat DELETE requests to remove the connection of two interfaces by front or back

        URL: interface/<id_interface>/<back_or_front>/
        """

        try:

            self.log.info("Disconnect")

            # Valid Interface ID
            id_interface = kwargs.get('id_interface')
            if not is_valid_int_greater_zero_param(id_interface):
                self.log.error(
                    u'The id_interface parameter is not a valid value: %s.',
                    id_interface)
                raise InvalidValueError(None, 'id_interface', id_interface)

            # Valid back or front param
            back_or_front = kwargs.get('back_or_front')
            if not is_valid_zero_one_param(back_or_front):
                self.log.error(
                    u'The back_or_front parameter is not a valid value: %s.',
                    back_or_front)
                raise InvalidValueError(None, 'back_or_front', back_or_front)
            else:
                back_or_front = int(back_or_front)

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

            # Checks if interface exists in database
            interface_1 = Interface.get_by_pk(id_interface)

            with distributedlock(LOCK_INTERFACE % id_interface):

                if interface_1.channel:
                    raise api_interface_exceptions.InterfaceException(
                        "Interface está em um Port Channel")

                # Is valid back or front connection
                if back_or_front:
                    try:
                        interface_2 = Interface.get_by_pk(
                            interface_1.ligacao_front_id)
                    except InterfaceNotFoundError:
                        raise InterfaceInvalidBackFrontError(
                            None,
                            "Interface two has no connection with front of Interface one"
                        )
                else:
                    try:
                        interface_2 = Interface.get_by_pk(
                            interface_1.ligacao_back_id)
                    except InterfaceNotFoundError:
                        raise InterfaceInvalidBackFrontError(
                            None,
                            "Interface two has no connection with back of Interface one"
                        )

                if interface_2.channel:
                    raise api_interface_exceptions.InterfaceException(
                        "Interface está em um Port Channel")

                if interface_2.ligacao_front_id == interface_1.id:
                    back_or_front_2 = 1
                elif interface_2.ligacao_back_id == interface_1.id:
                    back_or_front_2 = 0
                else:
                    raise InterfaceInvalidBackFrontError(
                        None,
                        "Interface one has no connection with front or back of Interface two"
                    )

                # Business Rules

                # Remove Interface one connection
                if back_or_front:
                    interface_1.ligacao_front = None
                else:
                    interface_1.ligacao_back = None

                # Remove Interface two connection
                if back_or_front_2:
                    interface_2.ligacao_front = None
                else:
                    interface_2.ligacao_back = None

                # Save
                interface_1.save()
                interface_2.save()

            # Return None for success
            return self.response(dumps_networkapi({}))

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

        URL: /interface/

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

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

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

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

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

            # Check existence
            Equipamento.get_by_pk(id_equipamento)

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

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

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

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

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

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

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

            vlan = interface_map.get('vlan')

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

            interface.create(user)

            networkapi_map = dict()
            interface_map = dict()

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

            return self.response(dumps_networkapi(networkapi_map))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
Ejemplo n.º 52
0
def gerar_arquivo_config(ids):
    log.debug("gerar_arquivo_config")

    for id in ids:
        rack = Rack().get_rack(idt=id)
        equips = list()
        lf1 = dict()
        lf2 = dict()
        oob = dict()

        # Equipamentos
        try:
            lf1["sw"] = 1
            lf1["id"] = rack.id_sw1.id
            lf1["nome"] = rack.id_sw1.nome
            lf1["mac"] = rack.mac_sw1
            lf1["marca"] = rack.id_sw1.modelo.marca.nome
            lf1["modelo"] = rack.id_sw1.modelo.nome
            equips.append(lf1)
            lf2["sw"] = 2
            lf2["id"] = rack.id_sw2.id
            lf2["nome"] = rack.id_sw2.nome
            lf2["mac"] = rack.mac_sw2
            lf2["marca"] = rack.id_sw2.modelo.marca.nome
            lf2["modelo"] = rack.id_sw2.modelo.nome
            equips.append(lf2)
            oob["sw"] = 3
            oob["id"] = rack.id_ilo.id
            oob["nome"] = rack.id_ilo.nome
            oob["mac"] = rack.mac_ilo
            oob["marca"] = rack.id_ilo.modelo.marca.nome
            oob["modelo"] = rack.id_ilo.modelo.nome
            equips.append(oob)
        except:
            raise Exception("Erro: Informações incompletas. Verifique o cadastro do Datacenter, do Fabric e do Rack")

        prefixspn = "SPN"
        prefixlf = "LF-"
        prefixoob = "OOB"

        # Interface e Roteiro
        for equip in equips:
            try:
                interfaces = Interface.search(equip.get("id"))
                equip["interfaces"] = list()
                for interface in interfaces:
                    dic = dict()
                    try:
                        sw = interface.get_switch_and_router_interface_from_host_interface(None)
                        if sw.equipamento.nome[:3] in [prefixlf, prefixoob, prefixspn]:
                            dic["nome"] = sw.equipamento.nome
                            dic["id"] = sw.equipamento.id
                            dic["ip_mngt"] = _buscar_ip(sw.equipamento.id)
                            dic["interface"] = sw.interface
                            dic["eq_interface"] = interface.interface
                            dic["roteiro"] = _buscar_roteiro(sw.equipamento.id, "CONFIGURACAO")
                            equip["interfaces"].append(dic)
                    except:
                        pass
            except:
                raise Exception("Erro ao buscar o roteiro de configuracao ou as interfaces associadas ao equipamento: "
                                "%s." % equip.get("nome"))
            try:
                equip["roteiro"] = _buscar_roteiro(equip.get("id"), "CONFIGURACAO")
                equip["ip_mngt"] = _buscar_ip(equip.get("id"))
            except:
                raise Exception("Erro ao buscar os roteiros do equipamento: %s" % equip.get("nome"))

        autoprovision.autoprovision_splf(rack, equips)
        autoprovision.autoprovision_coreoob(rack, equips)

    return True