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