Add helper method to generate simulator config
[integration.git] / test / mocks / mass-pnf-sim / MassPnfSim.py
1 #!/usr/bin/env python3
2 import logging
3 from subprocess import run, CalledProcessError
4 import argparse
5 import ipaddress
6 from sys import exit
7 from os import chdir, getcwd, path, popen, kill, getuid, stat, mkdir
8 from shutil import copytree, rmtree, move
9 from json import loads, dumps
10 from yaml import load, SafeLoader, dump
11 from glob import glob
12 from time import strftime
13 from docker import from_env
14 from requests import get, codes, post
15 from requests.exceptions import MissingSchema, InvalidSchema, InvalidURL, ConnectionError, ConnectTimeout
16
17 def validate_url(url):
18     '''Helper function to perform --urlves input param validation'''
19     logger = logging.getLogger("urllib3")
20     logger.setLevel(logging.WARNING)
21     try:
22         get(url, timeout=0.001)
23     except (MissingSchema, InvalidSchema, InvalidURL):
24         raise argparse.ArgumentTypeError(f'{url} is not a valid URL')
25     except (ConnectionError, ConnectTimeout):
26         pass
27     return url
28
29 def validate_ip(ip):
30     '''Helper function to validate input param is a vaild IP address'''
31     try:
32         ip_valid = ipaddress.ip_address(ip)
33     except ValueError:
34         raise argparse.ArgumentTypeError(f'{ip} is not a valid IP address')
35     else:
36         return ip_valid
37
38 def get_parser():
39     '''Process input arguments'''
40
41     parser = argparse.ArgumentParser()
42     subparsers = parser.add_subparsers(title='Subcommands', dest='subcommand')
43     # Build command parser
44     subparsers.add_parser('build', help='Build simulator image')
45     # Bootstrap command parser
46     parser_bootstrap = subparsers.add_parser('bootstrap', help='Bootstrap the system')
47     parser_bootstrap.add_argument('--count', help='Instance count to bootstrap', type=int, metavar='INT', default=1)
48     parser_bootstrap.add_argument('--urlves', help='URL of the VES collector', type=validate_url, metavar='URL', required=True)
49     parser_bootstrap.add_argument('--ipfileserver', help='Visible IP of the file server (SFTP/FTPS) to be included in the VES event',
50                                   type=validate_ip, metavar='IP', required=True)
51     parser_bootstrap.add_argument('--typefileserver', help='Type of the file server (SFTP/FTPS) to be included in the VES event',
52                                   type=str, choices=['sftp', 'ftps'], required=True)
53     parser_bootstrap.add_argument('--ipstart', help='IP address range beginning', type=validate_ip, metavar='IP', required=True)
54     # Start command parser
55     parser_start = subparsers.add_parser('start', help='Start instances')
56     parser_start.add_argument('--count', help='Instance count to start', type=int, metavar='INT', default=0)
57     # Stop command parser
58     parser_stop = subparsers.add_parser('stop', help='Stop instances')
59     parser_stop.add_argument('--count', help='Instance count to stop', type=int, metavar='INT', default=0)
60     # Trigger command parser
61     parser_trigger = subparsers.add_parser('trigger', help='Trigger one single VES event from each simulator')
62     parser_trigger.add_argument('--count', help='Instance count to trigger', type=int, metavar='INT', default=0)
63     # Stop-simulator command parser
64     parser_stopsimulator = subparsers.add_parser('stop_simulator', help='Stop sending PNF registration messages')
65     parser_stopsimulator.add_argument('--count', help='Instance count to stop', type=int, metavar='INT', default=0)
66     # Trigger-custom command parser
67     parser_triggerstart = subparsers.add_parser('trigger_custom', help='Trigger one single VES event from specific simulators')
68     parser_triggerstart.add_argument('--triggerstart', help='First simulator id to trigger', type=int,
69                                      metavar='INT', required=True)
70     parser_triggerstart.add_argument('--triggerend', help='Last simulator id to trigger', type=int,
71                                      metavar='INT', required=True)
72     # Status command parser
73     parser_status = subparsers.add_parser('status', help='Status')
74     parser_status.add_argument('--count', help='Instance count to show status for', type=int, metavar='INT', default=0)
75     # Clean command parser
76     subparsers.add_parser('clean', help='Clean work-dirs')
77     # General options parser
78     parser.add_argument('--verbose', help='Verbosity level', choices=['info', 'debug'],
79                         type=str, default='info')
80     return parser
81
82 class MassPnfSim:
83
84     log_lvl = logging.INFO
85     sim_config = 'config/config.yml'
86     sim_msg_config = 'config/config.json'
87     sim_port = 5000
88     sim_base_url = 'http://{}:' + str(sim_port) + '/simulator'
89     sim_start_url = sim_base_url + '/start'
90     sim_status_url = sim_base_url + '/status'
91     sim_stop_url = sim_base_url + '/stop'
92     sim_container_name = 'pnf-simulator'
93     rop_script_name = 'ROP_file_creator.sh'
94
95     def __init__(self, args):
96         self.args = args
97         self.logger = logging.getLogger(__name__)
98         self.logger.setLevel(self.log_lvl)
99         self.sim_dirname_pattern = "pnf-sim-lw-"
100         self.mvn_build_cmd = 'mvn clean package docker:build -Dcheckstyle.skip'
101         self.docker_compose_status_cmd = 'docker-compose ps'
102         self.existing_sim_instances = self._enum_sim_instances()
103
104         # Validate 'trigger_custom' subcommand options
105         if self.args.subcommand == 'trigger_custom':
106             if (self.args.triggerend + 1) > self.existing_sim_instances:
107                 self.logger.error('--triggerend value greater than existing instance count.')
108                 exit(1)
109
110         # Validate --count option for subcommands that support it
111         if self.args.subcommand in ['start', 'stop', 'trigger', 'status', 'stop_simulator']:
112             if self.args.count > self.existing_sim_instances:
113                 self.logger.error('--count value greater that existing instance count')
114                 exit(1)
115             if not self.existing_sim_instances:
116                 self.logger.error('No bootstrapped instance found')
117                 exit(1)
118
119         # Validate 'bootstrap' subcommand
120         if (self.args.subcommand == 'bootstrap') and self.existing_sim_instances:
121             self.logger.error('Bootstrapped instances detected, not overwiriting, clean first')
122             exit(1)
123
124     def _run_cmd(self, cmd, dir_context='.'):
125         old_pwd = getcwd()
126         try:
127             chdir(dir_context)
128             self.logger.debug(f'_run_cmd: Current direcotry: {getcwd()}')
129             self.logger.debug(f'_run_cmd: Command string: {cmd}')
130             run(cmd, check=True, shell=True)
131             chdir(old_pwd)
132         except FileNotFoundError:
133             self.logger.error(f"Directory {dir_context} not found")
134         except CalledProcessError as e:
135             exit(e.returncode)
136
137     def _enum_sim_instances(self):
138         '''Helper method that returns bootstraped simulator instances count'''
139         return len(glob(f"{self.sim_dirname_pattern}[0-9]*"))
140
141     def _get_sim_instance_data(self, instance_id):
142         '''Helper method that returns specific instance data'''
143         oldpwd = getcwd()
144         chdir(f"{self.sim_dirname_pattern}{instance_id}")
145         with open(self.sim_config) as cfg:
146             yml = load(cfg, Loader=SafeLoader)
147         chdir(oldpwd)
148         return yml['ippnfsim']
149
150     def _get_docker_containers(self):
151         '''Returns a list containing 'name' attribute of running docker containers'''
152         dc = from_env()
153         containers = []
154         for container in dc.containers.list():
155             containers.append(container.attrs['Name'][1:])
156         return containers
157
158     def _get_iter_range(self):
159         '''Helper routine to get the iteration range
160         for the lifecycle commands'''
161         if hasattr(self.args, 'count'):
162             if not self.args.count:
163                 return [self.existing_sim_instances]
164             else:
165                 return [self.args.count]
166         elif hasattr(self.args, 'triggerstart'):
167             return [self.args.triggerstart, self.args.triggerend + 1]
168         else:
169             return [self.existing_sim_instances]
170
171     def _archive_logs(self, sim_dir):
172         '''Helper function to archive simulator logs or create the log dir'''
173         old_pwd = getcwd()
174         try:
175             chdir(sim_dir)
176             if path.isdir('logs'):
177                 arch_dir = f"logs/archive_{strftime('%Y-%m-%d_%T')}"
178                 mkdir(arch_dir)
179                 self.logger.debug(f'Created {arch_dir}')
180                 # Collect file list to move
181                 self.logger.debug('Archiving log files')
182                 for fpattern in ['*.log', '*.xml']:
183                     for f in glob('logs/' + fpattern):
184                         # Move files from list to arch dir
185                         move(f, arch_dir)
186                         self.logger.debug(f'Moving {f} to {arch_dir}')
187             else:
188                 mkdir('logs')
189                 self.logger.debug("Logs dir didn't exist, created")
190             chdir(old_pwd)
191         except FileNotFoundError:
192             self.logger.error(f"Directory {sim_dir} not found")
193
194     def _generate_pnf_sim_config(self, i, port_sftp, port_ftps, pnf_sim_ip):
195         '''Writes a yaml formatted configuration file for Java simulator app'''
196         yml = {}
197         yml['urlves'] = self.args.urlves
198         yml['urlsftp'] = f'sftp://onap:pano@{self.args.ipfileserver}:{port_sftp}'
199         yml['urlftps'] = f'ftps://onap:pano@{self.args.ipfileserver}:{port_ftps}'
200         yml['ippnfsim'] = pnf_sim_ip
201         yml['typefileserver'] = self.args.typefileserver
202         self.logger.debug(f'Generated simulator config:\n{dump(yml)}')
203         with open(f'{self.sim_dirname_pattern}{i}/{self.sim_config}', 'w') as fout:
204             fout.write(dump(yml))
205
206     def bootstrap(self):
207         self.logger.info("Bootstrapping PNF instances")
208
209         start_port = 2000
210         ftps_pasv_port_start = 8000
211         ftps_pasv_port_num_of_ports = 10
212
213         ftps_pasv_port_end = ftps_pasv_port_start + ftps_pasv_port_num_of_ports
214
215         for i in range(self.args.count):
216             self.logger.info(f"PNF simulator instance: {i}")
217
218             # The IP ranges are in distance of 16 compared to each other.
219             # This is matching the /28 subnet mask used in the dockerfile inside.
220             instance_ip_offset = i * 16
221             ip_properties = [
222                       'subnet',
223                       'gw',
224                       'PnfSim',
225                       'ftps',
226                       'sftp'
227                     ]
228
229             ip_offset = 0
230             ip = {}
231             for prop in ip_properties:
232                 ip.update({prop: str(self.args.ipstart + ip_offset + instance_ip_offset)})
233                 ip_offset += 1
234
235             self.logger.debug(f'Instance #{i} properties:\n {dumps(ip, indent=4)}')
236
237             PortSftp = start_port + 1
238             PortFtps = start_port + 2
239             start_port += 2
240
241             self.logger.info(f'\tCreating {self.sim_dirname_pattern}{i}')
242             copytree('pnf-sim-lightweight', f'{self.sim_dirname_pattern}{i}')
243
244             composercmd = " ".join([
245                     "./simulator.sh compose",
246                     ip['gw'],
247                     ip['subnet'],
248                     str(i),
249                     self.args.urlves,
250                     ip['PnfSim'],
251                     str(self.args.ipfileserver),
252                     self.args.typefileserver,
253                     str(PortSftp),
254                     str(PortFtps),
255                     ip['ftps'],
256                     ip['sftp'],
257                     str(ftps_pasv_port_start),
258                     str(ftps_pasv_port_end)
259                 ])
260             self.logger.debug(f"Script cmdline: {composercmd}")
261             self.logger.info(f"\tCreating instance #{i} configuration ")
262             self._generate_pnf_sim_config(i, PortSftp, PortFtps, ip['PnfSim'])
263             self._run_cmd(composercmd, f"{self.sim_dirname_pattern}{i}")
264
265             ftps_pasv_port_start += ftps_pasv_port_num_of_ports + 1
266             ftps_pasv_port_end += ftps_pasv_port_num_of_ports + 1
267
268             # ugly hack to chown vsftpd config file to root
269             if getuid():
270                 self._run_cmd('sudo chown root config/vsftpd_ssl.conf', f'{self.sim_dirname_pattern}{i}')
271                 self.logger.debug(f"vsftpd_ssl.conf file owner UID: {stat(self.sim_dirname_pattern + str(i) + '/config/vsftpd_ssl.conf').st_uid}")
272
273             self.logger.info(f'Done setting up instance #{i}')
274
275     def build(self):
276         self.logger.info("Building simulator image")
277         if path.isfile('pnf-sim-lightweight/pom.xml'):
278             self._run_cmd(self.mvn_build_cmd, 'pnf-sim-lightweight')
279         else:
280             self.logger.error('POM file was not found, Maven cannot run')
281             exit(1)
282
283     def clean(self):
284         self.logger.info('Cleaning simulators workdirs')
285         for sim_id in range(self.existing_sim_instances):
286             rmtree(f"{self.sim_dirname_pattern}{sim_id}")
287
288     def start(self):
289         for i in range(*self._get_iter_range()):
290             # If container is not running
291             if f"{self.sim_container_name}-{i}" not in self._get_docker_containers():
292                 self.logger.info(f'Starting {self.sim_dirname_pattern}{i} instance:')
293                 self.logger.info(f' PNF-Sim IP: {self._get_sim_instance_data(i)}')
294                 #Move logs to archive
295                 self._archive_logs(self.sim_dirname_pattern + str(i))
296                 self.logger.info(' Starting simulator containers using netconf model specified in config/netconf.env')
297                 self._run_cmd('docker-compose up -d', self.sim_dirname_pattern + str(i))
298             else:
299                 self.logger.warning(f'Instance {self.sim_dirname_pattern}{i} containers are already up')
300
301     def status(self):
302         for i in range(*self._get_iter_range()):
303             self.logger.info(f'Getting {self.sim_dirname_pattern}{i} instance status:')
304             if f"{self.sim_container_name}-{i}" in self._get_docker_containers():
305                 try:
306                     sim_ip = self._get_sim_instance_data(i)
307                     self.logger.info(f' PNF-Sim IP: {sim_ip}')
308                     self._run_cmd(self.docker_compose_status_cmd, f"{self.sim_dirname_pattern}{i}")
309                     sim_response = get('{}'.format(self.sim_status_url).format(sim_ip))
310                     if sim_response.status_code == codes.ok:
311                         self.logger.info(sim_response.text)
312                     else:
313                         self.logger.error(f'Simulator request returned http code {sim_response.status_code}')
314                 except KeyError:
315                     self.logger.error(f'Unable to get sim instance IP from {self.sim_config}')
316             else:
317                 self.logger.info(' Simulator containers are down')
318
319     def stop(self):
320         for i in range(*self._get_iter_range()):
321             self.logger.info(f'Stopping {self.sim_dirname_pattern}{i} instance:')
322             self.logger.info(f' PNF-Sim IP: {self._get_sim_instance_data(i)}')
323             # attempt killing ROP script
324             rop_pid = []
325             for ps_line in iter(popen(f'ps --no-headers -C {self.rop_script_name} -o pid,cmd').readline, ''):
326                 # try getting ROP script pid
327                 try:
328                     ps_line_arr = ps_line.split()
329                     assert self.rop_script_name in ps_line_arr[2]
330                     assert ps_line_arr[3] == str(i)
331                     rop_pid = ps_line_arr[0]
332                 except AssertionError:
333                     pass
334                 else:
335                     # get rop script childs, kill ROP script and all childs
336                     childs = popen(f'pgrep -P {rop_pid}').read().split()
337                     for pid in [rop_pid] + childs:
338                         kill(int(pid), 15)
339                     self.logger.info(f' ROP_file_creator.sh {i} successfully killed')
340             if not rop_pid:
341                 # no process found
342                 self.logger.warning(f' ROP_file_creator.sh {i} already not running')
343             # try tearing down docker-compose application
344             if f"{self.sim_container_name}-{i}" in self._get_docker_containers():
345                 self._run_cmd('docker-compose down', self.sim_dirname_pattern + str(i))
346                 self._run_cmd('docker-compose rm', self.sim_dirname_pattern + str(i))
347             else:
348                 self.logger.warning(" Simulator containers are already down")
349
350     def trigger(self):
351         self.logger.info("Triggering VES sending:")
352         for i in range(*self._get_iter_range()):
353             sim_ip = self._get_sim_instance_data(i)
354             self.logger.info(f'Triggering {self.sim_dirname_pattern}{i} instance:')
355             self.logger.info(f' PNF-Sim IP: {sim_ip}')
356             # setup req headers
357             req_headers = {
358                     "Content-Type": "application/json",
359                     "X-ONAP-RequestID": "123",
360                     "X-InvocationID": "456"
361                 }
362             self.logger.debug(f' Request headers: {req_headers}')
363             try:
364                 # get payload for the request
365                 with open(f'{self.sim_dirname_pattern}{i}/{self.sim_msg_config}') as data:
366                     json_data = loads(data.read())
367                     self.logger.debug(f' JSON payload for the simulator:\n{json_data}')
368                     # make a http request to the simulator
369                     sim_response = post('{}'.format(self.sim_start_url).format(sim_ip), headers=req_headers, json=json_data)
370                     if sim_response.status_code == codes.ok:
371                         self.logger.info(' Simulator response: ' + sim_response.text)
372                     else:
373                         self.logger.warning(' Simulator response ' + sim_response.text)
374             except TypeError:
375                 self.logger.error(f' Could not load JSON data from {self.sim_dirname_pattern}{i}/{self.sim_msg_config}')
376
377     # Make the 'trigger_custom' an alias to the 'trigger' method
378     trigger_custom = trigger
379
380     def stop_simulator(self):
381         self.logger.info("Stopping sending PNF registration messages:")
382         for i in range(*self._get_iter_range()):
383             sim_ip = self._get_sim_instance_data(i)
384             self.logger.info(f'Stopping {self.sim_dirname_pattern}{i} instance:')
385             self.logger.info(f' PNF-Sim IP: {sim_ip}')
386             sim_response = post('{}'.format(self.sim_stop_url).format(sim_ip))
387             if sim_response.status_code == codes.ok:
388                 self.logger.info(' Simulator response: ' + sim_response.text)
389             else:
390                 self.logger.warning(' Simulator response ' + sim_response.text)