Exemplo n.º 1
0
    def create(self, data):
        """ Creates a new Port Channel """

        log.info("Create Channel")
        log.debug(data)

        interfaces = data.get('interfaces')
        nome = data.get('name')
        lacp = data.get('lacp')
        int_type = data.get('int_type')
        vlan_nativa = data.get('vlan')
        envs_vlans = data.get('envs_vlans')

        api_interface_facade.verificar_vlan_nativa(vlan_nativa)

        # Checks if Port Channel name already exists on equipment
        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, True)
        self.channel.create()

        ifaces_on_channel = []
        for interface in interfaces:

            iface = Interface.objects.get(id=interface)
            type_obj = TipoInterface.objects.get(tipo=int_type)

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

            if iface.equipamento.id not in ifaces_on_channel:
                ifaces_on_channel.append(int(iface.equipamento.id))
                if len(ifaces_on_channel) > 2:
                    raise InterfaceError('More than one equipment selected')

            iface.channel = self.channel
            iface.int_type = type_obj
            iface.vlan_nativa = vlan_nativa
            iface.save()

            log.debug("interface updated %s" % iface.id)

            self._dissociate_ifaces_envs(iface)

            if 'trunk' in int_type.lower():
                self._create_ifaces_on_trunks(iface, envs_vlans)

        return {'channels': self.channel.id}
Exemplo n.º 2
0
def generate_and_deploy_channel_config_sync(user, id_channel):

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

    channel = PortChannel.get_by_pk(id_channel)

    interfaces = channel.list_interfaces()

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

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

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

    return status_deploy
    def handle_get(self, request, user, *args, **kwargs):
        """Trata uma requisição PUT para alterar informações de um channel.
        URL: channel/get-by-name/
        """
        # Get request data and check permission

        try:
            self.log.info("Get 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)

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

            channel_name = kwargs.get('channel_name')

            channel = PortChannel.get_by_name(channel_name)
            channel = model_to_dict(channel)

            return self.response(dumps_networkapi({'channel': channel}))


        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>/

        """
        # Get request data and check permission
        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)

            channel_name = kwargs.get('channel_name')

            channel = PortChannel.get_by_name(str(channel_name))

            channel.delete(user)

            return self.response(dumps_networkapi({}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
Exemplo n.º 5
0
def generate_and_deploy_channel_config_sync(user, id_channel):

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

    channel = PortChannel.get_by_pk(id_channel)

    interfaces = channel.list_interfaces()

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

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

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

    return status_deploy
Exemplo n.º 6
0
    def update(self, data):

        try:
            id_channel = data.get('id_channel')
            nome = data.get('nome')

            if not is_valid_int_greater_zero_param(nome):
                raise InvalidValueError(None, 'Channel number',
                                        'must be integer.')

            lacp = data.get('lacp')
            int_type = data.get('int_type')
            vlan_nativa = data.get('vlan')
            envs_vlans = data.get('envs')
            ids_interface = data.get('ids_interface')

            if ids_interface is None:
                raise InterfaceError('No interfaces selected')

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

            api_interface_facade.verificar_vlan_nativa(vlan_nativa)

            # verifica se o nome do port channel já existe no equipamento
            self.channel = PortChannel.get_by_pk(int(id_channel))

            if not nome == self.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)

            self._dissociate_interfaces_from_channel(ids_list, ids_interface)

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

            int_type = TipoInterface.get_by_name(str(int_type))

            self._update_interfaces_from_http_put(ids_interface, int_type,
                                                  vlan_nativa, envs_vlans)

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

        return {"port_channel": self.channel}
Exemplo n.º 7
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}
Exemplo n.º 8
0
    def retrieve_by_id(self, channel_id):
        """ Tries to retrieve a Port Channel based on its id """

        channel = {}
        try:
            channel = PortChannel.get_by_pk(channel_id)

            # Copied from old implementation. We really need to iterate?
            for ch in channel:
                channel = model_to_dict(ch)

        except InterfaceNotFoundError as err:
            return None
        except BaseException:
            channel = model_to_dict(channel)

        return {"channel": channel}
Exemplo n.º 9
0
    def handle_get(self, request, user, *args, **kwargs):
        """Trata uma requisição PUT para alterar informações de um channel.
        URL: channel/get-by-name/
        """
        # Get request data and check permission

        try:
            self.log.info('Get 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)

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

            channel_name = kwargs.get('channel_name')

            channel = PortChannel.get_by_name(channel_name)

            try:
                for ch in channel:
                    channel = model_to_dict(ch)
            except:
                channel = model_to_dict(channel)
                pass

            return self.response(dumps_networkapi({'channel': channel}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
Exemplo n.º 10
0
    def retrieve(self, channel_name):
        """ Tries to retrieve a Port Channel based on its name """

        channel = {}
        try:
            channel = PortChannel.get_by_name(channel_name)

            # Copied from old implementation. We really need to iterate?
            for ch in channel:
                channel = model_to_dict(ch)

        except InterfaceNotFoundError as err:
            return None
        except BaseException:
            channel = model_to_dict(channel)

        # We could do it on the model implementation. But because we need
        # compatibility with older version of the API this verification is
        # made here. Returning None means that no channel were found.
        if len(channel) == 0:
            return None

        return {"channel": channel}
Exemplo n.º 11
0
class ChannelV3(object):
    """ Facade class that implements business rules for interfaces channels """

    def __init__(self, user=None):
        """ Contructor of Port Channels V3 implementation """
        self.user = user
        self.channel = None

    def create(self, data):
        """ Creates a new Port Channel """

        log.info("Create Channel")
        log.debug(data)

        interfaces = data.get('interfaces')
        nome = data.get('name')
        lacp = data.get('lacp')
        int_type = data.get('int_type')
        vlan_nativa = data.get('vlan')
        envs_vlans = data.get('envs_vlans')

        api_interface_facade.verificar_vlan_nativa(vlan_nativa)

        # Checks if Port Channel name already exists on equipment
        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, True)
        self.channel.create()

        ifaces_on_channel = []
        for interface in interfaces:

            iface = Interface.objects.get(id=interface)
            type_obj = TipoInterface.objects.get(tipo=int_type)

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

            if iface.equipamento.id not in ifaces_on_channel:
                ifaces_on_channel.append(int(iface.equipamento.id))
                if len(ifaces_on_channel) > 2:
                    raise InterfaceError('More than one equipment selected')

            iface.channel = self.channel
            iface.int_type = type_obj
            iface.vlan_nativa = vlan_nativa
            iface.save()

            log.debug("interface updated %s" % iface.id)

            self._dissociate_ifaces_envs(iface)

            if 'trunk' in int_type.lower():
                self._create_ifaces_on_trunks(iface, envs_vlans)

        return {'channels': self.channel.id}

    def _update_interfaces_from_a_channel(self, iface, vlan_nativa,
                                          ifaces_on_channel, int_type):
        log.info("_update_interfaces_from_a_channel")

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

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

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

        interface_obj = dict(native_vlan=vlan_nativa,
                             type=int_type,
                             channel=self.channel,
                             interface=iface.interface,
                             equipment=iface.equipamento,
                             description=iface.descricao,
                             protected=iface.protegida,
                             front_interface=iface.ligacao_front,
                             back_interface=iface.ligacao_back)

        iface.update_V3(interface_obj)

    def _create_ifaces_on_trunks(self, iface, envs_vlans):
        log.debug("_create_ifaces_on_trunks")

        for i in envs_vlans:

            environment = Ambiente.get_by_pk(int(i.get('env')))
            env_iface = EnvironmentInterface()
            env_iface.interface = iface
            env_iface.ambiente = environment
            env_iface.vlans = i.get('vlans')
            env_iface.create()

    def _dissociate_ifaces_envs(self, iface):
        interface_list = EnvironmentInterface.objects.all().filter(interface=iface.id)

        for int_env in interface_list:
            int_env.delete()

    def retrieve(self, channel_name):
        """ Tries to retrieve a Port Channel based on its name """

        channel = {}
        try:
            channel = PortChannel.get_by_name(channel_name)

            # Copied from old implementation. We really need to iterate?
            for ch in channel:
                channel = model_to_dict(ch)

        except InterfaceNotFoundError as err:
            return None
        except BaseException:
            channel = model_to_dict(channel)

        # We could do it on the model implementation. But because we need
        # compatibility with older version of the API this verification is
        # made here. Returning None means that no channel were found.
        if len(channel) == 0:
            return None

        return {"channel": channel}

    def update(self, data):

        try:
            id_channel = data.get('id')
            name = data.get('name')
            lacp = data.get('lacp')
            int_type = data.get('int_type')
            vlan_nativa = data.get('vlan')
            envs_vlans = data.get('envs_vlans')
            interfaces = data.get('interfaces')
            protected = data.get('protected')

            self.channel = PortChannel.get_by_pk(int(id_channel))

            if not interfaces:
                raise InterfaceError('No interfaces selected')

            if not is_valid_int_greater_zero_param(name):
                raise InvalidValueError(None, 'Channel number',
                                        'must be integer.')

            api_interface_facade.verificar_vlan_nativa(vlan_nativa)

            # Dissociate old interfaces
            interfaces_old = Interface.objects.filter(
                channel__id=int(id_channel)
                )
            log.debug(interfaces_old)
            server = None
            for i in interfaces_old:
                server = i.ligacao_front.equipamento.id
                i.channel = None
                i.save()
                log.debug(i.id)

            api_interface_facade.check_channel_name_on_equipment(name,
                                                                 interfaces)

            # update channel
            self.channel.nome = str(name)
            self.channel.lacp = convert_string_or_int_to_boolean(lacp, True)
            self.channel.save()

            type_obj = TipoInterface.objects.get(tipo=int_type)

            ifaces_on_channel = list()

            for interface in interfaces:

                iface = Interface.objects.get(id=int(interface))

                if server:
                    if not int(iface.ligacao_front.equipamento.id) == int(server):
                        raise Exception('Interface is connected to another server. Ids: %s %s ' %
                                        (iface.ligacao_front.equipamento.id, server))

                if iface.channel:
                    raise InterfaceError(
                        'Interface %s is already in a Channel'
                        % iface.interface
                        )

                if iface.equipamento.id not in ifaces_on_channel:
                    ifaces_on_channel.append(int(iface.equipamento.id))
                    if len(ifaces_on_channel) > 2:
                        raise InterfaceError(
                            'More than one equipment selected.'
                            )

                iface.channel = self.channel
                iface.tipo = type_obj
                iface.vlan_nativa = vlan_nativa
                iface.protegida = convert_string_or_int_to_boolean(protected,
                                                                   True)
                iface.save()

                log.debug("interface updated %s" % iface.id)

                self._dissociate_ifaces_envs(iface)

                # associate the new envs
                if 'trunk' in int_type.lower():
                    self._create_ifaces_on_trunks(iface, envs_vlans)

        except Exception as err:
            log.error(str(err))
            raise Exception({"error": str(err)})

        return {'channels': self.channel.id}

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

    def delete(self, channel_id):
        """ tries to delete a channel and update equipments interfaces """

        try:

            PortChannel.objects.get(id=int(channel_id)).delete()

        except (InterfaceException, InvalidKeyException,
                InterfaceTemplateException) as err:
            return {"error": str(err)}

    def _get_equipment_dict(self, interfaces):
        """ Filters all equipments from a list of interfaces """

        equip_dict = {}
        for equip_id in [i.equipamento.id for i in interfaces]:

            equip_dict[str(equip_id)] = interfaces.filter(
                    equipamento__id=equip_id)

        return equip_dict

    def _update_equipments(self, equip_dict, iface_type, user, channel):
        """ Updates data on models instances of each equipment interface """

        for equip_id, ifaces in equip_dict.items():
            for iface in ifaces:
                try:
                    front = iface.ligacao_front.id
                except BaseException:
                    front = None

                try:
                    back = iface.ligacao_back.id
                except BaseException:
                    back = None

                iface.update(
                    self.user,
                    iface.id,
                    interface=iface.interface,
                    protegida=iface.protegida,
                    descricao=iface.descricao,
                    ligacao_front_id=front,
                    ligacao_back_id=back,
                    tipo=iface_type,
                    vlan_nativa='1'
                 )

            api_interface_facade.delete_channel(
                self.user, equip_id, ifaces, channel)

    def retrieve_by_id(self, channel_id):
        """ Tries to retrieve a Port Channel based on its id """

        channel = {}
        try:
            channel = PortChannel.get_by_pk(channel_id)

            # Copied from old implementation. We really need to iterate?
            for ch in channel:
                channel = model_to_dict(ch)

        except InterfaceNotFoundError as err:
            return None
        except BaseException:
            channel = model_to_dict(channel)

        return {"channel": channel}
Exemplo n.º 12
0
    def update(self, data):

        try:
            id_channel = data.get('id')
            name = data.get('name')
            lacp = data.get('lacp')
            int_type = data.get('int_type')
            vlan_nativa = data.get('vlan')
            envs_vlans = data.get('envs_vlans')
            interfaces = data.get('interfaces')
            protected = data.get('protected')

            self.channel = PortChannel.get_by_pk(int(id_channel))

            if not interfaces:
                raise InterfaceError('No interfaces selected')

            if not is_valid_int_greater_zero_param(name):
                raise InvalidValueError(None, 'Channel number',
                                        'must be integer.')

            api_interface_facade.verificar_vlan_nativa(vlan_nativa)

            # Dissociate old interfaces
            interfaces_old = Interface.objects.filter(
                channel__id=int(id_channel)
                )
            log.debug(interfaces_old)
            server = None
            for i in interfaces_old:
                server = i.ligacao_front.equipamento.id
                i.channel = None
                i.save()
                log.debug(i.id)

            api_interface_facade.check_channel_name_on_equipment(name,
                                                                 interfaces)

            # update channel
            self.channel.nome = str(name)
            self.channel.lacp = convert_string_or_int_to_boolean(lacp, True)
            self.channel.save()

            type_obj = TipoInterface.objects.get(tipo=int_type)

            ifaces_on_channel = list()

            for interface in interfaces:

                iface = Interface.objects.get(id=int(interface))

                if server:
                    if not int(iface.ligacao_front.equipamento.id) == int(server):
                        raise Exception('Interface is connected to another server. Ids: %s %s ' %
                                        (iface.ligacao_front.equipamento.id, server))

                if iface.channel:
                    raise InterfaceError(
                        'Interface %s is already in a Channel'
                        % iface.interface
                        )

                if iface.equipamento.id not in ifaces_on_channel:
                    ifaces_on_channel.append(int(iface.equipamento.id))
                    if len(ifaces_on_channel) > 2:
                        raise InterfaceError(
                            'More than one equipment selected.'
                            )

                iface.channel = self.channel
                iface.tipo = type_obj
                iface.vlan_nativa = vlan_nativa
                iface.protegida = convert_string_or_int_to_boolean(protected,
                                                                   True)
                iface.save()

                log.debug("interface updated %s" % iface.id)

                self._dissociate_ifaces_envs(iface)

                # associate the new envs
                if 'trunk' in int_type.lower():
                    self._create_ifaces_on_trunks(iface, envs_vlans)

        except Exception as err:
            log.error(str(err))
            raise Exception({"error": str(err)})

        return {'channels': self.channel.id}
Exemplo n.º 13
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)
    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_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)
Exemplo n.º 16
0
class ChannelV3(object):
    """ Facade class that implements business rules for interfaces channels """
    def __init__(self, user=None):
        """ Contructor of Port Channels V3 implementation """
        self.user = user
        self.channel = None

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

    def _create_ifaces_on_trunks(self, sw_router, envs_vlans):

        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:
            envs_vlans = [envs_vlans]

        for i in envs_vlans:

            environment = Ambiente.get_by_pk(int(i.get('env')))
            env_iface = EnvironmentInterface()
            env_iface.interface = sw_router
            env_iface.ambiente = environment

            range_vlans = i.get('vlans')
            if range_vlans:
                api_interface_facade.verificar_vlan_range(
                    environment, range_vlans)

                env_iface.vlans = range_vlans

            env_iface.create(user)

    def retrieve(self, channel_name):
        """ Tries to retrieve a Port Channel based on its name """

        channel = {}
        try:
            channel = PortChannel.get_by_name(channel_name)

            # Copied from old implementation. We really need to iterate?
            for ch in channel:
                channel = model_to_dict(ch)

        except InterfaceNotFoundError as err:
            return None
        except:
            channel = model_to_dict(channel)

        # We could do it on the model implementation. But because we need
        # compatibility with older version of the API this verification is
        # made here. Returning None means that no channel were found.
        if len(channel) == 0:
            return None

        return {"channel": channel}

    def update(self, data):

        try:
            id_channel = data.get('id_channel')
            nome = data.get('nome')

            if not is_valid_int_greater_zero_param(nome):
                raise InvalidValueError(None, 'Channel number',
                                        'must be integer.')

            lacp = data.get('lacp')
            int_type = data.get('int_type')
            vlan_nativa = data.get('vlan')
            envs_vlans = data.get('envs')
            ids_interface = data.get('ids_interface')

            if ids_interface is None:
                raise InterfaceError('No interfaces selected')

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

            api_interface_facade.verificar_vlan_nativa(vlan_nativa)

            # verifica se o nome do port channel já existe no equipamento
            self.channel = PortChannel.get_by_pk(int(id_channel))

            if not nome == self.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)

            self._dissociate_interfaces_from_channel(ids_list, ids_interface)

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

            int_type = TipoInterface.get_by_name(str(int_type))

            self._update_interfaces_from_http_put(ids_interface, int_type,
                                                  vlan_nativa, envs_vlans)

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

        return {"port_channel": self.channel}

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

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

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

    def _get_equipment_dict(self, interfaces):
        """ Filters all equipments from a list of interfaces """

        equip_dict = {}
        for equip_id in [i.equipamento.id for i in interfaces]:

            equip_dict[str(equip_id)] = interfaces.filter(
                equipamento__id=equip_id)

        return equip_dict

    def _update_equipments(self, equip_dict, iface_type, user, channel):
        """ Updates data on models instances of each equipment interface """

        for equip_id, ifaces in equip_dict.items():
            for iface in ifaces:
                try:
                    front = iface.ligacao_front.id
                except:
                    front = None

                try:
                    back = iface.ligacao_back.id
                except:
                    back = None

                iface.update(self.user,
                             iface.id,
                             interface=iface.interface,
                             protegida=iface.protegida,
                             descricao=iface.descricao,
                             ligacao_front_id=front,
                             ligacao_back_id=back,
                             tipo=iface_type,
                             vlan_nativa='1')

            api_interface_facade.delete_channel(self.user, equip_id, ifaces,
                                                channel)

    def retrieve_by_id(self, channel_id):
        """ Tries to retrieve a Port Channel based on its id """

        channel = {}
        try:
            channel = PortChannel.get_by_pk(channel_id)

            # Copied from old implementation. We really need to iterate?
            for ch in channel:
                channel = model_to_dict(ch)

        except InterfaceNotFoundError as err:
            return None
        except:
            channel = model_to_dict(channel)

        return {"channel": channel}
    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)
Exemplo n.º 18
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)
    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)
    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)