Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
log.info("Webserver not yet supported, please run as seperate module")
if options.file:
with open(options.file, "r") as fh:
input_string = fh.read()
timestamp = os.stat(options.file).st_mtime
elif options.stdin:
input_string = sys.stdin
now = datetime.now()
timestamp = now.strftime("%Y%m%d_%H%M%S_%f")
elif options.grid:
input_string = ""
now = datetime.now()
timestamp = now.strftime("%Y%m%d_%H%M%S_%f")
else:
log.info("No input file specified. Exiting")
return
try:
workflow.manage_network(input_string, timestamp,
grid=options.grid, **build_options)
except Exception, err:
log.error(
"Error generating network configurations: %s" % err)
log.debug("Error generating network configurations", exc_info=True)
if settings['General']['stack_trace']:
print traceback.print_exc()
sys.exit("Unable to build configurations.")
# TODO: work out why build_options is being clobbered for monitor mode
build_options['monitor'] = options.monitor or settings['General'][
'monitor']
def load(input_graph_string, defaults = True):
# TODO: look at XML header for file type
import autonetkit.load.graphml as graphml
import autonetkit.load.load_json as load_json
try:
input_graph = graphml.load_graphml(input_graph_string, defaults=defaults)
except autonetkit.exception.AnkIncorrectFileFormat:
try:
input_graph = load_json.load_json(input_graph_string, defaults=defaults)
except (ValueError, autonetkit.exception.AnkIncorrectFileFormat):
# try a different reader
try:
from autonetkit_cisco import load as cisco_load
except ImportError, error:
log.debug("Unable to load autonetkit_cisco %s", error)
return # module not present (development module)
else:
input_graph = cisco_load.load(input_graph_string)
# add local deployment host
SETTINGS['General']['deploy'] = True
SETTINGS['Deploy Hosts']['internal'] = {
'VIRL': {
'deploy': True,
},
}
return input_graph
try:
# test if can import, if not present will fail and not add to template
# path
import autonetkit_cisco
except ImportError:
pass
else:
import autonetkit_cisco.version
version_banner = autonetkit_cisco.version.banner()
log.info("%s" % version_banner)
log.info("AutoNetkit %s" % ANK_VERSION)
if options.target == "cisco":
# output target is Cisco
log.info("Setting output target as Cisco")
settings['Graphml']['Node Defaults']['platform'] = "cisco"
settings['Graphml']['Node Defaults']['host'] = "internal"
#settings['Graphml']['Node Defaults']['syntax'] = "ios"
settings['Graphml']['Node Defaults']['syntax'] = options.syntax
settings['JSON']['Node Defaults']['syntax'] = options.syntax
settings['Compiler']['Cisco']['to memory'] = 1
settings['General']['deploy'] = 1
settings['Deploy Hosts']['internal'] = {'cisco':
{'deploy': 1}}
if options.debug or settings['General']['debug']:
# TODO: fix this
import logging
logger = logging.getLogger("ANK")
logger.setLevel(logging.DEBUG)
if server.device_subtype in ("SNAT", "FLAT"):
continue # Don't warn on ASN for NAT elements
l3_neighbors = list(server['layer3'].neighbors())
l3_neighbor_asns = set(n.asn for n in l3_neighbors)
if server.asn not in l3_neighbor_asns:
neighs_with_asn = ["%s: AS %s" % (n, n.asn)
for n in l3_neighbors]
# tuples for warning message
server.log.warning("Server does not belong to same ASN "
"as neighbors %s" % (neighs_with_asn))
if len(l3_neighbors) == 1:
# single ASN of neighbor -> auto correct
if server['input'].default_asn:
neigh_asn = l3_neighbor_asns.pop()
log.warning("Updating server %s AS from %s"
" to %s", server, server.asn, neigh_asn)
server.asn = neigh_asn
else:
log.info("Server %s ASN %s explictly set by user, "
"not auto-correcting", server, server.asn)
if global_infra_block is not None:
mismatched_interfaces += [i for i in connected_interfaces
if i.ip_address not in global_infra_block]
if len(cd_subnets) == 0:
log.warning(
"Collision domain %s is not connected to any nodes" % coll_dom)
continue
try:
assert len(set(cd_subnets)) == 1
except AssertionError:
mismatch_subnets = '; '.join('%s: %s/%s' % (i,
i.subnet.network, i.prefixlen) for i in
connected_interfaces)
log.warning('Non matching subnets from collision domain %s: %s'
% (coll_dom, mismatch_subnets))
else:
coll_dom.subnet = cd_subnets[0] # take first entry
# apply to remote interfaces
for edge in coll_dom.edges():
edge.dst_int.subnet = coll_dom.subnet
# also need to form aggregated IP blocks (used for e.g. routing prefix
# advertisement)
# import autonetkit
# autonetkit.update_vis(anm)
if len(mismatched_interfaces):
log.warning("IPv4 Infrastructure IPs %s are not in global "
"loopback allocation block %s"
options.debug = True
options.syntax = syntax
#Since input is coming from poap we can assume that it will
#be a dictionary. Otherwise it will be a file.
#options.file = 'temp.json'
options.file = 'dictionary'
options.dictionary = ank_data
try:
dst_folder = console_script.main(options)
log.debug("json_converter.py...call to ank completed.")
log.debug(str(dst_folder))
return dst_folder
except:
log.error("json_converter.py...call to ank failed.")
return dst_folder
def lab_topology(self):
#TODO: replace name/label and use attribute from subgraph
lab_topology = self.nidb.topology[self.host]
lab_topology.render_template = "templates/netkit_lab_conf.mako"
lab_topology.render_dst_folder = "rendered/%s/%s" % (self.host, "netkit")
lab_topology.render_dst_file = "lab.conf"
lab_topology.description = "AutoNetkit Lab"
lab_topology.author = "AutoNetkit"
lab_topology.web = "www.autonetkit.org"
host_nodes = list(self.nidb.nodes(host = self.host, platform = "netkit"))
if not len(host_nodes):
log.debug("No Netkit hosts for %s" % self.host)
#TODO: make so can return here
#return
# also need collision domains for this host
cd_nodes = self.nidb.nodes("collision_domain", host = self.host) # add in collision domains for this host (don't have platform)
#TODO: need to allocate cds to a platform
host_nodes += cd_nodes
subgraph = self.nidb.subgraph(host_nodes, self.host)
#TODO: sort this numerically, not just by string
lab_topology.machines = " ".join(alpha_sort(naming.network_hostname(phy_node)
for phy_node in subgraph.nodes("is_l3device")))
G_ip = self.anm['ip']
lab_topology.config_items = []
for node in sorted(subgraph.nodes("is_l3device")):
for edge in node.edges():
def manual_ipv4_loopback_allocation(anm):
"""Applies manual IPv4 allocation"""
import netaddr
g_ipv4 = anm['ipv4']
g_in = anm['input']
for l3_device in g_ipv4.l3devices():
try:
l3_device.loopback = IPAddress(l3_device['input'].loopback_v4)
except netaddr.AddrFormatError:
log.debug("Unable to parse IP address %s on %s",
l3_device['input'].loopback_v6, l3_device)
try:
loopback_subnet = g_in.data.ipv4_loopback_subnet
loopback_prefix = g_in.data.ipv4_loopback_prefix
loopback_block = sn_preflen_to_network(loopback_subnet,
loopback_prefix)
except Exception, e:
log.info("Unable to parse specified ipv4 loopback subnets %s/%s")
else:
mismatched_nodes = [n for n in g_ipv4.l3devices()
if n.loopback and n.loopback not in loopback_block]
if len(mismatched_nodes):
log.warning("IPv4 loopbacks set on nodes %s are not in global "
"loopback allocation block %s"
% (sorted(mismatched_nodes), loopback_block))
def compile(self):
log.info("Compiling Netkit for %s" % self.host)
G_phy = self.anm['phy']
quagga_compiler = QuaggaCompiler(self.nidb, self.anm)
#TODO: this should be all l3 devices not just routers
for phy_node in G_phy.nodes('is_router', host = self.host, syntax='quagga'):
folder_name = naming.network_hostname(phy_node)
nidb_node = self.nidb.node(phy_node)
nidb_node.render.base = "templates/quagga"
nidb_node.render.template = "templates/netkit_startup.mako"
nidb_node.render.dst_folder = "rendered/%s/%s" % (self.host, "netkit")
nidb_node.render.base_dst_folder = "rendered/%s/%s/%s" % (self.host, "netkit", folder_name)
nidb_node.render.dst_file = "%s.startup" % folder_name
# allocate zebra information
nidb_node.zebra.password = "1234"
hostname = folder_name
if hostname[0] in string.digits:
def mpls_te(anm):
g_in = anm['input']
g_phy = anm['phy']
g_l3 = anm['layer3']
# add regardless, so allows quick check of node in anm['mpls_te'] in
# compilers
g_mpls_te = anm.add_overlay('mpls_te')
if not any(True for n in g_in.routers() if n.mpls_te_enabled):
log.debug('No nodes with mpls_te_enabled set')
return
# te head end set if here
g_mpls_te.add_nodes_from(g_in.routers())
# build up edge list sequentially, to provide meaningful messages for
# multipoint links
multipoint_edges = [e for e in g_l3.edges() if e.multipoint]
if len(multipoint_edges):
log.info('Excluding multi-point edges from MPLS TE topology: %s'
% ', '.join(str(e) for e in multipoint_edges))
edges_to_add = set(g_l3.edges()) - set(multipoint_edges)
g_mpls_te.add_edges_from(edges_to_add)