Merge branch 'feat/14-tid-webui' into 'develop'

WebUI to support NSC overall functioning **This merge request was implemented by Javier Velazquez with support from Javier Grimaldos.

Edited by Javier Velázquez

Merge request reports

Loading
+362 −0
Changes for src/realizers/ixia/NEII_V4.py: 362 added lines, 0 removed lines.
Original line number Diff line number Diff line
###SPDX-FileCopyrightText: © 2024 Telefónica Innovación Digital S.L.
###SPDX-License-Identifier: AGPL-3.0-or-later

from .automatizacion_ne2v4 import automatizacion
import ipaddress, logging
from src.Constants import IXIA_IP

class NEII_controller:
    def __init__(self, ixia_ip=IXIA_IP):
        self.ixia_ip = ixia_ip

    def menu_principal(self, ip=IXIA_IP):
        '''
        Inputs:
        Outputs:
        Work: The main menu of the application.
        Notes: If the file is executed from the terminal, ensure that the import 
               of "automatizacion_ne2v4" does not include a dot at the beggining.
        '''
        ip=input("¿Cuál es la IP del network emulator?: ")
        accion=input("¿Qué deseas hacer?: \n(1) Ver información de IP\n(2) Consultar información del Hardware\n(3) Configurar un perfil nuevo\n(4) Consultar perfiles existentes\nSelecciona una opción: ")
        if accion=="1":
            self.ver_info(ip)
        if accion=="2":
            self.hardware(ip)
        if accion=="3":
            self.nuevo_perfil(ip)
        if accion=="4":
            self.existentes(ip)
        return

    ## FUNCIONES MENÚ PRINCIPAL ##

    def ver_info(self,ip):
        '''
        Inputs: -ip: the ip where the Axia API is located.
        Outputs:
        Work: It gives the information of the API.
        
        '''
        informacion_ip=automatizacion.obtener_informacion_ip(ip)
        if informacion_ip:
            print(informacion_ip)

    def hardware(self,ip):
        '''
        Inputs: -ip: the ip where the Axia API is located.
        Outputs:
        Work: It gives the information of the hardware.
        
        '''
        informacion_hardware=automatizacion.obtener_informacion_hardware(ip)
        if informacion_hardware:
            print(informacion_hardware)

    def nuevo_perfil(self,ip):
        '''
        Inputs: -ip: the ip where the Axia API is located.
        Outputs:
        Work: Creates and configures the profiles requested in the Axia API on the specified port.
        Notes: It is NOT required to fill all the information requested.

        '''
        puerto=input("¿Qué puerto quieres configurar?: ")
        num_perfiles=int(input("¿Cuantos perfiles quieres añadir?: "))
        configuraciones_totales=[]
        for i in range(num_perfiles):
            nombre=f"perfil{i+1}"
            accion=input("¿Qué deseas configurar?\n1)IPv4\t2)IPv6\n3)VLAN\t4)Delay\n5)Packet Drop\t6)Policer (Rx Bandwidth)\n7)Shaper (Rx Bandwidth)\nPor favor, separa las opciones con comas: ")
            opciones=accion.split(',')
            configuraciones={}
            for opcion in opciones:
                opcion=opcion.strip()
                if opcion=="1":
                    source_ip=input("Introduce la IP de origen (IPv4): ")
                    destination_ip=input("Introduce la IP destino (IPv4): ")
                    prt=input("¿Qué protocolo quieres usar, IP o TCP? ")
                    configuraciones['ipv4']=self.ipv4(source_ip,destination_ip,prt)
                elif opcion=="2":
                    source=input("Introduce la IP de origen (IPv6): ")
                    destination=input("Introduce la IP destino (IPv6): ")
                    configuraciones['ipv6']=self.ipv6(source, destination)
                elif opcion=="3":
                    vlan_id=int(input("Introduce identificador de VLAN: "))
                    configuraciones['vlan']=self.vlan(vlan_id)
                elif opcion=="4":
                    delay_perfil=input("Introduce el delay que quieres introducir en el perfil test_api: ")
                    configuraciones['ethernetDelay']=self.delay(delay_perfil)
                elif opcion=="5":
                    configuraciones['packetDrop']=self.packetDrop()
                elif opcion=="6": 
                    bandwidth=int(input('Introduzca el ancho de banda (Kbps): '))
                    configuraciones['policer']=self.policer(bandwidth)
                elif opcion=="7":
                    configuraciones['shaper']=self.shaper()
                else:
                    print(f"Opción '{opcion}' no es válida.")
            configuracion_perfil=self.configuracion_total(configuraciones, nombre)
            configuraciones_totales.append(configuracion_perfil)
        perfil_final = {'profiles': configuraciones_totales}
        configuracion_puerto=automatizacion.envio_peticion(ip, puerto, perfil_final)
        if configuracion_puerto:
            print(configuracion_puerto)

    def existentes(self,ip):
        '''
        Inputs: -ip: the ip where the Axia API is located.
        Outputs:
        Work: Shows the information of a given port-
               
        '''
        puerto=input("¿Qué puerto quieres consultar?: ")
        informacion_puerto=automatizacion.obtener_informacion_puerto(ip, puerto)
        if informacion_puerto:
            print(informacion_puerto)

    def existentes_auto(self,ip,puerto):
        '''
        Inputs: -ip: the ip where the Axia API is located.
                - puerto: the port we want to get the information.
        Outputs:
        Work: Creates and configures the profiles requested in the Axia API on the specified port.
               
        '''
        informacion_puerto=automatizacion.obtener_informacion_puerto(ip, puerto)
        if informacion_puerto:
            print(f'info puerto\n{informacion_puerto}')
        return informacion_puerto

    ## FUNCION PARA LA GUI DEL NSC ##

    import ipaddress

    def nscNEII(self, json_data):
        configuraciones = {}
        ip = self.ixia_ip
        puerto = "5"
        dataProfile = self.existentes_auto(ip, puerto)

        print(f'\n\n{json_data}\n')

        ip_version = json_data.get("ip_version", None)
        src_node_ip = json_data.get("src_node_ip", None)
        dst_node_ip = json_data.get("dst_node_ip", None)
        src_node_ipv6 = json_data.get("src_node_ipv6", None)
        dst_node_ipv6 = json_data.get("dst_node_ipv6", None)
        vlan_id = json_data.get("vlan_id", None)
        bandwidth = json_data.get("bandwidth", None)
        latency = json_data.get("latency", None)
        latency_version = json_data.get("latency_version", None)
        reliability = json_data.get("reliability", None)
        tolerance = json_data.get("tolerance", None)
        packet_reorder = json_data.get("packet_reorder", None)
        num_pack = json_data.get("num_pack", None)
        pack_reorder = json_data.get("pack_reorder", None)
        num_reorder = json_data.get("num_reorder", None)
        max_reorder = json_data.get("max_reorder", None)
        drop_version = json_data.get("drop_version", None)
        desv_reorder = json_data.get("desv_reorder", None)
        packets_drop = json_data.get("packets_drop", None)
        drops = json_data.get("drops", None)
        desv_drop = json_data.get("desv_drop", None)

        # --- Variables de configuración ---

        # Configuración de IPv4 / IPv6
        if src_node_ip and dst_node_ip:
            if isinstance(ipaddress.ip_address(src_node_ip), ipaddress.IPv4Address) and isinstance(ipaddress.ip_address(dst_node_ip), ipaddress.IPv4Address):
                configuraciones['ipv4'] = self.ipv4(src_node_ip, dst_node_ip, 5)
        if src_node_ipv6 and dst_node_ipv6:
            if isinstance(ipaddress.ip_address(src_node_ipv6), ipaddress.IPv6Address) and isinstance(ipaddress.ip_address(dst_node_ipv6), ipaddress.IPv6Address):
                configuraciones['ipv6'] = self.ipv6(src_node_ipv6, dst_node_ipv6)

        # VLAN
        if vlan_id:
            configuraciones['vlan'] = self.vlan(int(vlan_id))

        # Policer
        if bandwidth:
            configuraciones['policer'] = self.policer(bandwidth)

        # Latencia
        if latency:
            if float(latency) > 0:
                configuraciones['ethernetDelay'] = self.delay_gui(float(latency), latency_version, float(tolerance))

        # Packet Reorder
        if packet_reorder:
            configuraciones['reorder'] = self.packetReorder(num_reorder, pack_reorder, num_pack, max_reorder, packet_reorder, desv_reorder)

        # Packet Reorder when reliability
        if reliability:
            configuraciones['reorder'] = self.packetReorder(int(reliability))

        #Dropper
        if drop_version:
            configuraciones['packetDrop'] = self.packetDrop(drops, packets_drop, drop_version, desv_drop)

        # Agregar perfil
        num_profiles = len(dataProfile.get("profiles", []))
        configuracion_perfil = self.configuracion_total(configuraciones, f"profile{num_profiles + 1}")
        dataProfile['profiles'].append(configuracion_perfil)
        logging.info(f"Configuración del perfil: {configuracion_perfil}")
        
        # Enviar la configuración
        automatizacion.envio_peticion(ip, puerto, dataProfile)
        return automatizacion.obtener_informacion_puerto(ip, puerto)
        

    ## FUNCIONES DE CONFIGURACIÓN DE PUERTO ##

    def delay(self,delay_perfil):
        '''
        Inputs: -delay_perfil: the delay we want to configurate.
        Outputs: the information of the delay for the controller.
        Work: Creates the configuration JSON for delay of the controller.
               
        '''
        delay_perfil = input("Enter the delay you want to set in the test_api profile: ")
        print(f"delay en main: {delay_perfil}")
        delay_type = input("Select one option of stadistics:\n1)None\t2)Gaussian\n3)Internet\n(Type the number)")
        configuracion_delay = automatizacion.añadir_configuracion_puerto_delay(delay_perfil,delay_type)
        print(f"Config delay:\n{configuracion_delay}")
        return configuracion_delay
    
    def delay_gui(self,delay_perfil, latency_version, max_latency):
        '''
        Inputs: -delay_perfil: the delay we want to configurate.
        Outputs: the information of the delay for the controller.
        Work: Creates the configuration JSON for delay of the controller.
               
        '''
        print(f'\nPero: {max_latency}\n')
        configuracion_delay = automatizacion.añadir_configuracion_puerto_delay(delay_perfil,latency_version,max_latency)
        return configuracion_delay

    def ipv4(self,source_ip,destination_ip,prt):
        '''
        Inputs: -source_ip: the source IPv4 we want to configurate.
                -destination_ip: the destination IPv4 we want to configurate.
                -prt: the protocol we want to configurate
        Outputs: the information of the IPv4 for the controller.
        Work: Creates the configuration JSON for IPv4 of the controller.
        Notes: by default, the protocol is TCP (6).
               
        '''
        source_hx=None 
        destination_hx=None
        protocolo=None
        if source_ip:
            source_hx=hex(int(ipaddress.IPv4Address(source_ip)))[2:]
        if destination_ip:
            destination_hx=hex(int(ipaddress.IPv4Address(destination_ip)))[2:]
        if prt:
            protocolo="4" if prt=="IP" else "6"
        configuracion_puerto=automatizacion.añadir_configuracion_puerto_ipv4(source_hx, destination_hx, protocolo)
        return configuracion_puerto

    def ipv6(self,source, destination):
        '''
        Inputs: -source: the source IPv6 we want to configurate.
                -destination: the destination IPv6 we want to configurate.
        Outputs: the information of the IPv6 for the controller.
        Work: Creates the configuration JSON for IPv6 of the controller.
               
        '''
        if source:
            source=ipaddress.IPv6Address(source).exploded.replace(":", "")
        elif not source: source=None
        if destination:
            destination=ipaddress.IPv6Address(destination).exploded.replace(":", "")
        elif not destination: destination=None
        configuracion_puerto=automatizacion.añadir_configuracion_puerto_ipv6(source, destination)
        return configuracion_puerto

    def vlan(self,vlan_id):
        '''
        Inputs: -vlan_id: the VLAN we want to configurate.
        Outputs: the information of the VLAN for the controller.
        Work: Creates the configuration JSON for VLAN of the controller.
               
        '''
        configuracion_vlan=automatizacion.añadir_configuracion_VLAN(vlan_id)
        return configuracion_vlan

    def packetDrop(self, drop, total,version,dev):
        '''
        Inputs:
        Outputs: the information of the packet drop configuration for the controller.
        Work: Creates the configuration JSON for packet drop of the controller.
               
        '''
        configuracionPD=automatizacion.añadir_configuración_packetDrop(drop,total,version,dev)
        return configuracionPD

    def policer(self,bandwidth):
        '''
        Inputs: -bandwidth: the TX bandwdth we want to configurate.
        Outputs: the information of the TX bandwidth for the controller.
        Work: Creates the configuration JSON for the TX bandwidth of the controller.
               
        '''
        configuracion_policer=automatizacion.añadir_configuracion_policer(bandwidth)
        return configuracion_policer

    def shaper(self):
        '''
        Inputs:
        Outputs: the information of the RX bandwidth for the controller.
        Work: Creates the configuration JSON for the RX bandwidth of the controller.
               
        '''
        bandwidth=int(input('Introduzca el ancho de banda (Kbps): '))
        configuracion_policer=automatizacion.añadir_configuracion_shaper(bandwidth)
        return configuracion_policer
    
    def packetReorder(self,reorder,packages=None, npackagesreorder=None, maxreord=None, version=None, stev=None):
        print(f"\n\n\nNEII ANTES DEL PASO\nPACKAGES:{packages}\nREORDER:{reorder}\nMAXREORD:{maxreord}\nNPACKAGESORDER:{npackagesreorder}\n\n\n")
        configuracion_reorder=automatizacion.añadir_configuracion_reorder(packages,reorder,npackagesreorder, maxreord, version, stev)
        return configuracion_reorder

    def configuracion_total(self,configuraciones, nombre_perfil):
        '''
        Inputs: -configuraciones: the informtion of all the configurations for the controller.
                -nombre_perfil: the name of the profile where the information is going to be allocated.
        Outputs: the information of a configurated profile.
        Work: Creates the configuration JSON for a profile for the controller.
               
        '''
        perfil = {
            'tag': nombre_perfil,
            'dramAllocation': {},
            'rules': [],
            'ethernetDelay': {'enabled': False},
            'packetDrop': {'enabled': False},
            'enabled':True
        }
        if 'ipv4' in configuraciones:
            ipv4_config = configuraciones['ipv4']
            perfil['dramAllocation'] = ipv4_config['profiles'][0]['dramAllocation']
            perfil['rules'].extend(ipv4_config['profiles'][0]['rules'])
        if 'ipv6' in configuraciones:
            ipv6_config = configuraciones['ipv6']
            perfil['rules'].extend(ipv6_config['profiles'][0]['rules'])
        if 'vlan' in configuraciones:
            vlan_config = configuraciones['vlan']
            perfil['rules'].extend(vlan_config['profiles'][0]['rules'])
        if 'ethernetDelay' in configuraciones:
            perfil['ethernetDelay'] = configuraciones['ethernetDelay']['ethernetDelay']
        if 'packetDrop' in configuraciones:
            perfil['packetDrop'] = configuraciones['packetDrop']['packetDrop']
        if 'policer' in configuraciones:
            perfil['policer']=configuraciones['policer']['policer']
        if 'shaper' in configuraciones:
            perfil['shaper']=configuraciones['shaper']['shaper']
        if 'reorder' in configuraciones:
            perfil['reorder']=configuraciones['reorder']['reorder']
        return perfil

if __name__=="__main__":
    controller=NEII_controller()
    controller.menu_principal()
 No newline at end of file
+454 −0
Changes for src/realizers/ixia/automatizacion_ne2v4.py: 454 added lines, 0 removed lines.
Original line number Diff line number Diff line
###SPDX-FileCopyrightText: © 2024 Telefónica Innovación Digital S.L.
###SPDX-License-Identifier: AGPL-3.0-or-later

import requests
class automatizacion:
    def obtener_informacion_ip(ip):
        '''
        Gets the information IP of the NE2
        Args:
            ip: IP.
        Returns:
            A dictionary with the IP infotmationx.
        '''
        url= "http://"+ip+"/api/actions/ipInfo"
        body= {"ip": ip}
        response = requests.get(url, json=body, auth=('admin', 'admin'))
        if response.status_code==200:
            return response.json()
        else:
            print(f"error al obtener la informacion de la IP; {response.status_code}")
            return None
        
    def obtener_informacion_hardware(ip):
        """
        Obtiene información de una dirección IP.

        Args:
            ip: La dirección IP del NE2.

        Returns:
            Un diccionario con la información de IP.
        """
        url = "http://"+ip+"/api/actions/hwInfo"
        body = {"ip": ip}
        response = requests.get(url, json=body, auth=('admin', 'admin'))
        if response.status_code == 200:
            return response.json()
        else:
            print(f"Error al obtener la información de la IP: {response.status_code}")
            return None
        
    def obtener_informacion_puerto(ip,puerto):
        """
        Obtiene información de una dirección IP.

        Args:
            ip: La dirección IP del NE2.

        Returns:
            Un diccionario con la información de IP.
        """
        url = "http://"+ip+"/api/hw/Port/"+puerto
        body = {"ip": ip}
        response = requests.get(url, json=body, auth=('admin', 'admin'))
        if response.status_code == 200:
            return response.json()
        else:
            print(f"Error al obtener la información de la IP: {response.status_code}")
            return None
        
    def añadir_configuracion_puerto_delay(delay, latency_type, max_latency):
        """
        Añade una configuración de puerto según su delay a un NE2.

        Args:
            delay (int): Cantidad de delay en la simulación.

        Returns:
            La respuesta de la API (texto).
        """
        configuracion=None
        print(f'\n\nTipo de latencia: {latency_type}\n latencia: {delay}\n')
        if latency_type=='1' or latency_type==None:
            configuracion={'ethernetDelay': {'delay': delay, 'delayMax': 15.0, 'isUncorrelated': False, 'maxNegDelta': 0.1, 'pdvMode': 'NONE', 'delayMin': 5.0, 'units': 'MS', 'maxPosDelta': 0.1, 'enabled': True, 'spread': 1.0}}
        if latency_type=='2' or latency_type=='gauss':
            delay_f=float(delay)
            ancho=float(max_latency)
            max_delay=delay_f+ancho
            min_delay=delay_f-ancho
            configuracion={'ethernetDelay': {'delay': delay, 'delayMax': max_delay, 'isUncorrelated': False,'maxNegDelta': ancho/3, 'pdvMode': 'GAUSSIAN', 'delayMin':min_delay, 'units': 'MS', 'maxPosDelta':ancho/3, 'enabled': True, 'spread': 1.58}}
        if latency_type =='3' or latency_type=='internet':
            ancho=float(max_latency)
            max_delay = float(delay)+0.9*float(ancho)
            min_delay = float(delay)-0.1*float(ancho)
            configuracion={'ethernetDelay': {'delay': delay, 'delayMax': max_delay, 'isUncorrelated': False, 'maxNegDelta': 0.4, 'pdvMode': 'INTERNET', 'delayMin': min_delay, 'units': 'MS', 'maxPosDelta': 0.5, 'enabled': True, 'spread': 100.0}}
        print(f"\n\nConf Delay: {configuracion}\n")    
        return configuracion
        
    def añadir_configuracion_puerto_ipv4(source_hx,destination_hx,protocolo):
        """
        Añade una configuración de puerto según las IPv4s de origen y destino de la comunicación.

        Args:
            source_hx (int): Dirección IPv4 de origen en hexadecimal.
            destination_hx (int): Dirección IPv4 de destino en hexadecimal.
            protocolo (string): Numero asociado al protocolo elegido.

        Returns:
            La respuesta de la API (texto).
        """
        reglas = [{"field": "Common::IPv4::Version", "value": "4", "mask": "f"}]
        if source_hx:
            reglas.append({"field": "Common::IPv4::Source Address", "value": source_hx, "mask": "ffffffff"})
        if destination_hx:
            reglas.append({"field": "Common::IPv4::Destination Address", "value": destination_hx, "mask": "ffffffff"})
        if protocolo:
            reglas.append({"field": "Common::IPv4::Protocol", "value": protocolo, "mask": "ff"})
        configuracion = {"profiles": [{"dramAllocation": {"mode": "AUTO","fixedSize": 1700352},"rules": reglas,"tag": "test_api"}],"defaultProfile": {"dramAllocation": {"mode": "AUTO","fixedSize": 1700352},"tag": "defaultProfile"}}
        return configuracion

    def añadir_configuracion_puerto_ipv6(source,destination):
        """
        Añade una configuración de puerto según las IPv6s de origen y destino de la comunicación.

        Args:
            source (int): Dirección IPv6 de origen en hexadecimal.
            destination (int): Dirección IPv6 de destino en hexadecimal.

        Returns:
            La respuesta de la API (texto).
        """
        reglas=[{'field': 'Common::IPv6::Version', 'bitRange': 'L3@0[7]+3', 'value': '6', 'mask': 'f'}]
        if source:
            reglas.append({'field': 'Common::IPv6::Source Address', 'bitRange': 'L3@8[7]+127', 'value': source, 'mask': 'ffffffffffffffffffffffffffffffff'})
        if destination:
            reglas.append({'field': 'Common::IPv6::Destination Address', 'bitRange': 'L3@24[7]+127', 'value': destination, 'mask': 'ffffffffffffffffffffffffffffffff'})
        configuracion = {"profiles": [{"dramAllocation": {"mode": "AUTO","fixedSize": 1700352},"rules": reglas,"tag": "test_api"}],"defaultProfile": {"dramAllocation": {"mode": "AUTO","fixedSize": 1700352},"tag": "defaultProfile"}}
        return configuracion

    def añadir_configuracion_VLAN(vlan):
        """
        Añade una configuración de puerto según su VLAN.

        Args:
            vlan (int): Número de identificación de la VLAN.

        Returns:
            La respuesta de la API (texto).
        """
        vlan=hex(vlan)[2:]
        configuracion={'profiles': [{'dramAllocation': {'mode': 'AUTO', 'fixedSize': 1700352}, 'rules': [{'field': 'Common::Second Tag::VLAN ID', 'bitRange': 'L2@18[3]+11', 'value': vlan, 'mask': 'fff'}]}]}
        return configuracion

    def añadir_configuración_packetDrop(drops,total):
        """
        Añade una configuración de puerto según su configuracion de packet Drop un NE2.

        Args:
            drops (int): cantidad de paquetes dropeados
            total (int): cantidad total de paquetes

        Returns:
            La respuesta de la API (texto).
        """
        configuracion={'packetDrop': {'rdmSel': {'dist': 'PERIODIC', 'burstlen': drops, 'interval': total, 'stddev': 10.0}, 'enabled': True}}
        return configuracion

    def añadir_configuracion_policer(bitrate):
        """
        Añade una configuración de puerto según su TX bandwidth a un NE2.

        Args:
            bitrate (int): bandwith en Tx

        Returns:
            La respuesta de la API (texto).
        """
        configuracion={'policer':{'excessBitRate': bitrate, 'excessBurstTolerance': 64000, 'commitedBurstTolerance': 64000, 'commitedBitRate': bitrate, 'enabled': True, 'enableRateCoupling': False}}
        return configuracion
    
    def añadir_configuracion_shaper(bitrate):
        """
        Añade una configuración de puerto según su RX bandwidth a un NE2.

        Args:
            bitrate (int): bandwith en Rx

        Returns:
            La respuesta de la API (texto).
        """
        configuracion={'shaper': {'burstTolerance': 64000, 'bitRate': bitrate, 'enabled': True}}
        return configuracion
    
    def añadir_configuracion_reorder(reorder):
        """
        Adds reorder configuration.

        Args:
            reorder (int): reorder

        Returns:
            response of the API (texto).
        """
        reorder=100-reorder
        print(f"\nReorder:{reorder}\n")
        configuracion={"reorder": {"rdmSel": {"dist": "PERIODIC", "burstlen": reorder, "interval": 100, "stddev": 10.0 }, "reorderByMin": 1, "reorderByMax": 5, "enabled": True}} #Los demas valores los he dejado como defecto por no poder configurarlos
        return configuracion

    def envio_peticion(ip,puerto, configuracion):
        """
        Envía una configuración de puerto a un NE2.

        Args:
            ip (int): IP del NE2
            puerto: número del puerto a configurar
            configuración: la información que se quiere configurar en el puerto

        Returns:
            La respuesta de la API (texto).
        """

import requests
class automatizacion:
    def obtener_informacion_ip(ip):
        '''
        obtiene informacion ip del NE2
        Args:
            ip: la direccion IP del NE2.

        Returns:
            un diccionario con la informacion de IP.
        '''
        url= "http://"+ip+"/api/actions/ipInfo"
        body= {"ip": ip}
        response = requests.get(url, json=body, auth=('admin', 'admin'))
        if response.status_code==200:
            return response.json()
        else:
            print(f"error al obtener la informacion de la IP; {response.status_code}")
            return None
        
    def obtener_informacion_hardware(ip):
        """
        Obtiene información de una dirección IP.

        Args:
            ip: La dirección IP del NE2.

        Returns:
            Un diccionario con la información de IP.
        """
        url = "http://"+ip+"/api/actions/hwInfo"
        body = {"ip": ip}
        response = requests.get(url, json=body, auth=('admin', 'admin'))
        if response.status_code == 200:
            return response.json()
        else:
            print(f"Error al obtener la información de la IP: {response.status_code}")
            return None
        
    def obtener_informacion_puerto(ip,puerto):
        """
        Obtiene información de una dirección IP.

        Args:
            ip: La dirección IP del NE2.

        Returns:
            Un diccionario con la información de IP.
        """
        url = "http://"+ip+"/api/hw/Port/"+puerto
        body = {"ip": ip}
        response = requests.get(url, json=body, auth=('admin', 'admin'))
        if response.status_code == 200:
            return response.json()
        else:
            print(f"Error al obtener la información de la IP: {response.status_code}")
            return None
        
    def añadir_configuracion_puerto_delay(delay, latency_type, max_latency):
        """
        Añade una configuración de puerto según su delay a un NE2.

        Args:
            delay (int): Cantidad de delay en la simulación.

        Returns:
            La respuesta de la API (texto).
        """
        configuracion=None
        print(f'\n\nTipo de latencia: {latency_type}\n latencia: {delay}\n')
        if latency_type=='1' or latency_type==None:
            configuracion={'ethernetDelay': {'delay': delay, 'delayMax': 15.0, 'isUncorrelated': False, 'maxNegDelta': 0.1, 'pdvMode': 'NONE', 'delayMin': 5.0, 'units': 'MS', 'maxPosDelta': 0.1, 'enabled': True, 'spread': 1.0}}
        if latency_type=='2' or latency_type=='gauss':
            delay_f=float(delay)
            ancho=float(max_latency)
            max_delay=delay_f+ancho
            min_delay=delay_f-ancho
            configuracion={'ethernetDelay': {'delay': delay, 'delayMax': max_delay, 'isUncorrelated': False,'maxNegDelta': ancho/3, 'pdvMode': 'GAUSSIAN', 'delayMin':min_delay, 'units': 'MS', 'maxPosDelta':ancho/3, 'enabled': True, 'spread': 1.58}}
        if latency_type =='3' or latency_type=='internet':
            ancho=float(max_latency)
            max_delay = float(delay)+0.9*float(ancho)
            min_delay = float(delay)-0.1*float(ancho)
            configuracion={'ethernetDelay': {'delay': delay, 'delayMax': max_delay, 'isUncorrelated': False, 'maxNegDelta': 0.4, 'pdvMode': 'INTERNET', 'delayMin': min_delay, 'units': 'MS', 'maxPosDelta': 0.5, 'enabled': True, 'spread': 100.0}}
        print(f"\n\nConf Delay: {configuracion}\n")    
        return configuracion
        
    def añadir_configuracion_puerto_ipv4(source_hx,destination_hx,protocolo):
        """
        Añade una configuración de puerto según las IPv4s de origen y destino de la comunicación.

        Args:
            source_hx (int): Dirección IPv4 de origen en hexadecimal.
            destination_hx (int): Dirección IPv4 de destino en hexadecimal.
            protocolo (string): Numero asociado al protocolo elegido.

        Returns:
            La respuesta de la API (texto).
        """
        reglas = [{"field": "Common::IPv4::Version", "value": "4", "mask": "f"}]
        if source_hx:
            reglas.append({"field": "Common::IPv4::Source Address", "value": source_hx, "mask": "ffffffff"})
        if destination_hx:
            reglas.append({"field": "Common::IPv4::Destination Address", "value": destination_hx, "mask": "ffffffff"})
        if protocolo:
            reglas.append({"field": "Common::IPv4::Protocol", "value": protocolo, "mask": "ff"})
        configuracion = {"profiles": [{"dramAllocation": {"mode": "AUTO","fixedSize": 1700352},"rules": reglas,"tag": "test_api"}],"defaultProfile": {"dramAllocation": {"mode": "AUTO","fixedSize": 1700352},"tag": "defaultProfile"}}
        return configuracion

    def añadir_configuracion_puerto_ipv6(source,destination):
        """
        Añade una configuración de puerto según las IPv6s de origen y destino de la comunicación.

        Args:
            source (int): Dirección IPv6 de origen en hexadecimal.
            destination (int): Dirección IPv6 de destino en hexadecimal.

        Returns:
            La respuesta de la API (texto).
        """
        reglas=[{'field': 'Common::IPv6::Version', 'bitRange': 'L3@0[7]+3', 'value': '6', 'mask': 'f'}]
        if source:
            reglas.append({'field': 'Common::IPv6::Source Address', 'bitRange': 'L3@8[7]+127', 'value': source, 'mask': 'ffffffffffffffffffffffffffffffff'})
        if destination:
            reglas.append({'field': 'Common::IPv6::Destination Address', 'bitRange': 'L3@24[7]+127', 'value': destination, 'mask': 'ffffffffffffffffffffffffffffffff'})
        configuracion = {"profiles": [{"dramAllocation": {"mode": "AUTO","fixedSize": 1700352},"rules": reglas,"tag": "test_api"}],"defaultProfile": {"dramAllocation": {"mode": "AUTO","fixedSize": 1700352},"tag": "defaultProfile"}}
        return configuracion

    def añadir_configuracion_VLAN(vlan):
        """
        Añade una configuración de puerto según su VLAN.

        Args:
            vlan (int): Número de identificación de la VLAN.

        Returns:
            La respuesta de la API (texto).
        """
        vlan=hex(vlan)[2:]
        configuracion={'profiles': [{'dramAllocation': {'mode': 'AUTO', 'fixedSize': 1700352}, 'rules': [{'field': 'Common::Second Tag::VLAN ID', 'bitRange': 'L2@18[3]+11', 'value': vlan, 'mask': 'fff'}]}]}
        return configuracion

    def añadir_configuración_packetDrop(drops,total,version,desv):
        """
        Añade una configuración de puerto según su configuracion de packet Drop un NE2.

        Args:
            drops (int): cantidad de paquetes dropeados
            total (int): cantidad total de paquetes
            version (string): version of the probability

        Returns:
            La respuesta de la API (texto).
        """
        if version != "GAUSSIAN" and version !="POISSON":
            configuracion={'packetDrop': {'rdmSel': {'dist': version, 'burstlen': drops, 'interval': total, 'stddev': 10.0}, 'enabled': True}}
        else:
            configuracion={'packetDrop': {'rdmSel': {'dist': version, 'burstlen': drops, 'interval': total, 'stddev': desv}, 'enabled': True}}
        return configuracion

    def añadir_configuracion_policer(bitrate):
        """
        Añade una configuración de puerto según su TX bandwidth a un NE2.

        Args:
            bitrate (int): bandwith en Tx

        Returns:
            La respuesta de la API (texto).
        """
        configuracion={'policer':{'excessBitRate': bitrate, 'excessBurstTolerance': 64000, 'commitedBurstTolerance': 64000, 'commitedBitRate': bitrate, 'enabled': True, 'enableRateCoupling': False}}
        return configuracion
    
    def añadir_configuracion_shaper(bitrate):
        """
        Añade una configuración de puerto según su RX bandwidth a un NE2.

        Args:
            bitrate (int): bandwith en Rx

        Returns:
            La respuesta de la API (texto).
        """
        configuracion={'shaper': {'burstTolerance': 64000, 'bitRate': bitrate, 'enabled': True}}
        return configuracion
    
    def añadir_configuracion_reorder(packages,reorder,npackagesreorder, maxreord, version, stev):
        """
        Adds reorder configuration.

        Args:
            packages: number of packages total
            reorder: number of packages to reorder
            npackagesreorder: number of packages of reorder
            maxreord: total number of packages of reorder
            version: version of reorder
            stev: desviation

        Returns:
            response of the API (text).
        """
        if packages is not None and npackagesreorder is not None and maxreord is not None: 
            reorderByMin = min(npackagesreorder, maxreord)
            reorderByMax = max(npackagesreorder, maxreord)
            if version != 'GAUSSIAN':
                configuracion={"reorder": {"rdmSel": {"dist": version, "burstlen": reorder, "interval": packages, "stddev": 10.0 }, "reorderByMin": reorderByMin, "reorderByMax": reorderByMax, "enabled": True}} 
            else:
                configuracion={"reorder": {"rdmSel": {"dist": "GAUSSIAN", "burstlen": reorder, "interval": packages, "stddev": stev }, "reorderByMin": reorderByMin, "reorderByMax": reorderByMax, "enabled": True}} 
            if int(reorder) <= 0:
                configuracion["filterWarning"] = "El valor de reorder es inválido, está fuera del rango permitido."
        else:
            reorder=10000-reorder
            configuracion={"reorder": {"rdmSel": {"dist": "PERIODIC", "burstlen": int(reorder/100), "interval": 100, "stddev": 10.0 }, "reorderByMin": 1, "reorderByMax": 5, "enabled": True}}
        return configuracion

    def envio_peticion(ip,puerto, configuracion):
        """
        Envía una configuración de puerto a un NE2.

        Args:
            ip (int): IP del NE2
            puerto: número del puerto a configurar
            configuración: la información que se quiere configurar en el puerto

        Returns:
            La respuesta de la API (texto).
        """
        print(f'\nCONFIGURACION\n{configuracion}')
        url = f"http://{ip}/api/hw/Port/{puerto}"
        response = requests.put(url, json=configuracion, auth=('admin', 'admin'))

        if response.status_code == 200:
            print(f'\n{configuracion}')
            return response.text
        else:
            try:
                error_info = response.json()
            except ValueError:
                error_info = response.text

            print(f"\n\nError al añadir configuración de puerto: {response.status_code}")
            print(f"Mensaje de error: {error_info}")
            print(f"Configuración enviada: {configuracion}\n\n")
            return None
 No newline at end of file
+0 −2
Changes for src/templates/L2-VPN_template_empty.json: 0 added lines, 2 removed lines.
Original line number Diff line number Diff line
@@ -12,8 +12,6 @@
                {"device_id": {"device_uuid": {"uuid": ""}}, "endpoint_uuid": {"uuid": "eth-1/0/21"}} 
            ],
            "service_constraints": [
                {"custom": {"constraint_type": "bandwidth[kbps]", "constraint_value": "0"}}, 
                {"custom": {"constraint_type": "latency[ms]", "constraint_value": "0"}}
            ],
            "service_config": {"config_rules": [
                {"action": 1, "custom": {"resource_key": "/settings", "resource_value": {
+12 −188
Changes for src/templates/L2-VPN_template_example.json: 12 added lines, 188 removed lines.
Original line number Diff line number Diff line
@@ -8,7 +8,7 @@
               }
            },
            "service_uuid":{
          "uuid": "l2-acl-svc-17429923732568250"
               "uuid":"l2-acl-svc-17429923732568250765476542"
            }
         },
         "service_type":2,
@@ -19,21 +19,21 @@
            {
               "device_id":{
                  "device_uuid":{
              "uuid": "4.4.4.4"
                     "uuid":"1.1.1.1"
                  }
               },
               "endpoint_uuid":{
            "uuid": "0/0/0-GigabitEthernet0/0/0/0"
                  "uuid":"eth0"
               }
            },
            {
               "device_id":{
                  "device_uuid":{
              "uuid": "5.5.5.5"
                     "uuid":"3.3.3.3"
                  }
               },
               "endpoint_uuid":{
            "uuid": "0/0/3-GigabitEthernet0/0/0/3"
                  "uuid":"eth0"
               }
            }
         ],
@@ -57,18 +57,20 @@
                  "action":1,
                  "custom":{
                     "resource_key":"/settings",
              "resource_value": {}
                     "resource_value":{
                        
                     }
                  }
               },
               {
                  "action":1,
                  "custom":{
              "resource_key": "/device[4.4.4.4]/endpoint[0/0/0-GigabitEthernet0/0/0/0]/settings",
                     "resource_key":"/device[1.1.1.1]/endpoint[eth0]/settings",
                     "resource_value":{
                        "sub_interface_index":0,
                        "vlan_id":100,
                        "circuit_id":"100",
                "remote_router": "5.5.5.5",
                        "remote_router":"3.3.3.3",
                        "ni_name":"ELAN100"
                     }
                  }
@@ -76,196 +78,18 @@
               {
                  "action":1,
                  "custom":{
              "resource_key": "/device[5.5.5.5]/endpoint[0/0/3-GigabitEthernet0/0/0/3]/settings",
                     "resource_key":"/device[3.3.3.3]/endpoint[eth0]/settings",
                     "resource_value":{
                        "sub_interface_index":0,
                        "vlan_id":100,
                        "circuit_id":"100",
                "remote_router": "4.4.4.4",
                        "remote_router":"1.1.1.1",
                        "ni_name":"ELAN100"
                     }
                  }
               }
            ]
         }
    },
    {
      "service_id": {
        "context_id": {
          "context_uuid": {
            "uuid": "admin"
          }
        },
        "service_uuid": {
          "uuid": "l2-acl-svc-17429923733224160"
        }
      },
      "service_type": 2,
      "service_status": {
        "service_status": 1
      },
      "service_endpoint_ids": [
        {
          "device_id": {
            "device_uuid": {
              "uuid": "4.4.4.4"
            }
          },
          "endpoint_uuid": {
            "uuid": "0/0/0-GigabitEthernet0/0/0/0"
          }
        },
        {
          "device_id": {
            "device_uuid": {
              "uuid": "5.5.5.5"
            }
          },
          "endpoint_uuid": {
            "uuid": "0/0/3-GigabitEthernet0/0/0/3"
          }
        }
      ],
      "service_constraints": [
        {
          "custom": {
            "constraint_type": "bandwidth[kbps]",
            "constraint_value": "200"
          }
        },
        {
          "custom": {
            "constraint_type": "latency[ms]",
            "constraint_value": "5"
          }
        }
      ],
      "service_config": {
        "config_rules": [
          {
            "action": 1,
            "custom": {
              "resource_key": "/settings",
              "resource_value": {}
            }
          },
          {
            "action": 1,
            "custom": {
              "resource_key": "/device[4.4.4.4]/endpoint[0/0/0-GigabitEthernet0/0/0/0]/settings",
              "resource_value": {
                "sub_interface_index": 0,
                "vlan_id": 101,
                "circuit_id": "101",
                "remote_router": "5.5.5.5",
                "ni_name": "ELAN101"
              }
            }
          },
          {
            "action": 1,
            "custom": {
              "resource_key": "/device[5.5.5.5]/endpoint[0/0/3-GigabitEthernet0/0/0/3]/settings",
              "resource_value": {
                "sub_interface_index": 0,
                "vlan_id": 101,
                "circuit_id": "101",
                "remote_router": "4.4.4.4",
                "ni_name": "ELAN101"
              }
            }
          }
        ]
      }
    },
    {
      "service_id": {
        "context_id": {
          "context_uuid": {
            "uuid": "admin"
          }
        },
        "service_uuid": {
          "uuid": "l2-acl-svc-17429923733753200"
        }
      },
      "service_type": 2,
      "service_status": {
        "service_status": 1
      },
      "service_endpoint_ids": [
        {
          "device_id": {
            "device_uuid": {
              "uuid": "4.4.4.4"
            }
          },
          "endpoint_uuid": {
            "uuid": "0/0/0-GigabitEthernet0/0/0/0"
          }
        },
        {
          "device_id": {
            "device_uuid": {
              "uuid": "5.5.5.5"
            }
          },
          "endpoint_uuid": {
            "uuid": "0/0/3-GigabitEthernet0/0/0/3"
          }
        }
      ],
      "service_constraints": [
        {
          "custom": {
            "constraint_type": "bandwidth[kbps]",
            "constraint_value": "200"
          }
        },
        {
          "custom": {
            "constraint_type": "latency[ms]",
            "constraint_value": "10"
          }
        }
      ],
      "service_config": {
        "config_rules": [
          {
            "action": 1,
            "custom": {
              "resource_key": "/settings",
              "resource_value": {}
            }
          },
          {
            "action": 1,
            "custom": {
              "resource_key": "/device[4.4.4.4]/endpoint[0/0/0-GigabitEthernet0/0/0/0]/settings",
              "resource_value": {
                "sub_interface_index": 0,
                "vlan_id": 102,
                "circuit_id": "102",
                "remote_router": "5.5.5.5",
                "ni_name": "ELAN102"
              }
            }
          },
          {
            "action": 1,
            "custom": {
              "resource_key": "/device[5.5.5.5]/endpoint[0/0/3-GigabitEthernet0/0/0/3]/settings",
              "resource_value": {
                "sub_interface_index": 0,
                "vlan_id": 102,
                "circuit_id": "102",
                "remote_router": "4.4.4.4",
                "ni_name": "ELAN102"
              }
            }
          }
        ]
      }
      }
   ]
}
 No newline at end of file
+0 −2
Changes for src/templates/L3-VPN_template_empty.json: 0 added lines, 2 removed lines.
Original line number Diff line number Diff line
@@ -12,8 +12,6 @@
                {"device_id": {"device_uuid": {"uuid": ""}}, "endpoint_uuid": {"uuid": ""}} 
            ],
            "service_constraints": [
                {"custom": {"constraint_type": "bandwidth[kbps]", "constraint_value": "0"}},
                {"custom": {"constraint_type": "latency[ms]", "constraint_value": "0"}}
            ],
            "service_config": {"config_rules": [
                {"action": 1, "custom": {"resource_key": "/settings", "resource_value": {
Loading
Loading