Merge pull request #470 from coreemu/cleanup/variable-names

refactor variables to use numbers instead of letters
This commit is contained in:
bharnden 2020-06-13 21:27:41 -07:00 committed by GitHub
commit 0bcf7c1d83
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
50 changed files with 1057 additions and 1213 deletions

View file

@ -609,30 +609,30 @@ class CoreGrpcClient:
def add_link( def add_link(
self, self,
session_id: int, session_id: int,
node_one_id: int, node1_id: int,
node_two_id: int, node2_id: int,
interface_one: core_pb2.Interface = None, interface1: core_pb2.Interface = None,
interface_two: core_pb2.Interface = None, interface2: core_pb2.Interface = None,
options: core_pb2.LinkOptions = None, options: core_pb2.LinkOptions = None,
) -> core_pb2.AddLinkResponse: ) -> core_pb2.AddLinkResponse:
""" """
Add a link between nodes. Add a link between nodes.
:param session_id: session id :param session_id: session id
:param node_one_id: node one id :param node1_id: node one id
:param node_two_id: node two id :param node2_id: node two id
:param interface_one: node one interface data :param interface1: node one interface data
:param interface_two: node two interface data :param interface2: node two interface data
:param options: options for link (jitter, bandwidth, etc) :param options: options for link (jitter, bandwidth, etc)
:return: response with result of success or failure :return: response with result of success or failure
:raises grpc.RpcError: when session or one of the nodes don't exist :raises grpc.RpcError: when session or one of the nodes don't exist
""" """
link = core_pb2.Link( link = core_pb2.Link(
node_one_id=node_one_id, node1_id=node1_id,
node_two_id=node_two_id, node2_id=node2_id,
type=core_pb2.LinkType.WIRED, type=core_pb2.LinkType.WIRED,
interface_one=interface_one, interface1=interface1,
interface_two=interface_two, interface2=interface2,
options=options, options=options,
) )
request = core_pb2.AddLinkRequest(session_id=session_id, link=link) request = core_pb2.AddLinkRequest(session_id=session_id, link=link)
@ -641,59 +641,59 @@ class CoreGrpcClient:
def edit_link( def edit_link(
self, self,
session_id: int, session_id: int,
node_one_id: int, node1_id: int,
node_two_id: int, node2_id: int,
options: core_pb2.LinkOptions, options: core_pb2.LinkOptions,
interface_one_id: int = None, interface1_id: int = None,
interface_two_id: int = None, interface2_id: int = None,
) -> core_pb2.EditLinkResponse: ) -> core_pb2.EditLinkResponse:
""" """
Edit a link between nodes. Edit a link between nodes.
:param session_id: session id :param session_id: session id
:param node_one_id: node one id :param node1_id: node one id
:param node_two_id: node two id :param node2_id: node two id
:param options: options for link (jitter, bandwidth, etc) :param options: options for link (jitter, bandwidth, etc)
:param interface_one_id: node one interface id :param interface1_id: node one interface id
:param interface_two_id: node two interface id :param interface2_id: node two interface id
:return: response with result of success or failure :return: response with result of success or failure
:raises grpc.RpcError: when session or one of the nodes don't exist :raises grpc.RpcError: when session or one of the nodes don't exist
""" """
request = core_pb2.EditLinkRequest( request = core_pb2.EditLinkRequest(
session_id=session_id, session_id=session_id,
node_one_id=node_one_id, node1_id=node1_id,
node_two_id=node_two_id, node2_id=node2_id,
options=options, options=options,
interface_one_id=interface_one_id, interface1_id=interface1_id,
interface_two_id=interface_two_id, interface2_id=interface2_id,
) )
return self.stub.EditLink(request) return self.stub.EditLink(request)
def delete_link( def delete_link(
self, self,
session_id: int, session_id: int,
node_one_id: int, node1_id: int,
node_two_id: int, node2_id: int,
interface_one_id: int = None, interface1_id: int = None,
interface_two_id: int = None, interface2_id: int = None,
) -> core_pb2.DeleteLinkResponse: ) -> core_pb2.DeleteLinkResponse:
""" """
Delete a link between nodes. Delete a link between nodes.
:param session_id: session id :param session_id: session id
:param node_one_id: node one id :param node1_id: node one id
:param node_two_id: node two id :param node2_id: node two id
:param interface_one_id: node one interface id :param interface1_id: node one interface id
:param interface_two_id: node two interface id :param interface2_id: node two interface id
:return: response with result of success or failure :return: response with result of success or failure
:raises grpc.RpcError: when session doesn't exist :raises grpc.RpcError: when session doesn't exist
""" """
request = core_pb2.DeleteLinkRequest( request = core_pb2.DeleteLinkRequest(
session_id=session_id, session_id=session_id,
node_one_id=node_one_id, node1_id=node1_id,
node_two_id=node_two_id, node2_id=node2_id,
interface_one_id=interface_one_id, interface1_id=interface1_id,
interface_two_id=interface_two_id, interface2_id=interface2_id,
) )
return self.stub.DeleteLink(request) return self.stub.DeleteLink(request)
@ -1111,20 +1111,20 @@ class CoreGrpcClient:
return self.stub.OpenXml(request) return self.stub.OpenXml(request)
def emane_link( def emane_link(
self, session_id: int, nem_one: int, nem_two: int, linked: bool self, session_id: int, nem1: int, nem2: int, linked: bool
) -> EmaneLinkResponse: ) -> EmaneLinkResponse:
""" """
Helps broadcast wireless link/unlink between EMANE nodes. Helps broadcast wireless link/unlink between EMANE nodes.
:param session_id: session to emane link :param session_id: session to emane link
:param nem_one: first nem for emane link :param nem1: first nem for emane link
:param nem_two: second nem for emane link :param nem2: second nem for emane link
:param linked: True to link, False to unlink :param linked: True to link, False to unlink
:return: get emane link response :return: get emane link response
:raises grpc.RpcError: when session or nodes related to nems do not exist :raises grpc.RpcError: when session or nodes related to nems do not exist
""" """
request = EmaneLinkRequest( request = EmaneLinkRequest(
session_id=session_id, nem_one=nem_one, nem_two=nem_two, linked=linked session_id=session_id, nem1=nem1, nem2=nem2, linked=linked
) )
return self.stub.EmaneLink(request) return self.stub.EmaneLink(request)
@ -1243,24 +1243,24 @@ class CoreGrpcClient:
return self.stub.ExecuteScript(request) return self.stub.ExecuteScript(request)
def wlan_link( def wlan_link(
self, session_id: int, wlan: int, node_one: int, node_two: int, linked: bool self, session_id: int, wlan_id: int, node1_id: int, node2_id: int, linked: bool
) -> WlanLinkResponse: ) -> WlanLinkResponse:
""" """
Links/unlinks nodes on the same WLAN. Links/unlinks nodes on the same WLAN.
:param session_id: session id containing wlan and nodes :param session_id: session id containing wlan and nodes
:param wlan: wlan nodes must belong to :param wlan_id: wlan nodes must belong to
:param node_one: first node of pair to link/unlink :param node1_id: first node of pair to link/unlink
:param node_two: second node of pair to link/unlin :param node2_id: second node of pair to link/unlin
:param linked: True to link, False to unlink :param linked: True to link, False to unlink
:return: wlan link response :return: wlan link response
:raises grpc.RpcError: when session or one of the nodes do not exist :raises grpc.RpcError: when session or one of the nodes do not exist
""" """
request = WlanLinkRequest( request = WlanLinkRequest(
session_id=session_id, session_id=session_id,
wlan=wlan, wlan=wlan_id,
node_one=node_one, node1_id=node1_id,
node_two=node_two, node2_id=node2_id,
linked=linked, linked=linked,
) )
return self.stub.WlanLink(request) return self.stub.WlanLink(request)

View file

@ -59,13 +59,13 @@ def link_interface(interface_proto: core_pb2.Interface) -> InterfaceData:
:param interface_proto: interface proto :param interface_proto: interface proto
:return: interface data :return: interface data
""" """
interface = None interface_data = None
if interface_proto: if interface_proto:
name = interface_proto.name if interface_proto.name else None name = interface_proto.name if interface_proto.name else None
mac = interface_proto.mac if interface_proto.mac else None mac = interface_proto.mac if interface_proto.mac else None
ip4 = interface_proto.ip4 if interface_proto.ip4 else None ip4 = interface_proto.ip4 if interface_proto.ip4 else None
ip6 = interface_proto.ip6 if interface_proto.ip6 else None ip6 = interface_proto.ip6 if interface_proto.ip6 else None
interface = InterfaceData( interface_data = InterfaceData(
id=interface_proto.id, id=interface_proto.id,
name=name, name=name,
mac=mac, mac=mac,
@ -74,7 +74,7 @@ def link_interface(interface_proto: core_pb2.Interface) -> InterfaceData:
ip6=ip6, ip6=ip6,
ip6_mask=interface_proto.ip6mask, ip6_mask=interface_proto.ip6mask,
) )
return interface return interface_data
def add_link_data( def add_link_data(
@ -86,8 +86,8 @@ def add_link_data(
:param link_proto: link proto :param link_proto: link proto
:return: link interfaces and options :return: link interfaces and options
""" """
interface_one = link_interface(link_proto.interface_one) interface1_data = link_interface(link_proto.interface1)
interface_two = link_interface(link_proto.interface_two) interface2_data = link_interface(link_proto.interface2)
link_type = LinkTypes(link_proto.type) link_type = LinkTypes(link_proto.type)
options = LinkOptions(type=link_type) options = LinkOptions(type=link_type)
options_data = link_proto.options options_data = link_proto.options
@ -103,7 +103,7 @@ def add_link_data(
options.unidirectional = options_data.unidirectional options.unidirectional = options_data.unidirectional
options.key = options_data.key options.key = options_data.key
options.opaque = options_data.opaque options.opaque = options_data.opaque
return interface_one, interface_two, options return interface1_data, interface2_data, options
def create_nodes( def create_nodes(
@ -141,10 +141,10 @@ def create_links(
""" """
funcs = [] funcs = []
for link_proto in link_protos: for link_proto in link_protos:
node_one_id = link_proto.node_one_id node1_id = link_proto.node1_id
node_two_id = link_proto.node_two_id node2_id = link_proto.node2_id
interface_one, interface_two, options = add_link_data(link_proto) interface1, interface2, options = add_link_data(link_proto)
args = (node_one_id, node_two_id, interface_one, interface_two, options) args = (node1_id, node2_id, interface1, interface2, options)
funcs.append((session.add_link, args, {})) funcs.append((session.add_link, args, {}))
start = time.monotonic() start = time.monotonic()
results, exceptions = utils.threadpool(funcs) results, exceptions = utils.threadpool(funcs)
@ -165,10 +165,10 @@ def edit_links(
""" """
funcs = [] funcs = []
for link_proto in link_protos: for link_proto in link_protos:
node_one_id = link_proto.node_one_id node1_id = link_proto.node1_id
node_two_id = link_proto.node_two_id node2_id = link_proto.node2_id
interface_one, interface_two, options = add_link_data(link_proto) interface1, interface2, options = add_link_data(link_proto)
args = (node_one_id, node_two_id, interface_one.id, interface_two.id, options) args = (node1_id, node2_id, interface1.id, interface2.id, options)
funcs.append((session.update_link, args, {})) funcs.append((session.update_link, args, {}))
start = time.monotonic() start = time.monotonic()
results, exceptions = utils.threadpool(funcs) results, exceptions = utils.threadpool(funcs)
@ -315,9 +315,9 @@ def convert_link(link_data: LinkData) -> core_pb2.Link:
:param link_data: link to convert :param link_data: link to convert
:return: core protobuf Link :return: core protobuf Link
""" """
interface_one = None interface1 = None
if link_data.interface1_id is not None: if link_data.interface1_id is not None:
interface_one = core_pb2.Interface( interface1 = core_pb2.Interface(
id=link_data.interface1_id, id=link_data.interface1_id,
name=link_data.interface1_name, name=link_data.interface1_name,
mac=convert_value(link_data.interface1_mac), mac=convert_value(link_data.interface1_mac),
@ -326,9 +326,9 @@ def convert_link(link_data: LinkData) -> core_pb2.Link:
ip6=convert_value(link_data.interface1_ip6), ip6=convert_value(link_data.interface1_ip6),
ip6mask=link_data.interface1_ip6_mask, ip6mask=link_data.interface1_ip6_mask,
) )
interface_two = None interface2 = None
if link_data.interface2_id is not None: if link_data.interface2_id is not None:
interface_two = core_pb2.Interface( interface2 = core_pb2.Interface(
id=link_data.interface2_id, id=link_data.interface2_id,
name=link_data.interface2_name, name=link_data.interface2_name,
mac=convert_value(link_data.interface2_mac), mac=convert_value(link_data.interface2_mac),
@ -352,10 +352,10 @@ def convert_link(link_data: LinkData) -> core_pb2.Link:
) )
return core_pb2.Link( return core_pb2.Link(
type=link_data.link_type.value, type=link_data.link_type.value,
node_one_id=link_data.node1_id, node1_id=link_data.node1_id,
node_two_id=link_data.node2_id, node2_id=link_data.node2_id,
interface_one=interface_one, interface1=interface1,
interface_two=interface_two, interface2=interface2,
options=options, options=options,
network_id=link_data.network_id, network_id=link_data.network_id,
label=link_data.label, label=link_data.label,

View file

@ -845,27 +845,23 @@ class CoreGrpcServer(core_pb2_grpc.CoreApiServicer):
:return: add-link response :return: add-link response
""" """
logging.debug("add link: %s", request) logging.debug("add link: %s", request)
# validate session and nodes
session = self.get_session(request.session_id, context) session = self.get_session(request.session_id, context)
self.get_node(session, request.link.node_one_id, context, NodeBase) node1_id = request.link.node1_id
self.get_node(session, request.link.node_two_id, context, NodeBase) node2_id = request.link.node2_id
self.get_node(session, node1_id, context, NodeBase)
node_one_id = request.link.node_one_id self.get_node(session, node2_id, context, NodeBase)
node_two_id = request.link.node_two_id interface1, interface2, options = grpcutils.add_link_data(request.link)
interface_one, interface_two, options = grpcutils.add_link_data(request.link) node1_interface, node2_interface = session.add_link(
node_one_interface, node_two_interface = session.add_link( node1_id, node2_id, interface1, interface2, options=options
node_one_id, node_two_id, interface_one, interface_two, options=options
) )
interface_one_proto = None interface1_proto = None
interface_two_proto = None interface2_proto = None
if node_one_interface: if node1_interface:
interface_one_proto = grpcutils.interface_to_proto(node_one_interface) interface1_proto = grpcutils.interface_to_proto(node1_interface)
if node_two_interface: if node2_interface:
interface_two_proto = grpcutils.interface_to_proto(node_two_interface) interface2_proto = grpcutils.interface_to_proto(node2_interface)
return core_pb2.AddLinkResponse( return core_pb2.AddLinkResponse(
result=True, result=True, interface1=interface1_proto, interface2=interface2_proto
interface_one=interface_one_proto,
interface_two=interface_two_proto,
) )
def EditLink( def EditLink(
@ -880,10 +876,10 @@ class CoreGrpcServer(core_pb2_grpc.CoreApiServicer):
""" """
logging.debug("edit link: %s", request) logging.debug("edit link: %s", request)
session = self.get_session(request.session_id, context) session = self.get_session(request.session_id, context)
node_one_id = request.node_one_id node1_id = request.node1_id
node_two_id = request.node_two_id node2_id = request.node2_id
interface_one_id = request.interface_one_id interface1_id = request.interface1_id
interface_two_id = request.interface_two_id interface2_id = request.interface2_id
options_data = request.options options_data = request.options
options = LinkOptions( options = LinkOptions(
delay=options_data.delay, delay=options_data.delay,
@ -898,9 +894,7 @@ class CoreGrpcServer(core_pb2_grpc.CoreApiServicer):
key=options_data.key, key=options_data.key,
opaque=options_data.opaque, opaque=options_data.opaque,
) )
session.update_link( session.update_link(node1_id, node2_id, interface1_id, interface2_id, options)
node_one_id, node_two_id, interface_one_id, interface_two_id, options
)
return core_pb2.EditLinkResponse(result=True) return core_pb2.EditLinkResponse(result=True)
def DeleteLink( def DeleteLink(
@ -915,13 +909,11 @@ class CoreGrpcServer(core_pb2_grpc.CoreApiServicer):
""" """
logging.debug("delete link: %s", request) logging.debug("delete link: %s", request)
session = self.get_session(request.session_id, context) session = self.get_session(request.session_id, context)
node_one_id = request.node_one_id node1_id = request.node1_id
node_two_id = request.node_two_id node2_id = request.node2_id
interface_one_id = request.interface_one_id interface1_id = request.interface1_id
interface_two_id = request.interface_two_id interface2_id = request.interface2_id
session.delete_link( session.delete_link(node1_id, node2_id, interface1_id, interface2_id)
node_one_id, node_two_id, interface_one_id, interface_two_id
)
return core_pb2.DeleteLinkResponse(result=True) return core_pb2.DeleteLinkResponse(result=True)
def GetHooks( def GetHooks(
@ -937,8 +929,8 @@ class CoreGrpcServer(core_pb2_grpc.CoreApiServicer):
logging.debug("get hooks: %s", request) logging.debug("get hooks: %s", request)
session = self.get_session(request.session_id, context) session = self.get_session(request.session_id, context)
hooks = [] hooks = []
for state in session._hooks: for state in session.hooks:
state_hooks = session._hooks[state] state_hooks = session.hooks[state]
for file_name, file_data in state_hooks: for file_name, file_data in state_hooks:
hook = core_pb2.Hook(state=state.value, file=file_name, data=file_data) hook = core_pb2.Hook(state=state.value, file=file_name, data=file_data)
hooks.append(hook) hooks.append(hook)
@ -1520,30 +1512,30 @@ class CoreGrpcServer(core_pb2_grpc.CoreApiServicer):
""" """
logging.debug("emane link: %s", request) logging.debug("emane link: %s", request)
session = self.get_session(request.session_id, context) session = self.get_session(request.session_id, context)
nem_one = request.nem_one nem1 = request.nem1
emane_one, netif = session.emane.nemlookup(nem_one) emane1, netif = session.emane.nemlookup(nem1)
if not emane_one or not netif: if not emane1 or not netif:
context.abort(grpc.StatusCode.NOT_FOUND, f"nem one {nem_one} not found") context.abort(grpc.StatusCode.NOT_FOUND, f"nem one {nem1} not found")
node_one = netif.node node1 = netif.node
nem_two = request.nem_two nem2 = request.nem2
emane_two, netif = session.emane.nemlookup(nem_two) emane2, netif = session.emane.nemlookup(nem2)
if not emane_two or not netif: if not emane2 or not netif:
context.abort(grpc.StatusCode.NOT_FOUND, f"nem two {nem_two} not found") context.abort(grpc.StatusCode.NOT_FOUND, f"nem two {nem2} not found")
node_two = netif.node node2 = netif.node
if emane_one.id == emane_two.id: if emane1.id == emane2.id:
if request.linked: if request.linked:
flag = MessageFlags.ADD flag = MessageFlags.ADD
else: else:
flag = MessageFlags.DELETE flag = MessageFlags.DELETE
color = session.get_link_color(emane_one.id) color = session.get_link_color(emane1.id)
link = LinkData( link = LinkData(
message_type=flag, message_type=flag,
link_type=LinkTypes.WIRELESS, link_type=LinkTypes.WIRELESS,
node1_id=node_one.id, node1_id=node1.id,
node2_id=node_two.id, node2_id=node2.id,
network_id=emane_one.id, network_id=emane1.id,
color=color, color=color,
) )
session.broadcast_link(link) session.broadcast_link(link)
@ -1740,21 +1732,23 @@ class CoreGrpcServer(core_pb2_grpc.CoreApiServicer):
grpc.StatusCode.NOT_FOUND, grpc.StatusCode.NOT_FOUND,
f"wlan node {request.wlan} does not using BasicRangeModel", f"wlan node {request.wlan} does not using BasicRangeModel",
) )
n1 = self.get_node(session, request.node_one, context, CoreNode) node1 = self.get_node(session, request.node1_id, context, CoreNode)
n2 = self.get_node(session, request.node_two, context, CoreNode) node2 = self.get_node(session, request.node2_id, context, CoreNode)
n1_netif, n2_netif = None, None node1_interface, node2_interface = None, None
for net, netif1, netif2 in n1.commonnets(n2): for net, interface1, interface2 in node1.commonnets(node2):
if net == wlan: if net == wlan:
n1_netif = netif1 node1_interface = interface1
n2_netif = netif2 node2_interface = interface2
break break
result = False result = False
if n1_netif and n2_netif: if node1_interface and node2_interface:
if request.linked: if request.linked:
wlan.link(n1_netif, n2_netif) wlan.link(node1_interface, node2_interface)
else: else:
wlan.unlink(n1_netif, n2_netif) wlan.unlink(node1_interface, node2_interface)
wlan.model.sendlinkmsg(n1_netif, n2_netif, unlink=not request.linked) wlan.model.sendlinkmsg(
node1_interface, node2_interface, unlink=not request.linked
)
result = True result = True
return WlanLinkResponse(result=result) return WlanLinkResponse(result=result)
@ -1765,9 +1759,9 @@ class CoreGrpcServer(core_pb2_grpc.CoreApiServicer):
) -> EmanePathlossesResponse: ) -> EmanePathlossesResponse:
for request in request_iterator: for request in request_iterator:
session = self.get_session(request.session_id, context) session = self.get_session(request.session_id, context)
n1 = self.get_node(session, request.node_one, context, CoreNode) node1 = self.get_node(session, request.node1_id, context, CoreNode)
nem1 = grpcutils.get_nem_id(n1, request.interface_one_id, context) nem1 = grpcutils.get_nem_id(node1, request.interface1_id, context)
n2 = self.get_node(session, request.node_two, context, CoreNode) node2 = self.get_node(session, request.node2_id, context, CoreNode)
nem2 = grpcutils.get_nem_id(n2, request.interface_two_id, context) nem2 = grpcutils.get_nem_id(node2, request.interface2_id, context)
session.emane.publish_pathloss(nem1, nem2, request.rx_one, request.rx_two) session.emane.publish_pathloss(nem1, nem2, request.rx1, request.rx2)
return EmanePathlossesResponse() return EmanePathlossesResponse()

View file

@ -12,6 +12,7 @@ import threading
import time import time
from itertools import repeat from itertools import repeat
from queue import Empty, Queue from queue import Empty, Queue
from typing import Optional
from core import utils from core import utils
from core.api.tlv import coreapi, dataconversion, structutils from core.api.tlv import coreapi, dataconversion, structutils
@ -39,6 +40,7 @@ from core.emulator.enumerations import (
NodeTypes, NodeTypes,
RegisterTlvs, RegisterTlvs,
) )
from core.emulator.session import Session
from core.errors import CoreCommandError, CoreError from core.errors import CoreCommandError, CoreError
from core.location.mobility import BasicRangeModel from core.location.mobility import BasicRangeModel
from core.nodes.base import CoreNode, CoreNodeBase, NodeBase from core.nodes.base import CoreNode, CoreNodeBase, NodeBase
@ -83,7 +85,7 @@ class CoreHandler(socketserver.BaseRequestHandler):
thread.start() thread.start()
self.handler_threads.append(thread) self.handler_threads.append(thread)
self.session = None self.session: Optional[Session] = None
self.coreemu = server.coreemu self.coreemu = server.coreemu
utils.close_onexec(request.fileno()) utils.close_onexec(request.fileno())
socketserver.BaseRequestHandler.__init__(self, request, client_address, server) socketserver.BaseRequestHandler.__init__(self, request, client_address, server)
@ -176,7 +178,7 @@ class CoreHandler(socketserver.BaseRequestHandler):
node_count_list.append(str(session.get_node_count())) node_count_list.append(str(session.get_node_count()))
date_list.append(time.ctime(session._state_time)) date_list.append(time.ctime(session.state_time))
thumb = session.thumbnail thumb = session.thumbnail
if not thumb: if not thumb:
@ -745,10 +747,9 @@ class CoreHandler(socketserver.BaseRequestHandler):
:param core.api.tlv.coreapi.CoreLinkMessage message: link message to handle :param core.api.tlv.coreapi.CoreLinkMessage message: link message to handle
:return: link message replies :return: link message replies
""" """
node_one_id = message.get_tlv(LinkTlvs.N1_NUMBER.value) node1_id = message.get_tlv(LinkTlvs.N1_NUMBER.value)
node_two_id = message.get_tlv(LinkTlvs.N2_NUMBER.value) node2_id = message.get_tlv(LinkTlvs.N2_NUMBER.value)
interface1_data = InterfaceData(
interface_one = InterfaceData(
id=message.get_tlv(LinkTlvs.INTERFACE1_NUMBER.value), id=message.get_tlv(LinkTlvs.INTERFACE1_NUMBER.value),
name=message.get_tlv(LinkTlvs.INTERFACE1_NAME.value), name=message.get_tlv(LinkTlvs.INTERFACE1_NAME.value),
mac=message.get_tlv(LinkTlvs.INTERFACE1_MAC.value), mac=message.get_tlv(LinkTlvs.INTERFACE1_MAC.value),
@ -757,7 +758,7 @@ class CoreHandler(socketserver.BaseRequestHandler):
ip6=message.get_tlv(LinkTlvs.INTERFACE1_IP6.value), ip6=message.get_tlv(LinkTlvs.INTERFACE1_IP6.value),
ip6_mask=message.get_tlv(LinkTlvs.INTERFACE1_IP6_MASK.value), ip6_mask=message.get_tlv(LinkTlvs.INTERFACE1_IP6_MASK.value),
) )
interface_two = InterfaceData( interface2_data = InterfaceData(
id=message.get_tlv(LinkTlvs.INTERFACE2_NUMBER.value), id=message.get_tlv(LinkTlvs.INTERFACE2_NUMBER.value),
name=message.get_tlv(LinkTlvs.INTERFACE2_NAME.value), name=message.get_tlv(LinkTlvs.INTERFACE2_NAME.value),
mac=message.get_tlv(LinkTlvs.INTERFACE2_MAC.value), mac=message.get_tlv(LinkTlvs.INTERFACE2_MAC.value),
@ -766,45 +767,39 @@ class CoreHandler(socketserver.BaseRequestHandler):
ip6=message.get_tlv(LinkTlvs.INTERFACE2_IP6.value), ip6=message.get_tlv(LinkTlvs.INTERFACE2_IP6.value),
ip6_mask=message.get_tlv(LinkTlvs.INTERFACE2_IP6_MASK.value), ip6_mask=message.get_tlv(LinkTlvs.INTERFACE2_IP6_MASK.value),
) )
link_type = LinkTypes.WIRED link_type = LinkTypes.WIRED
link_type_value = message.get_tlv(LinkTlvs.TYPE.value) link_type_value = message.get_tlv(LinkTlvs.TYPE.value)
if link_type_value is not None: if link_type_value is not None:
link_type = LinkTypes(link_type_value) link_type = LinkTypes(link_type_value)
options = LinkOptions(type=link_type)
options.delay = message.get_tlv(LinkTlvs.DELAY.value)
options.bandwidth = message.get_tlv(LinkTlvs.BANDWIDTH.value)
options.session = message.get_tlv(LinkTlvs.SESSION.value)
options.loss = message.get_tlv(LinkTlvs.LOSS.value)
options.dup = message.get_tlv(LinkTlvs.DUP.value)
options.jitter = message.get_tlv(LinkTlvs.JITTER.value)
options.mer = message.get_tlv(LinkTlvs.MER.value)
options.burst = message.get_tlv(LinkTlvs.BURST.value)
options.mburst = message.get_tlv(LinkTlvs.MBURST.value)
options.gui_attributes = message.get_tlv(LinkTlvs.GUI_ATTRIBUTES.value)
options.unidirectional = message.get_tlv(LinkTlvs.UNIDIRECTIONAL.value)
options.emulation_id = message.get_tlv(LinkTlvs.EMULATION_ID.value)
options.network_id = message.get_tlv(LinkTlvs.NETWORK_ID.value)
options.key = message.get_tlv(LinkTlvs.KEY.value)
options.opaque = message.get_tlv(LinkTlvs.OPAQUE.value)
link_options = LinkOptions(type=link_type)
link_options.delay = message.get_tlv(LinkTlvs.DELAY.value)
link_options.bandwidth = message.get_tlv(LinkTlvs.BANDWIDTH.value)
link_options.session = message.get_tlv(LinkTlvs.SESSION.value)
link_options.loss = message.get_tlv(LinkTlvs.LOSS.value)
link_options.dup = message.get_tlv(LinkTlvs.DUP.value)
link_options.jitter = message.get_tlv(LinkTlvs.JITTER.value)
link_options.mer = message.get_tlv(LinkTlvs.MER.value)
link_options.burst = message.get_tlv(LinkTlvs.BURST.value)
link_options.mburst = message.get_tlv(LinkTlvs.MBURST.value)
link_options.gui_attributes = message.get_tlv(LinkTlvs.GUI_ATTRIBUTES.value)
link_options.unidirectional = message.get_tlv(LinkTlvs.UNIDIRECTIONAL.value)
link_options.emulation_id = message.get_tlv(LinkTlvs.EMULATION_ID.value)
link_options.network_id = message.get_tlv(LinkTlvs.NETWORK_ID.value)
link_options.key = message.get_tlv(LinkTlvs.KEY.value)
link_options.opaque = message.get_tlv(LinkTlvs.OPAQUE.value)
if message.flags & MessageFlags.ADD.value: if message.flags & MessageFlags.ADD.value:
self.session.add_link( self.session.add_link(
node_one_id, node_two_id, interface_one, interface_two, link_options node1_id, node2_id, interface1_data, interface2_data, options
) )
elif message.flags & MessageFlags.DELETE.value: elif message.flags & MessageFlags.DELETE.value:
self.session.delete_link( self.session.delete_link(
node_one_id, node_two_id, interface_one.id, interface_two.id node1_id, node2_id, interface1_data.id, interface2_data.id
) )
else: else:
self.session.update_link( self.session.update_link(
node_one_id, node1_id, node2_id, interface1_data.id, interface2_data.id, options
node_two_id,
interface_one.id,
interface_two.id,
link_options,
) )
return () return ()
def handle_execute_message(self, message): def handle_execute_message(self, message):
@ -1827,7 +1822,7 @@ class CoreHandler(socketserver.BaseRequestHandler):
""" """
# find all nodes and links # find all nodes and links
links_data = [] links_data = []
with self.session._nodes_lock: with self.session.nodes_lock:
for node_id in self.session.nodes: for node_id in self.session.nodes:
node = self.session.nodes[node_id] node = self.session.nodes[node_id]
self.session.broadcast_node(node, MessageFlags.ADD) self.session.broadcast_node(node, MessageFlags.ADD)
@ -1905,8 +1900,8 @@ class CoreHandler(socketserver.BaseRequestHandler):
# TODO: send location info # TODO: send location info
# send hook scripts # send hook scripts
for state in sorted(self.session._hooks.keys()): for state in sorted(self.session.hooks.keys()):
for file_name, config_data in self.session._hooks[state]: for file_name, config_data in self.session.hooks[state]:
file_data = FileData( file_data = FileData(
message_type=MessageFlags.ADD, message_type=MessageFlags.ADD,
name=str(file_name), name=str(file_name),

View file

@ -279,7 +279,7 @@ class EmaneManager(ModelManager):
logging.debug("emane setup") logging.debug("emane setup")
# TODO: drive this from the session object # TODO: drive this from the session object
with self.session._nodes_lock: with self.session.nodes_lock:
for node_id in self.session.nodes: for node_id in self.session.nodes:
node = self.session.nodes[node_id] node = self.session.nodes[node_id]
if isinstance(node, EmaneNet): if isinstance(node, EmaneNet):

View file

@ -269,11 +269,11 @@ class EmaneLinkMonitor:
self.scheduler.enter(self.link_interval, 0, self.check_links) self.scheduler.enter(self.link_interval, 0, self.check_links)
def get_complete_id(self, link_id: Tuple[int, int]) -> Tuple[int, int]: def get_complete_id(self, link_id: Tuple[int, int]) -> Tuple[int, int]:
value_one, value_two = link_id value1, value2 = link_id
if value_one < value_two: if value1 < value2:
return value_one, value_two return value1, value2
else: else:
return value_two, value_one return value2, value1
def is_complete_link(self, link_id: Tuple[int, int]) -> bool: def is_complete_link(self, link_id: Tuple[int, int]) -> bool:
reverse_id = link_id[1], link_id[0] reverse_id = link_id[1], link_id[0]
@ -287,8 +287,8 @@ class EmaneLinkMonitor:
return f"{source_link.sinr:.1f} / {dest_link.sinr:.1f}" return f"{source_link.sinr:.1f} / {dest_link.sinr:.1f}"
def send_link(self, message_type: MessageFlags, link_id: Tuple[int, int]) -> None: def send_link(self, message_type: MessageFlags, link_id: Tuple[int, int]) -> None:
nem_one, nem_two = link_id nem1, nem2 = link_id
link = self.emane_manager.get_nem_link(nem_one, nem_two, message_type) link = self.emane_manager.get_nem_link(nem1, nem2, message_type)
if link: if link:
label = self.get_link_label(link_id) label = self.get_link_label(link_id)
link.label = label link.label = label
@ -298,16 +298,16 @@ class EmaneLinkMonitor:
self, self,
message_type: MessageFlags, message_type: MessageFlags,
label: str, label: str,
node_one: int, node1: int,
node_two: int, node2: int,
emane_id: int, emane_id: int,
) -> None: ) -> None:
color = self.emane_manager.session.get_link_color(emane_id) color = self.emane_manager.session.get_link_color(emane_id)
link_data = LinkData( link_data = LinkData(
message_type=message_type, message_type=message_type,
label=label, label=label,
node1_id=node_one, node1_id=node1,
node2_id=node_two, node2_id=node2,
network_id=emane_id, network_id=emane_id,
link_type=LinkTypes.WIRELESS, link_type=LinkTypes.WIRELESS,
color=color, color=color,

View file

@ -224,18 +224,20 @@ class DistributedController:
self.tunnels[key] = tunnel self.tunnels[key] = tunnel
return tunnel return tunnel
def tunnel_key(self, n1_id: int, n2_id: int) -> int: def tunnel_key(self, node1_id: int, node2_id: int) -> int:
""" """
Compute a 32-bit key used to uniquely identify a GRE tunnel. Compute a 32-bit key used to uniquely identify a GRE tunnel.
The hash(n1num), hash(n2num) values are used, so node numbers may be The hash(n1num), hash(n2num) values are used, so node numbers may be
None or string values (used for e.g. "ctrlnet"). None or string values (used for e.g. "ctrlnet").
:param n1_id: node one id :param node1_id: node one id
:param n2_id: node two id :param node2_id: node two id
:return: tunnel key for the node pair :return: tunnel key for the node pair
""" """
logging.debug("creating tunnel key for: %s, %s", n1_id, n2_id) logging.debug("creating tunnel key for: %s, %s", node1_id, node2_id)
key = ( key = (
(self.session.id << 16) ^ utils.hashkey(n1_id) ^ (utils.hashkey(n2_id) << 8) (self.session.id << 16)
^ utils.hashkey(node1_id)
^ (utils.hashkey(node2_id) << 8)
) )
return key & 0xFFFFFFFF return key & 0xFFFFFFFF

View file

@ -201,6 +201,6 @@ class IpPrefixes:
generation generation
:return: new interface data for the provided node :return: new interface data for the provided node
""" """
interface = self.gen_interface(node.id, name, mac) interface_data = self.gen_interface(node.id, name, mac)
interface.id = node.newifindex() interface_data.id = node.newifindex()
return interface return interface_data

View file

@ -6,7 +6,6 @@ that manages a CORE session.
import logging import logging
import os import os
import pwd import pwd
import random
import shutil import shutil
import subprocess import subprocess
import tempfile import tempfile
@ -113,15 +112,13 @@ class Session:
# dict of nodes: all nodes and nets # dict of nodes: all nodes and nets
self.nodes: Dict[int, NodeBase] = {} self.nodes: Dict[int, NodeBase] = {}
self._nodes_lock = threading.Lock() self.nodes_lock = threading.Lock()
# states and hooks handlers
self.state: EventTypes = EventTypes.DEFINITION_STATE self.state: EventTypes = EventTypes.DEFINITION_STATE
self._state_time: float = time.monotonic() self.state_time: float = time.monotonic()
self._state_file: str = os.path.join(self.session_dir, "state") self.hooks: Dict[EventTypes, Tuple[str, str]] = {}
self.state_hooks: Dict[EventTypes, List[Callable[[EventTypes], None]]] = {}
# hooks handlers
self._hooks: Dict[EventTypes, Tuple[str, str]] = {}
self._state_hooks: Dict[EventTypes, Callable[[int], None]] = {}
self.add_state_hook( self.add_state_hook(
state=EventTypes.RUNTIME_STATE, hook=self.runtime_state_hook state=EventTypes.RUNTIME_STATE, hook=self.runtime_state_hook
) )
@ -154,15 +151,6 @@ class Session:
self.emane: EmaneManager = EmaneManager(self) self.emane: EmaneManager = EmaneManager(self)
self.sdt: Sdt = Sdt(self) self.sdt: Sdt = Sdt(self)
# initialize default node services
self.services.default_services = {
"mdr": ("zebra", "OSPFv3MDR", "IPForward"),
"PC": ("DefaultRoute",),
"prouter": (),
"router": ("zebra", "OSPFv2", "OSPFv3", "IPForward"),
"host": ("DefaultRoute", "SSH"),
}
# config services # config services
self.service_manager: Optional[ConfigServiceManager] = None self.service_manager: Optional[ConfigServiceManager] = None
@ -194,13 +182,13 @@ class Session:
return node_type return node_type
def _link_wireless( def _link_wireless(
self, node_one: CoreNodeBase, node_two: CoreNodeBase, connect: bool self, node1: CoreNodeBase, node2: CoreNodeBase, connect: bool
) -> None: ) -> None:
""" """
Objects to deal with when connecting/disconnecting wireless links. Objects to deal with when connecting/disconnecting wireless links.
:param node_one: node one for wireless link :param node1: node one for wireless link
:param node_two: node two for wireless link :param node2: node two for wireless link
:param connect: link interfaces if True, unlink otherwise :param connect: link interfaces if True, unlink otherwise
:return: nothing :return: nothing
:raises core.CoreError: when objects to link is less than 2, or no common :raises core.CoreError: when objects to link is less than 2, or no common
@ -208,14 +196,14 @@ class Session:
""" """
logging.info( logging.info(
"handling wireless linking node1(%s) node2(%s): %s", "handling wireless linking node1(%s) node2(%s): %s",
node_one.name, node1.name,
node_two.name, node2.name,
connect, connect,
) )
common_networks = node_one.commonnets(node_one) common_networks = node1.commonnets(node1)
if not common_networks: if not common_networks:
raise CoreError("no common network found for wireless link/unlink") raise CoreError("no common network found for wireless link/unlink")
for common_network, interface_one, interface_two in common_networks: for common_network, interface1, interface2 in common_networks:
if not isinstance(common_network, (WlanNode, EmaneNet)): if not isinstance(common_network, (WlanNode, EmaneNet)):
logging.info( logging.info(
"skipping common network that is not wireless/emane: %s", "skipping common network that is not wireless/emane: %s",
@ -223,26 +211,26 @@ class Session:
) )
continue continue
if connect: if connect:
common_network.link(interface_one, interface_two) common_network.link(interface1, interface2)
else: else:
common_network.unlink(interface_one, interface_two) common_network.unlink(interface1, interface2)
def add_link( def add_link(
self, self,
node_one_id: int, node1_id: int,
node_two_id: int, node2_id: int,
interface_one: InterfaceData = None, interface1_data: InterfaceData = None,
interface_two: InterfaceData = None, interface2_data: InterfaceData = None,
options: LinkOptions = None, options: LinkOptions = None,
) -> Tuple[CoreInterface, CoreInterface]: ) -> Tuple[CoreInterface, CoreInterface]:
""" """
Add a link between nodes. Add a link between nodes.
:param node_one_id: node one id :param node1_id: node one id
:param node_two_id: node two id :param node2_id: node two id
:param interface_one: node one interface :param interface1_data: node one interface
data, defaults to none data, defaults to none
:param interface_two: node two interface :param interface2_data: node two interface
data, defaults to none data, defaults to none
:param options: data for creating link, :param options: data for creating link,
defaults to no options defaults to no options
@ -250,10 +238,10 @@ class Session:
""" """
if not options: if not options:
options = LinkOptions() options = LinkOptions()
node1 = self.get_node(node_one_id, NodeBase) node1 = self.get_node(node1_id, NodeBase)
node2 = self.get_node(node_two_id, NodeBase) node2 = self.get_node(node2_id, NodeBase)
node1_interface = None interface1 = None
node2_interface = None interface2 = None
# wireless link # wireless link
if options.type == LinkTypes.WIRELESS: if options.type == LinkTypes.WIRELESS:
@ -270,22 +258,22 @@ class Session:
logging.info("linking ptp: %s - %s", node1.name, node2.name) logging.info("linking ptp: %s - %s", node1.name, node2.name)
start = self.state.should_start() start = self.state.should_start()
ptp = self.create_node(PtpNet, start=start) ptp = self.create_node(PtpNet, start=start)
node1_interface = node1.newnetif(ptp, interface_one) interface1 = node1.newnetif(ptp, interface1_data)
node2_interface = node2.newnetif(ptp, interface_two) interface2 = node2.newnetif(ptp, interface2_data)
ptp.linkconfig(node1_interface, options) ptp.linkconfig(interface1, options)
if not options.unidirectional: if not options.unidirectional:
ptp.linkconfig(node2_interface, options) ptp.linkconfig(interface2, options)
# link node to net # link node to net
elif isinstance(node1, CoreNodeBase) and isinstance(node2, CoreNetworkBase): elif isinstance(node1, CoreNodeBase) and isinstance(node2, CoreNetworkBase):
node1_interface = node1.newnetif(node2, interface_one) interface1 = node1.newnetif(node2, interface1_data)
if not isinstance(node2, (EmaneNet, WlanNode)): if not isinstance(node2, (EmaneNet, WlanNode)):
node2.linkconfig(node1_interface, options) node2.linkconfig(interface1, options)
# link net to node # link net to node
elif isinstance(node2, CoreNodeBase) and isinstance(node1, CoreNetworkBase): elif isinstance(node2, CoreNodeBase) and isinstance(node1, CoreNetworkBase):
node2_interface = node2.newnetif(node1, interface_two) interface2 = node2.newnetif(node1, interface2_data)
wireless_net = isinstance(node1, (EmaneNet, WlanNode)) wireless_net = isinstance(node1, (EmaneNet, WlanNode))
if not options.unidirectional and not wireless_net: if not options.unidirectional and not wireless_net:
node1.linkconfig(node2_interface, options) node1.linkconfig(interface2, options)
# network to network # network to network
elif isinstance(node1, CoreNetworkBase) and isinstance( elif isinstance(node1, CoreNetworkBase) and isinstance(
node2, CoreNetworkBase node2, CoreNetworkBase
@ -293,12 +281,12 @@ class Session:
logging.info( logging.info(
"linking network to network: %s - %s", node1.name, node2.name "linking network to network: %s - %s", node1.name, node2.name
) )
node1_interface = node1.linknet(node2) interface1 = node1.linknet(node2)
node1.linkconfig(node1_interface, options) node1.linkconfig(interface1, options)
if not options.unidirectional: if not options.unidirectional:
node1_interface.swapparams("_params_up") interface1.swapparams("_params_up")
node2.linkconfig(node1_interface, options) node2.linkconfig(interface1, options)
node1_interface.swapparams("_params_up") interface1.swapparams("_params_up")
else: else:
raise CoreError( raise CoreError(
f"cannot link node1({type(node1)}) node2({type(node2)})" f"cannot link node1({type(node1)}) node2({type(node2)})"
@ -308,41 +296,41 @@ class Session:
key = options.key key = options.key
if isinstance(node1, TunnelNode): if isinstance(node1, TunnelNode):
logging.info("setting tunnel key for: %s", node1.name) logging.info("setting tunnel key for: %s", node1.name)
node1.setkey(key, interface_one) node1.setkey(key, interface1_data)
if isinstance(node2, TunnelNode): if isinstance(node2, TunnelNode):
logging.info("setting tunnel key for: %s", node2.name) logging.info("setting tunnel key for: %s", node2.name)
node2.setkey(key, interface_two) node2.setkey(key, interface2_data)
self.sdt.add_link(node_one_id, node_two_id) self.sdt.add_link(node1_id, node2_id)
return node1_interface, node2_interface return interface1, interface2
def delete_link( def delete_link(
self, self,
node_one_id: int, node1_id: int,
node_two_id: int, node2_id: int,
interface_one_id: int = None, interface1_id: int = None,
interface_two_id: int = None, interface2_id: int = None,
link_type: LinkTypes = LinkTypes.WIRED, link_type: LinkTypes = LinkTypes.WIRED,
) -> None: ) -> None:
""" """
Delete a link between nodes. Delete a link between nodes.
:param node_one_id: node one id :param node1_id: node one id
:param node_two_id: node two id :param node2_id: node two id
:param interface_one_id: interface id for node one :param interface1_id: interface id for node one
:param interface_two_id: interface id for node two :param interface2_id: interface id for node two
:param link_type: link type to delete :param link_type: link type to delete
:return: nothing :return: nothing
:raises core.CoreError: when no common network is found for link being deleted :raises core.CoreError: when no common network is found for link being deleted
""" """
node1 = self.get_node(node_one_id, NodeBase) node1 = self.get_node(node1_id, NodeBase)
node2 = self.get_node(node_two_id, NodeBase) node2 = self.get_node(node2_id, NodeBase)
logging.info( logging.info(
"deleting link(%s) node(%s):interface(%s) node(%s):interface(%s)", "deleting link(%s) node(%s):interface(%s) node(%s):interface(%s)",
link_type.name, link_type.name,
node1.name, node1.name,
interface_one_id, interface1_id,
node2.name, node2.name,
interface_two_id, interface2_id,
) )
# wireless link # wireless link
@ -357,15 +345,15 @@ class Session:
# wired link # wired link
else: else:
if isinstance(node1, CoreNodeBase) and isinstance(node2, CoreNodeBase): if isinstance(node1, CoreNodeBase) and isinstance(node2, CoreNodeBase):
interface1 = node1.netif(interface_one_id) interface1 = node1.netif(interface1_id)
interface2 = node2.netif(interface_two_id) interface2 = node2.netif(interface2_id)
if not interface1: if not interface1:
raise CoreError( raise CoreError(
f"node({node1.name}) missing interface({interface_one_id})" f"node({node1.name}) missing interface({interface1_id})"
) )
if not interface2: if not interface2:
raise CoreError( raise CoreError(
f"node({node2.name}) missing interface({interface_two_id})" f"node({node2.name}) missing interface({interface2_id})"
) )
if interface1.net != interface2.net: if interface1.net != interface2.net:
raise CoreError( raise CoreError(
@ -373,30 +361,30 @@ class Session:
"not connected to same net" "not connected to same net"
) )
ptp = interface1.net ptp = interface1.net
node1.delnetif(interface_one_id) node1.delnetif(interface1_id)
node2.delnetif(interface_two_id) node2.delnetif(interface2_id)
self.delete_node(ptp.id) self.delete_node(ptp.id)
elif isinstance(node1, CoreNodeBase) and isinstance(node2, CoreNetworkBase): elif isinstance(node1, CoreNodeBase) and isinstance(node2, CoreNetworkBase):
node1.delnetif(interface_one_id) node1.delnetif(interface1_id)
elif isinstance(node2, CoreNodeBase) and isinstance(node1, CoreNetworkBase): elif isinstance(node2, CoreNodeBase) and isinstance(node1, CoreNetworkBase):
node2.delnetif(interface_two_id) node2.delnetif(interface2_id)
self.sdt.delete_link(node_one_id, node_two_id) self.sdt.delete_link(node1_id, node2_id)
def update_link( def update_link(
self, self,
node_one_id: int, node1_id: int,
node_two_id: int, node2_id: int,
interface_one_id: int = None, interface1_id: int = None,
interface_two_id: int = None, interface2_id: int = None,
options: LinkOptions = None, options: LinkOptions = None,
) -> None: ) -> None:
""" """
Update link information between nodes. Update link information between nodes.
:param node_one_id: node one id :param node1_id: node one id
:param node_two_id: node two id :param node2_id: node two id
:param interface_one_id: interface id for node one :param interface1_id: interface id for node one
:param interface_two_id: interface id for node two :param interface2_id: interface id for node two
:param options: data to update link with :param options: data to update link with
:return: nothing :return: nothing
:raises core.CoreError: when updating a wireless type link, when there is a :raises core.CoreError: when updating a wireless type link, when there is a
@ -404,15 +392,15 @@ class Session:
""" """
if not options: if not options:
options = LinkOptions() options = LinkOptions()
node1 = self.get_node(node_one_id, NodeBase) node1 = self.get_node(node1_id, NodeBase)
node2 = self.get_node(node_two_id, NodeBase) node2 = self.get_node(node2_id, NodeBase)
logging.info( logging.info(
"update link(%s) node(%s):interface(%s) node(%s):interface(%s)", "update link(%s) node(%s):interface(%s) node(%s):interface(%s)",
options.type.name, options.type.name,
node1.name, node1.name,
interface_one_id, interface1_id,
node2.name, node2.name,
interface_two_id, interface2_id,
) )
# wireless link # wireless link
@ -420,15 +408,15 @@ class Session:
raise CoreError("cannot update wireless link") raise CoreError("cannot update wireless link")
else: else:
if isinstance(node1, CoreNodeBase) and isinstance(node2, CoreNodeBase): if isinstance(node1, CoreNodeBase) and isinstance(node2, CoreNodeBase):
interface1 = node1.netif(interface_one_id) interface1 = node1.netif(interface1_id)
interface2 = node2.netif(interface_two_id) interface2 = node2.netif(interface2_id)
if not interface1: if not interface1:
raise CoreError( raise CoreError(
f"node({node1.name}) missing interface({interface_one_id})" f"node({node1.name}) missing interface({interface1_id})"
) )
if not interface2: if not interface2:
raise CoreError( raise CoreError(
f"node({node2.name}) missing interface({interface_two_id})" f"node({node2.name}) missing interface({interface2_id})"
) )
if interface1.net != interface2.net: if interface1.net != interface2.net:
raise CoreError( raise CoreError(
@ -440,10 +428,10 @@ class Session:
if not options.unidirectional: if not options.unidirectional:
ptp.linkconfig(interface2, options, interface1) ptp.linkconfig(interface2, options, interface1)
elif isinstance(node1, CoreNodeBase) and isinstance(node2, CoreNetworkBase): elif isinstance(node1, CoreNodeBase) and isinstance(node2, CoreNetworkBase):
interface = node1.netif(interface_one_id) interface = node1.netif(interface1_id)
node2.linkconfig(interface, options) node2.linkconfig(interface, options)
elif isinstance(node2, CoreNodeBase) and isinstance(node1, CoreNetworkBase): elif isinstance(node2, CoreNodeBase) and isinstance(node1, CoreNetworkBase):
interface = node2.netif(interface_two_id) interface = node2.netif(interface2_id)
node1.linkconfig(interface, options) node1.linkconfig(interface, options)
elif isinstance(node1, CoreNetworkBase) and isinstance( elif isinstance(node1, CoreNetworkBase) and isinstance(
node2, CoreNetworkBase node2, CoreNetworkBase
@ -473,7 +461,7 @@ class Session:
f"cannot update link node1({type(node1)}) node2({type(node2)})" f"cannot update link node1({type(node1)}) node2({type(node2)})"
) )
def _next_node_id(self) -> int: def next_node_id(self) -> int:
""" """
Find the next valid node id, starting from 1. Find the next valid node id, starting from 1.
@ -506,7 +494,7 @@ class Session:
# determine node id # determine node id
if not _id: if not _id:
_id = self._next_node_id() _id = self.next_node_id()
# generate name if not provided # generate name if not provided
if not options: if not options:
@ -692,7 +680,7 @@ class Session:
"setting state hook: %s - %s source(%s)", state, file_name, source_name "setting state hook: %s - %s source(%s)", state, file_name, source_name
) )
hook = file_name, data hook = file_name, data
state_hooks = self._hooks.setdefault(state, []) state_hooks = self.hooks.setdefault(state, [])
state_hooks.append(hook) state_hooks.append(hook)
# immediately run a hook if it is in the current state # immediately run a hook if it is in the current state
@ -727,7 +715,7 @@ class Session:
self.emane.shutdown() self.emane.shutdown()
self.delete_nodes() self.delete_nodes()
self.distributed.shutdown() self.distributed.shutdown()
self.del_hooks() self.hooks.clear()
self.emane.reset() self.emane.reset()
self.emane.config_reset() self.emane.config_reset()
self.location.reset() self.location.reset()
@ -795,7 +783,6 @@ class Session:
:param event_data: event data to send out :param event_data: event data to send out
:return: nothing :return: nothing
""" """
for handler in self.event_handlers: for handler in self.event_handlers:
handler(event_data) handler(event_data)
@ -806,7 +793,6 @@ class Session:
:param exception_data: exception data to send out :param exception_data: exception data to send out
:return: nothing :return: nothing
""" """
for handler in self.exception_handlers: for handler in self.exception_handlers:
handler(exception_data) handler(exception_data)
@ -837,7 +823,6 @@ class Session:
:param file_data: file data to send out :param file_data: file data to send out
:return: nothing :return: nothing
""" """
for handler in self.file_handlers: for handler in self.file_handlers:
handler(file_data) handler(file_data)
@ -848,7 +833,6 @@ class Session:
:param config_data: config data to send out :param config_data: config data to send out
:return: nothing :return: nothing
""" """
for handler in self.config_handlers: for handler in self.config_handlers:
handler(config_data) handler(config_data)
@ -859,7 +843,6 @@ class Session:
:param link_data: link data to send out :param link_data: link data to send out
:return: nothing :return: nothing
""" """
for handler in self.link_handlers: for handler in self.link_handlers:
handler(link_data) handler(link_data)
@ -871,22 +854,14 @@ class Session:
:param send_event: if true, generate core API event messages :param send_event: if true, generate core API event messages
:return: nothing :return: nothing
""" """
state_name = state.name
if self.state == state: if self.state == state:
logging.info(
"session(%s) is already in state: %s, skipping change",
self.id,
state_name,
)
return return
self.state = state self.state = state
self._state_time = time.monotonic() self.state_time = time.monotonic()
logging.info("changing session(%s) to state %s", self.id, state_name) logging.info("changing session(%s) to state %s", self.id, state.name)
self.write_state(state) self.write_state(state)
self.run_hooks(state) self.run_hooks(state)
self.run_state_hooks(state) self.run_state_hooks(state)
if send_event: if send_event:
event_data = EventData(event_type=state, time=str(time.monotonic())) event_data = EventData(event_type=state, time=str(time.monotonic()))
self.broadcast_event(event_data) self.broadcast_event(event_data)
@ -898,10 +873,10 @@ class Session:
:param state: state to write to file :param state: state to write to file
:return: nothing :return: nothing
""" """
state_file = os.path.join(self.session_dir, "state")
try: try:
state_file = open(self._state_file, "w") with open(state_file, "w") as f:
state_file.write(f"{state.value} {state.name}\n") f.write(f"{state.value} {state.name}\n")
state_file.close()
except IOError: except IOError:
logging.exception("error writing state file: %s", state.name) logging.exception("error writing state file: %s", state.name)
@ -913,61 +888,10 @@ class Session:
:param state: state to run hooks for :param state: state to run hooks for
:return: nothing :return: nothing
""" """
hooks = self.hooks.get(state, [])
# check that state change hooks exist for hook in hooks:
if state not in self._hooks:
return
# retrieve all state hooks
hooks = self._hooks.get(state, [])
# execute all state hooks
if hooks:
for hook in hooks:
self.run_hook(hook)
else:
logging.info("no state hooks for %s", state)
def set_hook(
self, hook_type: str, file_name: str, source_name: str, data: str
) -> None:
"""
Store a hook from a received file message.
:param hook_type: hook type
:param file_name: file name for hook
:param source_name: source name
:param data: hook data
:return: nothing
"""
logging.info(
"setting state hook: %s - %s from %s", hook_type, file_name, source_name
)
_hook_id, state = hook_type.split(":")[:2]
if not state.isdigit():
logging.error("error setting hook having state '%s'", state)
return
state = int(state)
hook = file_name, data
# append hook to current state hooks
state_hooks = self._hooks.setdefault(state, [])
state_hooks.append(hook)
# immediately run a hook if it is in the current state
# (this allows hooks in the definition and configuration states)
if self.state == state:
logging.info("immediately running new state hook")
self.run_hook(hook) self.run_hook(hook)
def del_hooks(self) -> None:
"""
Clear the hook scripts dict.
"""
self._hooks.clear()
def run_hook(self, hook: Tuple[str, str]) -> None: def run_hook(self, hook: Tuple[str, str]) -> None:
""" """
Run a hook. Run a hook.
@ -977,37 +901,23 @@ class Session:
""" """
file_name, data = hook file_name, data = hook
logging.info("running hook %s", file_name) logging.info("running hook %s", file_name)
file_path = os.path.join(self.session_dir, file_name)
# write data to hook file log_path = os.path.join(self.session_dir, f"{file_name}.log")
try: try:
hook_file = open(os.path.join(self.session_dir, file_name), "w") with open(file_path, "w") as f:
hook_file.write(data) f.write(data)
hook_file.close() with open(log_path, "w") as f:
except IOError: args = ["/bin/sh", file_name]
logging.exception("error writing hook '%s'", file_name) subprocess.check_call(
args,
# setup hook stdout and stderr stdout=f,
try: stderr=subprocess.STDOUT,
stdout = open(os.path.join(self.session_dir, file_name + ".log"), "w") close_fds=True,
stderr = subprocess.STDOUT cwd=self.session_dir,
except IOError: env=self.get_environment(),
logging.exception("error setting up hook stderr and stdout") )
stdout = None except (IOError, subprocess.CalledProcessError):
stderr = None logging.exception("error running hook: %s", file_path)
# execute hook file
try:
args = ["/bin/sh", file_name]
subprocess.check_call(
args,
stdout=stdout,
stderr=stderr,
close_fds=True,
cwd=self.session_dir,
env=self.get_environment(),
)
except (OSError, subprocess.CalledProcessError):
logging.exception("error running hook: %s", file_name)
def run_state_hooks(self, state: EventTypes) -> None: def run_state_hooks(self, state: EventTypes) -> None:
""" """
@ -1016,17 +926,16 @@ class Session:
:param state: state to run hooks for :param state: state to run hooks for
:return: nothing :return: nothing
""" """
for hook in self._state_hooks.get(state, []): for hook in self.state_hooks.get(state, []):
try: self.run_state_hook(state, hook)
hook(state)
except Exception: def run_state_hook(self, state: EventTypes, hook: Callable[[EventTypes], None]):
message = ( try:
f"exception occured when running {state.name} state hook: {hook}" hook(state)
) except Exception:
logging.exception(message) message = f"exception occurred when running {state.name} state hook: {hook}"
self.exception( logging.exception(message)
ExceptionLevels.ERROR, "Session.run_state_hooks", message self.exception(ExceptionLevels.ERROR, "Session.run_state_hooks", message)
)
def add_state_hook( def add_state_hook(
self, state: EventTypes, hook: Callable[[EventTypes], None] self, state: EventTypes, hook: Callable[[EventTypes], None]
@ -1038,15 +947,16 @@ class Session:
:param hook: hook callback for the state :param hook: hook callback for the state
:return: nothing :return: nothing
""" """
hooks = self._state_hooks.setdefault(state, []) hooks = self.state_hooks.setdefault(state, [])
if hook in hooks: if hook in hooks:
raise CoreError("attempting to add duplicate state hook") raise CoreError("attempting to add duplicate state hook")
hooks.append(hook) hooks.append(hook)
if self.state == state: if self.state == state:
hook(state) self.run_state_hook(state, hook)
def del_state_hook(self, state: int, hook: Callable[[int], None]) -> None: def del_state_hook(
self, state: EventTypes, hook: Callable[[EventTypes], None]
) -> None:
""" """
Delete a state hook. Delete a state hook.
@ -1054,24 +964,23 @@ class Session:
:param hook: hook to delete :param hook: hook to delete
:return: nothing :return: nothing
""" """
hooks = self._state_hooks.setdefault(state, []) hooks = self.state_hooks.get(state, [])
hooks.remove(hook) if hook in hooks:
hooks.remove(hook)
def runtime_state_hook(self, state: EventTypes) -> None: def runtime_state_hook(self, _state: EventTypes) -> None:
""" """
Runtime state hook check. Runtime state hook check.
:param state: state to check :param _state: state to check
:return: nothing :return: nothing
""" """
if state == EventTypes.RUNTIME_STATE: self.emane.poststartup()
self.emane.poststartup() # create session deployed xml
xml_file_name = os.path.join(self.session_dir, "session-deployed.xml")
# create session deployed xml xml_writer = corexml.CoreXmlWriter(self)
xml_file_name = os.path.join(self.session_dir, "session-deployed.xml") corexmldeployment.CoreXmlDeployment(self, xml_writer.scenario)
xml_writer = corexml.CoreXmlWriter(self) xml_writer.write(xml_file_name)
corexmldeployment.CoreXmlDeployment(self, xml_writer.scenario)
xml_writer.write(xml_file_name)
def get_environment(self, state: bool = True) -> Dict[str, str]: def get_environment(self, state: bool = True) -> Dict[str, str]:
""" """
@ -1090,10 +999,8 @@ class Session:
env["SESSION_FILENAME"] = str(self.file_name) env["SESSION_FILENAME"] = str(self.file_name)
env["SESSION_USER"] = str(self.user) env["SESSION_USER"] = str(self.user)
env["SESSION_NODE_COUNT"] = str(self.get_node_count()) env["SESSION_NODE_COUNT"] = str(self.get_node_count())
if state: if state:
env["SESSION_STATE"] = str(self.state) env["SESSION_STATE"] = str(self.state)
# attempt to read and add environment config file # attempt to read and add environment config file
environment_config_file = os.path.join(constants.CORE_CONF_DIR, "environment") environment_config_file = os.path.join(constants.CORE_CONF_DIR, "environment")
try: try:
@ -1104,7 +1011,6 @@ class Session:
"environment configuration file does not exist: %s", "environment configuration file does not exist: %s",
environment_config_file, environment_config_file,
) )
# attempt to read and add user environment file # attempt to read and add user environment file
if self.user: if self.user:
environment_user_file = os.path.join( environment_user_file = os.path.join(
@ -1117,7 +1023,6 @@ class Session:
"user core environment settings file not present: %s", "user core environment settings file not present: %s",
environment_user_file, environment_user_file,
) )
return env return env
def set_thumbnail(self, thumb_file: str) -> None: def set_thumbnail(self, thumb_file: str) -> None:
@ -1131,7 +1036,6 @@ class Session:
logging.error("thumbnail file to set does not exist: %s", thumb_file) logging.error("thumbnail file to set does not exist: %s", thumb_file)
self.thumbnail = None self.thumbnail = None
return return
destination_file = os.path.join(self.session_dir, os.path.basename(thumb_file)) destination_file = os.path.join(self.session_dir, os.path.basename(thumb_file))
shutil.copy(thumb_file, destination_file) shutil.copy(thumb_file, destination_file)
self.thumbnail = destination_file self.thumbnail = destination_file
@ -1151,20 +1055,8 @@ class Session:
os.chown(self.session_dir, uid, gid) os.chown(self.session_dir, uid, gid)
except IOError: except IOError:
logging.exception("failed to set permission on %s", self.session_dir) logging.exception("failed to set permission on %s", self.session_dir)
self.user = user self.user = user
def get_node_id(self) -> int:
"""
Return a unique, new node id.
"""
with self._nodes_lock:
while True:
node_id = random.randint(1, 0xFFFF)
if node_id not in self.nodes:
break
return node_id
def create_node(self, _class: Type[NT], *args: Any, **kwargs: Any) -> NT: def create_node(self, _class: Type[NT], *args: Any, **kwargs: Any) -> NT:
""" """
Create an emulation node. Create an emulation node.
@ -1176,7 +1068,7 @@ class Session:
:raises core.CoreError: when id of the node to create already exists :raises core.CoreError: when id of the node to create already exists
""" """
node = _class(self, *args, **kwargs) node = _class(self, *args, **kwargs)
with self._nodes_lock: with self.nodes_lock:
if node.id in self.nodes: if node.id in self.nodes:
node.shutdown() node.shutdown()
raise CoreError(f"duplicate node id {node.id} for {node.name}") raise CoreError(f"duplicate node id {node.id} for {node.name}")
@ -1192,9 +1084,9 @@ class Session:
:return: node for the given id :return: node for the given id
:raises core.CoreError: when node does not exist :raises core.CoreError: when node does not exist
""" """
if _id not in self.nodes: node = self.nodes.get(_id)
if node is None:
raise CoreError(f"unknown node id {_id}") raise CoreError(f"unknown node id {_id}")
node = self.nodes[_id]
if not isinstance(node, _class): if not isinstance(node, _class):
actual = node.__class__.__name__ actual = node.__class__.__name__
expected = _class.__name__ expected = _class.__name__
@ -1210,7 +1102,7 @@ class Session:
""" """
# delete node and check for session shutdown if a node was removed # delete node and check for session shutdown if a node was removed
node = None node = None
with self._nodes_lock: with self.nodes_lock:
if _id in self.nodes: if _id in self.nodes:
node = self.nodes.pop(_id) node = self.nodes.pop(_id)
logging.info("deleted node(%s)", node.name) logging.info("deleted node(%s)", node.name)
@ -1224,7 +1116,7 @@ class Session:
""" """
Clear the nodes dictionary, and call shutdown for each node. Clear the nodes dictionary, and call shutdown for each node.
""" """
with self._nodes_lock: with self.nodes_lock:
funcs = [] funcs = []
while self.nodes: while self.nodes:
_, node = self.nodes.popitem() _, node = self.nodes.popitem()
@ -1237,29 +1129,15 @@ class Session:
Write nodes to a 'nodes' file in the session dir. Write nodes to a 'nodes' file in the session dir.
The 'nodes' file lists: number, name, api-type, class-type The 'nodes' file lists: number, name, api-type, class-type
""" """
file_path = os.path.join(self.session_dir, "nodes")
try: try:
with self._nodes_lock: with self.nodes_lock:
file_path = os.path.join(self.session_dir, "nodes")
with open(file_path, "w") as f: with open(file_path, "w") as f:
for _id in self.nodes.keys(): for _id, node in self.nodes.items():
node = self.nodes[_id]
f.write(f"{_id} {node.name} {node.apitype} {type(node)}\n") f.write(f"{_id} {node.name} {node.apitype} {type(node)}\n")
except IOError: except IOError:
logging.exception("error writing nodes file") logging.exception("error writing nodes file")
def dump_session(self) -> None:
"""
Log information about the session in its current state.
"""
logging.info("session id=%s name=%s state=%s", self.id, self.name, self.state)
logging.info(
"file=%s thumbnail=%s node_count=%s/%s",
self.file_name,
self.thumbnail,
self.get_node_count(),
len(self.nodes),
)
def exception( def exception(
self, level: ExceptionLevels, source: str, text: str, node_id: int = None self, level: ExceptionLevels, source: str, text: str, node_id: int = None
) -> None: ) -> None:
@ -1327,17 +1205,15 @@ class Session:
:return: created node count :return: created node count
""" """
with self._nodes_lock: with self.nodes_lock:
count = 0 count = 0
for node_id in self.nodes: for node in self.nodes.values():
node = self.nodes[node_id]
is_p2p_ctrlnet = isinstance(node, (PtpNet, CtrlNet)) is_p2p_ctrlnet = isinstance(node, (PtpNet, CtrlNet))
is_tap = isinstance(node, GreTapBridge) and not isinstance( is_tap = isinstance(node, GreTapBridge) and not isinstance(
node, TunnelNode node, TunnelNode
) )
if is_p2p_ctrlnet or is_tap: if is_p2p_ctrlnet or is_tap:
continue continue
count += 1 count += 1
return count return count
@ -1359,7 +1235,6 @@ class Session:
if self.state == EventTypes.RUNTIME_STATE: if self.state == EventTypes.RUNTIME_STATE:
logging.info("valid runtime state found, returning") logging.info("valid runtime state found, returning")
return return
# start event loop and set to runtime # start event loop and set to runtime
self.event_loop.run() self.event_loop.run()
self.set_state(EventTypes.RUNTIME_STATE, send_event=True) self.set_state(EventTypes.RUNTIME_STATE, send_event=True)
@ -1375,7 +1250,7 @@ class Session:
self.event_loop.stop() self.event_loop.stop()
# stop node services # stop node services
with self._nodes_lock: with self.nodes_lock:
funcs = [] funcs = []
for node_id in self.nodes: for node_id in self.nodes:
node = self.nodes[node_id] node = self.nodes[node_id]
@ -1447,7 +1322,7 @@ class Session:
:return: service boot exceptions :return: service boot exceptions
""" """
with self._nodes_lock: with self.nodes_lock:
funcs = [] funcs = []
start = time.monotonic() start = time.monotonic()
for _id in self.nodes: for _id in self.nodes:
@ -1545,7 +1420,6 @@ class Session:
else: else:
prefix_spec = CtrlNet.DEFAULT_PREFIX_LIST[net_index] prefix_spec = CtrlNet.DEFAULT_PREFIX_LIST[net_index]
logging.debug("prefix spec: %s", prefix_spec) logging.debug("prefix spec: %s", prefix_spec)
server_interface = self.get_control_net_server_interfaces()[net_index] server_interface = self.get_control_net_server_interfaces()[net_index]
# return any existing controlnet bridge # return any existing controlnet bridge
@ -1685,7 +1559,7 @@ class Session:
if not in runtime. if not in runtime.
""" """
if self.state == EventTypes.RUNTIME_STATE: if self.state == EventTypes.RUNTIME_STATE:
return time.monotonic() - self._state_time return time.monotonic() - self.state_time
else: else:
return 0.0 return 0.0
@ -1708,7 +1582,6 @@ class Session:
""" """
event_time = float(event_time) event_time = float(event_time)
current_time = self.runtime() current_time = self.runtime()
if current_time > 0: if current_time > 0:
if event_time <= current_time: if event_time <= current_time:
logging.warning( logging.warning(
@ -1718,11 +1591,9 @@ class Session:
) )
return return
event_time = event_time - current_time event_time = event_time - current_time
self.event_loop.add_event( self.event_loop.add_event(
event_time, self.run_event, node=node, name=name, data=data event_time, self.run_event, node=node, name=name, data=data
) )
if not name: if not name:
name = "" name = ""
logging.info( logging.info(
@ -1732,8 +1603,6 @@ class Session:
data, data,
) )
# TODO: if data is None, this blows up, but this ties into how event functions
# are ran, need to clean that up
def run_event( def run_event(
self, node_id: int = None, name: str = None, data: str = None self, node_id: int = None, name: str = None, data: str = None
) -> None: ) -> None:
@ -1745,10 +1614,12 @@ class Session:
:param data: event data :param data: event data
:return: nothing :return: nothing
""" """
if data is None:
logging.warning("no data for event node(%s) name(%s)", node_id, name)
return
now = self.runtime() now = self.runtime()
if not name: if not name:
name = "" name = ""
logging.info("running event %s at time %s cmd=%s", name, now, data) logging.info("running event %s at time %s cmd=%s", name, now, data)
if not node_id: if not node_id:
utils.mute_detach(data) utils.mute_detach(data)

View file

@ -164,25 +164,19 @@ class CoreClient:
def handle_link_event(self, event: core_pb2.LinkEvent): def handle_link_event(self, event: core_pb2.LinkEvent):
logging.debug("Link event: %s", event) logging.debug("Link event: %s", event)
node_one_id = event.link.node_one_id node1_id = event.link.node1_id
node_two_id = event.link.node_two_id node2_id = event.link.node2_id
if node_one_id == node_two_id: if node1_id == node2_id:
logging.warning("ignoring links with loops: %s", event) logging.warning("ignoring links with loops: %s", event)
return return
canvas_node_one = self.canvas_nodes[node_one_id] canvas_node1 = self.canvas_nodes[node1_id]
canvas_node_two = self.canvas_nodes[node_two_id] canvas_node2 = self.canvas_nodes[node2_id]
if event.message_type == core_pb2.MessageType.ADD: if event.message_type == core_pb2.MessageType.ADD:
self.app.canvas.add_wireless_edge( self.app.canvas.add_wireless_edge(canvas_node1, canvas_node2, event.link)
canvas_node_one, canvas_node_two, event.link
)
elif event.message_type == core_pb2.MessageType.DELETE: elif event.message_type == core_pb2.MessageType.DELETE:
self.app.canvas.delete_wireless_edge( self.app.canvas.delete_wireless_edge(canvas_node1, canvas_node2, event.link)
canvas_node_one, canvas_node_two, event.link
)
elif event.message_type == core_pb2.MessageType.NONE: elif event.message_type == core_pb2.MessageType.NONE:
self.app.canvas.update_wireless_edge( self.app.canvas.update_wireless_edge(canvas_node1, canvas_node2, event.link)
canvas_node_one, canvas_node_two, event.link
)
else: else:
logging.warning("unknown link event: %s", event) logging.warning("unknown link event: %s", event)
@ -472,10 +466,10 @@ class CoreClient:
for edge in self.links.values(): for edge in self.links.values():
link = core_pb2.Link() link = core_pb2.Link()
link.CopyFrom(edge.link) link.CopyFrom(edge.link)
if link.HasField("interface_one") and not link.interface_one.mac: if link.HasField("interface1") and not link.interface1.mac:
link.interface_one.mac = self.interfaces_manager.next_mac() link.interface1.mac = self.interfaces_manager.next_mac()
if link.HasField("interface_two") and not link.interface_two.mac: if link.HasField("interface2") and not link.interface2.mac:
link.interface_two.mac = self.interfaces_manager.next_mac() link.interface2.mac = self.interfaces_manager.next_mac()
links.append(link) links.append(link)
wlan_configs = self.get_wlan_configs_proto() wlan_configs = self.get_wlan_configs_proto()
mobility_configs = self.get_mobility_configs_proto() mobility_configs = self.get_mobility_configs_proto()
@ -693,10 +687,10 @@ class CoreClient:
for link_proto in link_protos: for link_proto in link_protos:
response = self.client.add_link( response = self.client.add_link(
self.session_id, self.session_id,
link_proto.node_one_id, link_proto.node1_id,
link_proto.node_two_id, link_proto.node2_id,
link_proto.interface_one, link_proto.interface1,
link_proto.interface_two, link_proto.interface2,
link_proto.options, link_proto.options,
) )
logging.debug("create link: %s", response) logging.debug("create link: %s", response)
@ -881,20 +875,20 @@ class CoreClient:
link = core_pb2.Link( link = core_pb2.Link(
type=core_pb2.LinkType.WIRED, type=core_pb2.LinkType.WIRED,
node_one_id=src_node.id, node1_id=src_node.id,
node_two_id=dst_node.id, node2_id=dst_node.id,
interface_one=src_interface, interface1=src_interface,
interface_two=dst_interface, interface2=dst_interface,
) )
# assign after creating link proto, since interfaces are copied # assign after creating link proto, since interfaces are copied
if src_interface: if src_interface:
interface_one = link.interface_one interface1 = link.interface1
edge.src_interface = interface_one edge.src_interface = interface1
canvas_src_node.interfaces[interface_one.id] = interface_one canvas_src_node.interfaces[interface1.id] = interface1
if dst_interface: if dst_interface:
interface_two = link.interface_two interface2 = link.interface2
edge.dst_interface = interface_two edge.dst_interface = interface2
canvas_dst_node.interfaces[interface_two.id] = interface_two canvas_dst_node.interfaces[interface2.id] = interface2
edge.set_link(link) edge.set_link(link)
self.links[edge.token] = edge self.links[edge.token] = edge
logging.info("Add link between %s and %s", src_node.name, dst_node.name) logging.info("Add link between %s and %s", src_node.name, dst_node.name)

View file

@ -227,21 +227,21 @@ class LinkConfigurationDialog(Dialog):
) )
link.options.CopyFrom(options) link.options.CopyFrom(options)
interface_one = None interface1_id = None
if link.HasField("interface_one"): if link.HasField("interface1"):
interface_one = link.interface_one.id interface1_id = link.interface1.id
interface_two = None interface2_id = None
if link.HasField("interface_two"): if link.HasField("interface2"):
interface_two = link.interface_two.id interface2_id = link.interface2.id
if not self.is_symmetric: if not self.is_symmetric:
link.options.unidirectional = True link.options.unidirectional = True
asym_interface_one = None asym_interface1 = None
if interface_one: if interface1_id:
asym_interface_one = core_pb2.Interface(id=interface_one) asym_interface1 = core_pb2.Interface(id=interface1_id)
asym_interface_two = None asym_interface2 = None
if interface_two: if interface2_id:
asym_interface_two = core_pb2.Interface(id=interface_two) asym_interface2 = core_pb2.Interface(id=interface2_id)
down_bandwidth = get_int(self.down_bandwidth) down_bandwidth = get_int(self.down_bandwidth)
down_jitter = get_int(self.down_jitter) down_jitter = get_int(self.down_jitter)
down_delay = get_int(self.down_delay) down_delay = get_int(self.down_delay)
@ -256,10 +256,10 @@ class LinkConfigurationDialog(Dialog):
unidirectional=True, unidirectional=True,
) )
self.edge.asymmetric_link = core_pb2.Link( self.edge.asymmetric_link = core_pb2.Link(
node_one_id=link.node_two_id, node1_id=link.node2_id,
node_two_id=link.node_one_id, node2_id=link.node1_id,
interface_one=asym_interface_one, interface1=asym_interface1,
interface_two=asym_interface_two, interface2=asym_interface2,
options=options, options=options,
) )
else: else:
@ -270,20 +270,20 @@ class LinkConfigurationDialog(Dialog):
session_id = self.app.core.session_id session_id = self.app.core.session_id
self.app.core.client.edit_link( self.app.core.client.edit_link(
session_id, session_id,
link.node_one_id, link.node1_id,
link.node_two_id, link.node2_id,
link.options, link.options,
interface_one, interface1_id,
interface_two, interface2_id,
) )
if self.edge.asymmetric_link: if self.edge.asymmetric_link:
self.app.core.client.edit_link( self.app.core.client.edit_link(
session_id, session_id,
link.node_two_id, link.node2_id,
link.node_one_id, link.node1_id,
self.edge.asymmetric_link.options, self.edge.asymmetric_link.options,
interface_one, interface1_id,
interface_two, interface2_id,
) )
self.destroy() self.destroy()

View file

@ -296,13 +296,13 @@ class CanvasEdge(Edge):
return label return label
def create_node_labels(self) -> Tuple[str, str]: def create_node_labels(self) -> Tuple[str, str]:
label_one = None label1 = None
if self.link.HasField("interface_one"): if self.link.HasField("interface1"):
label_one = self.interface_label(self.link.interface_one) label1 = self.interface_label(self.link.interface1)
label_two = None label2 = None
if self.link.HasField("interface_two"): if self.link.HasField("interface2"):
label_two = self.interface_label(self.link.interface_two) label2 = self.interface_label(self.link.interface2)
return label_one, label_two return label1, label2
def draw_labels(self) -> None: def draw_labels(self) -> None:
src_text, dst_text = self.create_node_labels() src_text, dst_text = self.create_node_labels()

View file

@ -300,41 +300,39 @@ class CanvasGraph(tk.Canvas):
# draw existing links # draw existing links
for link in session.links: for link in session.links:
logging.debug("drawing link: %s", link) logging.debug("drawing link: %s", link)
canvas_node_one = self.core.canvas_nodes[link.node_one_id] canvas_node1 = self.core.canvas_nodes[link.node1_id]
node_one = canvas_node_one.core_node node1 = canvas_node1.core_node
canvas_node_two = self.core.canvas_nodes[link.node_two_id] canvas_node2 = self.core.canvas_nodes[link.node2_id]
node_two = canvas_node_two.core_node node2 = canvas_node2.core_node
token = create_edge_token(canvas_node_one.id, canvas_node_two.id) token = create_edge_token(canvas_node1.id, canvas_node2.id)
if link.type == core_pb2.LinkType.WIRELESS: if link.type == core_pb2.LinkType.WIRELESS:
self.add_wireless_edge(canvas_node_one, canvas_node_two, link) self.add_wireless_edge(canvas_node1, canvas_node2, link)
else: else:
if token not in self.edges: if token not in self.edges:
src_pos = (node_one.position.x, node_one.position.y) src_pos = (node1.position.x, node1.position.y)
dst_pos = (node_two.position.x, node_two.position.y) dst_pos = (node2.position.x, node2.position.y)
edge = CanvasEdge(self, canvas_node_one.id, src_pos, dst_pos) edge = CanvasEdge(self, canvas_node1.id, src_pos, dst_pos)
edge.token = token edge.token = token
edge.dst = canvas_node_two.id edge.dst = canvas_node2.id
edge.set_link(link) edge.set_link(link)
edge.check_wireless() edge.check_wireless()
canvas_node_one.edges.add(edge) canvas_node1.edges.add(edge)
canvas_node_two.edges.add(edge) canvas_node2.edges.add(edge)
self.edges[edge.token] = edge self.edges[edge.token] = edge
self.core.links[edge.token] = edge self.core.links[edge.token] = edge
if link.HasField("interface_one"): if link.HasField("interface1"):
interface_one = link.interface_one interface1 = link.interface1
self.core.interface_to_edge[(node1.id, interface1.id)] = token
canvas_node1.interfaces[interface1.id] = interface1
edge.src_interface = interface1
if link.HasField("interface2"):
interface2 = link.interface2
self.core.interface_to_edge[ self.core.interface_to_edge[
(node_one.id, interface_one.id) (node2.id, interface2.id)
] = token
canvas_node_one.interfaces[interface_one.id] = interface_one
edge.src_interface = interface_one
if link.HasField("interface_two"):
interface_two = link.interface_two
self.core.interface_to_edge[
(node_two.id, interface_two.id)
] = edge.token ] = edge.token
canvas_node_two.interfaces[interface_two.id] = interface_two canvas_node2.interfaces[interface2.id] = interface2
edge.dst_interface = interface_two edge.dst_interface = interface2
elif link.options.unidirectional: elif link.options.unidirectional:
edge = self.edges[token] edge = self.edges[token]
edge.asymmetric_link = link edge.asymmetric_link = link
@ -965,26 +963,26 @@ class CanvasGraph(tk.Canvas):
copy_link = copy_edge.link copy_link = copy_edge.link
options = edge.link.options options = edge.link.options
copy_link.options.CopyFrom(options) copy_link.options.CopyFrom(options)
interface_one = None interface1_id = None
if copy_link.HasField("interface_one"): if copy_link.HasField("interface1"):
interface_one = copy_link.interface_one.id interface1_id = copy_link.interface1.id
interface_two = None interface2_id = None
if copy_link.HasField("interface_two"): if copy_link.HasField("interface2"):
interface_two = copy_link.interface_two.id interface2_id = copy_link.interface2.id
if not options.unidirectional: if not options.unidirectional:
copy_edge.asymmetric_link = None copy_edge.asymmetric_link = None
else: else:
asym_interface_one = None asym_interface1 = None
if interface_one: if interface1_id:
asym_interface_one = core_pb2.Interface(id=interface_one) asym_interface1 = core_pb2.Interface(id=interface1_id)
asym_interface_two = None asym_interface2 = None
if interface_two: if interface2_id:
asym_interface_two = core_pb2.Interface(id=interface_two) asym_interface2 = core_pb2.Interface(id=interface2_id)
copy_edge.asymmetric_link = core_pb2.Link( copy_edge.asymmetric_link = core_pb2.Link(
node_one_id=copy_link.node_two_id, node1_id=copy_link.node2_id,
node_two_id=copy_link.node_one_id, node2_id=copy_link.node1_id,
interface_one=asym_interface_one, interface1=asym_interface1,
interface_two=asym_interface_two, interface2=asym_interface2,
options=edge.asymmetric_link.options, options=edge.asymmetric_link.options,
) )
self.itemconfig( self.itemconfig(

View file

@ -89,21 +89,21 @@ class InterfaceManager:
remaining_subnets = set() remaining_subnets = set()
for edge in self.app.core.links.values(): for edge in self.app.core.links.values():
link = edge.link link = edge.link
if link.HasField("interface_one"): if link.HasField("interface1"):
subnets = self.get_subnets(link.interface_one) subnets = self.get_subnets(link.interface1)
remaining_subnets.add(subnets) remaining_subnets.add(subnets)
if link.HasField("interface_two"): if link.HasField("interface2"):
subnets = self.get_subnets(link.interface_two) subnets = self.get_subnets(link.interface2)
remaining_subnets.add(subnets) remaining_subnets.add(subnets)
# remove all subnets from used subnets when no longer present # remove all subnets from used subnets when no longer present
# or remove used indexes from subnet # or remove used indexes from subnet
interfaces = [] interfaces = []
for link in links: for link in links:
if link.HasField("interface_one"): if link.HasField("interface1"):
interfaces.append(link.interface_one) interfaces.append(link.interface1)
if link.HasField("interface_two"): if link.HasField("interface2"):
interfaces.append(link.interface_two) interfaces.append(link.interface2)
for interface in interfaces: for interface in interfaces:
subnets = self.get_subnets(interface) subnets = self.get_subnets(interface)
if subnets not in remaining_subnets: if subnets not in remaining_subnets:
@ -117,10 +117,10 @@ class InterfaceManager:
def joined(self, links: List["core_pb2.Link"]) -> None: def joined(self, links: List["core_pb2.Link"]) -> None:
interfaces = [] interfaces = []
for link in links: for link in links:
if link.HasField("interface_one"): if link.HasField("interface1"):
interfaces.append(link.interface_one) interfaces.append(link.interface1)
if link.HasField("interface_two"): if link.HasField("interface2"):
interfaces.append(link.interface_two) interfaces.append(link.interface2)
# add to used subnets and mark used indexes # add to used subnets and mark used indexes
for interface in interfaces: for interface in interfaces:

View file

@ -63,7 +63,7 @@ class NodeBase:
self.session: "Session" = session self.session: "Session" = session
if _id is None: if _id is None:
_id = session.get_node_id() _id = session.next_node_id()
self.id: int = _id self.id: int = _id
if name is None: if name is None:
name = f"o{self.id}" name = f"o{self.id}"
@ -475,13 +475,13 @@ class CoreNodeBase(NodeBase):
raise NotImplementedError raise NotImplementedError
def newnetif( def newnetif(
self, net: "CoreNetworkBase", interface: InterfaceData self, net: "CoreNetworkBase", interface_data: InterfaceData
) -> CoreInterface: ) -> CoreInterface:
""" """
Create a new network interface. Create a new network interface.
:param net: network to associate with :param net: network to associate with
:param interface: interface data for new interface :param interface_data: interface data for new interface
:return: interface index :return: interface index
""" """
raise NotImplementedError raise NotImplementedError
@ -860,34 +860,34 @@ class CoreNode(CoreNodeBase):
self.node_net_client.device_up(interface_name) self.node_net_client.device_up(interface_name)
def newnetif( def newnetif(
self, net: "CoreNetworkBase", interface: InterfaceData self, net: "CoreNetworkBase", interface_data: InterfaceData
) -> CoreInterface: ) -> CoreInterface:
""" """
Create a new network interface. Create a new network interface.
:param net: network to associate with :param net: network to associate with
:param interface: interface data for new interface :param interface_data: interface data for new interface
:return: interface index :return: interface index
""" """
addresses = interface.get_addresses() addresses = interface_data.get_addresses()
with self.lock: with self.lock:
# TODO: emane specific code # TODO: emane specific code
if net.is_emane is True: if net.is_emane is True:
ifindex = self.newtuntap(interface.id, interface.name) ifindex = self.newtuntap(interface_data.id, interface_data.name)
# TUN/TAP is not ready for addressing yet; the device may # TUN/TAP is not ready for addressing yet; the device may
# take some time to appear, and installing it into a # take some time to appear, and installing it into a
# namespace after it has been bound removes addressing; # namespace after it has been bound removes addressing;
# save addresses with the interface now # save addresses with the interface now
self.attachnet(ifindex, net) self.attachnet(ifindex, net)
netif = self.netif(ifindex) netif = self.netif(ifindex)
netif.sethwaddr(interface.mac) netif.sethwaddr(interface_data.mac)
for address in addresses: for address in addresses:
netif.addaddr(address) netif.addaddr(address)
else: else:
ifindex = self.newveth(interface.id, interface.name) ifindex = self.newveth(interface_data.id, interface_data.name)
self.attachnet(ifindex, net) self.attachnet(ifindex, net)
if interface.mac: if interface_data.mac:
self.sethwaddr(ifindex, interface.mac) self.sethwaddr(ifindex, interface_data.mac)
for address in addresses: for address in addresses:
self.addaddr(ifindex, address) self.addaddr(ifindex, address)
self.ifup(ifindex) self.ifup(ifindex)

View file

@ -157,25 +157,27 @@ class PhysicalNode(CoreNodeBase):
self.ifindex += 1 self.ifindex += 1
return ifindex return ifindex
def newnetif(self, net: CoreNetworkBase, interface: InterfaceData) -> CoreInterface: def newnetif(
self, net: CoreNetworkBase, interface_data: InterfaceData
) -> CoreInterface:
logging.info("creating interface") logging.info("creating interface")
addresses = interface.get_addresses() addresses = interface_data.get_addresses()
ifindex = interface.id ifindex = interface_data.id
if ifindex is None: if ifindex is None:
ifindex = self.newifindex() ifindex = self.newifindex()
name = interface.name name = interface_data.name
if name is None: if name is None:
name = f"gt{ifindex}" name = f"gt{ifindex}"
if self.up: if self.up:
# this is reached when this node is linked to a network node # this is reached when this node is linked to a network node
# tunnel to net not built yet, so build it now and adopt it # tunnel to net not built yet, so build it now and adopt it
_, remote_tap = self.session.distributed.create_gre_tunnel(net, self.server) _, remote_tap = self.session.distributed.create_gre_tunnel(net, self.server)
self.adoptnetif(remote_tap, ifindex, interface.mac, addresses) self.adoptnetif(remote_tap, ifindex, interface_data.mac, addresses)
return remote_tap return remote_tap
else: else:
# this is reached when configuring services (self.up=False) # this is reached when configuring services (self.up=False)
netif = GreTap(node=self, name=name, session=self.session, start=False) netif = GreTap(node=self, name=name, session=self.session, start=False)
self.adoptnetif(netif, ifindex, interface.mac, addresses) self.adoptnetif(netif, ifindex, interface_data.mac, addresses)
return netif return netif
def privatedir(self, path: str) -> None: def privatedir(self, path: str) -> None:
@ -297,19 +299,21 @@ class Rj45Node(CoreNodeBase):
self.up = False self.up = False
self.restorestate() self.restorestate()
def newnetif(self, net: CoreNetworkBase, interface: InterfaceData) -> CoreInterface: def newnetif(
self, net: CoreNetworkBase, interface_data: InterfaceData
) -> CoreInterface:
""" """
This is called when linking with another node. Since this node This is called when linking with another node. Since this node
represents an interface, we do not create another object here, represents an interface, we do not create another object here,
but attach ourselves to the given network. but attach ourselves to the given network.
:param net: new network instance :param net: new network instance
:param interface: interface data for new interface :param interface_data: interface data for new interface
:return: interface index :return: interface index
:raises ValueError: when an interface has already been created, one max :raises ValueError: when an interface has already been created, one max
""" """
with self.lock: with self.lock:
ifindex = interface.id ifindex = interface_data.id
if ifindex is None: if ifindex is None:
ifindex = 0 ifindex = 0
if self.interface.net is not None: if self.interface.net is not None:
@ -318,7 +322,7 @@ class Rj45Node(CoreNodeBase):
self.ifindex = ifindex self.ifindex = ifindex
if net is not None: if net is not None:
self.interface.attachnet(net) self.interface.attachnet(net)
for addr in interface.get_addresses(): for addr in interface_data.get_addresses():
self.addaddr(addr) self.addaddr(addr)
return self.interface return self.interface

View file

@ -21,8 +21,8 @@ if TYPE_CHECKING:
from core.emulator.session import Session from core.emulator.session import Session
def get_link_id(node_one: int, node_two: int, network_id: int) -> str: def get_link_id(node1_id: int, node2_id: int, network_id: int) -> str:
link_id = f"{node_one}-{node_two}" link_id = f"{node1_id}-{node2_id}"
if network_id is not None: if network_id is not None:
link_id = f"{link_id}-{network_id}" link_id = f"{link_id}-{network_id}"
return link_id return link_id
@ -215,7 +215,7 @@ class Sdt:
for layer in CORE_LAYERS: for layer in CORE_LAYERS:
self.cmd(f"layer {layer}") self.cmd(f"layer {layer}")
with self.session._nodes_lock: with self.session.nodes_lock:
for node_id in self.session.nodes: for node_id in self.session.nodes:
node = self.session.nodes[node_id] node = self.session.nodes[node_id]
if isinstance(node, CoreNetworkBase): if isinstance(node, CoreNetworkBase):
@ -351,27 +351,27 @@ class Sdt:
return result return result
def add_link( def add_link(
self, node_one: int, node_two: int, network_id: int = None, label: str = None self, node1_id: int, node2_id: int, network_id: int = None, label: str = None
) -> None: ) -> None:
""" """
Handle adding a link in SDT. Handle adding a link in SDT.
:param node_one: node one id :param node1_id: node one id
:param node_two: node two id :param node2_id: node two id
:param network_id: network link is associated with, None otherwise :param network_id: network link is associated with, None otherwise
:param label: label for link :param label: label for link
:return: nothing :return: nothing
""" """
logging.debug("sdt add link: %s, %s, %s", node_one, node_two, network_id) logging.debug("sdt add link: %s, %s, %s", node1_id, node2_id, network_id)
if not self.connect(): if not self.connect():
return return
if self.wireless_net_check(node_one) or self.wireless_net_check(node_two): if self.wireless_net_check(node1_id) or self.wireless_net_check(node2_id):
return return
color = DEFAULT_LINK_COLOR color = DEFAULT_LINK_COLOR
if network_id: if network_id:
color = self.session.get_link_color(network_id) color = self.session.get_link_color(network_id)
line = f"{color},2" line = f"{color},2"
link_id = get_link_id(node_one, node_two, network_id) link_id = get_link_id(node1_id, node2_id, network_id)
layer = LINK_LAYER layer = LINK_LAYER
if network_id: if network_id:
node = self.session.nodes.get(network_id) node = self.session.nodes.get(network_id)
@ -383,47 +383,47 @@ class Sdt:
if label: if label:
link_label = f'linklabel on,"{label}"' link_label = f'linklabel on,"{label}"'
self.cmd( self.cmd(
f"link {node_one},{node_two},{link_id} linkLayer {layer} line {line} " f"link {node1_id},{node2_id},{link_id} linkLayer {layer} line {line} "
f"{link_label}" f"{link_label}"
) )
def delete_link(self, node_one: int, node_two: int, network_id: int = None) -> None: def delete_link(self, node1_id: int, node2_id: int, network_id: int = None) -> None:
""" """
Handle deleting a link in SDT. Handle deleting a link in SDT.
:param node_one: node one id :param node1_id: node one id
:param node_two: node two id :param node2_id: node two id
:param network_id: network link is associated with, None otherwise :param network_id: network link is associated with, None otherwise
:return: nothing :return: nothing
""" """
logging.debug("sdt delete link: %s, %s, %s", node_one, node_two, network_id) logging.debug("sdt delete link: %s, %s, %s", node1_id, node2_id, network_id)
if not self.connect(): if not self.connect():
return return
if self.wireless_net_check(node_one) or self.wireless_net_check(node_two): if self.wireless_net_check(node1_id) or self.wireless_net_check(node2_id):
return return
link_id = get_link_id(node_one, node_two, network_id) link_id = get_link_id(node1_id, node2_id, network_id)
self.cmd(f"delete link,{node_one},{node_two},{link_id}") self.cmd(f"delete link,{node1_id},{node2_id},{link_id}")
def edit_link( def edit_link(
self, node_one: int, node_two: int, network_id: int, label: str self, node1_id: int, node2_id: int, network_id: int, label: str
) -> None: ) -> None:
""" """
Handle editing a link in SDT. Handle editing a link in SDT.
:param node_one: node one id :param node1_id: node one id
:param node_two: node two id :param node2_id: node two id
:param network_id: network link is associated with, None otherwise :param network_id: network link is associated with, None otherwise
:param label: label to update :param label: label to update
:return: nothing :return: nothing
""" """
logging.debug("sdt edit link: %s, %s, %s", node_one, node_two, network_id) logging.debug("sdt edit link: %s, %s, %s", node1_id, node2_id, network_id)
if not self.connect(): if not self.connect():
return return
if self.wireless_net_check(node_one) or self.wireless_net_check(node_two): if self.wireless_net_check(node1_id) or self.wireless_net_check(node2_id):
return return
link_id = get_link_id(node_one, node_two, network_id) link_id = get_link_id(node1_id, node2_id, network_id)
link_label = f'linklabel on,"{label}"' link_label = f'linklabel on,"{label}"'
self.cmd(f"link {node_one},{node_two},{link_id} {link_label}") self.cmd(f"link {node1_id},{node2_id},{link_id} {link_label}")
def handle_link_update(self, link_data: LinkData) -> None: def handle_link_update(self, link_data: LinkData) -> None:
""" """
@ -432,13 +432,13 @@ class Sdt:
:param link_data: link data to handle :param link_data: link data to handle
:return: nothing :return: nothing
""" """
node_one = link_data.node1_id node1_id = link_data.node1_id
node_two = link_data.node2_id node2_id = link_data.node2_id
network_id = link_data.network_id network_id = link_data.network_id
label = link_data.label label = link_data.label
if link_data.message_type == MessageFlags.ADD: if link_data.message_type == MessageFlags.ADD:
self.add_link(node_one, node_two, network_id, label) self.add_link(node1_id, node2_id, network_id, label)
elif link_data.message_type == MessageFlags.DELETE: elif link_data.message_type == MessageFlags.DELETE:
self.delete_link(node_one, node_two, network_id) self.delete_link(node1_id, node2_id, network_id)
elif link_data.message_type == MessageFlags.NONE and label: elif link_data.message_type == MessageFlags.NONE and label:
self.edit_link(node_one, node_two, network_id, label) self.edit_link(node1_id, node2_id, network_id, label)

View file

@ -325,7 +325,13 @@ class CoreServices:
""" """
self.session = session self.session = session
# dict of default services tuples, key is node type # dict of default services tuples, key is node type
self.default_services = {} self.default_services = {
"mdr": ("zebra", "OSPFv3MDR", "IPForward"),
"PC": ("DefaultRoute",),
"prouter": (),
"router": ("zebra", "OSPFv2", "OSPFv3", "IPForward"),
"host": ("DefaultRoute", "SSH"),
}
# dict of node ids to dict of custom services by name # dict of node ids to dict of custom services by name
self.custom_services = {} self.custom_services = {}

View file

@ -320,8 +320,8 @@ class CoreXmlWriter:
def write_session_hooks(self) -> None: def write_session_hooks(self) -> None:
# hook scripts # hook scripts
hooks = etree.Element("session_hooks") hooks = etree.Element("session_hooks")
for state in sorted(self.session._hooks, key=lambda x: x.value): for state in sorted(self.session.hooks, key=lambda x: x.value):
for file_name, data in self.session._hooks[state]: for file_name, data in self.session.hooks[state]:
hook = etree.SubElement(hooks, "hook") hook = etree.SubElement(hooks, "hook")
add_attribute(hook, "name", file_name) add_attribute(hook, "name", file_name)
add_attribute(hook, "state", state.value) add_attribute(hook, "state", state.value)
@ -534,7 +534,7 @@ class CoreXmlWriter:
# check for interface one # check for interface one
if link_data.interface1_id is not None: if link_data.interface1_id is not None:
interface_one = self.create_interface_element( interface1 = self.create_interface_element(
"interface_one", "interface_one",
link_data.node1_id, link_data.node1_id,
link_data.interface1_id, link_data.interface1_id,
@ -544,11 +544,11 @@ class CoreXmlWriter:
link_data.interface1_ip6, link_data.interface1_ip6,
link_data.interface1_ip6_mask, link_data.interface1_ip6_mask,
) )
link_element.append(interface_one) link_element.append(interface1)
# check for interface two # check for interface two
if link_data.interface2_id is not None: if link_data.interface2_id is not None:
interface_two = self.create_interface_element( interface2 = self.create_interface_element(
"interface_two", "interface_two",
link_data.node2_id, link_data.node2_id,
link_data.interface2_id, link_data.interface2_id,
@ -558,14 +558,14 @@ class CoreXmlWriter:
link_data.interface2_ip6, link_data.interface2_ip6,
link_data.interface2_ip6_mask, link_data.interface2_ip6_mask,
) )
link_element.append(interface_two) link_element.append(interface2)
# check for options, don't write for emane/wlan links # check for options, don't write for emane/wlan links
node_one = self.session.get_node(link_data.node1_id, NodeBase) node1 = self.session.get_node(link_data.node1_id, NodeBase)
node_two = self.session.get_node(link_data.node2_id, NodeBase) node2 = self.session.get_node(link_data.node2_id, NodeBase)
is_node_one_wireless = isinstance(node_one, (WlanNode, EmaneNet)) is_node1_wireless = isinstance(node1, (WlanNode, EmaneNet))
is_node_two_wireless = isinstance(node_two, (WlanNode, EmaneNet)) is_node2_wireless = isinstance(node2, (WlanNode, EmaneNet))
if not any([is_node_one_wireless, is_node_two_wireless]): if not any([is_node1_wireless, is_node2_wireless]):
options = etree.Element("options") options = etree.Element("options")
add_attribute(options, "delay", link_data.delay) add_attribute(options, "delay", link_data.delay)
add_attribute(options, "bandwidth", link_data.bandwidth) add_attribute(options, "bandwidth", link_data.bandwidth)
@ -932,19 +932,19 @@ class CoreXmlReader:
node_sets = set() node_sets = set()
for link_element in link_elements.iterchildren(): for link_element in link_elements.iterchildren():
node_one = get_int(link_element, "node_one") node1_id = get_int(link_element, "node_one")
node_two = get_int(link_element, "node_two") node2_id = get_int(link_element, "node_two")
node_set = frozenset((node_one, node_two)) node_set = frozenset((node1_id, node2_id))
interface_one_element = link_element.find("interface_one") interface1_element = link_element.find("interface_one")
interface_one = None interface1_data = None
if interface_one_element is not None: if interface1_element is not None:
interface_one = create_interface_data(interface_one_element) interface1_data = create_interface_data(interface1_element)
interface_two_element = link_element.find("interface_two") interface2_element = link_element.find("interface_two")
interface_two = None interface2_data = None
if interface_two_element is not None: if interface2_element is not None:
interface_two = create_interface_data(interface_two_element) interface2_data = create_interface_data(interface2_element)
options_element = link_element.find("options") options_element = link_element.find("options")
options = LinkOptions() options = LinkOptions()
@ -968,18 +968,14 @@ class CoreXmlReader:
options.gui_attributes = options_element.get("gui_attributes") options.gui_attributes = options_element.get("gui_attributes")
if options.unidirectional == 1 and node_set in node_sets: if options.unidirectional == 1 and node_set in node_sets:
logging.info( logging.info("updating link node1(%s) node2(%s)", node1_id, node2_id)
"updating link node_one(%s) node_two(%s)", node_one, node_two
)
self.session.update_link( self.session.update_link(
node_one, node_two, interface_one.id, interface_two.id, options node1_id, node2_id, interface1_data.id, interface2_data.id, options
) )
else: else:
logging.info( logging.info("adding link node1(%s) node2(%s)", node1_id, node2_id)
"adding link node_one(%s) node_two(%s)", node_one, node_two
)
self.session.add_link( self.session.add_link(
node_one, node_two, interface_one, interface_two, options node1_id, node2_id, interface1_data, interface2_data, options
) )
node_sets.add(node_set) node_sets.add(node_set)

View file

@ -11,7 +11,7 @@ if __name__ == "__main__":
# setup basic network # setup basic network
prefixes = IpPrefixes(ip4_prefix="10.83.0.0/16") prefixes = IpPrefixes(ip4_prefix="10.83.0.0/16")
options = NodeOptions(model="nothing") options = NodeOptions(model=None)
coreemu = CoreEmu() coreemu = CoreEmu()
session = coreemu.create_session() session = coreemu.create_session()
session.set_state(EventTypes.CONFIGURATION_STATE) session.set_state(EventTypes.CONFIGURATION_STATE)
@ -19,14 +19,14 @@ if __name__ == "__main__":
# node one # node one
options.config_services = ["DefaultRoute", "IPForward"] options.config_services = ["DefaultRoute", "IPForward"]
node_one = session.add_node(CoreNode, options=options) node1 = session.add_node(CoreNode, options=options)
interface = prefixes.create_interface(node_one) interface = prefixes.create_interface(node1)
session.add_link(node_one.id, switch.id, interface_one=interface) session.add_link(node1.id, switch.id, interface1_data=interface)
# node two # node two
node_two = session.add_node(CoreNode, options=options) node2 = session.add_node(CoreNode, options=options)
interface = prefixes.create_interface(node_two) interface = prefixes.create_interface(node2)
session.add_link(node_two.id, switch.id, interface_one=interface) session.add_link(node2.id, switch.id, interface1_data=interface)
# start session and run services # start session and run services
session.instantiate() session.instantiate()

View file

@ -17,15 +17,15 @@ if __name__ == "__main__":
options = NodeOptions(model=None, image="ubuntu") options = NodeOptions(model=None, image="ubuntu")
# create node one # create node one
node_one = session.add_node(DockerNode, options=options) node1 = session.add_node(DockerNode, options=options)
interface_one = prefixes.create_interface(node_one) interface1_data = prefixes.create_interface(node1)
# create node two # create node two
node_two = session.add_node(CoreNode) node2 = session.add_node(CoreNode)
interface_two = prefixes.create_interface(node_two) interface2_data = prefixes.create_interface(node2)
# add link # add link
session.add_link(node_one.id, node_two.id, interface_one, interface_two) session.add_link(node1.id, node2.id, interface1_data, interface2_data)
# instantiate # instantiate
session.instantiate() session.instantiate()

View file

@ -18,15 +18,15 @@ if __name__ == "__main__":
options = NodeOptions(model=None, image="ubuntu") options = NodeOptions(model=None, image="ubuntu")
# create node one # create node one
node_one = session.add_node(DockerNode, options=options) node1 = session.add_node(DockerNode, options=options)
interface_one = prefixes.create_interface(node_one) interface1_data = prefixes.create_interface(node1)
# create node two # create node two
node_two = session.add_node(DockerNode, options=options) node2 = session.add_node(DockerNode, options=options)
interface_two = prefixes.create_interface(node_two) interface2_data = prefixes.create_interface(node2)
# add link # add link
session.add_link(node_one.id, node_two.id, interface_one, interface_two) session.add_link(node1.id, node2.id, interface1_data, interface2_data)
# instantiate # instantiate
session.instantiate() session.instantiate()

View file

@ -22,20 +22,20 @@ if __name__ == "__main__":
switch = session.add_node(SwitchNode) switch = session.add_node(SwitchNode)
# node one # node one
node_one = session.add_node(DockerNode, options=options) node1 = session.add_node(DockerNode, options=options)
interface_one = prefixes.create_interface(node_one) interface1_data = prefixes.create_interface(node1)
# node two # node two
node_two = session.add_node(DockerNode, options=options) node2 = session.add_node(DockerNode, options=options)
interface_two = prefixes.create_interface(node_two) interface2_data = prefixes.create_interface(node2)
# node three # node three
node_three = session.add_node(CoreNode) node_three = session.add_node(CoreNode)
interface_three = prefixes.create_interface(node_three) interface_three = prefixes.create_interface(node_three)
# add links # add links
session.add_link(node_one.id, switch.id, interface_one) session.add_link(node1.id, switch.id, interface1_data)
session.add_link(node_two.id, switch.id, interface_two) session.add_link(node2.id, switch.id, interface2_data)
session.add_link(node_three.id, switch.id, interface_three) session.add_link(node_three.id, switch.id, interface_three)
# instantiate # instantiate

View file

@ -44,11 +44,11 @@ def main(args):
node = Node(position=position) node = Node(position=position)
response = core.add_node(session_id, node) response = core.add_node(session_id, node)
logging.info("created node one: %s", response) logging.info("created node one: %s", response)
node_one_id = response.node_id node1_id = response.node_id
# create link # create link
interface_one = interface_helper.create_interface(node_one_id, 0) interface1 = interface_helper.create_interface(node1_id, 0)
response = core.add_link(session_id, node_one_id, switch_id, interface_one) response = core.add_link(session_id, node1_id, switch_id, interface1)
logging.info("created link from node one to switch: %s", response) logging.info("created link from node one to switch: %s", response)
# create node two # create node two
@ -56,11 +56,11 @@ def main(args):
node = Node(position=position, server=server_name) node = Node(position=position, server=server_name)
response = core.add_node(session_id, node) response = core.add_node(session_id, node)
logging.info("created node two: %s", response) logging.info("created node two: %s", response)
node_two_id = response.node_id node2_id = response.node_id
# create link # create link
interface_one = interface_helper.create_interface(node_two_id, 0) interface1 = interface_helper.create_interface(node2_id, 0)
response = core.add_link(session_id, node_two_id, switch_id, interface_one) response = core.add_link(session_id, node2_id, switch_id, interface1)
logging.info("created link from node two to switch: %s", response) logging.info("created link from node two to switch: %s", response)
# change session state # change session state

View file

@ -57,11 +57,11 @@ def main():
node2_id = response.node_id node2_id = response.node_id
# links nodes to switch # links nodes to switch
interface_one = interface_helper.create_interface(node1_id, 0) interface1 = interface_helper.create_interface(node1_id, 0)
response = core.add_link(session_id, node1_id, emane_id, interface_one) response = core.add_link(session_id, node1_id, emane_id, interface1)
logging.info("created link: %s", response) logging.info("created link: %s", response)
interface_one = interface_helper.create_interface(node2_id, 0) interface1 = interface_helper.create_interface(node2_id, 0)
response = core.add_link(session_id, node2_id, emane_id, interface_one) response = core.add_link(session_id, node2_id, emane_id, interface1)
logging.info("created link: %s", response) logging.info("created link: %s", response)
# change session state # change session state

View file

@ -53,11 +53,11 @@ def main():
node2_id = response.node_id node2_id = response.node_id
# links nodes to switch # links nodes to switch
interface_one = interface_helper.create_interface(node1_id, 0) interface1 = interface_helper.create_interface(node1_id, 0)
response = core.add_link(session_id, node1_id, switch_id, interface_one) response = core.add_link(session_id, node1_id, switch_id, interface1)
logging.info("created link: %s", response) logging.info("created link: %s", response)
interface_one = interface_helper.create_interface(node2_id, 0) interface1 = interface_helper.create_interface(node2_id, 0)
response = core.add_link(session_id, node2_id, switch_id, interface_one) response = core.add_link(session_id, node2_id, switch_id, interface1)
logging.info("created link: %s", response) logging.info("created link: %s", response)
# change session state # change session state

View file

@ -65,11 +65,11 @@ def main():
node2_id = response.node_id node2_id = response.node_id
# links nodes to switch # links nodes to switch
interface_one = interface_helper.create_interface(node1_id, 0) interface1 = interface_helper.create_interface(node1_id, 0)
response = core.add_link(session_id, node1_id, wlan_id, interface_one) response = core.add_link(session_id, node1_id, wlan_id, interface1)
logging.info("created link: %s", response) logging.info("created link: %s", response)
interface_one = interface_helper.create_interface(node2_id, 0) interface1 = interface_helper.create_interface(node2_id, 0)
response = core.add_link(session_id, node2_id, wlan_id, interface_one) response = core.add_link(session_id, node2_id, wlan_id, interface1)
logging.info("created link: %s", response) logging.info("created link: %s", response)
# change session state # change session state

View file

@ -17,15 +17,15 @@ if __name__ == "__main__":
options = NodeOptions(image="ubuntu") options = NodeOptions(image="ubuntu")
# create node one # create node one
node_one = session.add_node(LxcNode, options=options) node1 = session.add_node(LxcNode, options=options)
interface_one = prefixes.create_interface(node_one) interface1_data = prefixes.create_interface(node1)
# create node two # create node two
node_two = session.add_node(CoreNode) node2 = session.add_node(CoreNode)
interface_two = prefixes.create_interface(node_two) interface2_data = prefixes.create_interface(node2)
# add link # add link
session.add_link(node_one.id, node_two.id, interface_one, interface_two) session.add_link(node1.id, node2.id, interface1_data, interface2_data)
# instantiate # instantiate
session.instantiate() session.instantiate()

View file

@ -18,15 +18,15 @@ if __name__ == "__main__":
options = NodeOptions(image="ubuntu:18.04") options = NodeOptions(image="ubuntu:18.04")
# create node one # create node one
node_one = session.add_node(LxcNode, options=options) node1 = session.add_node(LxcNode, options=options)
interface_one = prefixes.create_interface(node_one) interface1_data = prefixes.create_interface(node1)
# create node two # create node two
node_two = session.add_node(LxcNode, options=options) node2 = session.add_node(LxcNode, options=options)
interface_two = prefixes.create_interface(node_two) interface2_data = prefixes.create_interface(node2)
# add link # add link
session.add_link(node_one.id, node_two.id, interface_one, interface_two) session.add_link(node1.id, node2.id, interface1_data, interface2_data)
# instantiate # instantiate
session.instantiate() session.instantiate()

View file

@ -22,21 +22,21 @@ if __name__ == "__main__":
switch = session.add_node(SwitchNode) switch = session.add_node(SwitchNode)
# node one # node one
node_one = session.add_node(LxcNode, options=options) node1 = session.add_node(LxcNode, options=options)
interface_one = prefixes.create_interface(node_one) interface1_data = prefixes.create_interface(node1)
# node two # node two
node_two = session.add_node(LxcNode, options=options) node2 = session.add_node(LxcNode, options=options)
interface_two = prefixes.create_interface(node_two) interface2_data = prefixes.create_interface(node2)
# node three # node three
node_three = session.add_node(CoreNode) node3 = session.add_node(CoreNode)
interface_three = prefixes.create_interface(node_three) interface3_data = prefixes.create_interface(node3)
# add links # add links
session.add_link(node_one.id, switch.id, interface_one) session.add_link(node1.id, switch.id, interface1_data)
session.add_link(node_two.id, switch.id, interface_two) session.add_link(node2.id, switch.id, interface2_data)
session.add_link(node_three.id, switch.id, interface_three) session.add_link(node3.id, switch.id, interface3_data)
# instantiate # instantiate
session.instantiate() session.instantiate()

View file

@ -52,17 +52,17 @@ def main(args):
# create local node, switch, and remote nodes # create local node, switch, and remote nodes
options = NodeOptions(model="mdr") options = NodeOptions(model="mdr")
options.set_position(0, 0) options.set_position(0, 0)
node_one = session.add_node(CoreNode, options=options) node1 = session.add_node(CoreNode, options=options)
emane_net = session.add_node(EmaneNet) emane_net = session.add_node(EmaneNet)
session.emane.set_model(emane_net, EmaneIeee80211abgModel) session.emane.set_model(emane_net, EmaneIeee80211abgModel)
options.server = server_name options.server = server_name
node_two = session.add_node(CoreNode, options=options) node2 = session.add_node(CoreNode, options=options)
# create node interfaces and link # create node interfaces and link
interface_one = prefixes.create_interface(node_one) interface1_data = prefixes.create_interface(node1)
interface_two = prefixes.create_interface(node_two) interface2_data = prefixes.create_interface(node2)
session.add_link(node_one.id, emane_net.id, interface_one=interface_one) session.add_link(node1.id, emane_net.id, interface1_data=interface1_data)
session.add_link(node_two.id, emane_net.id, interface_one=interface_two) session.add_link(node2.id, emane_net.id, interface1_data=interface2_data)
# instantiate session # instantiate session
session.instantiate() session.instantiate()

View file

@ -43,14 +43,14 @@ def main(args):
# create local node, switch, and remote nodes # create local node, switch, and remote nodes
options = NodeOptions(image="ubuntu:18.04") options = NodeOptions(image="ubuntu:18.04")
node_one = session.add_node(LxcNode, options=options) node1 = session.add_node(LxcNode, options=options)
options.server = server_name options.server = server_name
node_two = session.add_node(LxcNode, options=options) node2 = session.add_node(LxcNode, options=options)
# create node interfaces and link # create node interfaces and link
interface_one = prefixes.create_interface(node_one) interface1_data = prefixes.create_interface(node1)
interface_two = prefixes.create_interface(node_two) interface2_data = prefixes.create_interface(node2)
session.add_link(node_one.id, node_two.id, interface_one, interface_two) session.add_link(node1.id, node2.id, interface1_data, interface2_data)
# instantiate session # instantiate session
session.instantiate() session.instantiate()

View file

@ -43,14 +43,14 @@ def main(args):
# create local node, switch, and remote nodes # create local node, switch, and remote nodes
options = NodeOptions() options = NodeOptions()
node_one = session.add_node(CoreNode, options=options) node1 = session.add_node(CoreNode, options=options)
options.server = server_name options.server = server_name
node_two = session.add_node(CoreNode, options=options) node2 = session.add_node(CoreNode, options=options)
# create node interfaces and link # create node interfaces and link
interface_one = prefixes.create_interface(node_one) interface1_data = prefixes.create_interface(node1)
interface_two = prefixes.create_interface(node_two) interface2_data = prefixes.create_interface(node2)
session.add_link(node_one.id, node_two.id, interface_one, interface_two) session.add_link(node1.id, node2.id, interface1_data, interface2_data)
# instantiate session # instantiate session
session.instantiate() session.instantiate()

View file

@ -45,17 +45,17 @@ def main(args):
session.set_state(EventTypes.CONFIGURATION_STATE) session.set_state(EventTypes.CONFIGURATION_STATE)
# create local node, switch, and remote nodes # create local node, switch, and remote nodes
node_one = session.add_node(CoreNode) node1 = session.add_node(CoreNode)
switch = session.add_node(SwitchNode) switch = session.add_node(SwitchNode)
options = NodeOptions() options = NodeOptions()
options.server = server_name options.server = server_name
node_two = session.add_node(CoreNode, options=options) node2 = session.add_node(CoreNode, options=options)
# create node interfaces and link # create node interfaces and link
interface_one = prefixes.create_interface(node_one) interface1_data = prefixes.create_interface(node1)
interface_two = prefixes.create_interface(node_two) interface2_data = prefixes.create_interface(node2)
session.add_link(node_one.id, switch.id, interface_one=interface_one) session.add_link(node1.id, switch.id, interface1_data=interface1_data)
session.add_link(node_two.id, switch.id, interface_one=interface_two) session.add_link(node2.id, switch.id, interface1_data=interface2_data)
# instantiate session # instantiate session
session.instantiate() session.instantiate()

View file

@ -43,7 +43,7 @@ def main():
node = session.add_node(CoreNode, options=options) node = session.add_node(CoreNode, options=options)
node.setposition(x=150 * (i + 1), y=150) node.setposition(x=150 * (i + 1), y=150)
interface = prefixes.create_interface(node) interface = prefixes.create_interface(node)
session.add_link(node.id, emane_network.id, interface_one=interface) session.add_link(node.id, emane_network.id, interface1_data=interface)
# instantiate session # instantiate session
session.instantiate() session.instantiate()

View file

@ -32,7 +32,7 @@ def main():
for _ in range(NODES): for _ in range(NODES):
node = session.add_node(CoreNode) node = session.add_node(CoreNode)
interface = prefixes.create_interface(node) interface = prefixes.create_interface(node)
session.add_link(node.id, switch.id, interface_one=interface) session.add_link(node.id, switch.id, interface1_data=interface)
# instantiate session # instantiate session
session.instantiate() session.instantiate()

View file

@ -34,7 +34,7 @@ def main():
for _ in range(NODES): for _ in range(NODES):
node = session.add_node(CoreNode) node = session.add_node(CoreNode)
interface = prefixes.create_interface(node) interface = prefixes.create_interface(node)
session.add_link(node.id, switch.id, interface_one=interface) session.add_link(node.id, switch.id, interface1_data=interface)
# instantiate session # instantiate session
session.instantiate() session.instantiate()

View file

@ -36,7 +36,7 @@ def main():
for _ in range(NODES): for _ in range(NODES):
node = session.add_node(CoreNode, options=options) node = session.add_node(CoreNode, options=options)
interface = prefixes.create_interface(node) interface = prefixes.create_interface(node)
session.add_link(node.id, wlan.id, interface_one=interface) session.add_link(node.id, wlan.id, interface1_data=interface)
# instantiate session # instantiate session
session.instantiate() session.instantiate()

View file

@ -492,16 +492,16 @@ message AddLinkRequest {
message AddLinkResponse { message AddLinkResponse {
bool result = 1; bool result = 1;
Interface interface_one = 2; Interface interface1 = 2;
Interface interface_two = 3; Interface interface2 = 3;
} }
message EditLinkRequest { message EditLinkRequest {
int32 session_id = 1; int32 session_id = 1;
int32 node_one_id = 2; int32 node1_id = 2;
int32 node_two_id = 3; int32 node2_id = 3;
int32 interface_one_id = 4; int32 interface1_id = 4;
int32 interface_two_id = 5; int32 interface2_id = 5;
LinkOptions options = 6; LinkOptions options = 6;
} }
@ -511,10 +511,10 @@ message EditLinkResponse {
message DeleteLinkRequest { message DeleteLinkRequest {
int32 session_id = 1; int32 session_id = 1;
int32 node_one_id = 2; int32 node1_id = 2;
int32 node_two_id = 3; int32 node2_id = 3;
int32 interface_one_id = 4; int32 interface1_id = 4;
int32 interface_two_id = 5; int32 interface2_id = 5;
} }
message DeleteLinkResponse { message DeleteLinkResponse {
@ -702,11 +702,11 @@ message Node {
} }
message Link { message Link {
int32 node_one_id = 1; int32 node1_id = 1;
int32 node_two_id = 2; int32 node2_id = 2;
LinkType.Enum type = 3; LinkType.Enum type = 3;
Interface interface_one = 4; Interface interface1 = 4;
Interface interface_two = 5; Interface interface2 = 5;
LinkOptions options = 6; LinkOptions options = 6;
int32 network_id = 7; int32 network_id = 7;
string label = 8; string label = 8;

View file

@ -75,8 +75,8 @@ message GetEmaneEventChannelResponse {
message EmaneLinkRequest { message EmaneLinkRequest {
int32 session_id = 1; int32 session_id = 1;
int32 nem_one = 2; int32 nem1 = 2;
int32 nem_two = 3; int32 nem2 = 3;
bool linked = 4; bool linked = 4;
} }
@ -93,12 +93,12 @@ message EmaneModelConfig {
message EmanePathlossesRequest { message EmanePathlossesRequest {
int32 session_id = 1; int32 session_id = 1;
int32 node_one = 2; int32 node1_id = 2;
float rx_one = 3; float rx1 = 3;
int32 interface_one_id = 4; int32 interface1_id = 4;
int32 node_two = 5; int32 node2_id = 5;
float rx_two = 6; float rx2 = 6;
int32 interface_two_id = 7; int32 interface2_id = 7;
} }
message EmanePathlossesResponse { message EmanePathlossesResponse {

View file

@ -38,8 +38,8 @@ message SetWlanConfigResponse {
message WlanLinkRequest { message WlanLinkRequest {
int32 session_id = 1; int32 session_id = 1;
int32 wlan = 2; int32 wlan = 2;
int32 node_one = 3; int32 node1_id = 3;
int32 node_two = 4; int32 node2_id = 4;
bool linked = 5; bool linked = 5;
} }

View file

@ -3,6 +3,7 @@ Unit tests for testing CORE EMANE networks.
""" """
import os import os
from tempfile import TemporaryFile from tempfile import TemporaryFile
from typing import Type
from xml.etree import ElementTree from xml.etree import ElementTree
import pytest import pytest
@ -43,7 +44,9 @@ def ping(
class TestEmane: class TestEmane:
@pytest.mark.parametrize("model", _EMANE_MODELS) @pytest.mark.parametrize("model", _EMANE_MODELS)
def test_models(self, session: Session, model: EmaneModel, ip_prefixes: IpPrefixes): def test_models(
self, session: Session, model: Type[EmaneModel], ip_prefixes: IpPrefixes
):
""" """
Test emane models within a basic network. Test emane models within a basic network.
@ -70,20 +73,20 @@ class TestEmane:
# create nodes # create nodes
options = NodeOptions(model="mdr") options = NodeOptions(model="mdr")
options.set_position(150, 150) options.set_position(150, 150)
node_one = session.add_node(CoreNode, options=options) node1 = session.add_node(CoreNode, options=options)
options.set_position(300, 150) options.set_position(300, 150)
node_two = session.add_node(CoreNode, options=options) node2 = session.add_node(CoreNode, options=options)
for i, node in enumerate([node_one, node_two]): for i, node in enumerate([node1, node2]):
node.setposition(x=150 * (i + 1), y=150) node.setposition(x=150 * (i + 1), y=150)
interface = ip_prefixes.create_interface(node) interface = ip_prefixes.create_interface(node)
session.add_link(node.id, emane_network.id, interface_one=interface) session.add_link(node.id, emane_network.id, interface1_data=interface)
# instantiate session # instantiate session
session.instantiate() session.instantiate()
# ping n2 from n1 and assert success # ping node2 from node1 and assert success
status = ping(node_one, node_two, ip_prefixes, count=5) status = ping(node1, node2, ip_prefixes, count=5)
assert not status assert not status
def test_xml_emane( def test_xml_emane(
@ -110,22 +113,22 @@ class TestEmane:
# create nodes # create nodes
options = NodeOptions(model="mdr") options = NodeOptions(model="mdr")
options.set_position(150, 150) options.set_position(150, 150)
node_one = session.add_node(CoreNode, options=options) node1 = session.add_node(CoreNode, options=options)
options.set_position(300, 150) options.set_position(300, 150)
node_two = session.add_node(CoreNode, options=options) node2 = session.add_node(CoreNode, options=options)
for i, node in enumerate([node_one, node_two]): for i, node in enumerate([node1, node2]):
node.setposition(x=150 * (i + 1), y=150) node.setposition(x=150 * (i + 1), y=150)
interface = ip_prefixes.create_interface(node) interface = ip_prefixes.create_interface(node)
session.add_link(node.id, emane_network.id, interface_one=interface) session.add_link(node.id, emane_network.id, interface1_data=interface)
# instantiate session # instantiate session
session.instantiate() session.instantiate()
# get ids for nodes # get ids for nodes
emane_id = emane_network.id emane_id = emane_network.id
n1_id = node_one.id node1_id = node1.id
n2_id = node_two.id node2_id = node2.id
# save xml # save xml
xml_file = tmpdir.join("session.xml") xml_file = tmpdir.join("session.xml")
@ -141,9 +144,9 @@ class TestEmane:
# verify nodes have been removed from session # verify nodes have been removed from session
with pytest.raises(CoreError): with pytest.raises(CoreError):
assert not session.get_node(n1_id, CoreNode) assert not session.get_node(node1_id, CoreNode)
with pytest.raises(CoreError): with pytest.raises(CoreError):
assert not session.get_node(n2_id, CoreNode) assert not session.get_node(node2_id, CoreNode)
# load saved xml # load saved xml
session.open_xml(file_path, start=True) session.open_xml(file_path, start=True)
@ -154,7 +157,7 @@ class TestEmane:
) )
# verify nodes and configuration were restored # verify nodes and configuration were restored
assert session.get_node(n1_id, CoreNode) assert session.get_node(node1_id, CoreNode)
assert session.get_node(n2_id, CoreNode) assert session.get_node(node2_id, CoreNode)
assert session.get_node(emane_id, EmaneNet) assert session.get_node(emane_id, EmaneNet)
assert value == config_value assert value == config_value

View file

@ -14,11 +14,11 @@ from core.nodes.network import WlanNode
class TestConfigurableOptions(ConfigurableOptions): class TestConfigurableOptions(ConfigurableOptions):
name_one = "value1" name1 = "value1"
name_two = "value2" name2 = "value2"
options = [ options = [
Configuration(_id=name_one, _type=ConfigDataTypes.STRING, label=name_one), Configuration(_id=name1, _type=ConfigDataTypes.STRING, label=name1),
Configuration(_id=name_two, _type=ConfigDataTypes.STRING, label=name_two), Configuration(_id=name2, _type=ConfigDataTypes.STRING, label=name2),
] ]
@ -33,11 +33,11 @@ class TestConf:
# then # then
assert len(default_values) == 2 assert len(default_values) == 2
assert TestConfigurableOptions.name_one in default_values assert TestConfigurableOptions.name1 in default_values
assert TestConfigurableOptions.name_two in default_values assert TestConfigurableOptions.name2 in default_values
assert len(instance_default_values) == 2 assert len(instance_default_values) == 2
assert TestConfigurableOptions.name_one in instance_default_values assert TestConfigurableOptions.name1 in instance_default_values
assert TestConfigurableOptions.name_two in instance_default_values assert TestConfigurableOptions.name2 in instance_default_values
def test_nodes(self): def test_nodes(self):
# given # given

View file

@ -48,19 +48,19 @@ class TestCore:
net_node = session.add_node(net_type) net_node = session.add_node(net_type)
# create nodes # create nodes
node_one = session.add_node(CoreNode) node1 = session.add_node(CoreNode)
node_two = session.add_node(CoreNode) node2 = session.add_node(CoreNode)
# link nodes to net node # link nodes to net node
for node in [node_one, node_two]: for node in [node1, node2]:
interface = ip_prefixes.create_interface(node) interface = ip_prefixes.create_interface(node)
session.add_link(node.id, net_node.id, interface_one=interface) session.add_link(node.id, net_node.id, interface1_data=interface)
# instantiate session # instantiate session
session.instantiate() session.instantiate()
# ping n2 from n1 and assert success # ping node2 from node1 and assert success
status = ping(node_one, node_two, ip_prefixes) status = ping(node1, node2, ip_prefixes)
assert not status assert not status
def test_vnode_client(self, request, session: Session, ip_prefixes: IpPrefixes): def test_vnode_client(self, request, session: Session, ip_prefixes: IpPrefixes):
@ -75,16 +75,16 @@ class TestCore:
ptp_node = session.add_node(PtpNet) ptp_node = session.add_node(PtpNet)
# create nodes # create nodes
node_one = session.add_node(CoreNode) node1 = session.add_node(CoreNode)
node_two = session.add_node(CoreNode) node2 = session.add_node(CoreNode)
# link nodes to ptp net # link nodes to ptp net
for node in [node_one, node_two]: for node in [node1, node2]:
interface = ip_prefixes.create_interface(node) interface = ip_prefixes.create_interface(node)
session.add_link(node.id, ptp_node.id, interface_one=interface) session.add_link(node.id, ptp_node.id, interface1_data=interface)
# get node client for testing # get node client for testing
client = node_one.client client = node1.client
# instantiate session # instantiate session
session.instantiate() session.instantiate()
@ -108,13 +108,13 @@ class TestCore:
ptp_node = session.add_node(PtpNet) ptp_node = session.add_node(PtpNet)
# create nodes # create nodes
node_one = session.add_node(CoreNode) node1 = session.add_node(CoreNode)
node_two = session.add_node(CoreNode) node2 = session.add_node(CoreNode)
# link nodes to ptp net # link nodes to ptp net
for node in [node_one, node_two]: for node in [node1, node2]:
interface = ip_prefixes.create_interface(node) interface = ip_prefixes.create_interface(node)
session.add_link(node.id, ptp_node.id, interface_one=interface) session.add_link(node.id, ptp_node.id, interface1_data=interface)
# instantiate session # instantiate session
session.instantiate() session.instantiate()
@ -123,22 +123,22 @@ class TestCore:
assert ptp_node.all_link_data(MessageFlags.ADD) assert ptp_node.all_link_data(MessageFlags.ADD)
# check common nets exist between linked nodes # check common nets exist between linked nodes
assert node_one.commonnets(node_two) assert node1.commonnets(node2)
assert node_two.commonnets(node_one) assert node2.commonnets(node1)
# check we can retrieve netif index # check we can retrieve netif index
assert node_one.ifname(0) assert node1.ifname(0)
assert node_two.ifname(0) assert node2.ifname(0)
# check interface parameters # check interface parameters
interface = node_one.netif(0) interface = node1.netif(0)
interface.setparam("test", 1) interface.setparam("test", 1)
assert interface.getparam("test") == 1 assert interface.getparam("test") == 1
assert interface.getparams() assert interface.getparams()
# delete netif and test that if no longer exists # delete netif and test that if no longer exists
node_one.delnetif(0) node1.delnetif(0)
assert not node_one.netif(0) assert not node1.netif(0)
def test_wlan_ping(self, session: Session, ip_prefixes: IpPrefixes): def test_wlan_ping(self, session: Session, ip_prefixes: IpPrefixes):
""" """
@ -155,19 +155,19 @@ class TestCore:
# create nodes # create nodes
options = NodeOptions(model="mdr") options = NodeOptions(model="mdr")
options.set_position(0, 0) options.set_position(0, 0)
node_one = session.add_node(CoreNode, options=options) node1 = session.add_node(CoreNode, options=options)
node_two = session.add_node(CoreNode, options=options) node2 = session.add_node(CoreNode, options=options)
# link nodes # link nodes
for node in [node_one, node_two]: for node in [node1, node2]:
interface = ip_prefixes.create_interface(node) interface = ip_prefixes.create_interface(node)
session.add_link(node.id, wlan_node.id, interface_one=interface) session.add_link(node.id, wlan_node.id, interface1_data=interface)
# instantiate session # instantiate session
session.instantiate() session.instantiate()
# ping n2 from n1 and assert success # ping node2 from node1 and assert success
status = ping(node_one, node_two, ip_prefixes) status = ping(node1, node2, ip_prefixes)
assert not status assert not status
def test_mobility(self, session: Session, ip_prefixes: IpPrefixes): def test_mobility(self, session: Session, ip_prefixes: IpPrefixes):
@ -185,13 +185,13 @@ class TestCore:
# create nodes # create nodes
options = NodeOptions(model="mdr") options = NodeOptions(model="mdr")
options.set_position(0, 0) options.set_position(0, 0)
node_one = session.add_node(CoreNode, options=options) node1 = session.add_node(CoreNode, options=options)
node_two = session.add_node(CoreNode, options=options) node2 = session.add_node(CoreNode, options=options)
# link nodes # link nodes
for node in [node_one, node_two]: for node in [node1, node2]:
interface = ip_prefixes.create_interface(node) interface = ip_prefixes.create_interface(node)
session.add_link(node.id, wlan_node.id, interface_one=interface) session.add_link(node.id, wlan_node.id, interface1_data=interface)
# configure mobility script for session # configure mobility script for session
config = { config = {

View file

@ -34,23 +34,23 @@ class TestGrpc:
client = CoreGrpcClient() client = CoreGrpcClient()
session = grpc_server.coreemu.create_session() session = grpc_server.coreemu.create_session()
position = core_pb2.Position(x=50, y=100) position = core_pb2.Position(x=50, y=100)
node_one = core_pb2.Node(id=1, position=position, model="PC") node1 = core_pb2.Node(id=1, position=position, model="PC")
position = core_pb2.Position(x=100, y=100) position = core_pb2.Position(x=100, y=100)
node_two = core_pb2.Node(id=2, position=position, model="PC") node2 = core_pb2.Node(id=2, position=position, model="PC")
position = core_pb2.Position(x=200, y=200) position = core_pb2.Position(x=200, y=200)
wlan_node = core_pb2.Node( wlan_node = core_pb2.Node(
id=3, type=NodeTypes.WIRELESS_LAN.value, position=position id=3, type=NodeTypes.WIRELESS_LAN.value, position=position
) )
nodes = [node_one, node_two, wlan_node] nodes = [node1, node2, wlan_node]
interface_helper = InterfaceHelper(ip4_prefix="10.83.0.0/16") interface_helper = InterfaceHelper(ip4_prefix="10.83.0.0/16")
interface_one = interface_helper.create_interface(node_one.id, 0) interface1 = interface_helper.create_interface(node1.id, 0)
interface_two = interface_helper.create_interface(node_two.id, 0) interface2 = interface_helper.create_interface(node2.id, 0)
link = core_pb2.Link( link = core_pb2.Link(
type=core_pb2.LinkType.WIRED, type=core_pb2.LinkType.WIRED,
node_one_id=node_one.id, node1_id=node1.id,
node_two_id=node_two.id, node2_id=node2.id,
interface_one=interface_one, interface1=interface1,
interface_two=interface_two, interface2=interface2,
) )
links = [link] links = [link]
hook = core_pb2.Hook( hook = core_pb2.Hook(
@ -99,11 +99,11 @@ class TestGrpc:
) )
mobility_configs = [mobility_config] mobility_configs = [mobility_config]
service_config = ServiceConfig( service_config = ServiceConfig(
node_id=node_one.id, service="DefaultRoute", validate=["echo hello"] node_id=node1.id, service="DefaultRoute", validate=["echo hello"]
) )
service_configs = [service_config] service_configs = [service_config]
service_file_config = ServiceFileConfig( service_file_config = ServiceFileConfig(
node_id=node_one.id, node_id=node1.id,
service="DefaultRoute", service="DefaultRoute",
file="defaultroute.sh", file="defaultroute.sh",
data="echo hello", data="echo hello",
@ -128,12 +128,12 @@ class TestGrpc:
) )
# then # then
assert node_one.id in session.nodes assert node1.id in session.nodes
assert node_two.id in session.nodes assert node2.id in session.nodes
assert wlan_node.id in session.nodes assert wlan_node.id in session.nodes
assert session.nodes[node_one.id].netif(0) is not None assert session.nodes[node1.id].netif(0) is not None
assert session.nodes[node_two.id].netif(0) is not None assert session.nodes[node2.id].netif(0) is not None
hook_file, hook_data = session._hooks[EventTypes.RUNTIME_STATE][0] hook_file, hook_data = session.hooks[EventTypes.RUNTIME_STATE][0]
assert hook_file == hook.file assert hook_file == hook.file
assert hook_data == hook.data assert hook_data == hook.data
assert session.location.refxyz == (location_x, location_y, location_z) assert session.location.refxyz == (location_x, location_y, location_z)
@ -153,11 +153,11 @@ class TestGrpc:
) )
assert set_model_config[model_config_key] == model_config_value assert set_model_config[model_config_key] == model_config_value
service = session.services.get_service( service = session.services.get_service(
node_one.id, service_config.service, default_service=True node1.id, service_config.service, default_service=True
) )
assert service.validate == tuple(service_config.validate) assert service.validate == tuple(service_config.validate)
service_file = session.services.get_service_file( service_file = session.services.get_service_file(
node_one, service_file_config.service, service_file_config.file node1, service_file_config.service, service_file_config.file
) )
assert service_file.data == service_file_config.data assert service_file.data == service_file_config.data
@ -596,7 +596,7 @@ class TestGrpc:
# then # then
with client.context_connect(): with client.context_connect():
response = client.edit_link( response = client.edit_link(
session.id, node.id, switch.id, options, interface_one_id=interface.id session.id, node.id, switch.id, options, interface1_id=interface.id
) )
# then # then
@ -608,28 +608,28 @@ class TestGrpc:
# given # given
client = CoreGrpcClient() client = CoreGrpcClient()
session = grpc_server.coreemu.create_session() session = grpc_server.coreemu.create_session()
node_one = session.add_node(CoreNode) node1 = session.add_node(CoreNode)
interface_one = ip_prefixes.create_interface(node_one) interface1 = ip_prefixes.create_interface(node1)
node_two = session.add_node(CoreNode) node2 = session.add_node(CoreNode)
interface_two = ip_prefixes.create_interface(node_two) interface2 = ip_prefixes.create_interface(node2)
session.add_link(node_one.id, node_two.id, interface_one, interface_two) session.add_link(node1.id, node2.id, interface1, interface2)
link_node = None link_node = None
for node_id in session.nodes: for node_id in session.nodes:
node = session.nodes[node_id] node = session.nodes[node_id]
if node.id not in {node_one.id, node_two.id}: if node.id not in {node1.id, node2.id}:
link_node = node link_node = node
break break
assert len(link_node.all_link_data(0)) == 1 assert len(link_node.all_link_data()) == 1
# then # then
with client.context_connect(): with client.context_connect():
response = client.delete_link( response = client.delete_link(
session.id, node_one.id, node_two.id, interface_one.id, interface_two.id session.id, node1.id, node2.id, interface1.id, interface2.id
) )
# then # then
assert response.result is True assert response.result is True
assert len(link_node.all_link_data(0)) == 0 assert len(link_node.all_link_data()) == 0
def test_get_wlan_config(self, grpc_server: CoreGrpcServer): def test_get_wlan_config(self, grpc_server: CoreGrpcServer):
# given # given

View file

@ -50,12 +50,13 @@ class TestGui:
self, coretlv: CoreHandler, node_type: NodeTypes, model: Optional[str] self, coretlv: CoreHandler, node_type: NodeTypes, model: Optional[str]
): ):
node_id = 1 node_id = 1
name = "node1"
message = coreapi.CoreNodeMessage.create( message = coreapi.CoreNodeMessage.create(
MessageFlags.ADD.value, MessageFlags.ADD.value,
[ [
(NodeTlvs.NUMBER, node_id), (NodeTlvs.NUMBER, node_id),
(NodeTlvs.TYPE, node_type.value), (NodeTlvs.TYPE, node_type.value),
(NodeTlvs.NAME, "n1"), (NodeTlvs.NAME, name),
(NodeTlvs.X_POSITION, 0), (NodeTlvs.X_POSITION, 0),
(NodeTlvs.Y_POSITION, 0), (NodeTlvs.Y_POSITION, 0),
(NodeTlvs.MODEL, model), (NodeTlvs.MODEL, model),
@ -63,7 +64,9 @@ class TestGui:
) )
coretlv.handle_message(message) coretlv.handle_message(message)
assert coretlv.session.get_node(node_id, NodeBase) is not None node = coretlv.session.get_node(node_id, NodeBase)
assert node
assert node.name == name
def test_node_update(self, coretlv: CoreHandler): def test_node_update(self, coretlv: CoreHandler):
node_id = 1 node_id = 1
@ -99,71 +102,71 @@ class TestGui:
coretlv.session.get_node(node_id, NodeBase) coretlv.session.get_node(node_id, NodeBase)
def test_link_add_node_to_net(self, coretlv: CoreHandler): def test_link_add_node_to_net(self, coretlv: CoreHandler):
node_one = 1 node1_id = 1
coretlv.session.add_node(CoreNode, _id=node_one) coretlv.session.add_node(CoreNode, _id=node1_id)
switch = 2 switch_id = 2
coretlv.session.add_node(SwitchNode, _id=switch) coretlv.session.add_node(SwitchNode, _id=switch_id)
ip_prefix = netaddr.IPNetwork("10.0.0.0/24") ip_prefix = netaddr.IPNetwork("10.0.0.0/24")
interface_one = str(ip_prefix[node_one]) interface1_ip4 = str(ip_prefix[node1_id])
message = coreapi.CoreLinkMessage.create( message = coreapi.CoreLinkMessage.create(
MessageFlags.ADD.value, MessageFlags.ADD.value,
[ [
(LinkTlvs.N1_NUMBER, node_one), (LinkTlvs.N1_NUMBER, node1_id),
(LinkTlvs.N2_NUMBER, switch), (LinkTlvs.N2_NUMBER, switch_id),
(LinkTlvs.INTERFACE1_NUMBER, 0), (LinkTlvs.INTERFACE1_NUMBER, 0),
(LinkTlvs.INTERFACE1_IP4, interface_one), (LinkTlvs.INTERFACE1_IP4, interface1_ip4),
(LinkTlvs.INTERFACE1_IP4_MASK, 24), (LinkTlvs.INTERFACE1_IP4_MASK, 24),
], ],
) )
coretlv.handle_message(message) coretlv.handle_message(message)
switch_node = coretlv.session.get_node(switch, SwitchNode) switch_node = coretlv.session.get_node(switch_id, SwitchNode)
all_links = switch_node.all_link_data() all_links = switch_node.all_link_data()
assert len(all_links) == 1 assert len(all_links) == 1
def test_link_add_net_to_node(self, coretlv: CoreHandler): def test_link_add_net_to_node(self, coretlv: CoreHandler):
node_one = 1 node1_id = 1
coretlv.session.add_node(CoreNode, _id=node_one) coretlv.session.add_node(CoreNode, _id=node1_id)
switch = 2 switch_id = 2
coretlv.session.add_node(SwitchNode, _id=switch) coretlv.session.add_node(SwitchNode, _id=switch_id)
ip_prefix = netaddr.IPNetwork("10.0.0.0/24") ip_prefix = netaddr.IPNetwork("10.0.0.0/24")
interface_one = str(ip_prefix[node_one]) interface2_ip4 = str(ip_prefix[node1_id])
message = coreapi.CoreLinkMessage.create( message = coreapi.CoreLinkMessage.create(
MessageFlags.ADD.value, MessageFlags.ADD.value,
[ [
(LinkTlvs.N1_NUMBER, switch), (LinkTlvs.N1_NUMBER, switch_id),
(LinkTlvs.N2_NUMBER, node_one), (LinkTlvs.N2_NUMBER, node1_id),
(LinkTlvs.INTERFACE2_NUMBER, 0), (LinkTlvs.INTERFACE2_NUMBER, 0),
(LinkTlvs.INTERFACE2_IP4, interface_one), (LinkTlvs.INTERFACE2_IP4, interface2_ip4),
(LinkTlvs.INTERFACE2_IP4_MASK, 24), (LinkTlvs.INTERFACE2_IP4_MASK, 24),
], ],
) )
coretlv.handle_message(message) coretlv.handle_message(message)
switch_node = coretlv.session.get_node(switch, SwitchNode) switch_node = coretlv.session.get_node(switch_id, SwitchNode)
all_links = switch_node.all_link_data() all_links = switch_node.all_link_data()
assert len(all_links) == 1 assert len(all_links) == 1
def test_link_add_node_to_node(self, coretlv: CoreHandler): def test_link_add_node_to_node(self, coretlv: CoreHandler):
node_one = 1 node1_id = 1
coretlv.session.add_node(CoreNode, _id=node_one) coretlv.session.add_node(CoreNode, _id=node1_id)
node_two = 2 node2_id = 2
coretlv.session.add_node(CoreNode, _id=node_two) coretlv.session.add_node(CoreNode, _id=node2_id)
ip_prefix = netaddr.IPNetwork("10.0.0.0/24") ip_prefix = netaddr.IPNetwork("10.0.0.0/24")
interface_one = str(ip_prefix[node_one]) interface1_ip4 = str(ip_prefix[node1_id])
interface_two = str(ip_prefix[node_two]) interface2_ip4 = str(ip_prefix[node2_id])
message = coreapi.CoreLinkMessage.create( message = coreapi.CoreLinkMessage.create(
MessageFlags.ADD.value, MessageFlags.ADD.value,
[ [
(LinkTlvs.N1_NUMBER, node_one), (LinkTlvs.N1_NUMBER, node1_id),
(LinkTlvs.N2_NUMBER, node_two), (LinkTlvs.N2_NUMBER, node2_id),
(LinkTlvs.INTERFACE1_NUMBER, 0), (LinkTlvs.INTERFACE1_NUMBER, 0),
(LinkTlvs.INTERFACE1_IP4, interface_one), (LinkTlvs.INTERFACE1_IP4, interface1_ip4),
(LinkTlvs.INTERFACE1_IP4_MASK, 24), (LinkTlvs.INTERFACE1_IP4_MASK, 24),
(LinkTlvs.INTERFACE2_NUMBER, 0), (LinkTlvs.INTERFACE2_NUMBER, 0),
(LinkTlvs.INTERFACE2_IP4, interface_two), (LinkTlvs.INTERFACE2_IP4, interface2_ip4),
(LinkTlvs.INTERFACE2_IP4_MASK, 24), (LinkTlvs.INTERFACE2_IP4_MASK, 24),
], ],
) )
@ -177,24 +180,24 @@ class TestGui:
assert len(all_links) == 1 assert len(all_links) == 1
def test_link_update(self, coretlv: CoreHandler): def test_link_update(self, coretlv: CoreHandler):
node_one = 1 node1_id = 1
coretlv.session.add_node(CoreNode, _id=node_one) coretlv.session.add_node(CoreNode, _id=node1_id)
switch = 2 switch_id = 2
coretlv.session.add_node(SwitchNode, _id=switch) coretlv.session.add_node(SwitchNode, _id=switch_id)
ip_prefix = netaddr.IPNetwork("10.0.0.0/24") ip_prefix = netaddr.IPNetwork("10.0.0.0/24")
interface_one = str(ip_prefix[node_one]) interface1_ip4 = str(ip_prefix[node1_id])
message = coreapi.CoreLinkMessage.create( message = coreapi.CoreLinkMessage.create(
MessageFlags.ADD.value, MessageFlags.ADD.value,
[ [
(LinkTlvs.N1_NUMBER, node_one), (LinkTlvs.N1_NUMBER, node1_id),
(LinkTlvs.N2_NUMBER, switch), (LinkTlvs.N2_NUMBER, switch_id),
(LinkTlvs.INTERFACE1_NUMBER, 0), (LinkTlvs.INTERFACE1_NUMBER, 0),
(LinkTlvs.INTERFACE1_IP4, interface_one), (LinkTlvs.INTERFACE1_IP4, interface1_ip4),
(LinkTlvs.INTERFACE1_IP4_MASK, 24), (LinkTlvs.INTERFACE1_IP4_MASK, 24),
], ],
) )
coretlv.handle_message(message) coretlv.handle_message(message)
switch_node = coretlv.session.get_node(switch, SwitchNode) switch_node = coretlv.session.get_node(switch_id, SwitchNode)
all_links = switch_node.all_link_data() all_links = switch_node.all_link_data()
assert len(all_links) == 1 assert len(all_links) == 1
link = all_links[0] link = all_links[0]
@ -204,37 +207,37 @@ class TestGui:
message = coreapi.CoreLinkMessage.create( message = coreapi.CoreLinkMessage.create(
0, 0,
[ [
(LinkTlvs.N1_NUMBER, node_one), (LinkTlvs.N1_NUMBER, node1_id),
(LinkTlvs.N2_NUMBER, switch), (LinkTlvs.N2_NUMBER, switch_id),
(LinkTlvs.INTERFACE1_NUMBER, 0), (LinkTlvs.INTERFACE1_NUMBER, 0),
(LinkTlvs.BANDWIDTH, bandwidth), (LinkTlvs.BANDWIDTH, bandwidth),
], ],
) )
coretlv.handle_message(message) coretlv.handle_message(message)
switch_node = coretlv.session.get_node(switch, SwitchNode) switch_node = coretlv.session.get_node(switch_id, SwitchNode)
all_links = switch_node.all_link_data() all_links = switch_node.all_link_data()
assert len(all_links) == 1 assert len(all_links) == 1
link = all_links[0] link = all_links[0]
assert link.bandwidth == bandwidth assert link.bandwidth == bandwidth
def test_link_delete_node_to_node(self, coretlv: CoreHandler): def test_link_delete_node_to_node(self, coretlv: CoreHandler):
node_one = 1 node1_id = 1
coretlv.session.add_node(CoreNode, _id=node_one) coretlv.session.add_node(CoreNode, _id=node1_id)
node_two = 2 node2_id = 2
coretlv.session.add_node(CoreNode, _id=node_two) coretlv.session.add_node(CoreNode, _id=node2_id)
ip_prefix = netaddr.IPNetwork("10.0.0.0/24") ip_prefix = netaddr.IPNetwork("10.0.0.0/24")
interface_one = str(ip_prefix[node_one]) interface1_ip4 = str(ip_prefix[node1_id])
interface_two = str(ip_prefix[node_two]) interface2_ip4 = str(ip_prefix[node2_id])
message = coreapi.CoreLinkMessage.create( message = coreapi.CoreLinkMessage.create(
MessageFlags.ADD.value, MessageFlags.ADD.value,
[ [
(LinkTlvs.N1_NUMBER, node_one), (LinkTlvs.N1_NUMBER, node1_id),
(LinkTlvs.N2_NUMBER, node_two), (LinkTlvs.N2_NUMBER, node2_id),
(LinkTlvs.INTERFACE1_NUMBER, 0), (LinkTlvs.INTERFACE1_NUMBER, 0),
(LinkTlvs.INTERFACE1_IP4, interface_one), (LinkTlvs.INTERFACE1_IP4, interface1_ip4),
(LinkTlvs.INTERFACE1_IP4_MASK, 24), (LinkTlvs.INTERFACE1_IP4_MASK, 24),
(LinkTlvs.INTERFACE2_IP4, interface_two), (LinkTlvs.INTERFACE2_IP4, interface2_ip4),
(LinkTlvs.INTERFACE2_IP4_MASK, 24), (LinkTlvs.INTERFACE2_IP4_MASK, 24),
], ],
) )
@ -248,8 +251,8 @@ class TestGui:
message = coreapi.CoreLinkMessage.create( message = coreapi.CoreLinkMessage.create(
MessageFlags.DELETE.value, MessageFlags.DELETE.value,
[ [
(LinkTlvs.N1_NUMBER, node_one), (LinkTlvs.N1_NUMBER, node1_id),
(LinkTlvs.N2_NUMBER, node_two), (LinkTlvs.N2_NUMBER, node2_id),
(LinkTlvs.INTERFACE1_NUMBER, 0), (LinkTlvs.INTERFACE1_NUMBER, 0),
(LinkTlvs.INTERFACE2_NUMBER, 0), (LinkTlvs.INTERFACE2_NUMBER, 0),
], ],
@ -263,74 +266,74 @@ class TestGui:
assert len(all_links) == 0 assert len(all_links) == 0
def test_link_delete_node_to_net(self, coretlv: CoreHandler): def test_link_delete_node_to_net(self, coretlv: CoreHandler):
node_one = 1 node1_id = 1
coretlv.session.add_node(CoreNode, _id=node_one) coretlv.session.add_node(CoreNode, _id=node1_id)
switch = 2 switch_id = 2
coretlv.session.add_node(SwitchNode, _id=switch) coretlv.session.add_node(SwitchNode, _id=switch_id)
ip_prefix = netaddr.IPNetwork("10.0.0.0/24") ip_prefix = netaddr.IPNetwork("10.0.0.0/24")
interface_one = str(ip_prefix[node_one]) interface1_ip4 = str(ip_prefix[node1_id])
message = coreapi.CoreLinkMessage.create( message = coreapi.CoreLinkMessage.create(
MessageFlags.ADD.value, MessageFlags.ADD.value,
[ [
(LinkTlvs.N1_NUMBER, node_one), (LinkTlvs.N1_NUMBER, node1_id),
(LinkTlvs.N2_NUMBER, switch), (LinkTlvs.N2_NUMBER, switch_id),
(LinkTlvs.INTERFACE1_NUMBER, 0), (LinkTlvs.INTERFACE1_NUMBER, 0),
(LinkTlvs.INTERFACE1_IP4, interface_one), (LinkTlvs.INTERFACE1_IP4, interface1_ip4),
(LinkTlvs.INTERFACE1_IP4_MASK, 24), (LinkTlvs.INTERFACE1_IP4_MASK, 24),
], ],
) )
coretlv.handle_message(message) coretlv.handle_message(message)
switch_node = coretlv.session.get_node(switch, SwitchNode) switch_node = coretlv.session.get_node(switch_id, SwitchNode)
all_links = switch_node.all_link_data() all_links = switch_node.all_link_data()
assert len(all_links) == 1 assert len(all_links) == 1
message = coreapi.CoreLinkMessage.create( message = coreapi.CoreLinkMessage.create(
MessageFlags.DELETE.value, MessageFlags.DELETE.value,
[ [
(LinkTlvs.N1_NUMBER, node_one), (LinkTlvs.N1_NUMBER, node1_id),
(LinkTlvs.N2_NUMBER, switch), (LinkTlvs.N2_NUMBER, switch_id),
(LinkTlvs.INTERFACE1_NUMBER, 0), (LinkTlvs.INTERFACE1_NUMBER, 0),
], ],
) )
coretlv.handle_message(message) coretlv.handle_message(message)
switch_node = coretlv.session.get_node(switch, SwitchNode) switch_node = coretlv.session.get_node(switch_id, SwitchNode)
all_links = switch_node.all_link_data() all_links = switch_node.all_link_data()
assert len(all_links) == 0 assert len(all_links) == 0
def test_link_delete_net_to_node(self, coretlv: CoreHandler): def test_link_delete_net_to_node(self, coretlv: CoreHandler):
node_one = 1 node1_id = 1
coretlv.session.add_node(CoreNode, _id=node_one) coretlv.session.add_node(CoreNode, _id=node1_id)
switch = 2 switch_id = 2
coretlv.session.add_node(SwitchNode, _id=switch) coretlv.session.add_node(SwitchNode, _id=switch_id)
ip_prefix = netaddr.IPNetwork("10.0.0.0/24") ip_prefix = netaddr.IPNetwork("10.0.0.0/24")
interface_one = str(ip_prefix[node_one]) interface1_ip4 = str(ip_prefix[node1_id])
message = coreapi.CoreLinkMessage.create( message = coreapi.CoreLinkMessage.create(
MessageFlags.ADD.value, MessageFlags.ADD.value,
[ [
(LinkTlvs.N1_NUMBER, node_one), (LinkTlvs.N1_NUMBER, node1_id),
(LinkTlvs.N2_NUMBER, switch), (LinkTlvs.N2_NUMBER, switch_id),
(LinkTlvs.INTERFACE1_NUMBER, 0), (LinkTlvs.INTERFACE1_NUMBER, 0),
(LinkTlvs.INTERFACE1_IP4, interface_one), (LinkTlvs.INTERFACE1_IP4, interface1_ip4),
(LinkTlvs.INTERFACE1_IP4_MASK, 24), (LinkTlvs.INTERFACE1_IP4_MASK, 24),
], ],
) )
coretlv.handle_message(message) coretlv.handle_message(message)
switch_node = coretlv.session.get_node(switch, SwitchNode) switch_node = coretlv.session.get_node(switch_id, SwitchNode)
all_links = switch_node.all_link_data() all_links = switch_node.all_link_data()
assert len(all_links) == 1 assert len(all_links) == 1
message = coreapi.CoreLinkMessage.create( message = coreapi.CoreLinkMessage.create(
MessageFlags.DELETE.value, MessageFlags.DELETE.value,
[ [
(LinkTlvs.N1_NUMBER, switch), (LinkTlvs.N1_NUMBER, switch_id),
(LinkTlvs.N2_NUMBER, node_one), (LinkTlvs.N2_NUMBER, node1_id),
(LinkTlvs.INTERFACE2_NUMBER, 0), (LinkTlvs.INTERFACE2_NUMBER, 0),
], ],
) )
coretlv.handle_message(message) coretlv.handle_message(message)
switch_node = coretlv.session.get_node(switch, SwitchNode) switch_node = coretlv.session.get_node(switch_id, SwitchNode)
all_links = switch_node.all_link_data() all_links = switch_node.all_link_data()
assert len(all_links) == 0 assert len(all_links) == 0
@ -379,7 +382,7 @@ class TestGui:
def test_file_hook_add(self, coretlv: CoreHandler): def test_file_hook_add(self, coretlv: CoreHandler):
state = EventTypes.DATACOLLECT_STATE state = EventTypes.DATACOLLECT_STATE
assert coretlv.session._hooks.get(state) is None assert coretlv.session.hooks.get(state) is None
file_name = "test.sh" file_name = "test.sh"
file_data = "echo hello" file_data = "echo hello"
message = coreapi.CoreFileMessage.create( message = coreapi.CoreFileMessage.create(
@ -393,7 +396,7 @@ class TestGui:
coretlv.handle_message(message) coretlv.handle_message(message)
hooks = coretlv.session._hooks.get(state) hooks = coretlv.session.hooks.get(state)
assert len(hooks) == 1 assert len(hooks) == 1
name, data = hooks[0] name, data = hooks[0]
assert file_name == name assert file_name == name

View file

@ -10,71 +10,71 @@ def create_ptp_network(
session: Session, ip_prefixes: IpPrefixes session: Session, ip_prefixes: IpPrefixes
) -> Tuple[CoreNode, CoreNode]: ) -> Tuple[CoreNode, CoreNode]:
# create nodes # create nodes
node_one = session.add_node(CoreNode) node1 = session.add_node(CoreNode)
node_two = session.add_node(CoreNode) node2 = session.add_node(CoreNode)
# link nodes to net node # link nodes to net node
interface_one = ip_prefixes.create_interface(node_one) interface1_data = ip_prefixes.create_interface(node1)
interface_two = ip_prefixes.create_interface(node_two) interface2_data = ip_prefixes.create_interface(node2)
session.add_link(node_one.id, node_two.id, interface_one, interface_two) session.add_link(node1.id, node2.id, interface1_data, interface2_data)
# instantiate session # instantiate session
session.instantiate() session.instantiate()
return node_one, node_two return node1, node2
class TestLinks: class TestLinks:
def test_add_ptp(self, session: Session, ip_prefixes: IpPrefixes): def test_add_ptp(self, session: Session, ip_prefixes: IpPrefixes):
# given # given
node_one = session.add_node(CoreNode) node1 = session.add_node(CoreNode)
node_two = session.add_node(CoreNode) node2 = session.add_node(CoreNode)
interface_one = ip_prefixes.create_interface(node_one) interface1_data = ip_prefixes.create_interface(node1)
interface_two = ip_prefixes.create_interface(node_two) interface2_data = ip_prefixes.create_interface(node2)
# when # when
session.add_link(node_one.id, node_two.id, interface_one, interface_two) session.add_link(node1.id, node2.id, interface1_data, interface2_data)
# then # then
assert node_one.netif(interface_one.id) assert node1.netif(interface1_data.id)
assert node_two.netif(interface_two.id) assert node2.netif(interface2_data.id)
def test_add_node_to_net(self, session: Session, ip_prefixes: IpPrefixes): def test_add_node_to_net(self, session: Session, ip_prefixes: IpPrefixes):
# given # given
node_one = session.add_node(CoreNode) node1 = session.add_node(CoreNode)
node_two = session.add_node(SwitchNode) node2 = session.add_node(SwitchNode)
interface_one = ip_prefixes.create_interface(node_one) interface1_data = ip_prefixes.create_interface(node1)
# when # when
session.add_link(node_one.id, node_two.id, interface_one=interface_one) session.add_link(node1.id, node2.id, interface1_data=interface1_data)
# then # then
assert node_two.all_link_data() assert node2.all_link_data()
assert node_one.netif(interface_one.id) assert node1.netif(interface1_data.id)
def test_add_net_to_node(self, session: Session, ip_prefixes: IpPrefixes): def test_add_net_to_node(self, session: Session, ip_prefixes: IpPrefixes):
# given # given
node_one = session.add_node(SwitchNode) node1 = session.add_node(SwitchNode)
node_two = session.add_node(CoreNode) node2 = session.add_node(CoreNode)
interface_two = ip_prefixes.create_interface(node_two) interface2_data = ip_prefixes.create_interface(node2)
# when # when
session.add_link(node_one.id, node_two.id, interface_two=interface_two) session.add_link(node1.id, node2.id, interface2_data=interface2_data)
# then # then
assert node_one.all_link_data() assert node1.all_link_data()
assert node_two.netif(interface_two.id) assert node2.netif(interface2_data.id)
def test_add_net_to_net(self, session): def test_add_net_to_net(self, session):
# given # given
node_one = session.add_node(SwitchNode) node1 = session.add_node(SwitchNode)
node_two = session.add_node(SwitchNode) node2 = session.add_node(SwitchNode)
# when # when
session.add_link(node_one.id, node_two.id) session.add_link(node1.id, node2.id)
# then # then
assert node_one.all_link_data() assert node1.all_link_data()
def test_update_node_to_net(self, session: Session, ip_prefixes: IpPrefixes): def test_update_node_to_net(self, session: Session, ip_prefixes: IpPrefixes):
# given # given
@ -83,34 +83,31 @@ class TestLinks:
loss = 25 loss = 25
dup = 25 dup = 25
jitter = 10 jitter = 10
node_one = session.add_node(CoreNode) node1 = session.add_node(CoreNode)
node_two = session.add_node(SwitchNode) node2 = session.add_node(SwitchNode)
interface_one_data = ip_prefixes.create_interface(node_one) interface1_data = ip_prefixes.create_interface(node1)
session.add_link(node_one.id, node_two.id, interface_one_data) session.add_link(node1.id, node2.id, interface1_data)
interface_one = node_one.netif(interface_one_data.id) interface1 = node1.netif(interface1_data.id)
assert interface_one.getparam("delay") != delay assert interface1.getparam("delay") != delay
assert interface_one.getparam("bw") != bandwidth assert interface1.getparam("bw") != bandwidth
assert interface_one.getparam("loss") != loss assert interface1.getparam("loss") != loss
assert interface_one.getparam("duplicate") != dup assert interface1.getparam("duplicate") != dup
assert interface_one.getparam("jitter") != jitter assert interface1.getparam("jitter") != jitter
# when # when
link_options = LinkOptions( options = LinkOptions(
delay=delay, bandwidth=bandwidth, loss=loss, dup=dup, jitter=jitter delay=delay, bandwidth=bandwidth, loss=loss, dup=dup, jitter=jitter
) )
session.update_link( session.update_link(
node_one.id, node1.id, node2.id, interface1_id=interface1_data.id, options=options
node_two.id,
interface_one_id=interface_one_data.id,
options=link_options,
) )
# then # then
assert interface_one.getparam("delay") == delay assert interface1.getparam("delay") == delay
assert interface_one.getparam("bw") == bandwidth assert interface1.getparam("bw") == bandwidth
assert interface_one.getparam("loss") == loss assert interface1.getparam("loss") == loss
assert interface_one.getparam("duplicate") == dup assert interface1.getparam("duplicate") == dup
assert interface_one.getparam("jitter") == jitter assert interface1.getparam("jitter") == jitter
def test_update_net_to_node(self, session: Session, ip_prefixes: IpPrefixes): def test_update_net_to_node(self, session: Session, ip_prefixes: IpPrefixes):
# given # given
@ -119,34 +116,31 @@ class TestLinks:
loss = 25 loss = 25
dup = 25 dup = 25
jitter = 10 jitter = 10
node_one = session.add_node(SwitchNode) node1 = session.add_node(SwitchNode)
node_two = session.add_node(CoreNode) node2 = session.add_node(CoreNode)
interface_two_data = ip_prefixes.create_interface(node_two) interface2_data = ip_prefixes.create_interface(node2)
session.add_link(node_one.id, node_two.id, interface_two=interface_two_data) session.add_link(node1.id, node2.id, interface2_data=interface2_data)
interface_two = node_two.netif(interface_two_data.id) interface2 = node2.netif(interface2_data.id)
assert interface_two.getparam("delay") != delay assert interface2.getparam("delay") != delay
assert interface_two.getparam("bw") != bandwidth assert interface2.getparam("bw") != bandwidth
assert interface_two.getparam("loss") != loss assert interface2.getparam("loss") != loss
assert interface_two.getparam("duplicate") != dup assert interface2.getparam("duplicate") != dup
assert interface_two.getparam("jitter") != jitter assert interface2.getparam("jitter") != jitter
# when # when
link_options = LinkOptions( options = LinkOptions(
delay=delay, bandwidth=bandwidth, loss=loss, dup=dup, jitter=jitter delay=delay, bandwidth=bandwidth, loss=loss, dup=dup, jitter=jitter
) )
session.update_link( session.update_link(
node_one.id, node1.id, node2.id, interface2_id=interface2_data.id, options=options
node_two.id,
interface_two_id=interface_two_data.id,
options=link_options,
) )
# then # then
assert interface_two.getparam("delay") == delay assert interface2.getparam("delay") == delay
assert interface_two.getparam("bw") == bandwidth assert interface2.getparam("bw") == bandwidth
assert interface_two.getparam("loss") == loss assert interface2.getparam("loss") == loss
assert interface_two.getparam("duplicate") == dup assert interface2.getparam("duplicate") == dup
assert interface_two.getparam("jitter") == jitter assert interface2.getparam("jitter") == jitter
def test_update_ptp(self, session: Session, ip_prefixes: IpPrefixes): def test_update_ptp(self, session: Session, ip_prefixes: IpPrefixes):
# given # given
@ -155,93 +149,85 @@ class TestLinks:
loss = 25 loss = 25
dup = 25 dup = 25
jitter = 10 jitter = 10
node_one = session.add_node(CoreNode) node1 = session.add_node(CoreNode)
node_two = session.add_node(CoreNode) node2 = session.add_node(CoreNode)
interface_one_data = ip_prefixes.create_interface(node_one) interface1_data = ip_prefixes.create_interface(node1)
interface_two_data = ip_prefixes.create_interface(node_two) interface2_data = ip_prefixes.create_interface(node2)
session.add_link( session.add_link(node1.id, node2.id, interface1_data, interface2_data)
node_one.id, node_two.id, interface_one_data, interface_two_data interface1 = node1.netif(interface1_data.id)
) interface2 = node2.netif(interface2_data.id)
interface_one = node_one.netif(interface_one_data.id) assert interface1.getparam("delay") != delay
interface_two = node_two.netif(interface_two_data.id) assert interface1.getparam("bw") != bandwidth
assert interface_one.getparam("delay") != delay assert interface1.getparam("loss") != loss
assert interface_one.getparam("bw") != bandwidth assert interface1.getparam("duplicate") != dup
assert interface_one.getparam("loss") != loss assert interface1.getparam("jitter") != jitter
assert interface_one.getparam("duplicate") != dup assert interface2.getparam("delay") != delay
assert interface_one.getparam("jitter") != jitter assert interface2.getparam("bw") != bandwidth
assert interface_two.getparam("delay") != delay assert interface2.getparam("loss") != loss
assert interface_two.getparam("bw") != bandwidth assert interface2.getparam("duplicate") != dup
assert interface_two.getparam("loss") != loss assert interface2.getparam("jitter") != jitter
assert interface_two.getparam("duplicate") != dup
assert interface_two.getparam("jitter") != jitter
# when # when
link_options = LinkOptions( options = LinkOptions(
delay=delay, bandwidth=bandwidth, loss=loss, dup=dup, jitter=jitter delay=delay, bandwidth=bandwidth, loss=loss, dup=dup, jitter=jitter
) )
session.update_link( session.update_link(
node_one.id, node1.id, node2.id, interface1_data.id, interface2_data.id, options
node_two.id,
interface_one_data.id,
interface_two_data.id,
link_options,
) )
# then # then
assert interface_one.getparam("delay") == delay assert interface1.getparam("delay") == delay
assert interface_one.getparam("bw") == bandwidth assert interface1.getparam("bw") == bandwidth
assert interface_one.getparam("loss") == loss assert interface1.getparam("loss") == loss
assert interface_one.getparam("duplicate") == dup assert interface1.getparam("duplicate") == dup
assert interface_one.getparam("jitter") == jitter assert interface1.getparam("jitter") == jitter
assert interface_two.getparam("delay") == delay assert interface2.getparam("delay") == delay
assert interface_two.getparam("bw") == bandwidth assert interface2.getparam("bw") == bandwidth
assert interface_two.getparam("loss") == loss assert interface2.getparam("loss") == loss
assert interface_two.getparam("duplicate") == dup assert interface2.getparam("duplicate") == dup
assert interface_two.getparam("jitter") == jitter assert interface2.getparam("jitter") == jitter
def test_delete_ptp(self, session: Session, ip_prefixes: IpPrefixes): def test_delete_ptp(self, session: Session, ip_prefixes: IpPrefixes):
# given # given
node_one = session.add_node(CoreNode) node1 = session.add_node(CoreNode)
node_two = session.add_node(CoreNode) node2 = session.add_node(CoreNode)
interface_one = ip_prefixes.create_interface(node_one) interface1_data = ip_prefixes.create_interface(node1)
interface_two = ip_prefixes.create_interface(node_two) interface2_data = ip_prefixes.create_interface(node2)
session.add_link(node_one.id, node_two.id, interface_one, interface_two) session.add_link(node1.id, node2.id, interface1_data, interface2_data)
assert node_one.netif(interface_one.id) assert node1.netif(interface1_data.id)
assert node_two.netif(interface_two.id) assert node2.netif(interface2_data.id)
# when # when
session.delete_link( session.delete_link(node1.id, node2.id, interface1_data.id, interface2_data.id)
node_one.id, node_two.id, interface_one.id, interface_two.id
)
# then # then
assert not node_one.netif(interface_one.id) assert not node1.netif(interface1_data.id)
assert not node_two.netif(interface_two.id) assert not node2.netif(interface2_data.id)
def test_delete_node_to_net(self, session: Session, ip_prefixes: IpPrefixes): def test_delete_node_to_net(self, session: Session, ip_prefixes: IpPrefixes):
# given # given
node_one = session.add_node(CoreNode) node1 = session.add_node(CoreNode)
node_two = session.add_node(SwitchNode) node2 = session.add_node(SwitchNode)
interface_one = ip_prefixes.create_interface(node_one) interface1_data = ip_prefixes.create_interface(node1)
session.add_link(node_one.id, node_two.id, interface_one) session.add_link(node1.id, node2.id, interface1_data)
assert node_one.netif(interface_one.id) assert node1.netif(interface1_data.id)
# when # when
session.delete_link(node_one.id, node_two.id, interface_one_id=interface_one.id) session.delete_link(node1.id, node2.id, interface1_id=interface1_data.id)
# then # then
assert not node_one.netif(interface_one.id) assert not node1.netif(interface1_data.id)
def test_delete_net_to_node(self, session: Session, ip_prefixes: IpPrefixes): def test_delete_net_to_node(self, session: Session, ip_prefixes: IpPrefixes):
# given # given
node_one = session.add_node(SwitchNode) node1 = session.add_node(SwitchNode)
node_two = session.add_node(CoreNode) node2 = session.add_node(CoreNode)
interface_two = ip_prefixes.create_interface(node_two) interface2_data = ip_prefixes.create_interface(node2)
session.add_link(node_one.id, node_two.id, interface_two=interface_two) session.add_link(node1.id, node2.id, interface2_data=interface2_data)
assert node_two.netif(interface_two.id) assert node2.netif(interface2_data.id)
# when # when
session.delete_link(node_one.id, node_two.id, interface_two_id=interface_two.id) session.delete_link(node1.id, node2.id, interface2_id=interface2_data.id)
# then # then
assert not node_two.netif(interface_two.id) assert not node2.netif(interface2_data.id)

View file

@ -206,23 +206,23 @@ class TestServices:
# given # given
ServiceManager.add_services(_SERVICES_PATH) ServiceManager.add_services(_SERVICES_PATH)
my_service = ServiceManager.get(SERVICE_ONE) my_service = ServiceManager.get(SERVICE_ONE)
node_one = session.add_node(CoreNode) node1 = session.add_node(CoreNode)
node_two = session.add_node(CoreNode) node2 = session.add_node(CoreNode)
file_name = my_service.configs[0] file_name = my_service.configs[0]
file_data_one = "# custom file one" file_data1 = "# custom file one"
file_data_two = "# custom file two" file_data2 = "# custom file two"
session.services.set_service_file( session.services.set_service_file(
node_one.id, my_service.name, file_name, file_data_one node1.id, my_service.name, file_name, file_data1
) )
session.services.set_service_file( session.services.set_service_file(
node_two.id, my_service.name, file_name, file_data_two node2.id, my_service.name, file_name, file_data2
) )
# when # when
custom_service_one = session.services.get_service(node_one.id, my_service.name) custom_service1 = session.services.get_service(node1.id, my_service.name)
session.services.create_service_files(node_one, custom_service_one) session.services.create_service_files(node1, custom_service1)
custom_service_two = session.services.get_service(node_two.id, my_service.name) custom_service2 = session.services.get_service(node2.id, my_service.name)
session.services.create_service_files(node_two, custom_service_two) session.services.create_service_files(node2, custom_service2)
def test_service_import(self): def test_service_import(self):
""" """

View file

@ -48,7 +48,7 @@ class TestXml:
session.open_xml(file_path, start=True) session.open_xml(file_path, start=True)
# verify nodes have been recreated # verify nodes have been recreated
runtime_hooks = session._hooks.get(state) runtime_hooks = session.hooks.get(state)
assert runtime_hooks assert runtime_hooks
runtime_hook = runtime_hooks[0] runtime_hook = runtime_hooks[0]
assert file_name == runtime_hook[0] assert file_name == runtime_hook[0]
@ -68,20 +68,20 @@ class TestXml:
ptp_node = session.add_node(PtpNet) ptp_node = session.add_node(PtpNet)
# create nodes # create nodes
node_one = session.add_node(CoreNode) node1 = session.add_node(CoreNode)
node_two = session.add_node(CoreNode) node2 = session.add_node(CoreNode)
# link nodes to ptp net # link nodes to ptp net
for node in [node_one, node_two]: for node in [node1, node2]:
interface = ip_prefixes.create_interface(node) interface = ip_prefixes.create_interface(node)
session.add_link(node.id, ptp_node.id, interface_one=interface) session.add_link(node.id, ptp_node.id, interface1_data=interface)
# instantiate session # instantiate session
session.instantiate() session.instantiate()
# get ids for nodes # get ids for nodes
n1_id = node_one.id node1_id = node1.id
n2_id = node_two.id node2_id = node2.id
# save xml # save xml
xml_file = tmpdir.join("session.xml") xml_file = tmpdir.join("session.xml")
@ -97,16 +97,16 @@ class TestXml:
# verify nodes have been removed from session # verify nodes have been removed from session
with pytest.raises(CoreError): with pytest.raises(CoreError):
assert not session.get_node(n1_id, CoreNode) assert not session.get_node(node1_id, CoreNode)
with pytest.raises(CoreError): with pytest.raises(CoreError):
assert not session.get_node(n2_id, CoreNode) assert not session.get_node(node2_id, CoreNode)
# load saved xml # load saved xml
session.open_xml(file_path, start=True) session.open_xml(file_path, start=True)
# verify nodes have been recreated # verify nodes have been recreated
assert session.get_node(n1_id, CoreNode) assert session.get_node(node1_id, CoreNode)
assert session.get_node(n2_id, CoreNode) assert session.get_node(node2_id, CoreNode)
def test_xml_ptp_services( def test_xml_ptp_services(
self, session: Session, tmpdir: TemporaryFile, ip_prefixes: IpPrefixes self, session: Session, tmpdir: TemporaryFile, ip_prefixes: IpPrefixes
@ -123,28 +123,28 @@ class TestXml:
# create nodes # create nodes
options = NodeOptions(model="host") options = NodeOptions(model="host")
node_one = session.add_node(CoreNode, options=options) node1 = session.add_node(CoreNode, options=options)
node_two = session.add_node(CoreNode) node2 = session.add_node(CoreNode)
# link nodes to ptp net # link nodes to ptp net
for node in [node_one, node_two]: for node in [node1, node2]:
interface = ip_prefixes.create_interface(node) interface = ip_prefixes.create_interface(node)
session.add_link(node.id, ptp_node.id, interface_one=interface) session.add_link(node.id, ptp_node.id, interface1_data=interface)
# set custom values for node service # set custom values for node service
session.services.set_service(node_one.id, SshService.name) session.services.set_service(node1.id, SshService.name)
service_file = SshService.configs[0] service_file = SshService.configs[0]
file_data = "# test" file_data = "# test"
session.services.set_service_file( session.services.set_service_file(
node_one.id, SshService.name, service_file, file_data node1.id, SshService.name, service_file, file_data
) )
# instantiate session # instantiate session
session.instantiate() session.instantiate()
# get ids for nodes # get ids for nodes
n1_id = node_one.id node1_id = node1.id
n2_id = node_two.id node2_id = node2.id
# save xml # save xml
xml_file = tmpdir.join("session.xml") xml_file = tmpdir.join("session.xml")
@ -160,19 +160,19 @@ class TestXml:
# verify nodes have been removed from session # verify nodes have been removed from session
with pytest.raises(CoreError): with pytest.raises(CoreError):
assert not session.get_node(n1_id, CoreNode) assert not session.get_node(node1_id, CoreNode)
with pytest.raises(CoreError): with pytest.raises(CoreError):
assert not session.get_node(n2_id, CoreNode) assert not session.get_node(node2_id, CoreNode)
# load saved xml # load saved xml
session.open_xml(file_path, start=True) session.open_xml(file_path, start=True)
# retrieve custom service # retrieve custom service
service = session.services.get_service(node_one.id, SshService.name) service = session.services.get_service(node1.id, SshService.name)
# verify nodes have been recreated # verify nodes have been recreated
assert session.get_node(n1_id, CoreNode) assert session.get_node(node1_id, CoreNode)
assert session.get_node(n2_id, CoreNode) assert session.get_node(node2_id, CoreNode)
assert service.config_data.get(service_file) == file_data assert service.config_data.get(service_file) == file_data
def test_xml_mobility( def test_xml_mobility(
@ -192,21 +192,21 @@ class TestXml:
# create nodes # create nodes
options = NodeOptions(model="mdr") options = NodeOptions(model="mdr")
options.set_position(0, 0) options.set_position(0, 0)
node_one = session.add_node(CoreNode, options=options) node1 = session.add_node(CoreNode, options=options)
node_two = session.add_node(CoreNode, options=options) node2 = session.add_node(CoreNode, options=options)
# link nodes # link nodes
for node in [node_one, node_two]: for node in [node1, node2]:
interface = ip_prefixes.create_interface(node) interface = ip_prefixes.create_interface(node)
session.add_link(node.id, wlan_node.id, interface_one=interface) session.add_link(node.id, wlan_node.id, interface1_data=interface)
# instantiate session # instantiate session
session.instantiate() session.instantiate()
# get ids for nodes # get ids for nodes
wlan_id = wlan_node.id wlan_id = wlan_node.id
n1_id = node_one.id node1_id = node1.id
n2_id = node_two.id node2_id = node2.id
# save xml # save xml
xml_file = tmpdir.join("session.xml") xml_file = tmpdir.join("session.xml")
@ -222,9 +222,9 @@ class TestXml:
# verify nodes have been removed from session # verify nodes have been removed from session
with pytest.raises(CoreError): with pytest.raises(CoreError):
assert not session.get_node(n1_id, CoreNode) assert not session.get_node(node1_id, CoreNode)
with pytest.raises(CoreError): with pytest.raises(CoreError):
assert not session.get_node(n2_id, CoreNode) assert not session.get_node(node2_id, CoreNode)
# load saved xml # load saved xml
session.open_xml(file_path, start=True) session.open_xml(file_path, start=True)
@ -233,8 +233,8 @@ class TestXml:
value = str(session.mobility.get_config("test", wlan_id, BasicRangeModel.name)) value = str(session.mobility.get_config("test", wlan_id, BasicRangeModel.name))
# verify nodes and configuration were restored # verify nodes and configuration were restored
assert session.get_node(n1_id, CoreNode) assert session.get_node(node1_id, CoreNode)
assert session.get_node(n2_id, CoreNode) assert session.get_node(node2_id, CoreNode)
assert session.get_node(wlan_id, WlanNode) assert session.get_node(wlan_id, WlanNode)
assert value == "1" assert value == "1"
@ -246,18 +246,18 @@ class TestXml:
:param tmpdir: tmpdir to create data in :param tmpdir: tmpdir to create data in
""" """
# create nodes # create nodes
switch_one = session.add_node(SwitchNode) switch1 = session.add_node(SwitchNode)
switch_two = session.add_node(SwitchNode) switch2 = session.add_node(SwitchNode)
# link nodes # link nodes
session.add_link(switch_one.id, switch_two.id) session.add_link(switch1.id, switch2.id)
# instantiate session # instantiate session
session.instantiate() session.instantiate()
# get ids for nodes # get ids for nodes
n1_id = switch_one.id node1_id = switch1.id
n2_id = switch_two.id node2_id = switch2.id
# save xml # save xml
xml_file = tmpdir.join("session.xml") xml_file = tmpdir.join("session.xml")
@ -273,19 +273,19 @@ class TestXml:
# verify nodes have been removed from session # verify nodes have been removed from session
with pytest.raises(CoreError): with pytest.raises(CoreError):
assert not session.get_node(n1_id, SwitchNode) assert not session.get_node(node1_id, SwitchNode)
with pytest.raises(CoreError): with pytest.raises(CoreError):
assert not session.get_node(n2_id, SwitchNode) assert not session.get_node(node2_id, SwitchNode)
# load saved xml # load saved xml
session.open_xml(file_path, start=True) session.open_xml(file_path, start=True)
# verify nodes have been recreated # verify nodes have been recreated
switch_one = session.get_node(n1_id, SwitchNode) switch1 = session.get_node(node1_id, SwitchNode)
switch_two = session.get_node(n2_id, SwitchNode) switch2 = session.get_node(node2_id, SwitchNode)
assert switch_one assert switch1
assert switch_two assert switch2
assert len(switch_one.all_link_data() + switch_two.all_link_data()) == 1 assert len(switch1.all_link_data() + switch2.all_link_data()) == 1
def test_link_options( def test_link_options(
self, session: Session, tmpdir: TemporaryFile, ip_prefixes: IpPrefixes self, session: Session, tmpdir: TemporaryFile, ip_prefixes: IpPrefixes
@ -298,25 +298,25 @@ class TestXml:
:param ip_prefixes: generates ip addresses for nodes :param ip_prefixes: generates ip addresses for nodes
""" """
# create nodes # create nodes
node_one = session.add_node(CoreNode) node1 = session.add_node(CoreNode)
interface_one = ip_prefixes.create_interface(node_one) interface1_data = ip_prefixes.create_interface(node1)
switch = session.add_node(SwitchNode) switch = session.add_node(SwitchNode)
# create link # create link
link_options = LinkOptions() options = LinkOptions()
link_options.loss = 10.5 options.loss = 10.5
link_options.bandwidth = 50000 options.bandwidth = 50000
link_options.jitter = 10 options.jitter = 10
link_options.delay = 30 options.delay = 30
link_options.dup = 5 options.dup = 5
session.add_link(node_one.id, switch.id, interface_one, options=link_options) session.add_link(node1.id, switch.id, interface1_data, options=options)
# instantiate session # instantiate session
session.instantiate() session.instantiate()
# get ids for nodes # get ids for nodes
n1_id = node_one.id node1_id = node1.id
n2_id = switch.id node2_id = switch.id
# save xml # save xml
xml_file = tmpdir.join("session.xml") xml_file = tmpdir.join("session.xml")
@ -332,26 +332,26 @@ class TestXml:
# verify nodes have been removed from session # verify nodes have been removed from session
with pytest.raises(CoreError): with pytest.raises(CoreError):
assert not session.get_node(n1_id, CoreNode) assert not session.get_node(node1_id, CoreNode)
with pytest.raises(CoreError): with pytest.raises(CoreError):
assert not session.get_node(n2_id, SwitchNode) assert not session.get_node(node2_id, SwitchNode)
# load saved xml # load saved xml
session.open_xml(file_path, start=True) session.open_xml(file_path, start=True)
# verify nodes have been recreated # verify nodes have been recreated
assert session.get_node(n1_id, CoreNode) assert session.get_node(node1_id, CoreNode)
assert session.get_node(n2_id, SwitchNode) assert session.get_node(node2_id, SwitchNode)
links = [] links = []
for node_id in session.nodes: for node_id in session.nodes:
node = session.nodes[node_id] node = session.nodes[node_id]
links += node.all_link_data() links += node.all_link_data()
link = links[0] link = links[0]
assert link_options.loss == link.loss assert options.loss == link.loss
assert link_options.bandwidth == link.bandwidth assert options.bandwidth == link.bandwidth
assert link_options.jitter == link.jitter assert options.jitter == link.jitter
assert link_options.delay == link.delay assert options.delay == link.delay
assert link_options.dup == link.dup assert options.dup == link.dup
def test_link_options_ptp( def test_link_options_ptp(
self, session: Session, tmpdir: TemporaryFile, ip_prefixes: IpPrefixes self, session: Session, tmpdir: TemporaryFile, ip_prefixes: IpPrefixes
@ -364,28 +364,26 @@ class TestXml:
:param ip_prefixes: generates ip addresses for nodes :param ip_prefixes: generates ip addresses for nodes
""" """
# create nodes # create nodes
node_one = session.add_node(CoreNode) node1 = session.add_node(CoreNode)
interface_one = ip_prefixes.create_interface(node_one) interface1_data = ip_prefixes.create_interface(node1)
node_two = session.add_node(CoreNode) node2 = session.add_node(CoreNode)
interface_two = ip_prefixes.create_interface(node_two) interface2_data = ip_prefixes.create_interface(node2)
# create link # create link
link_options = LinkOptions() options = LinkOptions()
link_options.loss = 10.5 options.loss = 10.5
link_options.bandwidth = 50000 options.bandwidth = 50000
link_options.jitter = 10 options.jitter = 10
link_options.delay = 30 options.delay = 30
link_options.dup = 5 options.dup = 5
session.add_link( session.add_link(node1.id, node2.id, interface1_data, interface2_data, options)
node_one.id, node_two.id, interface_one, interface_two, link_options
)
# instantiate session # instantiate session
session.instantiate() session.instantiate()
# get ids for nodes # get ids for nodes
n1_id = node_one.id node1_id = node1.id
n2_id = node_two.id node2_id = node2.id
# save xml # save xml
xml_file = tmpdir.join("session.xml") xml_file = tmpdir.join("session.xml")
@ -401,26 +399,26 @@ class TestXml:
# verify nodes have been removed from session # verify nodes have been removed from session
with pytest.raises(CoreError): with pytest.raises(CoreError):
assert not session.get_node(n1_id, CoreNode) assert not session.get_node(node1_id, CoreNode)
with pytest.raises(CoreError): with pytest.raises(CoreError):
assert not session.get_node(n2_id, CoreNode) assert not session.get_node(node2_id, CoreNode)
# load saved xml # load saved xml
session.open_xml(file_path, start=True) session.open_xml(file_path, start=True)
# verify nodes have been recreated # verify nodes have been recreated
assert session.get_node(n1_id, CoreNode) assert session.get_node(node1_id, CoreNode)
assert session.get_node(n2_id, CoreNode) assert session.get_node(node2_id, CoreNode)
links = [] links = []
for node_id in session.nodes: for node_id in session.nodes:
node = session.nodes[node_id] node = session.nodes[node_id]
links += node.all_link_data() links += node.all_link_data()
link = links[0] link = links[0]
assert link_options.loss == link.loss assert options.loss == link.loss
assert link_options.bandwidth == link.bandwidth assert options.bandwidth == link.bandwidth
assert link_options.jitter == link.jitter assert options.jitter == link.jitter
assert link_options.delay == link.delay assert options.delay == link.delay
assert link_options.dup == link.dup assert options.dup == link.dup
def test_link_options_bidirectional( def test_link_options_bidirectional(
self, session: Session, tmpdir: TemporaryFile, ip_prefixes: IpPrefixes self, session: Session, tmpdir: TemporaryFile, ip_prefixes: IpPrefixes
@ -433,43 +431,37 @@ class TestXml:
:param ip_prefixes: generates ip addresses for nodes :param ip_prefixes: generates ip addresses for nodes
""" """
# create nodes # create nodes
node_one = session.add_node(CoreNode) node1 = session.add_node(CoreNode)
interface_one = ip_prefixes.create_interface(node_one) interface1_data = ip_prefixes.create_interface(node1)
node_two = session.add_node(CoreNode) node2 = session.add_node(CoreNode)
interface_two = ip_prefixes.create_interface(node_two) interface2_data = ip_prefixes.create_interface(node2)
# create link # create link
link_options_one = LinkOptions() options1 = LinkOptions()
link_options_one.unidirectional = 1 options1.unidirectional = 1
link_options_one.bandwidth = 5000 options1.bandwidth = 5000
link_options_one.delay = 10 options1.delay = 10
link_options_one.loss = 10.5 options1.loss = 10.5
link_options_one.dup = 5 options1.dup = 5
link_options_one.jitter = 5 options1.jitter = 5
session.add_link( session.add_link(node1.id, node2.id, interface1_data, interface2_data, options1)
node_one.id, node_two.id, interface_one, interface_two, link_options_one options2 = LinkOptions()
) options2.unidirectional = 1
link_options_two = LinkOptions() options2.bandwidth = 10000
link_options_two.unidirectional = 1 options2.delay = 20
link_options_two.bandwidth = 10000 options2.loss = 10
link_options_two.delay = 20 options2.dup = 10
link_options_two.loss = 10 options2.jitter = 10
link_options_two.dup = 10
link_options_two.jitter = 10
session.update_link( session.update_link(
node_two.id, node2.id, node1.id, interface2_data.id, interface1_data.id, options2
node_one.id,
interface_two.id,
interface_one.id,
link_options_two,
) )
# instantiate session # instantiate session
session.instantiate() session.instantiate()
# get ids for nodes # get ids for nodes
n1_id = node_one.id node1_id = node1.id
n2_id = node_two.id node2_id = node2.id
# save xml # save xml
xml_file = tmpdir.join("session.xml") xml_file = tmpdir.join("session.xml")
@ -485,30 +477,30 @@ class TestXml:
# verify nodes have been removed from session # verify nodes have been removed from session
with pytest.raises(CoreError): with pytest.raises(CoreError):
assert not session.get_node(n1_id, CoreNode) assert not session.get_node(node1_id, CoreNode)
with pytest.raises(CoreError): with pytest.raises(CoreError):
assert not session.get_node(n2_id, CoreNode) assert not session.get_node(node2_id, CoreNode)
# load saved xml # load saved xml
session.open_xml(file_path, start=True) session.open_xml(file_path, start=True)
# verify nodes have been recreated # verify nodes have been recreated
assert session.get_node(n1_id, CoreNode) assert session.get_node(node1_id, CoreNode)
assert session.get_node(n2_id, CoreNode) assert session.get_node(node2_id, CoreNode)
links = [] links = []
for node_id in session.nodes: for node_id in session.nodes:
node = session.nodes[node_id] node = session.nodes[node_id]
links += node.all_link_data() links += node.all_link_data()
assert len(links) == 2 assert len(links) == 2
link_one = links[0] link1 = links[0]
link_two = links[1] link2 = links[1]
assert link_options_one.bandwidth == link_one.bandwidth assert options1.bandwidth == link1.bandwidth
assert link_options_one.delay == link_one.delay assert options1.delay == link1.delay
assert link_options_one.loss == link_one.loss assert options1.loss == link1.loss
assert link_options_one.dup == link_one.dup assert options1.dup == link1.dup
assert link_options_one.jitter == link_one.jitter assert options1.jitter == link1.jitter
assert link_options_two.bandwidth == link_two.bandwidth assert options2.bandwidth == link2.bandwidth
assert link_options_two.delay == link_two.delay assert options2.delay == link2.delay
assert link_options_two.loss == link_two.loss assert options2.loss == link2.loss
assert link_options_two.dup == link_two.dup assert options2.dup == link2.dup
assert link_options_two.jitter == link_two.jitter assert options2.jitter == link2.jitter

View file

@ -62,7 +62,7 @@ def main():
for _ in range(NODES): for _ in range(NODES):
node = session.add_node(CoreNode) node = session.add_node(CoreNode)
interface = prefixes.create_interface(node) interface = prefixes.create_interface(node)
session.add_link(node.id, switch.id, interface_one=interface) session.add_link(node.id, switch.id, interface1_data=interface)
# instantiate session # instantiate session
session.instantiate() session.instantiate()