5c01704d3e00c684d12d5f94233d259c8a62d202
[integration.git] / test / mocks / mass-pnf-sim / MassPnfSim.py
1 #!/usr/bin/env python3
2 import logging
3 import subprocess
4 import argparse
5 import ipaddress
6 from sys import exit
7 from os import chdir, getcwd, path
8 from shutil import copytree
9 from json import dumps
10 from requests import get
11 from requests.exceptions import MissingSchema, InvalidSchema, InvalidURL, ConnectionError, ConnectTimeout
12
13 def validate_url(url):
14     '''Helper function to perform --urlves input param validation'''
15     logger = logging.getLogger("urllib3")
16     logger.setLevel(logging.WARNING)
17     try:
18         get(url, timeout=0.001)
19     except (MissingSchema, InvalidSchema, InvalidURL):
20         raise argparse.ArgumentTypeError(f'{url} is not a valid URL')
21     except (ConnectionError, ConnectTimeout):
22         pass
23     return url
24
25 def validate_ip(ip):
26     '''Helper function to validate input param is a vaild IP address'''
27     try:
28         ip_valid = ipaddress.ip_address(ip)
29     except ValueError:
30         raise argparse.ArgumentTypeError(f'{ip} is not a valid IP address')
31     else:
32         return ip_valid
33
34 def get_parser():
35     '''Process input arguments'''
36
37     parser = argparse.ArgumentParser()
38     subparsers = parser.add_subparsers(title='Subcommands', dest='subcommand')
39     # Build command parser
40     subparsers.add_parser('build', help='Build simulator image')
41     # Bootstrap command parser
42     parser_bootstrap = subparsers.add_parser('bootstrap', help='Bootstrap the system')
43     parser_bootstrap.add_argument('--count', help='Instance count to bootstrap', type=int, metavar='INT', default=1)
44     parser_bootstrap.add_argument('--urlves', help='URL of the VES collector', type=validate_url, metavar='URL', required=True)
45     parser_bootstrap.add_argument('--ipfileserver', help='Visible IP of the file server (SFTP/FTPS) to be included in the VES event',
46                                   type=validate_ip, metavar='IP', required=True)
47     parser_bootstrap.add_argument('--typefileserver', help='Type of the file server (SFTP/FTPS) to be included in the VES event',
48                                   type=str, choices=['sftp', 'ftps'], required=True)
49     parser_bootstrap.add_argument('--ipstart', help='IP address range beginning', type=validate_ip, metavar='IP', required=True)
50     # Start command parser
51     parser_start = subparsers.add_parser('start', help='Start instances')
52     parser_start.add_argument('--count', help='Instance count to start', type=int, metavar='INT', default=1)
53     # Stop command parser
54     parser_stop = subparsers.add_parser('stop', help='Stop instances')
55     parser_stop.add_argument('--count', help='Instance count to stop', type=int, metavar='INT', default=1)
56     # Trigger command parser
57     parser_trigger = subparsers.add_parser('trigger', help='Trigger one single VES event from each simulator')
58     parser_trigger.add_argument('--count', help='Instance count to trigger', type=int, metavar='INT', default=1)
59     # Trigger-custom command parser
60     parser_triggerstart = subparsers.add_parser('trigger_custom', help='Trigger one single VES event from specific simulators')
61     parser_triggerstart.add_argument('--triggerstart', help='First simulator id to trigger', type=int,
62                                      metavar='INT', required=True)
63     parser_triggerstart.add_argument('--triggerend', help='Last simulator id to trigger', type=int,
64                                      metavar='INT', required=True)
65     # Status command parser
66     parser_status = subparsers.add_parser('status', help='Status')
67     parser_status.add_argument('--count', help='Instance count to show status for', type=int, metavar='INT', default=1)
68     # Clean command parser
69     subparsers.add_parser('clean', help='Clean work-dirs')
70     # General options parser
71     parser.add_argument('--verbose', help='Verbosity level', choices=['info', 'debug'],
72                         type=str, default='info')
73     return parser
74
75 class MassPnfSim:
76
77     # MassPnfSim class actions decorator
78     class _MassPnfSim_Decorators:
79
80         @staticmethod
81         def do_action(action_string, cmd):
82             def action_decorator(method):
83                 def action_wrap(self):
84                     cmd_local = cmd
85                     # Append instance # if action is 'stop'
86                     if method.__name__ == 'stop':
87                         cmd_local += " {}"
88                     # Alter looping range if action is 'tigger_custom'
89                     if method.__name__ == 'trigger_custom':
90                         iter_range = [self.args.triggerstart, self.args.triggerend+1]
91                     else:
92                         iter_range = [self.args.count]
93                     method(self)
94                     for i in range(*iter_range):
95                         self.logger.info(f'{action_string} {self.sim_dirname_pattern}{i} instance:')
96                         self._run_cmd(cmd_local.format(i), f"{self.sim_dirname_pattern}{i}")
97                 return action_wrap
98             return action_decorator
99
100     log_lvl = logging.INFO
101
102     def __init__(self, args):
103         self.args = args
104         self.logger = logging.getLogger(__name__)
105         self.logger.setLevel(self.log_lvl)
106         self.sim_dirname_pattern = "pnf-sim-lw-"
107         self.mvn_build_cmd = 'mvn clean package docker:build -Dcheckstyle.skip'
108
109     def _run_cmd(self, cmd, dir_context='.'):
110         if self.args.verbose == 'debug':
111             cmd='bash -x ' + cmd
112         old_pwd = getcwd()
113         try:
114             chdir(dir_context)
115             subprocess.run(cmd, check=True, shell=True)
116             chdir(old_pwd)
117         except FileNotFoundError:
118             self.logger.error(f"Directory {dir_context} not found")
119         except subprocess.CalledProcessError as e:
120             exit(e.returncode)
121
122     def bootstrap(self):
123         self.logger.info("Bootstrapping PNF instances")
124
125         start_port = 2000
126         ftps_pasv_port_start = 8000
127         ftps_pasv_port_num_of_ports = 10
128
129         ftps_pasv_port_end = ftps_pasv_port_start + ftps_pasv_port_num_of_ports
130
131         for i in range(self.args.count):
132             self.logger.info(f"PNF simulator instance: {i}")
133
134             # The IP ranges are in distance of 16 compared to each other.
135             # This is matching the /28 subnet mask used in the dockerfile inside.
136             instance_ip_offset = i * 16
137             ip_properties = [
138                       'subnet',
139                       'gw',
140                       'PnfSim',
141                       'ftps',
142                       'sftp'
143                     ]
144
145             ip_offset = 0
146             ip = {}
147             for prop in ip_properties:
148                 ip.update({prop: str(self.args.ipstart + ip_offset + instance_ip_offset)})
149                 ip_offset += 1
150
151             self.logger.debug(f'Instance #{i} properties:\n {dumps(ip, indent=4)}')
152
153             PortSftp = start_port + 1
154             PortFtps = start_port + 2
155             start_port += 2
156
157             self.logger.info(f'\tCreating {self.sim_dirname_pattern}{i}')
158             try:
159                 copytree('pnf-sim-lightweight', f'{self.sim_dirname_pattern}{i}')
160             except FileExistsError:
161                 self.logger.error(f'Directory {self.sim_dirname_pattern}{i} already exists, cannot overwrite.')
162                 exit(1)
163
164             composercmd = " ".join([
165                     "./simulator.sh compose",
166                     ip['gw'],
167                     ip['subnet'],
168                     str(i),
169                     self.args.urlves,
170                     ip['PnfSim'],
171                     str(self.args.ipfileserver),
172                     self.args.typefileserver,
173                     str(PortSftp),
174                     str(PortFtps),
175                     ip['ftps'],
176                     ip['sftp'],
177                     str(ftps_pasv_port_start),
178                     str(ftps_pasv_port_end)
179                 ])
180             self.logger.debug(f"Script cmdline: {composercmd}")
181             self.logger.info(f"\tCreating instance #{i} configuration ")
182             self._run_cmd(composercmd, f"{self.sim_dirname_pattern}{i}")
183
184             ftps_pasv_port_start += ftps_pasv_port_num_of_ports + 1
185             ftps_pasv_port_end += ftps_pasv_port_num_of_ports + 1
186
187             self.logger.info(f'Done setting up instance #{i}')
188
189     def build(self):
190         self.logger.info("Building simulator image")
191         if path.isfile('pnf-sim-lightweight/pom.xml'):
192             self._run_cmd(self.mvn_build_cmd, 'pnf-sim-lightweight')
193         else:
194             self.logger.error('POM file was not found, Maven cannot run')
195             exit(1)
196
197     def clean(self):
198         self.logger.info('Cleaning simulators workdirs')
199         self._run_cmd(f"rm -rf {self.sim_dirname_pattern}*")
200
201     @_MassPnfSim_Decorators.do_action('Starting', './simulator.sh start')
202     def start(self):
203         pass
204
205     @_MassPnfSim_Decorators.do_action('Getting', './simulator.sh status')
206     def status(self):
207         pass
208
209     @_MassPnfSim_Decorators.do_action('Stopping', './simulator.sh stop')
210     def stop(self):
211         pass
212
213     @_MassPnfSim_Decorators.do_action('Triggering', './simulator.sh trigger-simulator')
214     def trigger(self):
215         self.logger.info("Triggering VES sending:")
216
217     @_MassPnfSim_Decorators.do_action('Triggering', './simulator.sh trigger-simulator')
218     def trigger_custom(self):
219         self.logger.info("Triggering VES sending by a range of simulators:")