7 from os import chdir, getcwd, path
8 from shutil import copytree
10 from requests import get
11 from requests.exceptions import MissingSchema, InvalidSchema, InvalidURL, ConnectionError, ConnectTimeout
13 def validate_url(url):
14 '''Helper function to perform --urlves input param validation'''
15 logger = logging.getLogger("urllib3")
16 logger.setLevel(logging.WARNING)
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):
26 '''Helper function to validate input param is a vaild IP address'''
28 ip_valid = ipaddress.ip_address(ip)
30 raise argparse.ArgumentTypeError(f'{ip} is not a valid IP address')
35 '''Process input arguments'''
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)
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')
77 # MassPnfSim class actions decorator
78 class _MassPnfSim_Decorators:
81 def do_action(action_string, cmd):
82 def action_decorator(method):
83 def action_wrap(self):
85 # Append instance # if action is 'stop'
86 if method.__name__ == 'stop':
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]
92 iter_range = [self.args.count]
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}")
98 return action_decorator
100 log_lvl = logging.INFO
102 def __init__(self, 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'
109 def _run_cmd(self, cmd, dir_context='.'):
110 if self.args.verbose == 'debug':
115 subprocess.run(cmd, check=True, shell=True)
117 except FileNotFoundError:
118 self.logger.error(f"Directory {dir_context} not found")
119 except subprocess.CalledProcessError as e:
123 self.logger.info("Bootstrapping PNF instances")
126 ftps_pasv_port_start = 8000
127 ftps_pasv_port_num_of_ports = 10
129 ftps_pasv_port_end = ftps_pasv_port_start + ftps_pasv_port_num_of_ports
131 for i in range(self.args.count):
132 self.logger.info(f"PNF simulator instance: {i}")
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
147 for prop in ip_properties:
148 ip.update({prop: str(self.args.ipstart + ip_offset + instance_ip_offset)})
151 self.logger.debug(f'Instance #{i} properties:\n {dumps(ip, indent=4)}')
153 PortSftp = start_port + 1
154 PortFtps = start_port + 2
157 self.logger.info(f'\tCreating {self.sim_dirname_pattern}{i}')
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.')
164 composercmd = " ".join([
165 "./simulator.sh compose",
171 str(self.args.ipfileserver),
172 self.args.typefileserver,
177 str(ftps_pasv_port_start),
178 str(ftps_pasv_port_end)
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}")
184 ftps_pasv_port_start += ftps_pasv_port_num_of_ports + 1
185 ftps_pasv_port_end += ftps_pasv_port_num_of_ports + 1
187 self.logger.info(f'Done setting up instance #{i}')
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')
194 self.logger.error('POM file was not found, Maven cannot run')
198 self.logger.info('Cleaning simulators workdirs')
199 self._run_cmd(f"rm -rf {self.sim_dirname_pattern}*")
201 @_MassPnfSim_Decorators.do_action('Starting', './simulator.sh start')
205 @_MassPnfSim_Decorators.do_action('Getting', './simulator.sh status')
209 @_MassPnfSim_Decorators.do_action('Stopping', './simulator.sh stop')
213 @_MassPnfSim_Decorators.do_action('Triggering', './simulator.sh trigger-simulator')
215 self.logger.info("Triggering VES sending:")
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:")