Пример #1
0
    def send_stats(self):

        global r

        global msg
        global site_seen

        self.send_data = json.dumps(r.publish())

        print "DC: Sending TS our stats!"
        self.sendLine(self.send_data)

        #clean up objects and refresh
        site_seen.clear()
        r = None
        msg = []
        r = router(q, labels, tkgs, args.fingerprint, args.consensus)
        for kid, a in zip(r.keys, tkgs):
            msg.append(r.authority_msg(kid))

        time.sleep(dc_reg_delay)
        for host, port in tkg_info:

            reactor.connectSSL(host, int(port), c_factory,
                               ssl.ClientContextFactory())
Пример #2
0
def app(env, start_response):
    # Create the request object
    request = Request(env)
    # Defines which app and controller is being requested
    # The url must be something like:
    #   http://127.0.0.1:8080/[app]/[controller]
    app_requested, controller_requested = router(request.url)
    try:
        # Try to import the controller requested.
        if MOPF_APPLICATIONS not in sys.path:
            sys.path.insert(0, MOPF_APPLICATIONS)
        # import the module and 'func' will get the attributes of the controller_requested
        func = getattr(import_module('{0}.controllers'.format(app_requested)),
                       controller_requested)
    except AttributeError:
        # The requested controller/app does not exists
        start_response('404 NOT FOUND',
                       [('Content-Type', 'text/html; charset=utf-8')])
        return [b'NOT FOUND']
    # Execute the controller
    controller_response = func(request)
    # Start the response
    start_response('200 Ok', [('Content-Type', 'text/html; charset=utf-8')])
    response_body = str(controller_response)
    return [response_body.encode()]
def get_routers_list(addresses_list, community_name):
        routers_list=[]
        for address in addresses_list:
	        ifs_number=int(get_ifs_number_SNMP(address, community_name))
	        r=router(get_hostname_SNMP(address, community_name),address, get_ifs_info_SNMP(address, ifs_number, community_name))
	        routers_list.append(r)
        return routers_list
Пример #4
0
def handler(event, context):

    packages = {}
    packages['requests'] = modules.requests

    result = router(packages, event)

    return {'body': json.dumps(result)}
Пример #5
0
 def on_success(self, data):
     if 'text' in data:
         user = data['user']['screen_name']
         message = data['text'].encode('utf-8')
         status_id = data['id']
         response = router(message, "twitter")
         # print response
         response = '@' + user + ' ' + response
         send_tweet(response[:140], status_id)
def get_routers_list(addresses_list, community_name):
	"""Given the addresses list in input and the community name, this function returns the routers objects list.
#See the router.py src code for more details."""
        routers_list=[]
        for address in addresses_list:
	        ifs_number=int(get_ifs_number_SNMP(address, community_name))
	        r=router(get_hostname_SNMP(address, community_name),address, get_ifs_info_SNMP(address, ifs_number, community_name))
	        routers_list.append(r)
        return routers_list
Пример #7
0
def CreatNetwork(argv):
    data = utills.parseJson(argv)
    routerList = []  #lista de roteadores
    for i in data["routers"]:  #roda em cada roteador
        station = router(i["id"], 10)  #instancia um roteador
        HostsLocatios = utills.gerate_xy(len(i["hosts"]), i["width"],
                                         i["height"])
        for index, j in enumerate(i["hosts"]):  #roda em cada host
            station.insertHost(
                host(i["id"], j["id"], HostsLocatios[index], j["energy"],
                     j["range"]))
        routerList.append(station)
    return routerList
Пример #8
0
def get_email():
    if request.method == 'GET':
        return False
        # return "<img src='/static/bilu.jpg' width='100%' height='100%'>"
    email_from = request.form["from"].encode('utf8')
    subject = request.form["subject"].encode('utf8')

    response = router(subject, "sendgrid", email=email_from, subject=subject)

    if response != 'SAIR':
        return send_email(response, email_from, subject)
    else:
        return "OK"
Пример #9
0
def get_email():
    if request.method == "GET":
        return False
        # return "<img src='/static/bilu.jpg' width='100%' height='100%'>"
    email_from = request.form["from"].encode("utf8")
    subject = request.form["subject"].encode("utf8")

    response = router(subject, "sendgrid", email=email_from, subject=subject)

    if response != "SAIR":
        return send_email(response, email_from, subject)
    else:
        return "OK"
Пример #10
0
            def __init__(self, name):
                design.design.__init__(self, name)
                debug.info(2, "Create {0} object".format(name))

                cell = gdscell(name)
                self.add_inst(name=name, mod=cell, offset=[0, 0])
                self.connect_inst([])

                self.gdsname = "{0}/{1}.gds".format(
                    os.path.dirname(os.path.realpath(__file__)), name)
                r = router.router(self.gdsname)
                layer_stack = ("metal1", "via1", "metal2")
                self.assertTrue(r.route(self, layer_stack, src="A", dest="B"))
Пример #11
0
    def test_login_required_view_with_token(self):
        path = "/website"
        customer = Customer(name="test",
                            password="******",
                            email="test",
                            subscription=None,
                            plan=None)
        customer.save()

        token_str = "token"
        token = Token(token=token_str, customer=customer.pk)
        token.save()

        view = router.router(path, token_str)
        self.assertIsInstance(view, WebsiteView)
        self.assertEqual(view.customer.pk, customer.pk)
def main():
	##In some way put the output of buildblablabla file in the addresses list. TODO


	##Addresses list in hard coded way
	community_name='public'
	addresses_list=['192.168.3.1','10.1.1.2']
	address=['192.168.3.1']


	routers_list=get_routers_list(address, community_name)
	routers_list[0].display_info()
	#An object router is obtained through this function. 
	##What is needed are two parameter: the address of the router and the community name
	r=get_routers_list(address, community_name)##Return a router list giving in input the addresses list
	my_router=router()##Router without information. Used later

	##Example #1 (Utilizations through VFile)
	##The utilizations of interfaces of a single router r are obtained.
	##The utilizations are obtained waiting 2 VFile sent by router r itself.
	#Only the router object needed for this function.
	#It takes at least one minute to see the output results.
	utilization_VFile_once=0
	if(utilization_VFile_once):
		my_router=get_utilization_router_VFile(r)##Return the router with the utilization by VFiles
		my_router.print_ifs_utilization()##print the interfaces utilizations of the router

	##Example #2(Utilizations through NOT periodic polling)
	##The utilizations of interfaces of a single router r are obtained.
	##The utilizations are obtained polling twice the information from the router.
	##Is necessary polling twice because to compute the utilizations.
	##Needed to parameters : the router object (r) and the community name.
	polling=0
	if(polling):
		my_router=get_utilization_single_router_polling(r, community_name)##Polling a specific router
		my_router.print_ifs_utilization()##print the interfaces utilizations of the router

	##Example #3(Utilizations through periodic polling)
	##The utilizations of interfaces of all routers are obtained.
	##The utilizations are obtained polling periodically all the information from all routers in the routers list.
	##These parameters are needed: the routers_list, polling_interval and commnunity name.
	##The routers_list can be obtained using the get_routers_list function.
	polling_periodic=1
	if(polling_periodic):
		polling_interval=1##SECONDS
		get_utilization_polling(routers_list, polling_interval, community_name)
Пример #13
0
            def __init__(self, name):
                design.design.__init__(self, name)
                debug.info(2, "Create {0} object".format(name))

                cell = gdscell(name)
                self.add_inst(name=name,
                              mod=cell,
                              offset=[0,0])
                self.connect_inst([])
                
                self.gdsname = "{0}/{1}.gds".format(os.path.dirname(os.path.realpath(__file__)),name)
                r=router.router(self.gdsname)
                layer_stack =("metal1","via1","metal2")
                # This should be infeasible because it is blocked without a detour. 
                self.assertFalse(r.route(self,layer_stack,src="A",dest="B",detour_scale=1))
                # This should be feasible because we allow it to detour
                self.assertTrue(r.route(self,layer_stack,src="A",dest="B",detour_scale=3))
Пример #14
0
            def __init__(self, name):
                design.design.__init__(self, name)
                debug.info(2, "Create {0} object".format(name))

                cell = gdscell(name)
                self.add_inst(name=name, mod=cell, offset=[0, 0])
                self.connect_inst([])

                self.gdsname = "{0}/{1}.gds".format(
                    os.path.dirname(os.path.realpath(__file__)), name)
                r = router.router(self.gdsname)
                layer_stack = ("metal1", "via1", "metal2")
                # these are user coordinates and layers
                src_pin = [[0.52, 4.099], 11]
                tgt_pin = [[3.533, 1.087], 11]
                #r.route(layer_stack,src="A",dest="B")
                self.assertTrue(
                    r.route(self, layer_stack, src=src_pin, dest=tgt_pin))
Пример #15
0
def select():
    if request.method == 'GET':
        args=['condition','order','page','desc']
        form = request.values.to_dict()
        for i in args:
            form.setdefault(i, "")
        # 路由分库取得所在数据库dy ↓
        dy = router.router(form['condition'])
        # 生成对象dx ↓
        dx = router.resolve(dy, form['condition'],form['order'],form['page'],form['desc'])
        dx.parsing()
        q = dx.qbase
        count = dx.qbase.count()
        if count == 0:
            return jsonify(error_code = 'error')
        else:
        # q = dy.TaskidFile.select(dy.TaskidFile.task,dy.TaskidFile.file,dy.File.status).join(dy.File).where(dy.TaskidFile.task == form['condition'])
            ret_task = dy.database.execute(q)
            task_data = []
            for i in ret_task:
                # 翻译status,字典在conf中
                sta0 = i[2]
                stat = conf.stadic[sta0]
                task_data.append({"Task_id":i[0],"File_id":i[1],"Status":stat})
            # 判断是否分析异常
            if (task_data[0]["Status"] == "分析异常"):
            #data = [{"Status": conf.stadic[i[2]], "File_id"} for i in ret]
            # 查询错误msg ↓
                query_err_msg = dy.ErrorMessage.select(dy.ErrorMessage.crash_flag, dy.ErrorMessage.error_message,
                                                           dy.ErrorMessage.error_location, dy.ErrorMessage.error_type) \
                        .where(dy.ErrorMessage.file == task_data[0]['File_id'])
                ret_err_msg = dy.database.execute(query_err_msg)
                err_info = []
                err_row_num = 0
                for i in ret_err_msg:
                    err_row_num += 1
                    tm = {"crash_flag": i[0], "error_msg": i[1], "error_location": i[2], "error_type": i[3]}
                    # crash_flag, error_msg, error_location, error_type = i
                    err_info.append(tm)
                det = {"task_data":task_data,"err_info":err_info,"error_row_num":err_row_num}
                return jsonify(det)
            else:
                det = {"task_data":task_data,"error_row_num":"none","error_code":'success'}
                return jsonify(det)
def app(env, start_response):
    # Create the request object
    request = Request(env)
    # Defines which app and controller is being requested
    # The url must be something like:
    #   http://127.0.0.1:8080/[app]/[controller]
    app_requested, controller_requested = router(request.url)
    try:
        # Try to import the controller requested.
        if MOPF_APPLICATIONS not in sys.path:
            sys.path.insert(0, MOPF_APPLICATIONS)
        # import the module and 'func' will get the attributes of the controller_requested
        func = getattr(import_module('{0}.controllers'.format(app_requested)),
                       controller_requested)
    except AttributeError:
        # The requested controller/app does not exists
        start_response('404 NOT FOUND', [('Content-Type', 'text/html; charset=utf-8')])
        return [b'NOT FOUND']
    # Execute the controller
    controller_response = func(request)
    # Start the response
    start_response('200 Ok', [('Content-Type', 'text/html; charset=utf-8')])
    response_body = str(controller_response)
    return [response_body.encode()]
Пример #17
0
            def __init__(self, name):
                design.design.__init__(self, name)
                debug.info(2, "Create {0} object".format(name))

                cell = gdscell(name)
                self.add_inst(name=name,
                              mod=cell,
                              offset=[0,0])
                self.connect_inst([])
                
                self.gdsname = "{0}/{1}.gds".format(os.path.dirname(os.path.realpath(__file__)),name)
                r=router.router(self.gdsname)
                layer_stack =("metal3","via2","metal2")
                connections=[('out_0_2', 'a_0_0'),
                             ('out_0_3', 'b_0_0'),
                             ('out_0_0', 'a_0_1'),
                             ('out_1_2', 'a_1_0'),
                             ('out_1_3', 'b_1_0'),
                             ('out_1_0', 'a_1_1'),
                             ('out_2_1', 'a_2_0'),
                             ('out_2_2', 'b_2_0'),
                             ('out_3_1', 'a_3_0'),
                             ('out_3_2', 'b_3_0'),
                             ('out_4_6', 'a_4_0'),
                             ('out_4_7', 'b_4_0'),
                             ('out_4_8', 'a_4_2'),
                             ('out_4_9', 'b_4_2'),
                             ('out_4_10', 'a_4_4'),
                             ('out_4_11', 'b_4_4'),
                             ('out_4_0', 'a_4_1'),
                             ('out_4_2', 'b_4_1'),
                             ('out_4_4', 'a_4_5'),
                             ('out_4_1', 'a_4_3'),
                             ('out_4_5', 'b_4_3')]
                for (src,tgt) in connections:
                    self.assertTrue(r.route(self,layer_stack,src=src,dest=tgt))
Пример #18
0
    def send_stats(self):

        global r

        global msg
        global site_seen

        self.send_data = json.dumps(r.publish())

        print "DC: Sending TS our stats!"
        self.sendLine(self.send_data)

        # clean up objects and refresh
        site_seen.clear()
        r = None
        msg = []
        r = router(q, labels, tkgs, args.fingerprint, args.consensus)
        for kid, a in zip(r.keys, tkgs):
            msg.append(r.authority_msg(kid))

        time.sleep(dc_reg_delay)
        for host, port in tkg_info:

            reactor.connectSSL(host, int(port), c_factory, ssl.ClientContextFactory())
Пример #19
0
import sys
from taxiCab import taxiCab
from router import router

beck = taxiCab(0, 0, 0)
beck_router = router(beck)

input_file = sys.argv[1]
with open(input_file, 'r') as f:
    text = f.read()

directions = text.split(',')
for move in directions:
    move = move.strip()
    if move[0] == 'R':
        beck.right_turn()
    else:  #'L'
        beck.left_turn()

    beck.move(int(move[1:]))

    if beck_router.check_and_update_intersection(
            beck):  #if 1 an intersection has occurred
        break
    else:
        beck_router.add_trip(beck)

#beck_router.print_trips()
print(abs(beck_router.intersect_point.x) + abs(beck_router.intersect_point.y))
Пример #20
0
from sys import argv

# list of all the possible transformations
from image_processing.convo import create_transformed_outputs
from router import router

actions = {
    'blend': 'blending two images together (using addWeighted)',
    'bitwise-operations': 'creates a logo that is inserted to a picture',
    'convolution': 'will run all available convolutions',
    'gamma-correction': 'gamma adjustment via linear stretching',
    'coin-detection':
    'compares outputs of manual and Hough detection of circles (coins)',
    'edge-detection': 'traces the edges of the image'
}

if len(argv) > 1:  #checks for argument inputed in console
    if argv[1] not in actions:
        print(
            'Argument does not exist, please choose an existing argument from the list below:\n'
        )
        for action, description in actions.items():
            print("\u2022\033[1m " + action + '\033[0m - ' + description)

    router(argv[1])()

else:
    print('\nPlease add an argument behind "start.py" from the list below:\n')
    for action, description in actions.items():
        print("\u2022\033[1m " + action + '\033[0m - ' + description)
Пример #21
0
def parse_internet2(router_name):
    global internet2_routers
    f = open(
        'data/Internet2/%s-show_route_forwarding-table_table_default.xml' %
        router_name, 'r')
    r = router(router_name)
    internet2_routers[router_name] = r
    for _ in range(7):
        f.readline()
    match = None
    flag = False
    c = 0
    for l in f:
        c += 1
        if c > 1000:
            break
        if l.find(':') != -1:
            continue
        if l.find('default.iso') != -1:
            break
        entry = l.strip('\n').split(' ')

        info = []
        for e in entry:
            if e is not '':
                info.append(e)

        if flag:
            flag = False
            if len(info) < 5:
                continue
            port = info[-1]
            next_hop = info[-5]
            r.add_peer_port(port, next_hop)
            r.add_rule(router_rule(match, next_hop, port))
        else:
            if len(info) < 5:
                continue
            match = info[0]
            if match.find('-') != -1:
                break
            ipv4 = match.split('/')
            if len(ipv4) != 2:
                break
            else:
                prefix = int(ipv4[1])
                if prefix > 32 or prefix == 0:
                    break
                ip = ipv4[0].split('.')
                if len(ip) > 4:
                    break

            if info[3] == 'indr':
                flag = True
            elif info[4] == 'locl':
                r.add_local_ip(entry[3])
            elif info[4] == 'ucst':
                port = info[-1]
                next_hop = info[-5]
                r.add_rule(router_rule(match, next_hop, port))
                r.add_local_port(port, next_hop)
            else:
                pass
    r.sort()
    f.close()
Пример #22
0
            if site not in labels:
                labels.append(site)
        labels.append("Other")
        labels.append("Censored")

    with open(args.tally, 'r') as f3:
        for tallyline in f3:
            tallyhost, tallyport = tallyline.strip().split()

    with open(args.tkgList, 'r') as f2:
        for tkgline in f2:
            tkgs.append(tkgserver(tkgline.strip()))
            host, port = tkgline.strip().split()
            tkg_info.append((host, port))

    r = router(q, labels, tkgs, args.fingerprint, args.consensus)

    for kid, a in zip(r.keys, tkgs):
        msg.append(r.authority_msg(kid))

    time.sleep((epoch - int(time.time()) % epoch) + dc_start_delay)
    print "DC starting up..."
    last_epoch_start = int(time.time()) / epoch

    def epoch_change():
        global last_epoch_start
        global should_send
        now = int(time.time()) / epoch
        if now > last_epoch_start:
            last_epoch_start = now
            print "Epoch Change!\n"
Пример #23
0
 def index_post(self, **data):
     data["method"] = "post"
     return router(data)
Пример #24
0
 def test_get_view(self):
     self.assertIsInstance(router.router("/register", ""), RegisterView)
Пример #25
0
 def index_delete(self, **data):
     data["method"] = "delete"
     return router(data)
Пример #26
0
def topology(your_ip,ip,community,username,password):
    #print "your ip : " + str(your_ip) +" ip device : " + str(ip) + " community : " + str(community)
    
    done_list = []
    notdone_list = []
    newData = []
    ipTraffic = []
    index = 0
    
    print "index : " + str(index)
    start_time = time.time()
    ## db topology
    collectionsName = router.name()
    coll = router.connectDatabase(collectionsName)
    filename = router.makeFile(collectionsName)
    ##

    ## db config
    config_name = collectionsName+"_config"
    coll_config = router.connectDatabase(config_name)
    coll_config.insert_one({"name":"none","date":collectionsName,"index":"0","traffic_index":"0","ip_traffic":"none","community":"none"})
    ##
    done_list.append(your_ip)
    ipTraffic.append(str(ip))

    print "done list : " + str(done_list)
    print "not done list : " + str(notdone_list)
    print "ip : " +str(ip)
    code = check.findCode(community,ip)
    if code == []:
        print "skip this ip"
        index -=1
    else:
        device = check.checkDevice(code)
        print "type : " + str(device)
        if device == "router":
            done_list,notdone_list,index = router.router(ip,done_list,notdone_list,filename,index,coll,ipTraffic,community)
        elif device == "switch":
            done_list,notdone_list,index = switch.switch(ip,done_list,notdone_list,filename,index,coll,ipTraffic,community,username,password)
        else:
            print "dont know the type of device"
    
        while(notdone_list):
            index += 1
            ip = notdone_list.pop()
            done_list.append(ip)
            
            print "index : " + str(index)
            print "ip " + str(ip)
            print "done list : " + str(done_list)
            print "not done list : " + str(notdone_list)
            code = check.findCode(community,ip)
            if code == []:
                print "skip this ip"
                index -=1
            else:
                device = check.checkDevice(code)
                print "type : " + str(device)
                if device == "router":
                    ipTraffic.append(ip)
                    done_list,notdone_list,index = router.router(ip,done_list,notdone_list,filename,index,coll,ipTraffic,community)
                elif device == "switch":
                    ipTraffic.append(ip)
                    done_list,notdone_list,index = switch.switch(ip,done_list,notdone_list,filename,index,coll,ipTraffic,community,username,password)
                else:
                    print "dont know the type of device"
            print index
    print("--- %s seconds ---" % (time.time() - start_time))
    return community,ipTraffic,collectionsName,config_name
def topology(your_ip, ip, community, username, password):
    #print "your ip : " + str(your_ip) +" ip device : " + str(ip) + " community : " + str(community)

    done_list = []
    notdone_list = []
    newData = []
    ipTraffic = []
    index = 0

    print "index : " + str(index)
    start_time = time.time()
    ## db topology
    collectionsName = router.name()
    coll = router.connectDatabase(collectionsName)
    filename = router.makeFile(collectionsName)
    ##

    ## db config
    config_name = collectionsName + "_config"
    coll_config = router.connectDatabase(config_name)
    coll_config.insert_one({
        "name": "none",
        "date": collectionsName,
        "index": "0",
        "traffic_index": "0",
        "ip_traffic": "none",
        "community": "none"
    })
    ##
    done_list.append(your_ip)
    ipTraffic.append(str(ip))

    print "done list : " + str(done_list)
    print "not done list : " + str(notdone_list)
    print "ip : " + str(ip)
    code = check.findCode(community, ip)
    if code == []:
        print "skip this ip"
        index -= 1
    else:
        device = check.checkDevice(code)
        print "type : " + str(device)
        if device == "router":
            done_list, notdone_list, index = router.router(
                ip, done_list, notdone_list, filename, index, coll, ipTraffic,
                community)
        elif device == "switch":
            done_list, notdone_list, index = switch.switch(
                ip, done_list, notdone_list, filename, index, coll, ipTraffic,
                community, username, password)
        else:
            print "dont know the type of device"

        while (notdone_list):
            index += 1
            ip = notdone_list.pop()
            done_list.append(ip)

            print "index : " + str(index)
            print "ip " + str(ip)
            print "done list : " + str(done_list)
            print "not done list : " + str(notdone_list)
            code = check.findCode(community, ip)
            if code == []:
                print "skip this ip"
                index -= 1
            else:
                device = check.checkDevice(code)
                print "type : " + str(device)
                if device == "router":
                    ipTraffic.append(ip)
                    done_list, notdone_list, index = router.router(
                        ip, done_list, notdone_list, filename, index, coll,
                        ipTraffic, community)
                elif device == "switch":
                    ipTraffic.append(ip)
                    done_list, notdone_list, index = switch.switch(
                        ip, done_list, notdone_list, filename, index, coll,
                        ipTraffic, community, username, password)
                else:
                    print "dont know the type of device"
            print index
    print("--- %s seconds ---" % (time.time() - start_time))
    return community, ipTraffic, collectionsName, config_name
Пример #28
0
 def _get_view(self):
     token = self.headers.get("Authorization", "")
     return router(self.path, token)
Пример #29
0
# @app.before_first_request
@app.cli.command("seed")
def seed():
    db.create_all()
    init_database(db)


@app.errorhandler(ValidationError)
def handle_marshmallow_validation(err):
    return max_err(err.messages, 400)


# This method will check if a token is blacklisted, and will be called automatically when blacklist is enabled
@jwt.token_in_blacklist_loader
def check_if_token_in_blacklist(decrypted_token):
    return decrypted_token["jti"] in BLACKLIST


api.prefix = '/api'

api.add_resource(UserRegister, "/register")
# api.add_resource(User, "/user/<int:user_id>")  # for security concerns
api.add_resource(UserInfo, "/userinfo")
api.add_resource(UserLogin, "/login")
api.add_resource(TokenRefresh, "/refresh")
api.add_resource(UserLogout, "/logout")
api.add_resource(UserProfile, "/profile")
router(api)

if __name__ == "__main__":
    app.run(port=5000, debug=True)
Пример #30
0
count = 0
while count < numTotalPC:
    ip = DHCPServer.getipDisponibles()[0]
    pc = PC("pc" + str(count), ip, network, gateway, hddSpace, "")
    switch.anadirPCs(pc)
    DHCPServer.getipDisponibles().pop(0)
    switch.getipDisponibles().pop(0)
    count += 1

print("Lista de ordenadores:")
switch.getInfoPcs()
print("")
print("IP libres restantes:")
print("")
print(switch.getipDisponibles())
print("")
print("Info router")
router = router()
switch.setDHCP(DHCPServer)
router.AddSwitch(switch)
for switchs in router.getSwitches():
    switch.getInfoPcs()

print("")
print("Ha que pc quieres intalar el siguiente SO?:")
print("")
print(so.getName() + so.getVersion() + " " + so.getArchitecture() + " " +
      so.getSpaceRequeriment() + "MB")
print("")
v = int(input())
Пример #31
0
 def index_get(self, **data):
     data["method"] = "get"
     return router(data)
Пример #32
0
if not os.path.exists('config.py'):
    contents = """#!/usr/bin/python3
import multiprocessing

PORT = 8080
CACHE_DIR = 'cache'
MAX_WORKERS = multiprocessing.cpu_count()
LAYER_DIR = 'examples'
# LAYER_DIR = 'data'
STYLESHEET = 'stylesheet.xml'"""
    with open('config.py', 'w') as fileHandler:
        fileHandler.write(contents)

import config
from router import router

define("port", default=str(config.PORT), help="Server port")

if __name__ == "__main__":
    options.parse_command_line()
    app = router()
    app.listen(options.port)
    print('{0}-{1}.{2}.{3}'.format(SERVICE, VERSION['major'], VERSION['minor'],
                                   VERSION['patch']))
    print("Magic happens on http://localhost:" + options.port)
    try:
        IOLoop.configure(TornadoUvloop)
    except NameError:
        pass
    IOLoop.current().start()
Пример #33
0
 def test_login_required_view_without_token(self):
     path = "/website"
     with self.assertRaises(UnauthenticatedError):
         router.router(path, "")
Пример #34
0
from taxiCab import taxiCab
from router import router

test_cab = taxiCab(0, 0, 0)
test_router = router(test_cab)

o = taxiCab(0, 0, 0)
a = taxiCab(5, 0, 0)
b = taxiCab(5, 1, 0)
c = taxiCab(4, 1, 0)
d = taxiCab(4, -5, 0)
f = taxiCab(-1, -5, 0)
g = taxiCab(-1, 0, 0)
h = taxiCab(3, 0, 0)

print test_router.intersects(a, b, c, d)
print test_router.intersects(o, a, c, d)
print test_router.intersects(o, a, g, h)

print "Testing ..."

a = taxiCab(8, 0, 0)
b = taxiCab(8, -4, 0)
c = taxiCab(4, -4, 0)
d = taxiCab(4, 4, 0)

print test_router.intersects(o, a, c, d)
test_router.update_intersection(o, a, c, d)
print test_router.intersect_point.x
print test_router.intersect_point.y
Пример #35
0
 def index_put(self, **data):
     print data
     data["method"] = "put"
     return router(data)
Пример #36
0
def main(argv): 
	# Check command line parameters
	if len(sys.argv) != 3: 
		print "python networksimulation.py (0,1,2) (0,1)"
		print "1st arg: con_ctrl: 0 - none; 1 - TCP Reno; 2 - FAST"
		print "2nd arg: verbose: 0 - no; 1 - yes"
		print('\n')
		sys.exit()

	# Store command line parameters
	con_ctrl = int(sys.argv[1])
	verbose = int(sys.argv[2])

	print('\n')
	# Give specifications for links file and flows file and then save
	# the filename in variables
	print("Enter the file of links.")
	print("Each line is one link in the following format: ")
	print("End1 End2 Rate Delay Capacity\n")
	print("Ends=host/source/destination/router ID (ex. H1,S2,T3,R4)")
	print("Rate(Mbps), Delay(ms), Capacity(KB)")
	linkFile = input('Enter link file: ')

	print('\n')
	print("Enter the file of flows.")
	print("Each line is one flow in the following format: ")
	print("Source Dest DataAmount StartTime\n")
	print("Source/Dest = ID's (ex. H1,S2,T3,R4)")
	print("DataAmount(MB), StartTime(s)")
	flowFile = input('Enter flow file: ')
	print('\n')

	# Variables to store the different network objects
	routers = {}
	linksLst = []
	flowsLst = []

	# Try to open the files. If fail, throw an error.
	try:
		links = open(linkFile, 'r')
		flows = open(flowFile, 'r')
	except IOError:
		print("Link and Flow files do not exist in this directory.")
		sys.exit()

	# First, make all the links
	i = 0
	for line in links:
		# Split the line into a list, which must have 5 values
		info = line.split(' ')
		if(len(info) != 5):
			print('Each link line must have 5 values')
			sys.exit()

		# Try converting the rate, delay and capacity. If fail, throw error
		try:
			rate, delay, capacity = float(info[2]), float(info[3]), float(info[4])
		except ValueError:
			print("The last 3 values must be numbers")
			sys.exit()

		# Either make a new entry in the routers table, or grab an entry

		# First get the end1 of the link
		if(info[0] not in routers.keys()):
			router1 = router(info[0])
			routers[info[0]] = router1
		else:
			router1 = routers[info[0]]

		# Next get end2
		if(info[1] not in routers.keys()):
			router2 = router(info[1])
			routers[info[1]] = router2
		else:
			router2 = routers[info[1]]

		# Build a link with all the information and add it to the list of links.
		temp = link(i, router1, router2, rate, delay, capacity)
		linksLst.append(temp)
		i += 1

	# Now, make all the flows.
	for line in flows:
		# Split the line into a list, which must have 4 values
		info = line.split(' ')
		if(len(info) != 4):
			print('Each flow line must have 4 values')
			sys.exit()

		# Try converting the amount and start time. If fail, throw error.
		try:
			amount, start = int(info[2]), float(info[3])
		except ValueError:
			print("The last 2 values must be numbers")
			sys.exit()

		# Try getting the source and dest from the dictionary. If they
		# don't exist, it means no link was connected to them, so we
		# can't have a flow.
		try:
			source = routers[info[0]]
			destination = routers[info[1]]
		except KeyError:
			print("Network not connected")
			sys.exit()

		# Build a flow with all the information and add it to the list of flows.
		temp = flow(source, destination, amount, start, con_ctrl)
		flowsLst.append(temp)

	# Make a list of all the routers using the routers dictionary.
	routersLst = []
	for key in routers:
		routersLst.append(routers[key])

	# intitialize an event queue
	the_event_queue = event_queue(verbose)

	# Statically initialize all the routing tables
	globalTable = sP.fillTable(linksLst, flowsLst)
	for fl in flowsLst:
		fl.src.updateStatic(globalTable)
	for rt in routersLst:
		rt.updateStatic(globalTable)

	# Start the simulation
	run_simulation(the_event_queue, flowsLst, linksLst, routersLst, con_ctrl)
Пример #37
0
            if site not in labels:
                labels.append(site)
        labels.append("Other")
        labels.append("Censored")

    with open(args.tally, "r") as f3:
        for tallyline in f3:
            tallyhost, tallyport = tallyline.strip().split()

    with open(args.tkgList, "r") as f2:
        for tkgline in f2:
            tkgs.append(tkgserver(tkgline.strip()))
            host, port = tkgline.strip().split()
            tkg_info.append((host, port))

    r = router(q, labels, tkgs, args.fingerprint, args.consensus)

    for kid, a in zip(r.keys, tkgs):
        msg.append(r.authority_msg(kid))

    time.sleep((epoch - int(time.time()) % epoch) + dc_start_delay)
    print "DC starting up..."
    last_epoch_start = int(time.time()) / epoch

    def epoch_change():
        global last_epoch_start
        global should_send
        now = int(time.time()) / epoch
        if now > last_epoch_start:
            last_epoch_start = now
            print "Epoch Change!\n"