Commit 749e9201 authored by Pablo Armingol's avatar Pablo Armingol
Browse files

Clean emulate driver

parent 9bcb765e
Loading
Loading
Loading
Loading
+30 −82
Original line number Diff line number Diff line
@@ -25,8 +25,7 @@ from device.service.driver_api._Driver import _Driver
from device.service.driver_api.AnyTreeTools import TreeNode, dump_subtree, get_subnode, set_subnode_value
from .Constants import SPECIAL_RESOURCE_MAPPINGS
from .SyntheticSamplingParameters import SyntheticSamplingParameters, do_sampling
from .Tools import compose_resource_endpoint,connect_to_xr_agent
import requests
from .Tools import compose_resource_endpoint

LOGGER = logging.getLogger(__name__)

@@ -39,7 +38,6 @@ class EmulatedDriver(_Driver):
    def __init__(self, address : str, port : int, **settings) -> None:
        super().__init__(DRIVER_NAME, address, port, **settings)
        self.__lock = threading.Lock()
        self.__address = address
        self.__initial = TreeNode('.')
        self.__running = TreeNode('.')
        self.__subscriptions = TreeNode('.')
@@ -119,10 +117,6 @@ class EmulatedDriver(_Driver):
        chk_type('resources', resources, list)
        if len(resources) == 0: return []
        results = []
        if 'ipowdm_ruleset' in str(resources):
            connect_to_xr_agent(resources)
            results.append(True)
        else:
                resolver = anytree.Resolver(pathattr='name')
        with self.__lock:
            for i,resource in enumerate(resources):
@@ -137,58 +131,12 @@ class EmulatedDriver(_Driver):
                    LOGGER.exception('Exception validating {:s}: {:s}'.format(str_resource_name, str(resource_key)))
                    results.append(e) # if validation fails, store the exception
                    continue

                try:
                    resource_value = json.loads(resource_value)
                except: # pylint: disable=bare-except
                    pass

                    if resource_key.startswith('/ipowdm/service/'):
                        LOGGER.info('[%s] Legacy IPoWDM Service Provisioning: Payload=%s', self.__address, str(resource_value))
                    elif resource_key.startswith('/ipowdm/l3nm/'):
                        LOGGER.info('[%s] L3NM Service Provisioning: Payload=%s', self.__address, str(resource_value))
                    elif resource_key.startswith('/ipowdm/pluggables/'):
                        LOGGER.info('[%s] Pluggables Service Provisioning: Payload=%s', self.__address, str(resource_value))
                        try:
                            key_parts = resource_key.split('/')
                            if len(key_parts) >= 5:
                                service_uuid_raw = key_parts[3]
                                # Normalize UUID: if serviceId contains '-pluggable-', take the part before it
                                if "-pluggable-" in service_uuid_raw:
                                     service_uuid = service_uuid_raw.split("-pluggable-")[0]
                                else:
                                     service_uuid = service_uuid_raw

                                if not hasattr(EmulatedDriver, 'pluggables_pending'):
                                    EmulatedDriver.pluggables_pending = {}

                                if service_uuid in EmulatedDriver.pluggables_pending:
                                    stored_payload = EmulatedDriver.pluggables_pending.pop(service_uuid)
                                    current_payload = resource_value

                                    def format_entry(payload):
                                        config = payload.get('config', {})
                                        return {
                                            'uuid': payload.get('device'),
                                            'power': config.get('target-output-power', 0.0),
                                            'frequency': config.get('frequency', 0.0)
                                        }
                                    combined_data = [
                                        {'src': format_entry(stored_payload)},
                                        {'dst': format_entry(current_payload)}
                                    ]
                                    LOGGER.info('[%s] Pluggables Service Provisioning Aggregated: %s', self.__address, json.dumps(combined_data, indent=2))
                                    # TODO Dynamic IP
                                    url = "http://192.168.88.17:9849/api-v0/transponders"
                                    headers = {'Content-Type': 'application/json'}
                                    response = requests.post(url, json=combined_data, headers=headers)
                                    LOGGER.info('[%s] Pluggables Service Provisioning Response: %s', self.__address, str(response.text))
                                else:
                                    EmulatedDriver.pluggables_pending[service_uuid] = resource_value
                                    LOGGER.debug('[%s] Pluggables Service Partial Provisioning stored for %s', self.__address, service_uuid)
                        except Exception as e:
                            LOGGER.warning("Error processing Pluggables aggregation: %s", str(e))
                            LOGGER.info('[%s] Pluggables Service Provisioning: Payload=%s', self.__address, str(resource_value))

                set_subnode_value(resolver, self.__running, resource_path, resource_value)

                match = RE_GET_ENDPOINT_FROM_INTERFACE.match(resource_key)
+1 −26
Original line number Diff line number Diff line
@@ -12,14 +12,12 @@
# See the License for the specific language governing permissions and
# limitations under the License.

import json
import logging
import requests
from typing import Any, Dict, Optional, Tuple
from common.proto.kpi_sample_types_pb2 import KpiSampleType
from common.type_checkers.Checkers import chk_attribute, chk_string, chk_type
from device.service.driver_api._Driver import RESOURCE_ENDPOINTS
from .Constants import SPECIAL_RESOURCE_MAPPINGS
from typing import Any, Dict, Optional, Tuple

LOGGER = logging.getLogger(__name__)

@@ -109,26 +107,3 @@ def compose_resource_endpoint(endpoint_data : Dict[str, Any]) -> Optional[Tuple[
    except: # pylint: disable=bare-except
        LOGGER.exception('Problem composing endpoint({:s})'.format(str(endpoint_data)))
        return None

# TODO Dynamic IP
def connect_to_xr_agent(resources):
    rule_set = resources[0][1]['rule_set']
    nodes = [
        {'src': {
            'uuid': rule_set['src'][0]['uuid'],
            'power': rule_set['src'][0]['power'],
            'frequency': rule_set['src'][0]['frequency']
        }},
        {'dst': {
            'uuid': rule_set['dst'][0]['uuid'],
            'power': rule_set['dst'][0]['power'],
            'frequency': rule_set['dst'][0]['frequency']
        }}
    ]
    url = "http://192.168.88.17:9849/api-v0/transponders"
    headers = {
            "Content-Type": "application/json",
            "Expect": ""
        }
    json_data = json.dumps(nodes)
    requests.post(url, data=json_data, headers=headers, timeout=10)