Migrate PCE functional tests to RFC8040
[transportpce.git] / tests / transportpce_tests / common / test_utils_rfc8040.py
1 #!/usr/bin/env python
2
3 ##############################################################################
4 # Copyright (c) 2021 Orange, Inc. and others.  All rights reserved.
5 #
6 # All rights reserved. This program and the accompanying materials
7 # are made available under the terms of the Apache License, Version 2.0
8 # which accompanies this distribution, and is available at
9 # http://www.apache.org/licenses/LICENSE-2.0
10 ##############################################################################
11
12 # pylint: disable=no-member
13
14 import json
15 import os
16 # pylint: disable=wrong-import-order
17 import sys
18 import re
19 import signal
20 import subprocess
21 import time
22
23 import psutil
24 import requests
25
26 # pylint: disable=import-error
27 import simulators
28
29 SIMS = simulators.SIMS
30
31 HONEYNODE_OK_START_MSG = 'Netconf SSH endpoint started successfully at 0.0.0.0'
32 KARAF_OK_START_MSG = "Blueprint container for bundle org.opendaylight.netconf.restconf.* was successfully created"
33 LIGHTY_OK_START_MSG = re.escape("lighty.io and RESTCONF-NETCONF started")
34
35 ODL_LOGIN = 'admin'
36 ODL_PWD = 'admin'
37 NODES_LOGIN = 'admin'
38 NODES_PWD = 'admin'
39
40 TYPE_APPLICATION_JSON = {'Content-Type': 'application/json', 'Accept': 'application/json'}
41 TYPE_APPLICATION_XML = {'Content-Type': 'application/xml', 'Accept': 'application/xml'}
42
43 CODE_SHOULD_BE_200 = 'Http status code should be 200'
44 CODE_SHOULD_BE_201 = 'Http status code should be 201'
45
46 SIM_LOG_DIRECTORY = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'log')
47
48 process_list = []
49
50 if 'USE_ODL_ALT_RESTCONF_PORT' in os.environ:
51     RESTCONF_PORT = os.environ['USE_ODL_ALT_RESTCONF_PORT']
52 else:
53     RESTCONF_PORT = 8181
54
55 RESTCONF_PATH_PREFIX = {'rfc8040': '/rests',
56                         'draft-bierman02': '/restconf'}
57 if 'USE_ODL_RESTCONF_VERSION' in os.environ:
58     RESTCONF_VERSION = os.environ['USE_ODL_RESTCONF_VERSION']
59     if RESTCONF_VERSION not in RESTCONF_PATH_PREFIX:
60         print('unsupported RESTCONF version ' + RESTCONF_VERSION)
61         sys.exit(3)
62 else:
63     RESTCONF_VERSION = 'rfc8040'
64
65 RESTCONF_BASE_URL = 'http://localhost:' + str(RESTCONF_PORT) + RESTCONF_PATH_PREFIX[RESTCONF_VERSION]
66
67 if 'USE_ODL_ALT_KARAF_INSTALL_DIR' in os.environ:
68     KARAF_INSTALLDIR = os.environ['USE_ODL_ALT_KARAF_INSTALL_DIR']
69 else:
70     KARAF_INSTALLDIR = 'karaf'
71
72 KARAF_LOG = os.path.join(
73     os.path.dirname(os.path.realpath(__file__)),
74     '..', '..', '..', KARAF_INSTALLDIR, 'target', 'assembly', 'data', 'log', 'karaf.log')
75
76 if 'USE_LIGHTY' in os.environ and os.environ['USE_LIGHTY'] == 'True':
77     TPCE_LOG = 'odl-' + str(os.getpid()) + '.log'
78 else:
79     TPCE_LOG = KARAF_LOG
80
81 #
82 # Basic HTTP operations
83 #
84
85
86 def get_request(url):
87     return requests.request(
88         'GET', url.format(RESTCONF_BASE_URL),
89         headers=TYPE_APPLICATION_JSON,
90         auth=(ODL_LOGIN, ODL_PWD))
91
92
93 def put_request(url, data):
94     return requests.request(
95         'PUT', url.format(RESTCONF_BASE_URL),
96         data=json.dumps(data),
97         headers=TYPE_APPLICATION_JSON,
98         auth=(ODL_LOGIN, ODL_PWD))
99
100
101 def delete_request(url):
102     return requests.request(
103         'DELETE', url.format(RESTCONF_BASE_URL),
104         headers=TYPE_APPLICATION_JSON,
105         auth=(ODL_LOGIN, ODL_PWD))
106
107
108 def post_request(url, data):
109     if data:
110         return requests.request(
111             "POST", url.format(RESTCONF_BASE_URL),
112             data=json.dumps(data),
113             headers=TYPE_APPLICATION_JSON,
114             auth=(ODL_LOGIN, ODL_PWD))
115     return requests.request(
116         "POST", url.format(RESTCONF_BASE_URL),
117         headers=TYPE_APPLICATION_JSON,
118         auth=(ODL_LOGIN, ODL_PWD))
119
120 #
121 # Process management
122 #
123
124
125 def start_sims(sims_list):
126     for sim in sims_list:
127         print('starting simulator ' + sim[0] + ' in OpenROADM device version ' + sim[1] + '...')
128         log_file = os.path.join(SIM_LOG_DIRECTORY, SIMS[sim]['logfile'])
129         process = start_honeynode(log_file, sim)
130         if wait_until_log_contains(log_file, HONEYNODE_OK_START_MSG, 100):
131             print('simulator for ' + sim[0] + ' started')
132         else:
133             print('simulator for ' + sim[0] + ' failed to start')
134             shutdown_process(process)
135             for pid in process_list:
136                 shutdown_process(pid)
137             sys.exit(3)
138         process_list.append(process)
139     return process_list
140
141
142 def start_tpce():
143     print('starting OpenDaylight...')
144     if 'USE_LIGHTY' in os.environ and os.environ['USE_LIGHTY'] == 'True':
145         process = start_lighty()
146         start_msg = LIGHTY_OK_START_MSG
147     else:
148         process = start_karaf()
149         start_msg = KARAF_OK_START_MSG
150     if wait_until_log_contains(TPCE_LOG, start_msg, time_to_wait=300):
151         print('OpenDaylight started !')
152     else:
153         print('OpenDaylight failed to start !')
154         shutdown_process(process)
155         for pid in process_list:
156             shutdown_process(pid)
157         sys.exit(1)
158     process_list.append(process)
159     return process_list
160
161
162 def start_karaf():
163     print('starting KARAF TransportPCE build...')
164     executable = os.path.join(
165         os.path.dirname(os.path.realpath(__file__)),
166         '..', '..', '..', KARAF_INSTALLDIR, 'target', 'assembly', 'bin', 'karaf')
167     with open('odl.log', 'w', encoding='utf-8') as outfile:
168         return subprocess.Popen(
169             ['sh', executable, 'server'], stdout=outfile, stderr=outfile, stdin=None)
170
171
172 def start_lighty():
173     print('starting LIGHTY.IO TransportPCE build...')
174     executable = os.path.join(
175         os.path.dirname(os.path.realpath(__file__)),
176         '..', '..', '..', 'lighty', 'target', 'tpce',
177         'clean-start-controller.sh')
178     with open(TPCE_LOG, 'w', encoding='utf-8') as outfile:
179         return subprocess.Popen(
180             ['sh', executable], stdout=outfile, stderr=outfile, stdin=None)
181
182
183 def install_karaf_feature(feature_name: str):
184     print('installing feature ' + feature_name)
185     executable = os.path.join(
186         os.path.dirname(os.path.realpath(__file__)),
187         '..', '..', '..', KARAF_INSTALLDIR, 'target', 'assembly', 'bin', 'client')
188     return subprocess.run([executable],
189                           input='feature:install ' + feature_name + '\n feature:list | grep '
190                           + feature_name + ' \n logout \n',
191                           universal_newlines=True, check=False)
192
193
194 def shutdown_process(process):
195     if process is not None:
196         for child in psutil.Process(process.pid).children():
197             child.send_signal(signal.SIGINT)
198             child.wait()
199         process.send_signal(signal.SIGINT)
200
201
202 def start_honeynode(log_file: str, sim):
203     executable = os.path.join(os.path.dirname(os.path.realpath(__file__)),
204                               '..', '..', 'honeynode', sim[1], 'honeynode-simulator', 'honeycomb-tpce')
205     sample_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)),
206                                     '..', '..', 'sample_configs', 'openroadm', sim[1])
207     if os.path.isfile(executable):
208         with open(log_file, 'w', encoding='utf-8') as outfile:
209             return subprocess.Popen(
210                 [executable, SIMS[sim]['port'], os.path.join(sample_directory, SIMS[sim]['configfile'])],
211                 stdout=outfile, stderr=outfile)
212     return None
213
214
215 def wait_until_log_contains(log_file, regexp, time_to_wait=60):
216     # pylint: disable=lost-exception
217     # pylint: disable=consider-using-with
218     stringfound = False
219     filefound = False
220     line = None
221     try:
222         with TimeOut(seconds=time_to_wait):
223             while not os.path.exists(log_file):
224                 time.sleep(0.2)
225             filelogs = open(log_file, 'r', encoding='utf-8')
226             filelogs.seek(0, 2)
227             filefound = True
228             print("Searching for pattern '" + regexp + "' in " + os.path.basename(log_file), end='... ', flush=True)
229             compiled_regexp = re.compile(regexp)
230             while True:
231                 line = filelogs.readline()
232                 if compiled_regexp.search(line):
233                     print('Pattern found!', end=' ')
234                     stringfound = True
235                     break
236                 if not line:
237                     time.sleep(0.1)
238     except TimeoutError:
239         print('Pattern not found after ' + str(time_to_wait), end=' seconds! ', flush=True)
240     except PermissionError:
241         print('Permission Error when trying to access the log file', end=' ... ', flush=True)
242     finally:
243         if filefound:
244             filelogs.close()
245         else:
246             print('log file does not exist or is not accessible... ', flush=True)
247         return stringfound
248
249
250 class TimeOut:
251     def __init__(self, seconds=1, error_message='Timeout'):
252         self.seconds = seconds
253         self.error_message = error_message
254
255     def handle_timeout(self, signum, frame):
256         raise TimeoutError(self.error_message)
257
258     def __enter__(self):
259         signal.signal(signal.SIGALRM, self.handle_timeout)
260         signal.alarm(self.seconds)
261
262     def __exit__(self, type, value, traceback):
263         # pylint: disable=W0622
264         signal.alarm(0)
265
266 #
267 # Basic NetCONF device operations
268 #
269
270
271 def mount_device(node: str, sim: str):
272     url = {'rfc8040': '{}/data/network-topology:network-topology/topology=topology-netconf/node={}',
273            'draft-bierman02': '{}/config/network-topology:network-topology/topology/topology-netconf/node/{}'}
274     body = {'node': [{
275         'node-id': node,
276         'netconf-node-topology:username': NODES_LOGIN,
277         'netconf-node-topology:password': NODES_PWD,
278         'netconf-node-topology:host': '127.0.0.1',
279         'netconf-node-topology:port': SIMS[sim]['port'],
280         'netconf-node-topology:tcp-only': 'false',
281         'netconf-node-topology:pass-through': {}}]}
282     response = put_request(url[RESTCONF_VERSION].format('{}', node), body)
283     if wait_until_log_contains(TPCE_LOG, 'Triggering notification stream NETCONF for node ' + node, 180):
284         print('Node ' + node + ' correctly added to tpce topology', end='... ', flush=True)
285     else:
286         print('Node ' + node + ' still not added to tpce topology', end='... ', flush=True)
287         if response.status_code == requests.codes.ok:
288             print('It was probably loaded at start-up', end='... ', flush=True)
289         # TODO an else-clause to abort test would probably be nice here
290     return response
291
292
293 def unmount_device(node: str):
294     url = {'rfc8040': '{}/data/network-topology:network-topology/topology=topology-netconf/node={}',
295            'draft-bierman02': '{}/config/network-topology:network-topology/topology/topology-netconf/node/{}'}
296     response = delete_request(url[RESTCONF_VERSION].format('{}', node))
297     if wait_until_log_contains(TPCE_LOG, re.escape("onDeviceDisConnected: " + node), 180):
298         print('Node ' + node + ' correctly deleted from tpce topology', end='... ', flush=True)
299     else:
300         print('Node ' + node + ' still not deleted from tpce topology', end='... ', flush=True)
301     return response
302
303
304 def check_device_connection(node: str):
305     url = {'rfc8040': '{}/data/network-topology:network-topology/topology=topology-netconf/node={}?content=nonconfig',
306            'draft-bierman02': '{}/operational/network-topology:network-topology/topology/topology-netconf/node/{}'}
307     response = get_request(url[RESTCONF_VERSION].format('{}', node))
308     res = response.json()
309     return_key = {'rfc8040': 'network-topology:node',
310                   'draft-bierman02': 'node'}
311     if return_key[RESTCONF_VERSION] in res.keys():
312         connection_status = res[return_key[RESTCONF_VERSION]][0]['netconf-node-topology:connection-status']
313     else:
314         connection_status = res['errors']['error'][0]
315     return {'status_code': response.status_code,
316             'connection-status': connection_status}
317
318
319 def check_node_request(node: str):
320     # pylint: disable=line-too-long
321     url = {'rfc8040': '{}/data/network-topology:network-topology/topology=topology-netconf/node={}/yang-ext:mount/org-openroadm-device:org-openroadm-device?content=config',  # nopep8
322            'draft-bierman02': '{}/config/network-topology:network-topology/topology/topology-netconf/node/{}/yang-ext:mount/org-openroadm-device:org-openroadm-device'}  # nopep8
323     response = get_request(url[RESTCONF_VERSION].format('{}', node))
324     res = response.json()
325     return_key = {'rfc8040': 'org-openroadm-device:org-openroadm-device',
326                   'draft-bierman02': 'org-openroadm-device'}
327     if return_key[RESTCONF_VERSION] in res.keys():
328         response_attribute = res[return_key[RESTCONF_VERSION]]
329     else:
330         response_attribute = res['errors']['error'][0]
331     return {'status_code': response.status_code,
332             'org-openroadm-device': response_attribute}
333
334
335 def check_node_attribute_request(node: str, attribute: str, attribute_value: str):
336     # pylint: disable=line-too-long
337     url = {'rfc8040': '{}/data/network-topology:network-topology/topology=topology-netconf/node={}/yang-ext:mount/org-openroadm-device:org-openroadm-device/{}={}?content=nonconfig',  # nopep8
338            'draft-bierman02': '{}/operational/network-topology:network-topology/topology/topology-netconf/node/{}/yang-ext:mount/org-openroadm-device:org-openroadm-device/{}/{}'}  # nopep8
339     response = get_request(url[RESTCONF_VERSION].format('{}', node, attribute, attribute_value))
340     res = response.json()
341     return_key = {'rfc8040': 'org-openroadm-device:' + attribute,
342                   'draft-bierman02': attribute}
343     if return_key[RESTCONF_VERSION] in res.keys():
344         response_attribute = res[return_key[RESTCONF_VERSION]]
345     else:
346         response_attribute = res['errors']['error'][0]
347     return {'status_code': response.status_code,
348             attribute: response_attribute}
349
350
351 def check_node_attribute2_request(node: str, attribute: str, attribute_value: str, attribute2: str):
352     # pylint: disable=line-too-long
353     url = {'rfc8040': '{}/data/network-topology:network-topology/topology=topology-netconf/node={}/yang-ext:mount/org-openroadm-device:org-openroadm-device/{}={}/{}?content=config',  # nopep8
354            'draft-bierman02': '{}/config/network-topology:network-topology/topology/topology-netconf/node/{}/yang-ext:mount/org-openroadm-device:org-openroadm-device/{}/{}/{}'}  # nopep8
355     response = get_request(url[RESTCONF_VERSION].format('{}', node, attribute, attribute_value, attribute2))
356     res = response.json()
357     if attribute2 in res.keys():
358         response_attribute = res[attribute2]
359     else:
360         response_attribute = res['errors']['error'][0]
361     return {'status_code': response.status_code,
362             attribute2: response_attribute}
363
364
365 def del_node_attribute_request(node: str, attribute: str, attribute_value: str):
366     # pylint: disable=line-too-long
367     url = {'rfc8040': '{}/data/network-topology:network-topology/topology=topology-netconf/node={}/yang-ext:mount/org-openroadm-device:org-openroadm-device/{}={}',  # nopep8
368            'draft-bierman02': '{}/config/network-topology:network-topology/topology/topology-netconf/node/{}/yang-ext:mount/org-openroadm-device:org-openroadm-device/{}/{}'}  # nopep8
369     response = delete_request(url[RESTCONF_VERSION].format('{}', node, attribute, attribute_value))
370     return response
371
372 #
373 # Portmapping operations
374 #
375
376
377 def post_portmapping(payload: str):
378     url = {'rfc8040': '{}/data/transportpce-portmapping:network',
379            'draft-bierman02': '{}/config/transportpce-portmapping:network'}
380     json_payload = json.loads(payload)
381     response = post_request(url[RESTCONF_VERSION].format('{}'), json_payload)
382     return {'status_code': response.status_code}
383
384
385 def del_portmapping():
386     url = {'rfc8040': '{}/data/transportpce-portmapping:network',
387            'draft-bierman02': '{}/config/transportpce-portmapping:network'}
388     response = delete_request(url[RESTCONF_VERSION].format('{}'))
389     return {'status_code': response.status_code}
390
391
392 def get_portmapping_node_attr(node: str, attr: str, value: str):
393     # pylint: disable=consider-using-f-string
394     url = {'rfc8040': '{}/data/transportpce-portmapping:network/nodes={}',
395            'draft-bierman02': '{}/config/transportpce-portmapping:network/nodes/{}'}
396     target_url = url[RESTCONF_VERSION].format('{}', node)
397     if attr is not None:
398         target_url = (target_url + '/{}').format('{}', attr)
399         if value is not None:
400             suffix = {'rfc8040': '={}', 'draft-bierman02': '/{}'}
401             target_url = (target_url + suffix[RESTCONF_VERSION]).format('{}', value)
402     else:
403         attr = 'nodes'
404     response = get_request(target_url)
405     res = response.json()
406     return_key = {'rfc8040': 'transportpce-portmapping:' + attr,
407                   'draft-bierman02': attr}
408     if return_key[RESTCONF_VERSION] in res.keys():
409         return_output = res[return_key[RESTCONF_VERSION]]
410     else:
411         return_output = res['errors']['error'][0]
412     return {'status_code': response.status_code,
413             attr: return_output}
414
415 #
416 # Topology operations
417 #
418
419
420 def get_ietf_network_request(network: str, content: str):
421     url = {'rfc8040': '{}/data/ietf-network:networks/network={}?content={}',
422            'draft-bierman02': '{}/{}/ietf-network:networks/network/{}'}
423     if RESTCONF_VERSION == 'rfc8040':
424         format_args = ('{}', network, content)
425     elif content == 'config':
426         format_args = ('{}', content, network)
427     else:
428         format_args = ('{}', 'operational', network)
429     response = get_request(url[RESTCONF_VERSION].format(*format_args))
430     if bool(response):
431         res = response.json()
432         return_key = {'rfc8040': 'ietf-network:network',
433                       'draft-bierman02': 'network'}
434         networks = res[return_key[RESTCONF_VERSION]]
435     else:
436         networks = None
437     return {'status_code': response.status_code,
438             'network': networks}
439
440
441 def put_ietf_network(network: str, payload: str):
442     url = {'rfc8040': '{}/data/ietf-network:networks/network={}',
443            'draft-bierman02': '{}/config/ietf-network:networks/network/{}'}
444     json_payload = json.loads(payload)
445     response = put_request(url[RESTCONF_VERSION].format('{}', network), json_payload)
446     return {'status_code': response.status_code}
447
448
449 def del_ietf_network(network: str):
450     url = {'rfc8040': '{}/data/ietf-network:networks/network={}',
451            'draft-bierman02': '{}/config/ietf-network:networks/network/{}'}
452     response = delete_request(url[RESTCONF_VERSION].format('{}', network))
453     return {'status_code': response.status_code}
454
455
456 def get_ietf_network_link_request(network: str, link: str, content: str):
457     url = {'rfc8040': '{}/data/ietf-network:networks/network={}/ietf-network-topology:link={}?content={}',
458            'draft-bierman02': '{}/{}/ietf-network:networks/network/{}/ietf-network-topology:link/{}'}
459     if RESTCONF_VERSION == 'rfc8040':
460         format_args = ('{}', network, link, content)
461     elif content == 'config':
462         format_args = ('{}', content, network, link)
463     else:
464         format_args = ('{}', 'operational', network, link)
465     response = get_request(url[RESTCONF_VERSION].format(*format_args))
466     res = response.json()
467     return_key = {'rfc8040': 'ietf-network-topology:link',
468                   'draft-bierman02': 'ietf-network-topology:link'}
469     link = res[return_key[RESTCONF_VERSION]][0]
470     return {'status_code': response.status_code,
471             'link': link}
472
473
474 def del_ietf_network_link_request(network: str, link: str, content: str):
475     url = {'rfc8040': '{}/data/ietf-network:networks/network={}/ietf-network-topology:link={}?content={}',
476            'draft-bierman02': '{}/{}/ietf-network:networks/network/{}/ietf-network-topology:link/{}'}
477     if RESTCONF_VERSION == 'rfc8040':
478         format_args = ('{}', network, link, content)
479     elif content == 'config':
480         format_args = ('{}', content, network, link)
481     else:
482         format_args = ('{}', 'operational', network, link)
483     response = delete_request(url[RESTCONF_VERSION].format(*format_args))
484     return response
485
486
487 def add_oms_attr_request(link: str, oms_attr: str):
488     url = {'rfc8040': '{}/data/ietf-network:networks/network={}/ietf-network-topology:link={}',
489            'draft-bierman02': '{}/config/ietf-network:networks/network/{}/ietf-network-topology:link/{}'}
490     url2 = url[RESTCONF_VERSION] + '/org-openroadm-network-topology:OMS-attributes/span'
491     network = 'openroadm-topology'
492     response = put_request(url2.format('{}', network, link), oms_attr)
493     return response
494
495
496 def del_oms_attr_request(link: str,):
497     url = {'rfc8040': '{}/data/ietf-network:networks/network={}/ietf-network-topology:link={}',
498            'draft-bierman02': '{}/config/ietf-network:networks/network/{}/ietf-network-topology:link/{}'}
499     url2 = url[RESTCONF_VERSION] + '/org-openroadm-network-topology:OMS-attributes/span'
500     network = 'openroadm-topology'
501     response = delete_request(url2.format('{}', network, link))
502     return response
503
504
505 def get_ietf_network_node_request(network: str, node: str, content: str):
506     url = {'rfc8040': '{}/data/ietf-network:networks/network={}/node={}?content={}',
507            'draft-bierman02': '{}/{}/ietf-network:networks/network/{}/node/{}'}
508     if RESTCONF_VERSION == 'rfc8040':
509         format_args = ('{}', network, node, content)
510     elif content == 'config':
511         format_args = ('{}', content, network, node)
512     else:
513         format_args = ('{}', 'operational', network, node)
514     response = get_request(url[RESTCONF_VERSION].format(*format_args))
515     if bool(response):
516         res = response.json()
517         return_key = {'rfc8040': 'ietf-network:node',
518                       'draft-bierman02': 'node'}
519         node = res[return_key[RESTCONF_VERSION]][0]
520     else:
521         node = None
522     return {'status_code': response.status_code,
523             'node': node}
524
525
526 def del_ietf_network_node_request(network: str, node: str, content: str):
527     url = {'rfc8040': '{}/data/ietf-network:networks/network={}/node={}?content={}',
528            'draft-bierman02': '{}/{}/ietf-network:networks/network/{}/node/{}'}
529     if RESTCONF_VERSION == 'rfc8040':
530         format_args = ('{}', network, node, content)
531     elif content == 'config':
532         format_args = ('{}', content, network, node)
533     else:
534         format_args = ('{}', 'operational', network, node)
535     response = delete_request(url[RESTCONF_VERSION].format(*format_args))
536     return response
537
538
539 #
540 # Service list operations
541 #
542
543
544 def get_ordm_serv_list_request():
545     url = {'rfc8040': '{}/data/org-openroadm-service:service-list?content=nonconfig',
546            'draft-bierman02': '{}/operational/org-openroadm-service:service-list/'}
547     response = get_request(url[RESTCONF_VERSION])
548     res = response.json()
549     return_key = {'rfc8040': 'org-openroadm-service:service-list',
550                   'draft-bierman02': 'service-list'}
551     if return_key[RESTCONF_VERSION] in res.keys():
552         response_attribute = res[return_key[RESTCONF_VERSION]]
553     else:
554         response_attribute = res['errors']['error'][0]
555     return {'status_code': response.status_code,
556             'service-list': response_attribute}
557
558
559 def get_ordm_serv_list_attr_request(attribute: str, value: str):
560     url = {'rfc8040': '{}/data/org-openroadm-service:service-list/{}={}?content=nonconfig',
561            'draft-bierman02': '{}/operational/org-openroadm-service:service-list/{}/{}'}
562     if RESTCONF_VERSION == 'rfc8040':
563         format_args = ('{}', attribute, value)
564     else:
565         format_args = ('{}', attribute, value)
566     response = get_request(url[RESTCONF_VERSION].format(*format_args))
567     res = response.json()
568     return_key = {'rfc8040': 'org-openroadm-service:' + attribute,
569                   'draft-bierman02': attribute}
570     if return_key[RESTCONF_VERSION] in res.keys():
571         response_attribute = res[return_key[RESTCONF_VERSION]]
572     else:
573         response_attribute = res['errors']['error'][0]
574     return {'status_code': response.status_code,
575             attribute: response_attribute}
576
577
578 #
579 # TransportPCE internal API RPCs
580 #
581
582
583 def prepend_dict_keys(input_dict: dict, prefix: str):
584     return_dict = {}
585     for key, value in input_dict.items():
586         newkey = prefix + key
587         if isinstance(value, dict):
588             return_dict[newkey] = prepend_dict_keys(value, prefix)
589             # TODO: perhaps some recursion depth limit or another solution has to be considered here
590             # even if recursion depth is given by the input_dict argument
591             # direct (self-)recursive functions may carry unwanted side-effects such as ressource consumptions
592         else:
593             return_dict[newkey] = value
594     return return_dict
595
596
597 def transportpce_api_rpc_request(api_module: str, rpc: str, payload: dict):
598     # pylint: disable=consider-using-f-string
599     url = "{}/operations/{}:{}".format('{}', api_module, rpc)
600     if payload is None:
601         data = None
602     elif RESTCONF_VERSION == 'draft-bierman02':
603         data = prepend_dict_keys({'input': payload}, api_module + ':')
604     else:
605         data = {'input': payload}
606     response = post_request(url, data)
607     res = response.json()
608     return_key = {'rfc8040': api_module + ':output',
609                   'draft-bierman02': 'output'}
610     return_output = res[return_key[RESTCONF_VERSION]]
611     return {'status_code': response.status_code,
612             'output': return_output}