e6b6f92093e177fd9e3f2181f22ac7c0fca00a7f
[transportpce.git] / tests / transportpce_tests / 2.2.1 / test_utils.py
1 #!/usr/bin/env python
2 ##############################################################################
3 # Copyright (c) 2020 Orange, Inc. and others.  All rights reserved.
4 #
5 # All rights reserved. This program and the accompanying materials
6 # are made available under the terms of the Apache License, Version 2.0
7 # which accompanies this distribution, and is available at
8 # http://www.apache.org/licenses/LICENSE-2.0
9 ##############################################################################
10 import json
11 import os
12 import re
13 import signal
14 import subprocess
15
16 import psutil
17 import requests
18
19 sims = {
20     'xpdra': {'port': '17840', 'configfile': 'oper-XPDRA.xml', 'logfile': 'oper-XPDRA.log'},
21     'roadma': {'port': '17841', 'configfile': 'oper-ROADMA.xml', 'logfile': 'oper-ROADMA.log'},
22     'roadmb': {'port': '17842', 'configfile': 'oper-ROADMB.xml', 'logfile': 'oper-ROADMB.log'},
23     'roadmc': {'port': '17843', 'configfile': 'oper-ROADMC.xml', 'logfile': 'oper-ROADMC.log'},
24     'xpdrc': {'port': '17844', 'configfile': 'oper-XPDRC.xml', 'logfile': 'oper-XPDRC.log'},
25     'spdrav2': {'port': '17845', 'configfile': 'oper-SPDRAv2.xml', 'logfile': 'oper-SPDRAv2.log'},
26     'spdrav1': {'port': '17846', 'configfile': 'oper-SPDRAv1.xml', 'logfile': 'oper-SPDRAv1.log'}
27 }
28
29 HONEYNODE_OK_START_MSG = re.escape("Netconf SSH endpoint started successfully at 0.0.0.0")
30
31 TYPE_APPLICATION_JSON = {'content-type': 'application/json'}
32
33 honeynode_executable = os.path.join(
34     os.path.dirname(os.path.realpath(__file__)),
35     "..", "..", "honeynode", "2.2.1", "honeynode-simulator", "honeycomb-tpce")
36 samples_directory = os.path.join(
37     os.path.dirname(os.path.realpath(__file__)),
38     "..", "..", "sample_configs", "openroadm", "2.2.1")
39
40 log_directory = os.path.dirname(os.path.realpath(__file__))
41
42
43 def start_sim(sim):
44     print("starting simulator for " + sim + "...")
45     log_file = os.path.join(log_directory, sims[sim]['logfile'])
46     process = start_node(log_file, sims[sim]['port'], sims[sim]['configfile'])
47     if wait_until_log_contains(log_file, HONEYNODE_OK_START_MSG, 5000):
48         print("simulator for " + sim + " started")
49     else:
50         print("simulator for " + sim + "failed to start")
51     return process
52
53
54 def start_tpce():
55     print("starting opendaylight...")
56     if "USE_LIGHTY" in os.environ and os.environ['USE_LIGHTY'] == 'True':
57         print("starting LIGHTY.IO TransportPCE build...")
58         executable = os.path.join(
59             os.path.dirname(os.path.realpath(__file__)),
60             "..", "..", "..", "lighty", "target", "tpce",
61             "clean-start-controller.sh")
62         with open('odl.log', 'w') as outfile:
63             return subprocess.Popen(
64                 ["sh", executable], stdout=outfile, stderr=outfile, stdin=None)
65     else:
66         print("starting KARAF TransportPCE build...")
67         executable = os.path.join(
68             os.path.dirname(os.path.realpath(__file__)),
69             "..", "..", "..", "karaf", "target", "assembly", "bin", "karaf")
70         with open('odl.log', 'w') as outfile:
71             return subprocess.Popen(
72                 ["sh", executable, "server"], stdout=outfile, stderr=outfile, stdin=None)
73
74
75 def install_karaf_feature(feature_name: str):
76     print("installing feature " + feature_name)
77     executable = os.path.join(
78         os.path.dirname(os.path.realpath(__file__)),
79         "..", "..", "..", "karaf", "target", "assembly", "bin", "client")
80     return subprocess.run([executable],
81                           input='feature:install ' + feature_name + '\n feature:list | grep tapi \n logout \n',
82                           universal_newlines=True)
83
84
85 def post_request(url, data, username, password):
86     return requests.request(
87         "POST", url, data=json.dumps(data),
88         headers=TYPE_APPLICATION_JSON, auth=(username, password))
89
90
91 def put_request(url, data, username, password):
92     return requests.request(
93         "PUT", url, data=json.dumps(data), headers=TYPE_APPLICATION_JSON,
94         auth=(username, password))
95
96
97 def delete_request(url, username, password):
98     return requests.request(
99         "DELETE", url, headers=TYPE_APPLICATION_JSON,
100         auth=(username, password))
101
102
103 def generate_connect_data(node_id: str, node_port: str):
104     data = {"node": [{
105         "node-id": node_id,
106         "netconf-node-topology:username": "admin",
107         "netconf-node-topology:password": "admin",
108         "netconf-node-topology:host": "127.0.0.1",
109         "netconf-node-topology:port": node_port,
110         "netconf-node-topology:tcp-only": "false",
111         "netconf-node-topology:pass-through": {}}]}
112     return data
113
114
115 def generate_link_data(xpdr_node: str, xpdr_num: str, network_num: str, rdm_node: str, srg_num: str,
116                        termination_num: str):
117     data = {
118         "networkutils:input": {
119             "networkutils:links-input": {
120                 "networkutils:xpdr-node": xpdr_node,
121                 "networkutils:xpdr-num": xpdr_num,
122                 "networkutils:network-num": network_num,
123                 "networkutils:rdm-node": rdm_node,
124                 "networkutils:srg-num": srg_num,
125                 "networkutils:termination-point-num": termination_num
126             }
127         }
128     }
129     return data
130
131
132 def shutdown_process(process):
133     if process is not None:
134         for child in psutil.Process(process.pid).children():
135             child.send_signal(signal.SIGINT)
136             child.wait()
137         process.send_signal(signal.SIGINT)
138
139
140 def start_node(log_file: str, node_port: str, node_config_file_name: str):
141     if os.path.isfile(honeynode_executable):
142         with open(log_file, 'w') as outfile:
143             return subprocess.Popen(
144                 [honeynode_executable, node_port, os.path.join(samples_directory, node_config_file_name)],
145                 stdout=outfile, stderr=outfile)
146
147
148 def wait_until_log_contains(log_file, searched_string, time_to_wait=20):
149     found = False
150     tail = None
151     try:
152         with timeout(seconds=time_to_wait):
153             print("Waiting for " + searched_string)
154             tail = subprocess.Popen(['tail', '-F', log_file], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
155             regexp = re.compile(searched_string)
156             while True:
157                 line = tail.stdout.readline().decode('utf-8')
158                 if regexp.search(line):
159                     print("Searched string found.")
160                     found = True
161                     break
162     except TimeoutError:
163         print("Cannot find string "+searched_string+" after waiting for "+str(time_to_wait))
164     finally:
165         if tail is not None:
166             print("Stopping tail command")
167             tail.stderr.close()
168             tail.stdout.close()
169             tail.kill()
170             tail.wait()
171         return found
172
173
174 class timeout:
175     def __init__(self, seconds=1, error_message='Timeout'):
176         self.seconds = seconds
177         self.error_message = error_message
178
179     def handle_timeout(self, signum, frame):
180         raise TimeoutError(self.error_message)
181
182     def __enter__(self):
183         signal.signal(signal.SIGALRM, self.handle_timeout)
184         signal.alarm(self.seconds)
185
186     def __exit__(self, type, value, traceback):
187         signal.alarm(0)