def test_create_link_routers_in_different_networks():
    """Attempt to create a link whose routers are in different networks."""
    network_1 = Network()
    network_2 = Network()
    alice = Router(network_1, "alice")
    bob = Router(network_2, "bob")
    with pytest.raises(AssertionError):
        _link = Link(alice, bob, 100)
def test_create_link_bad_lenght():
    """Attempt to create a link whose length is not greater than zero."""
    network = Network()
    alice = Router(network, "alice")
    bob = Router(network, "bob")
    with pytest.raises(AssertionError):
        _link = Link(alice, bob, -100)
    with pytest.raises(AssertionError):
        _link = Link(alice, bob, 0)
Example #3
0
def create_routers(ai_settings, screen):
    """创建路由器组"""
    routers = Group()
    router_1 = Router(ai_settings, screen, 300, 40, 'A')
    router_2 = Router(ai_settings, screen, 580, 40, 'B')
    router_3 = Router(ai_settings, screen, 860, 40, 'C')
    router_4 = Router(ai_settings, screen, 300, 190, 'D')
    router_5 = Router(ai_settings, screen, 580, 190, 'E')
    router_6 = Router(ai_settings, screen, 860, 190, 'F')
    router_7 = Router(ai_settings, screen, 300, 340, 'G')
    router_8 = Router(ai_settings, screen, 580, 340, 'H')
    router_9 = Router(ai_settings, screen, 860, 340, 'I')
    routers.add(router_1)
    routers.add(router_2)
    routers.add(router_3)
    routers.add(router_4)
    routers.add(router_5)
    routers.add(router_6)
    routers.add(router_7)
    routers.add(router_8)
    routers.add(router_9)
    router_list.append(router_1)
    router_list.append(router_2)
    router_list.append(router_3)
    router_list.append(router_4)
    router_list.append(router_5)
    router_list.append(router_6)
    router_list.append(router_7)
    router_list.append(router_8)
    router_list.append(router_9)

    return routers, router_list
def test_create_path():
    """Test creation of a path."""
    network = Network()
    demand = Demand(network)
    alice = Router(network, "alice")
    bob = Router(network, "bob")
    _path = Path(demand=demand,
                 name="alice-to-bob",
                 end_point_1=alice,
                 end_point_2=bob,
                 bandwidth=10,
                 fidelity=0.95)
def test_create_link():
    """Test creation of a link."""
    network = Network()
    alice = Router(network, "alice")
    bob = Router(network, "bob")
    link = Link(alice, bob, 100)
    assert link.router_1 == alice
    assert link.port_1 == 0
    assert link.router_2 == bob
    assert link.port_2 == 0
    assert link.length == 100
    assert alice.links[0] == link
    assert bob.links[0] == link
Example #6
0
def main():  # Programa principal
    # Routers
    RINT = Router('RINT', secret.ENABLE_PASSWORD, secret.CONSOLE_PASSWORD)
    RoExt = Router('RoExt', secret.ENABLE_PASSWORD, secret.CONSOLE_PASSWORD)
    RBor1 = Router('RBor1', secret.ENABLE_PASSWORD, secret.CONSOLE_PASSWORD)
    RBor2 = Router('RBor2', secret.ENABLE_PASSWORD, secret.CONSOLE_PASSWORD)

    #Switches
    SW1 = Switch('SW1', secret.ENABLE_PASSWORD, secret.CONSOLE_PASSWORD)
    SW2 = Switch('SW2', secret.ENABLE_PASSWORD, secret.CONSOLE_PASSWORD)
    SW3 = Switch('SW3', secret.ENABLE_PASSWORD, secret.CONSOLE_PASSWORD)
    SwExt = Switch('SwExt', secret.ENABLE_PASSWORD, secret.CONSOLE_PASSWORD)

    print(SW1.interfaces)
Example #7
0
    def init_router(self):
        if not os.path.exists(self.CONFIG_FILE):
            raise IOError('config file could not found. {0}'.format(
                self.CONFIG_FILE))

        self.r = Router(self.CONFIG_FILE)
        return self.r
Example #8
0
def device_setup(hostname, data, env_vars, que):
    device = Router(hostname=hostname,
                    mgmt_ip=data['mgmt'],
                    vendor=data['vendor'],
                    os=data['os'])

    for name, interface in data['interfaces'].items():
        device.add_interface(name=name,
                             ip=ipaddress.IPv4Interface(interface['ipaddr']),
                             description=interface['description'],
                             status=interface['state'])

    # BGP
    all_neighbors = []
    for neighbor in data['bgp']['neighbors']:
        all_neighbors.append((neighbor['ipaddr'], neighbor['remote_asn']))

    redistribute_options = []
    if 'redistribute' in data['bgp']:
        for option in data['bgp']['redistribute']:
            redistribute_options.append(option)

    device.add_bgp(rid=data['bgp']['rid'],
                   asn=data['bgp']['asn'],
                   redistribute=redistribute_options,
                   neighbors=all_neighbors)

    open_device = connect_to_device(device, env_vars)

    que.put((device, open_device))
Example #9
0
    def random_ride(self,
                    ne_lng,
                    ne_lat,
                    sw_lng,
                    sw_lat,
                    min_len=2,
                    max_len=10):
        """
        params are bounding box and minimum length in kilometres
        """
        print "seeking random route"
        while True:

            a = LatLon(Latitude(random.uniform(ne_lat, sw_lat)),
                       Longitude(random.uniform(sw_lng, ne_lng)))
            c = LatLon(Latitude(random.uniform(ne_lat, sw_lat)),
                       Longitude(random.uniform(sw_lng, ne_lng)))

            if a.distance(c) >= min_len and a.distance(c) <= max_len:
                self.point = (a.lon.decimal_degree, a.lat.decimal_degree)
                self.destination = (c.lon.decimal_degree, c.lat.decimal_degree)

                router = Router(points=[self.point, self.destination])
                if router.route:
                    self.route = router.route
                    self.save()
                    break
Example #10
0
def lambda_handler(event, context):
    debug = False
    if debug:
        return util.debug(event)

    router = Router(event)
    
    error_message = {'sessionAttributes': {'author': None}, 
                     'dialogAction': {
                         'type': 'ElicitIntent',
                         'message': {
                            'contentType': 'PlainText', 
                            'content': "I'm sorry. I'm having connection "
                                       "issues."
                         }
                     }
                     }

    try:
        res = router.route()
        return res
    except RuntimeError:
        return error_message
    except Exception as e:
        error_message['dialogAction']['message']['content'] = "I'm sorry, " \
                                    "I cannot answer that right now."
        return error_message
Example #11
0
def test_router(net, land):
    from router import Router

    net.init_flows()
    print 'edges'
    pprint([(edge, str(edge)) for edge in net.edges])
    path = Router.find_shortest_path(net, 0, net.nodes[1], net.nodes[6])
    print 'path 1 - 6'
    pprint(path)
    path = Router.find_shortest_path(net, 0, net.nodes[6], net.nodes[1])
    print 'path 6 - 1'
    pprint(path)
    paths = Router.find_shortest_path(net, 0, net.nodes[1])
    print 'paths 1 - *'
    pprint(paths)
    paths = Router.find_shortest_path(net, 0, net.nodes[100])
    print 'paths 100 - *'
    pprint(paths)
    router = Router(net, land)
    print 'building shortest paths...'
    router.build_shortest_paths()
    # logger.debug(pformat(dict(router.paths)))
    path = router.get_shortest_path(0, 100, 100)
    print 'path 100 - 100'
    pprint(path)
    path = router.get_shortest_path(0, 100, 200)
    print 'path 100 - 200'
    pprint(path)
    path = router.get_shortest_path(0, 100, 600)
    print 'path 100 - 600'
    pprint(path)
    return router
Example #12
0
    def _decorate_routes(cls):
        """sets up all the @route methods so they can be used to match requests
		and send replies

		need a way to have this called automatically. I would flex with the
		metaclass, or BaseHTTPServer, but the fuss isn't worth it. these are all
		old-style classes and I'd rather make any real improvements as a part of
		porting this functionaility to http.server in python 3

		Just call it manually when ya start the server.
		"""
        found_routes = {}
        # e.g. { 'GET': [Route, Route], 'POST': [Route], ... }
        # list of all route members:
        is_route = lambda member: isinstance(member, Route)
        for name, member in inspect.getmembers(cls, predicate=is_route):

            # since routes can be nested, find all the routes living under this one
            # along with the actual instance method to be called.
            nested_routes, original_method = member.all_routes
            for route in nested_routes:
                found_routes.setdefault(route.http_method, []).append(route)

            # replace the original method as well.
            setattr(cls, name, original_method)

        # once all the methods have been found and organized by http method,
        for http_method, routes in found_routes.items():
            cls.routers[http_method] = Router(routes)
Example #13
0
def setup_routes(app):
    router_instance = Router()
    
    app.router.add_get("/", index)
    app.router.add_get("/index.html", index)
    app.router.add_get("/register", register)
    app.router.add_get("/register.html", register)
    app.router.add_get("/request", request)
    app.router.add_get("/request.html", request)
    app.router.add_get("/statistics.html", statistic)
    
    app.router.add_get("/success-register.html", success_register)
    app.router.add_get("/fail-register.html", fail_register)
    app.router.add_get("/success-request.html", success_request)
    app.router.add_get("/fail-request.html", fail_request)
    
    app.router.add_post("/success-register.html", success_register)
    app.router.add_post("/fail-register.html", fail_register)
    app.router.add_post("/success-request.html", success_request)
    app.router.add_post("/fail-request.html", fail_request)
    #app.router.add_post('/login', router_instance.login)
    #app.router.add_post('/create_user', router_instance.create_user)
    app.router.add_post('/request_blood', router_instance.request_blood)
    app.router.add_get('/request_blood', router_instance.request_blood)

    #app.router.add_post('/check_login_user', router_instance.check_login_user)
    app.router.add_post('/register_blood_donation', router_instance.register_blood_donation)
    app.router.add_get('/register_blood_donation', router_instance.register_blood_donation)

    app.router.add_get('/show_statistic', router_instance.show_statistic)
Example #14
0
 def test_router_with_invalid_path(self):
     router = Router("root handler", "not found handler")
     with self.assertRaises(Exception) as context:
         router.add_handler("home/about",
                            "about handler")  # URL doesn't have a leading /
         self.assertTrue('URL is invalid as it does not start with /' in
                         context.exception)
 def __init__(self, server):
     self.services['server'] = server
     self.services['sentences_list'] = SentencesList(self)
     self.services['sentences_view'] = SentencesView(self)
     self.services['sentences_ressource'] = SentencesRessource(self)
     self.services['router'] = Router(self)
     self.services['ci_alert'] = CIAlert(self)
Example #16
0
 def test_router_with_url_not_found(self):
     router = Router("root handler", "not found handler")
     router.add_handler("/home/about/me", "me handler")
     router.add_handler("/home/cooking/recipe", "recipe handler")
     router.add_handler("/home/contact/email", "email handler")
     router.add_handler("/home/contact/facebook", "facebook handler")
     self.assertEqual(router.lookup("/home/cooking"), "not found handler")
Example #17
0
    def __init__(self):
        self.width = WIDTH
        self.height = HEIGHT
        self.host_quantity = HOSTS_QUANTITY
        self.signal_range = SIGNAL_RANGE
        
        self.hosts = list()

        ## HOSTS INSTANTIATION ##
        # generates a random position and creates a host with it 
        print(f"\nGenerating positions for {HOSTS_QUANTITY} hosts in a map {WIDTH}x{HEIGHT} Km...", end=" ")
        positions = utils.generate_coordinates(HOSTS_QUANTITY, WIDTH, HEIGHT)
        for position in positions:
            self.hosts.append(Host(position, SIGNAL_RANGE))
        print(f"{HOSTS_QUANTITY} hosts were created.")

        ## ROUTER INSTANTIATION ##
        print("Creating router...", end=" ")
        router = Router(self.hosts)
        print("Router created.")

        # gives an list of near active hosts for each host
        print("Running Hello for each host...", end=" ")
        router.hello()
        print("Host Hello status complete.\n")
Example #18
0
async def http_server(datadump, connection):
    # Create context for HTTP server
    app = Application()

    # Configure CORS options
    # Check https://github.com/aio-libs/aiohttp-cors for details
    cors_default_options = {}
    for host in WHITELIST:
        cors_default_options[host] = aiohttp_cors.ResourceOptions(
            allow_methods=['GET'],
            allow_headers=('Origin', 'X-Requested-With', 'Content-Type',
                           'Accept', 'x-timebase', 'Link'))
    cors = aiohttp_cors.setup(app, defaults=cors_default_options)

    # Configure routes
    router = Router(datadump, connection)
    router.register(app.router)

    # Configure CORS on all routes
    for route in list(app.router.routes()):
        cors.add(route)

    runner = AppRunner(app)
    await runner.setup()
    site = TCPSite(runner, '0.0.0.0', HTTP_PORT)
    return runner, site
Example #19
0
def main():
    seed = ord(os.urandom(1))
    #seed = 217
    print("Running with seed {}".format(seed))
    random.seed(seed)
    priests = create_priests(5)
    router = Router()
    for priest in priests:
        priest.connect_to(router)

    any_decree_committed = False
    iteration = 0
    while not any_decree_committed:
        print("Iteration {}".format(iteration))
        priests[0].initiate_ballot()
        for t in range(30):
            router.distribute()
            for priest in priests:
                priest.distribute()

        #printer = LogPrinter(router.get_log(), len(priests))
        #printer.print()
        #router.reset_log()

        for priest in priests:
            if priest.get_decree() is not None:
                any_decree_committed = True
                break

        iteration += 1

    printer = LogPrinter(router.get_log(), len(priests))
    printer.print()
    router.reset_log()
    print("Selected decree is {}".format(priest.get_decree()))
Example #20
0
	def __init__(self, text : str = "Top", **kwargs):
		super().__init__()
		root = Frame(self)
		menubar = Menu(self)
		self["menu"] = menubar
		#menu_action = Menu(menubar,tearoff=False)
		#menubar.add_cascade(label="Actions",menu=menu_action)
		menubar.add_command(label="Stats", command=self.on_stats)
		menubar.add_command(label="Redraw",command=self.on_redraw)
		menubar.add_command(label="Ripup",command=self.on_ripup)
		menubar.add_command(label="Manhattan", command=self.on_manhattan)
		menubar.add_command(label="Reset",command=self.on_reset)
		menubar.add_command(label="Cleanup", command=self.on_cleanup)
		self.canvas = Canvas(root)
		self.canvas.configure(scrollregion=(0, 0, 800, 600))

		self.canvas.pack(fill=BOTH,side=TOP,expand=True)

		#btn = Button(root,text="toto")
		#btn.pack(fill=BOTH)
		#self.geometry("800x600")
		self.title("SMUG Router")
		root.pack(fill=BOTH,expand=True)
		self.router: Router = Router(read_design())
		self.on_reset()
Example #21
0
async def add_router(routerid: 'Id6', rconfig: Mapping[str, Any],
                     pkfwduri: str) -> Router:
    assert routerid not in routerid2router
    r = Router(routerid, rconfig, pkfwduri)
    await r.start()
    routerid2router[routerid] = r
    return r
Example #22
0
def lambda_handler(event, context):
    debug = False
    if debug:
        return util.debug(event)
    print(context)
    intent = event['currentIntent']
    router = Router(intent)
    return router.route()
 def test_name(self):
     router = Router()
     router.name = "hostname"
     self.assertTrue(router.name == "hostname")
     self.assertTrue(router.router_name == "hostname")
     self.assertTrue(router.nvram['router_name'] == "hostname")
     self.assertTrue(router.wan_hostname == "hostname")
     self.assertTrue(router.nvram['wan_hostname'] == "hostname")
Example #24
0
def polling_routers(ipRouter):

    session = Session(hostname=ipRouter, community=COMMUNITY, version=2)
    name = (session.get('SNMPv2-MIB::sysName.0'))
    router = network.getRouter(name.value)
    if router is None:
        router = Router(name.value)
    print router.getName()
Example #25
0
    def __init__(self, serverId):
        self.serverId = int(serverId)
        self.model = Model(self)
        self.timeStamp = Clock(serverId=self.serverId)
        self.router = Router(self.serverId)

        self.lc_gossip = LoopingCall(self.gossip)
        self.lc_resend = LoopingCall(self.model.resend)
Example #26
0
def application(env: dict, start_response: Callable) -> Iterator[Any]:
    ctx = Context(env, VIEWS_STORAGE, MOCK_DB)

    router = Router(ctx, ROUTES)
    status, action = router.call()

    start_response(STATUS_CODES[status], [("Content-Type", "text/html")])

    yield action().encode()
Example #27
0
    def __init__(self):
        self.recieve_queue = []
        self.send_queue = []

        self.router = Router()
        self.language = LangProc()

        self.members = []
        self.groups = []
Example #28
0
 def __init__(self):
    # general bid auction settings
    self.auction_time_left = 10 # bid timeout
    self.auction_bid_stategy = self.perf_bid_strategy1 # bid min price
    bwrap = bw.BlockchainWrapper() # connector to the already blockchain
    self.blockchain = bwrap
    self.router = mr.Router() # auction router
    self.router_advertiser = 'xrtb pip ' # event service router
    return
Example #29
0
    def add_router(self, router_id):
        """Adds a new router to the network.

        Args:
            router_id (str): id of the router

        """
        router = Router(self, router_id)
        self.nodes[router_id] = router
Example #30
0
    def __init__(self, filename, duration):
        self.filename = filename
        # the duration of the simulation, in number of timesteps
        self.duration = int(duration / globals.dt)
        # Import the network object parameters
        with open(self.filename) as f:
            network_objects = json.load(f)
        # Create links
        for l in network_objects['links']:
            # Clear the variable
            link = None

            # Add to idmapping
            link = Link(l['id'], l['connection1'], l['connection2'], \
                        l['rate'], l['delay'], l['buffersize'], l['track1'] == 1, \
                        l['track2'] == 1)
            globals.idmapping['links'][l['id']] = link

        # Create hosts
        for h in network_objects['hosts']:
            # Clear the variable
            host = None

            # Add to idmapping
            host = Host(h['id'], h['linkid'])
            globals.idmapping['hosts'][h['id']] = host

        # Create routers
        if network_objects['routers'] != [{}]:
            for r in network_objects['routers']:
                # Clear the variable
                router = None

                # Get the list of links connected to each router
                link_list = []
                for lin_id in r['links']:
                    link_list.append(globals.idmapping['links'][lin_id])

                # Initialize router and add to idmapping
                router = Router(r['id'], link_list)
                globals.idmapping['routers'][r['id']] = router

        # Create flows
        for f in network_objects['flows']:
            # Clear the variable
            flow = None

            # add to idmapping
            if f['congestion_control'] == 'reno':
                flow = Flow(f['id'], f['source'], f['destination'], f['amount'], \
                    f['start'], f['track'] == 1)
            else:
                flow = Flow_FAST(f['id'], f['source'], f['destination'], f['amount'], \
                    f['start'], f['track'] == 1)

            globals.idmapping['flows'][f['id']] = flow