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