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