Skip to content
Snippets Groups Projects
Commit a59f105e authored by Attila Farkas's avatar Attila Farkas
Browse files

fix style errors

parent 25eca9ac
No related branches found
No related tags found
1 merge request!2Resolve "Add routing"
#!/usr/bin/python3 #!/usr/bin/python3
""" A script that generates a Vagrantfile from yaml. """
import sys import sys
import jinja2 import jinja2
from modules.device_creator import create_devices from modules.device_creator import create_devices
if (len(sys.argv) != 2): if len(sys.argv) != 2:
print ("Error: Expecting 1 argument (yml file).") print("Error: Expecting 1 argument (yml file).")
sys.exit(); sys.exit()
# A structure with formatted commands for each device # A structure with formatted commands for each device
devices = create_devices(str(sys.argv[1])) DEVICES = create_devices(str(sys.argv[1]))
# Generating output via Jinja2 # Generating output via Jinja2
templateLoader = jinja2.FileSystemLoader(searchpath="templates") TEMPLATE_LOADER = jinja2.FileSystemLoader(searchpath="templates")
templateEnv = jinja2.Environment(loader=templateLoader, trim_blocks=True) TEMPLATE_ENV = jinja2.Environment(loader=TEMPLATE_LOADER, trim_blocks=True)
baseTemplate = templateEnv.get_template("base") BASE_TEMPLATE = TEMPLATE_ENV.get_template("base")
output = baseTemplate.render(devices = devices) OUTPUT = BASE_TEMPLATE.render(devices=DEVICES)
print (output)
print(OUTPUT)
""" This module handles the creation of simple vagrant commands from yaml
attributes. """
def _format_and_add(key, value, mappings, device_definition): def _format_and_add(key, value, mappings, device_definition):
""" Formats and adds the definition of a simple attribute. """ """ Formats and adds the definition of a simple attribute. """
if (key in mappings['string']): if key in mappings['string']:
device_definition.append( device_definition.append(
'device.' + mappings['string'][key] 'device.' + mappings['string'][key]
+ ' = \"' + str(value) + '\"') + ' = \"' + str(value) + '\"')
elif (key in mappings['integer']): elif key in mappings['integer']:
device_definition.append( device_definition.append(
'device.' + mappings['integer'][key] 'device.' + mappings['integer'][key]
+ ' = ' + str(value)) + ' = ' + str(value))
elif (key in mappings['boolean']): elif key in mappings['boolean']:
device_definition.append( device_definition.append(
'device.' + mappings['boolean'][key] 'device.' + mappings['boolean'][key]
+ ' = ' + str(value).lower()) + ' = ' + str(value).lower())
def add_simple_commands(device, mappings, device_definition): def add_simple_commands(device, mappings, device_definition):
""" Adds definitions of string, integer and boolean vagrant attributes. """ """ Adds definitions of string, integer and boolean vagrant attributes. """
for key, value in device.items(): for key, value in device.items():
if (key != "name"): if key != "name":
_format_and_add(key, value, mappings, device_definition) _format_and_add(key, value, mappings, device_definition)
""" This package handles file import and creation of an input structure for
Jinja2 """
import yaml import yaml
from .attribute_formatter import add_simple_commands from modules.attribute_formatter import add_simple_commands
from .provider import add_prov_attributes, add_router_specification from modules.provider import add_prov_attributes, add_router_specification
from .network_parser import add_networks, add_router_ip from modules.network_parser import add_networks, add_router_ip
def _open_yml(yml_file_name): def _open_yml(yml_file_name):
...@@ -12,7 +15,7 @@ def _open_yml(yml_file_name): ...@@ -12,7 +15,7 @@ def _open_yml(yml_file_name):
yml = yaml.safe_load(ymlfile) yml = yaml.safe_load(ymlfile)
return yml return yml
except IOError: except IOError:
print ("Error: file does not exist.") print("Error: file does not exist.")
def _open_mappings(): def _open_mappings():
...@@ -22,7 +25,7 @@ def _open_mappings(): ...@@ -22,7 +25,7 @@ def _open_mappings():
mappings = yaml.safe_load(mapping_file) mappings = yaml.safe_load(mapping_file)
return mappings return mappings
except IOError: except IOError:
print ("Error: cannot find mappings.") print("Error: cannot find mappings.")
def _open_flavors(): def _open_flavors():
...@@ -32,7 +35,7 @@ def _open_flavors(): ...@@ -32,7 +35,7 @@ def _open_flavors():
flavors = yaml.safe_load(flavors_file) flavors = yaml.safe_load(flavors_file)
return flavors return flavors
except IOError: except IOError:
print ("Error: cannot find the list of flavors.") print("Error: cannot find the list of flavors.")
def _create_hosts(yml, mappings, flavors): def _create_hosts(yml, mappings, flavors):
...@@ -41,16 +44,16 @@ def _create_hosts(yml, mappings, flavors): ...@@ -41,16 +44,16 @@ def _create_hosts(yml, mappings, flavors):
for host in yml['hosts']: for host in yml['hosts']:
host_definitions[host['name']] = [] host_definitions[host['name']] = []
add_simple_commands(host, mappings, host_definitions[host['name']]) add_simple_commands(host, mappings, host_definitions[host['name']])
add_networks(host["name"], yml, host_definitions) add_networks(host["name"], yml, host_definitions)
add_prov_attributes(host, flavors add_prov_attributes(
, mappings['need_provider'], host_definitions) host, flavors, mappings['need_provider'], host_definitions)
return host_definitions return host_definitions
def _create_routers(yml, mappings): def _create_routers(yml):
""" Creates a dictionary with formatted definition of each router. """ """ Creates a dictionary with formatted definition of each router. """
router_definitions = {} router_definitions = {}
...@@ -69,6 +72,6 @@ def create_devices(yml_file_name): ...@@ -69,6 +72,6 @@ def create_devices(yml_file_name):
mappings = _open_mappings() mappings = _open_mappings()
flavors = _open_flavors() flavors = _open_flavors()
return dict(**_create_hosts(yml, mappings, flavors) return {
, **_create_routers(yml, mappings)) **_create_hosts(yml, mappings, flavors),
**_create_routers(yml)}
""" This module handles network creation. """
import sys
def _find_ip(hostname, mappings, device_type): def _find_ip(hostname, mappings, device_type):
""" Finds the ip address of a device. """ """ Finds the ip address of a device. """
for mapping in mappings: for mapping in mappings:
if ((device_type == 'host' if device_type == 'host':
and mapping['host'] and mapping['host'] == hostname) if mapping['host'] and mapping['host'] == hostname:
or (device_type == 'router' return mapping['ip']
and mapping['router'] and mapping['router'] == hostname)): elif device_type == 'router':
return mapping['ip'] if mapping['router'] and mapping['router'] == hostname:
return mapping['ip']
return None
def _add_ip(hostname, mappings, device_type, definitions): def _add_ip(hostname, mappings, device_type, definitions):
""" Adds a formatted ip address to a device definition. """ """ Adds a formatted ip address to a device definition. """
ip_address = _find_ip(hostname, mappings, device_type)
if not ip_address:
print("Cannot find network mapping.")
sys.exit()
definitions[hostname].append( definitions[hostname].append(
"device.vm.network :private_network, ip: \"" "device.vm.network :private_network, ip: \""
+ str(_find_ip(hostname, mappings, device_type)) + '\"') + ip_address + '\"')
def _add_netmask(hostname, my_network, networks, definitions): def _add_netmask(hostname, my_network, networks, definitions):
""" Adds netmask to the end of a formatted ip definition. """ """ Adds netmask to the end of a formatted ip definition. """
for network in networks: for network in networks:
if (network['name'] == my_network): if network['name'] == my_network:
address, mask = network['cidr'].split('/') address, mask = network['cidr'].split('/')
definitions[hostname][-1] += (', netmask: \"' + mask + "\"") definitions[hostname][-1] += (', netmask: \"' + mask + "\"")
...@@ -29,25 +43,23 @@ def _add_netmask(hostname, my_network, networks, definitions): ...@@ -29,25 +43,23 @@ def _add_netmask(hostname, my_network, networks, definitions):
def add_networks(hostname, yml, definitions): def add_networks(hostname, yml, definitions):
""" Adds ip address and natmask to a host. """ """ Adds ip address and natmask to a host. """
if (not yml['net_mappings']): if not yml['net_mappings']:
return return
for mapping in yml['net_mappings']: for mapping in yml['net_mappings']:
if (mapping['host'] == hostname): if mapping['host'] == hostname:
_add_ip(hostname, yml['net_mappings'], 'host', definitions) _add_ip(hostname, yml['net_mappings'], 'host', definitions)
if (yml['networks']): if yml['networks']:
_add_netmask( _add_netmask(
hostname, mapping['network'] hostname, mapping['network'], yml['networks'], definitions)
, yml['networks'], definitions)
def add_router_ip(routername, yml, definitions): def add_router_ip(routername, yml, definitions):
""" Adds ip address to a router. """ """ Adds ip address to a router. """
if (not yml['router_mappings']): if not yml['router_mappings']:
return return
for mapping in yml['router_mappings']: for mapping in yml['router_mappings']:
if (mapping['router'] == routername): if mapping['router'] == routername:
_add_ip(routername, yml['router_mappings'], 'router', definitions) _add_ip(routername, yml['router_mappings'], 'router', definitions)
""" This module handles VirtualBox attributes. """
def _print_flavor(host, flavors, provider_attributes, definitions): def _print_flavor(host, flavors, provider_attributes, definitions):
""" Formats and add a flavor for a device. """ """ Formats and add a flavor for a device. """
if ('memory' not in host): if 'memory' not in host:
definitions[host['name']].append(' vb.' definitions[host['name']].append(
+ provider_attributes['memory'] + ' = ' ' vb.' + provider_attributes['memory'] + ' = '
+ str(flavors[host['flavor']]['memory'])) + str(flavors[host['flavor']]['memory']))
if ('cpus' not in host): if 'cpus' not in host:
definitions[host['name']].append(' vb.' definitions[host['name']].append(
+ provider_attributes['cpus'] + ' = ' ' vb.' + provider_attributes['cpus'] + ' = '
+ str(flavors[host['flavor']]['cores'])) + str(flavors[host['flavor']]['cores']))
def _add_params(host, flavors, provider_attributes, definitions): def _add_params(host, flavors, provider_attributes, definitions):
""" Formats and adds simple provision attributes. """ """ Formats and adds simple provision attributes. """
if ('memory' in host): if 'memory' in host:
definitions[host['name']].append(' vb.' definitions[host['name']].append(
+ provider_attributes['memory'] + ' = ' ' vb.' + provider_attributes['memory'] + ' = '
+ str(host['memory'])) + str(host['memory']))
if ('cpus' in host): if 'cpus' in host:
definitions[host['name']].append(' vb.' definitions[host['name']].append(
+ provider_attributes['cpus'] + ' = ' ' vb.' + provider_attributes['cpus'] + ' = '
+ str(host['cpus'])) + str(host['cpus']))
if ('flavor' in host and host['flavor'] in flavors): if 'flavor' in host and host['flavor'] in flavors:
_print_flavor(host, flavors, provider_attributes, definitions) _print_flavor(host, flavors, provider_attributes, definitions)
...@@ -30,7 +33,7 @@ def _need_provider(host, provider_attributes): ...@@ -30,7 +33,7 @@ def _need_provider(host, provider_attributes):
""" Checks if provision attributes are present. """ """ Checks if provision attributes are present. """
for attribute in provider_attributes: for attribute in provider_attributes:
if (attribute in host): if attribute in host:
return True return True
return False return False
...@@ -38,22 +41,22 @@ def _need_provider(host, provider_attributes): ...@@ -38,22 +41,22 @@ def _need_provider(host, provider_attributes):
def add_prov_attributes(host, flavors, provider_attributes, definitions): def add_prov_attributes(host, flavors, provider_attributes, definitions):
""" Adds provider attributes. """ """ Adds provider attributes. """
if (_need_provider(host, provider_attributes)): if _need_provider(host, provider_attributes):
definitions[host['name']].append( definitions[host['name']].append(
"device.vm.provider \"virtualbox\" do |vb|") "device.vm.provider \"virtualbox\" do |vb|")
_add_params(host, flavors, provider_attributes, definitions) _add_params(host, flavors, provider_attributes, definitions)
definitions[host['name']].append("end") definitions[host['name']].append("end")
def add_router_specification(router, definitions): def add_router_specification(router, definitions):
""" Adds the default specification for a router. """ """ Adds the default specification for a router. """
ROUTER_BOX = "generic/debian10" ROUTER_BOX = "generic/debian10"
ROUTER_MEMORY = 256 ROUTER_MEMORY = 256
definitions[router['name']].append("device.vm.box = \"" + ROUTER_BOX + "\"")
definitions[router['name']].append( definitions[router['name']].append(
"device.vm.provider \"virtualbox\" do |vb|") "device.vm.box = \"" + ROUTER_BOX + "\"")
definitions[router['name']].append(
"device.vm.provider \"virtualbox\" do |vb|")
definitions[router['name']].append(" vb.memory = " + str(ROUTER_MEMORY)) definitions[router['name']].append(" vb.memory = " + str(ROUTER_MEMORY))
definitions[router['name']].append("end") definitions[router['name']].append("end")
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment