Beispiel #1
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
Beispiel #2
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, addr, heartbeatTime):
     """TODO: add your own class fields and initialization code here"""
     Router.__init__(self, addr)  # initialize superclass - don't remove
     self.heartbeatTime = heartbeatTime
     self.last_time = 0
     self.DEST={}
     self.Inf=16
Beispiel #4
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")
Beispiel #5
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
class Executor(object):
    def __init__(self,cmd,user,proto):
        self.argv = shlex.split(cmd)
        self.user = user
        self.proto = proto
        self.router = Router(self.argv[-1])
        self.authobj = Authenticator(user,self.argv)
        self.envobj = Env(self.user,self.router)
    def execute(self):
        repostring = self.argv[-1]
        self.router.route()
        auth_service_deferred = self.router.deferred
        auth_service_deferred.addCallback(self.authobj.getRepositoryAccess)
        auth_service_deferred.addCallback(self.envobj.setEnv)
        # Then the result of auth is passed to execGitCommand to run git-shell
        auth_service_deferred.addCallback(self.execGitCommand, self.argv, self.proto)
        auth_service_deferred.addErrback(self.errorHandler, self.proto)

    def execGitCommand(self, env , argv, proto):
        """After all authentication is done, setup an environment and execute the git-shell commands."""
        repopath = self.router.repopath
        sh = self.user.shell  
        command = ' '.join(argv[:-1] + ["'{0}'".format(repopath)])
        reactor.spawnProcess(proto, sh, (sh, '-c', command), env=env)
        
    def errorHandler(self, fail, proto):
        """Catch any unhandled errors and send the exception string to the remote client."""
        fail.trap(ConchError)
        message = fail.value.value
        log.err(message)
        if proto.connectionMade():
            proto.loseConnection()
        error_script = self.user.error_script
        reactor.spawnProcess(proto, error_script, (error_script, message))
Beispiel #7
0
 def __init__(self, addr, heartbeatTime):
     """TODO: add your own class fields and initialization code here"""
     Router.__init__(self, addr)  # initialize superclass - don't remove
     self.heartbeatTime = heartbeatTime
     self.last_time = 0
     # Hints: initialize local state
     pass
Beispiel #8
0
def show(ctx, path, order):
    router = Router(open(ctx.obj['CONFIG']))
    route = router.match(path)
    logging.debug("Matched route: %s" % route)
    if not route:
        print 'No queries matched'
        return
    es = Elasticsearch(hosts=route.get('elasticsearch_url'))
    request_body = {}
    for non_mandatory_key in ['sort', 'query']:
        value = route.get(non_mandatory_key)
        if value:
            request_body[non_mandatory_key] = value
    if order == 'asc':
        request_body['sort'] = {'@timestamp': 'asc'}
    elif order == 'desc':
        request_body['sort'] = {'@timestamp': 'desc'}
    elif order:
        click.echo("Unknown order format: %s" % order, err=True)
        return 1
    logging.debug("Query: %s" % (request_body,))
    result = es.search(index=route.get('index'), doc_type=None, body=request_body)
    hits = result['hits']['hits']
    template = Template(route.get("format", "{{ __at_timestamp }} {{ message }}"))
    for hit in hits:
        doc = hit['_source']
        doc['__at_timestamp'] = doc.get('@timestamp')
        print template.render(doc)
Beispiel #9
0
    def __init__(self, addr, heartbeatTime):
        """TODO: add your own class fields and initialization code here"""
        Router.__init__(self, addr)  # initialize superclass - don't remove
        self.heartbeatTime = heartbeatTime
        self.dist_table = {self.addr: {'port': -1, 'distance': 0}}

        self.debug_list = []
Beispiel #10
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
    def __init__(self, addr, heartbeatTime):
        """TODO: add your own class fields and initialization code here"""
        Router.__init__(self, addr)  # initialize superclass - don't remove
        self.heartbeatTime = heartbeatTime
        self.last_time = 0
        # Hints: initialize local state

        #forwarding table initialization
        self.forwarding_table = {
        }  #forwarding table consisting of addresses to neighbors of current router. Index is the destination node, and value is port number

        #graph initialization
        self.G = nx.Graph(
        )  #Initialize a Graph that would map the neighbors of current router, Directed because there may be different weights to and from routers based on traffic
        self.G.add_node(str(addr))  #add crrent node initially to the Graph

        #link state initialization
        self.link_states = {
        }  #The link state of a router contains the links and their weights between the router and its neighbors

        #Holds port numbers as values and endpoints as keys, and used to determine neighbors within link state
        self.new_links = {
        }  #this holds names of neighbors as indices and their port numbers as values
        self.port_to_link = {
        }  #this holds port numbers as indices and names of neighbors as values,
        self.link_costs = {
        }  #this array holds the cost of immediate neighbors and any new link

        #sequence number initialization
        self.sequence_numbers = {
        }  #this array holds the node this node is interacting with as indices and sequence numbers of the last encounter as the value
        self.last_seqnum = 0  #initialize last sequence number as 0 to start and it goes up after each broadcast

        pass
Beispiel #12
0
class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
    def __init__(self, request, client_address, server):
        self.router = Router(self)
        for key, value in ROUTES.items():
            self.router.add(key, value)
        BaseHTTPServer.BaseHTTPRequestHandler.__init__(self, request,
                                                       client_address, server)

    def do_HEAD(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()

    def do_GET(self):
        if self.path.startswith('/'):
            self.path = self.path[1:]

        routing_info = self.router.route(self.path)
        if routing_info:
            func, regex_match = routing_info
            content = func(**regex_match)

            self.do_HEAD()
            self.wfile.write(content)

        else:
            self.send_error(404)

    def do_POST(self):
        form = cgi.FieldStorage(fp=self.rfile,
                                headers=self.headers,
                                environ={
                                    'REQUEST_METHOD': 'POST',
                                    'CONTENT_TYPE':
                                    self.headers['Content-Type'],
                                })

        # Begin the response
        self.send_response(200)
        self.end_headers()
        self.wfile.write('Client: %s\n' % str(self.client_address))
        self.wfile.write('User-agent: %s\n' % str(self.headers['user-agent']))
        self.wfile.write('Path: %s\n' % self.path)
        self.wfile.write('Form data:\n')

        # Echo back information about what was posted in the form
        for field in form.keys():
            field_item = form[field]
            if field_item.filename:
                # The field contains an uploaded file
                file_data = field_item.file.read()
                file_len = len(file_data)
                del file_data
                self.wfile.write('\tUploaded %s as "%s" (%d bytes)\n' % \
                                (field, field_item.filename, file_len))
            else:
                # Regular form value
                self.wfile.write('\t%s=%s\n' % (field, form[field].value))
        return
Beispiel #13
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)
Beispiel #14
0
 def __init__(self, addr, heartbeatTime):
     """TODO: add your own class fields and initialization code here"""
     Router.__init__(self, addr)  # initialize superclass - don't remove
     self.last_time = 0
     self.heartbeatTime = heartbeatTime
     self.addr = addr
     self.table = {}  # {addr: {cost:, nextHop: addr, port: }}
     self.infinity = 16
Beispiel #15
0
 def test2(self):
     r = Router()
     r.route(Rule("/pages/<int:page_id>/"), target="pages")
     
     matches = r.matches("/pages/10/")
     m = matches.next()
     self.assertEqual(m.param("target"), "pages")
     self.assertEqual(m.param("page_id"), 10)
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)
Beispiel #17
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()
 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")
Beispiel #19
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_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)
Beispiel #21
0
 def __init__(self, addr, heartbeatTime):
     """TODO: add your own class fields and initialization code here"""
     Router.__init__(self, addr)  # initialize superclass - don't remove
     self.routersPort = {}
     self.routersCost = {}
     self.routersNext = {}
     self.routersAddr = {}
     self.heartBeat   = heartbeatTime
     self.last        = None
Beispiel #22
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()
Beispiel #23
0
class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
    def __init__(self, request, client_address, server):
        self.router = Router(self)
        for key, value in ROUTES.items():
            self.router.add(key, value)
        BaseHTTPServer.BaseHTTPRequestHandler.__init__(self, request, client_address, server)

    def do_HEAD(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()

    def do_GET(self):
        if self.path.startswith('/'):
            self.path = self.path[1:]

        routing_info = self.router.route(self.path)
        if routing_info:
            func, regex_match = routing_info
            content = func(**regex_match)

            self.do_HEAD()
            self.wfile.write(content)

        else:
            self.send_error(404)

    def do_POST(self):
        form = cgi.FieldStorage(
            fp=self.rfile,
            headers=self.headers,
            environ={'REQUEST_METHOD':'POST',
                     'CONTENT_TYPE':self.headers['Content-Type'],
                     })

        # Begin the response
        self.send_response(200)
        self.end_headers()
        self.wfile.write('Client: %s\n' % str(self.client_address))
        self.wfile.write('User-agent: %s\n' % str(self.headers['user-agent']))
        self.wfile.write('Path: %s\n' % self.path)
        self.wfile.write('Form data:\n')

        # Echo back information about what was posted in the form
        for field in form.keys():
            field_item = form[field]
            if field_item.filename:
                # The field contains an uploaded file
                file_data = field_item.file.read()
                file_len = len(file_data)
                del file_data
                self.wfile.write('\tUploaded %s as "%s" (%d bytes)\n' % \
                                (field, field_item.filename, file_len))
            else:
                # Regular form value
                self.wfile.write('\t%s=%s\n' % (field, form[field].value))
        return
 def __init__(self, addr, heartbeatTime):
     """TODO: add your own class fields and initialization code here"""
     Router.__init__(self, addr)  # initialize superclass - don't remove
     self.heartbeatTime = heartbeatTime
     self.last_time = 0
     self.G = Graph(undirected=True)
     self.SeqNum = {}
     self.Neighbours = {
     }  #Dictionary with key as address and cost and seqnum as values
     self.Curr_Seq = 0
Beispiel #25
0
 def __init__(self, addr, heartbeatTime):
     """class fields and initialization code here"""
     Router.__init__(self, addr)  # initialize superclass - don't remove
     self.routersNext = {}  # key》当前节点可到达的所有节点;value》以key作为目标根节点时最短路径中上一个节点
     self.routersCost = {}  # key》当前节点可到达的所有节点;value》以key作为目标根节点时最短路径的总权重
     self.routersPort = {
     }  # key》当前节点的所有邻居节点的名称(字母);value》key所表示的节点的编号(整数),编号值是根据节点名称ascii码值排序依次设为1,2,...
     self.routersAddr = {}  # 把 self.routersPort 的key和value交换一下
     self.heartbeat = heartbeatTime
     self.lasttime = None
 def __init__(self, addr, heartbeatTime):
     Router.__init__(self, addr)  # initialize superclass - don't remove
     self.heartbeatTime = heartbeatTime
     self.last_time = 0
     # Hints: initialize local state
     self.forward_table = {}  # dst_addr, (port, cost)
     self.local_link_state = {}  # neighbor->(port, cost)
     self.received_link_state = {
     }  # map: node_num->(seq_num, local_link_state)
     self.seq_num = 0
Beispiel #27
0
 def __init__(self, addr, heartbeatTime):
     """TODO: add your own class fields and initialization code here"""
     Router.__init__(self, addr)  # initialize superclass - don't remove
     self.heartbeatTime = heartbeatTime
     self.last_time = 0
     # Hints: initialize local state
     self.distance_vector = {}  # { destination: { via: cost } }
     self.received_distance_vector = {
     }  # { neighbor: { destination: { via: cost } } }
     self.neighbors = {}  # { node: ( port, cost ) }
Beispiel #28
0
 def _handle_recv(self):
     source_id, url, seed_id, method, url_params, params = self._sock.recv_multipart()
     try:
         params = json.loads(params)
         Router.dispatch(source_id, url, seed_id, method, params, json.loads(url_params), self.on_wrap)
     except http.HttpMethodNotAllowed as e:
         self._ioloop.add_callback(self.send, ['rep', source_id, seed_id, e.state, e.content])
     except Exception as e:
         self._ioloop.add_callback(self.send, ['rep', source_id, seed_id, '500', '(500): internal error'])
         app_log.exception(e)
Beispiel #29
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
Beispiel #30
0
 def __init__(self, catchall=True, autojson=True, config=None):
     self.routes = Router()
     self._logger = None
     self.mounts = {}
     self.error_handler = {}
     self.catchall = catchall
     self.config = config or {}
     self.serve = True
     self.castfilter = []
     if autojson and dumps:
         self.add_filter(dict, dumps)
Beispiel #31
0
def main():
    parser = CommandParser()
    try:
        command_list = parser.parse()
    except CommandParser.ParserException as e:
        sys.exit(e)

    router = Router(command_list)
    runner_class = router.get_runner()
    timeline = Timeline()
    runner_class(timeline).run(command_list)
Beispiel #32
0
def ListRouters(Where=''):
    out = []
    DbConnection = sqlite3.connect('main.db')
    DbCursor = DbConnection.cursor()
    for row in DbCursor.execute("SELECT * FROM ROUTERS " + Where).fetchall():
        Obj = Router()
        Obj.Id = row[0]
        Obj.Name = row[1]
        out.append(Obj)
    DbConnection.close()
    return out
Beispiel #33
0
    def test_hashing(self):
        router = Router(self.valid_list_file)
        router.set('forge', 13)
        router.set("spawning_pool", 18)

        key_hash, connection_uri = router.continuum.get_server('forge')
        self.assertEqual(key_hash, 4113771093)
        self.assertEqual(connection_uri, '127.0.0.1:6379')

        key_hash, connection_uri = router.continuum.get_server('spawning_pool')
        self.assertEqual(key_hash, 1434709819)
        self.assertEqual(connection_uri, '127.0.0.1:6380')
    def test_sshd_disable(self):
        nvram = {'sshd_enable': '1',
                 'sshd_wanport': '22',
                 'sshd_port': '22',
                 'sshd_passwd_auth': '1',
                 'sshd_authorized_keys': '',
                 'sshd_forwarding': '0',
                 }

        router = Router(nvram)
        router.enableSshd(False)
        self.assertEqual(router.nvram['sshd_enable'], '0')
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)
Beispiel #36
0
 def __init__(self, addr, heartbeatTime):
     """TODO: add your own class fields and initialization code here"""
     Router.__init__(self, addr)  # initialize superclass - don't remove
     self.heartbeatTime = heartbeatTime
     self.last_time = 0
     # Hints: initialize local state
     self.link_state = {}  #APNA LINK STATE
     self.link_state_local = {}  #BAKI SUB KA LINK STATE
     self.sequence_number = 0  #SEND KARTAY WAKT SEQ NUM
     self.check_sequence_number = {}  #RECIEVE KARTAY WAKT SEQ NUM
     self.network_graph = Graph(undirected=True)  #GRAPH
     self.forwarding_table = {}  #FRWD TABLE
Beispiel #37
0
def index(request):
    global TOKEN, router_error, router_reply
    weixinlogger = logging.getLogger('weixin')
    conversationlogger = logging.getLogger('conversation')
    if request.method == 'GET':
        if 'signature' not in request.GET or 'timestamp' not in request.GET or 'nonce' not in request.GET or 'echostr' not in request.GET:
                return HttpResponse('bad request %s' % str(request.GET))
        signature = request.GET['signature']
        timestamp = request.GET['timestamp']
        nonce = request.GET['nonce']
        echostr = request.GET['echostr']
        weixinlogger.info("receive one get message signature %s timestamp %s nonce %s echostr %s" % (signature, timestamp, nonce, echostr))
        weixin = WeiXin.on_connect(TOKEN, timestamp, nonce, signature, echostr)
        if weixin.validate():
            return HttpResponse(echostr, content_type="text/plain")
        else:
            return HttpResponse(None, content_type="text/plain")
    elif request.method == 'POST':
        try:
            weixin = WeiXin.on_message(smart_str(request.raw_post_data))
            message = weixin.to_json()
            weixinlogger.info("receive one message %s" % str(message))
            conversationlogger.info("receive one message %s" % str(message))
            try:
                user = WeixinUser.objects.get(uid=message['FromUserName'])
            except:
                user = WeixinUser()
                user.src = message['ToUserName']
                user.uid = message['FromUserName']
                user.integral = 0
                user.save()

            Router.get_instance().reply(message, _route_callback)
            
            if router_error is None and router_reply is not None:
                router_reply.platform = MessageBuilder.PLATFORM_WEIXIN
                if router_reply.type != MessageBuilder.TYPE_NO_RESPONSE:
                    weixinlogger.info("reply success type %s platform %s data %s" % (router_reply.type, router_reply.platform, router_reply.data))
                    conversationlogger.info("reply success type %s platform %s data %s" % (router_reply.type, router_reply.platform, router_reply.data))
                    return HttpResponse(MessageBuilder.build(message, router_reply), content_type="application/xml")
                else:
                    weixinlogger.info("%s", router_reply.data)
                    conversationlogger.info("%s", router_reply.data)
            else:
                weixinlogger.info("router error %s router reply %s" % (str(router_error), str(router_reply)))
                conversationlogger.info("router error %s router reply %s" % (str(router_error), str(router_reply)))
                raise "not find games"
                return HttpResponse('<xml></xml>', content_type="application/xml")
        except:
            logger.error(traceback.format_exc())
            reply_config = BuildConfig(MessageBuilder.TYPE_RAW_TEXT, MessageBuilder.PLATFORM_WEIXIN, u"非常抱歉,没能理解你的话")
            return HttpResponse(MessageBuilder.build(message, reply_config), content_type="application/xml")
Beispiel #38
0
	def load():

		configer = Configer('../config.ini')

		log_info = configer.get_configer('LOG','info')
		log_path = configer.get_configer('LOG','path')

		log_format = '%(asctime)s - %(name)s - %(levelname)s - %(filename)s - %(funcName)s - %(message)s'

		logger = Logger(info = log_info,path = log_path,format = log_format)
		LOG = logger.get_logger()

		router = Router(1,'InterThread')
		router.start()
Beispiel #39
0
 def run(connection, data):
     request = RequestBuilder.build(data)
     function = Router.get_function(request.path)
     static = Router.get_static(request.path)
     print request.path
     if function is not None:
         try:
             Processor._send_function_result(connection, request, function)
         except Exception as e:
             Processor._send_500(connection, str(e))
     elif static is not None:
         Processor._send_file(connection, request, static)
     else:
         Processor._send_404(connection)
     connection.close()
 def __init__(self,cmd,user,proto):
     self.argv = shlex.split(cmd)
     self.user = user
     self.proto = proto
     self.router = Router(self.argv[-1])
     self.authobj = Authenticator(user,self.argv)
     self.envobj = Env(self.user,self.router)
Beispiel #41
0
    def __init__(self, config):
        self.config = config
        self.data_port = config['port']
        self.command_port = config['commandport']
        self.sniff_port = config['sniffport']
        self.name = config.get('name', str(self.command_port))
        self.refdes = config.get('refdes', config['type'])
        self.ttl = config['ttl']

        self.data_name = 'port-agent'
        self.command_name = 'command-port-agent'
        self.sniffer_name = 'sniff-port-agent'
        self.data_port_id = '%s-%s' % (self.data_name, self.refdes)
        self.command_port_id = '%s-%s' % (self.command_name, self.refdes)
        self.sniffer_port_id = '%s-%s' % (self.sniffer_name, self.refdes)

        self.router = Router()
        self.connections = set()
        self.clients = set()

        self._register_loggers()
        self._create_routes()
        self._start_servers()
        self._heartbeat()
        self.num_connections = 0
        log.msg('Base PortAgent initialization complete')
Beispiel #42
0
def main():
    """Runs the gateway"""
    loop = asyncio.get_event_loop()

    router = Router()
    loop.run_until_complete(router.connect_to_message_queue())

    initialize_gpio()
    radio = Radio()

    router.set_send_packet(radio.send_packet)

    poll(loop, radio, router)
    try:
        loop.run_forever()
    finally:
        loop.close()
Beispiel #43
0
 def test1(self):
     r = Router()
     r.route(Rule("/blaat/"), target="0")
     r.route(Rule("/home/"), target="1")
     r.route(Rule("/news/"), target="2")
     r.route(Rule("/home/"), target="3")
     
     matches = r.matches("/home/")
     self.assertEqual(matches.next().param("target"), "1")
     self.assertEqual(matches.next().param("target"), "3")
Beispiel #44
0
    def __init__(self, protocols, uri='ws://173.255.213.55:9093/ws?'):
        super(ArdyhClient, self).__init__(uri, protocols)

        self.ARDYH_URI = uri
        self.LOG_DTFORMAT = "%Y-%m-%dT%H:%M:%SZ"
        self.channel = settings['bot_name']
        self.bot_name = settings['bot_name']
        self.bot_roles = settings['bot_roles']
        self.router = Router(self)
Beispiel #45
0
    def __init__(self, max_forks=0, prespawn=False, homogeneous=True):
        """
        max_forks: The maximum number of forks (default: 0 - unlimited)
        prespawn: Spawns and feeds forks before processing begins.
        homogeneous: Attempt to keep forks limited to one pattern
        """

        Router.__init__(self)

        self.max_forks = max_forks
        self.prespawn = prespawn
        self.homogeneous = homogeneous

        self.pattern_assignments = {}
        self.forks = []
        self.data = {}

        self.processing = False
Beispiel #46
0
	def __init__(self):
		logger.info('System starting')
		self.state = State()
		self.task_scheduler = TaskScheduler()
		self.router = Router()
		self.condition_engine = ConditionEngine()

		self.router.init(self.state, self.condition_engine)
		self.task_scheduler.init(self.condition_engine)
		self.condition_engine.init(self, self.state, self.router, self.task_scheduler)
		logger.info('System started successfully')
Beispiel #47
0
 def __init__(self, catchall=True, autojson=True, config=None):
     self.routes = Router()
     self._logger=None
     self.mounts = {}
     self.error_handler = {}
     self.catchall = catchall
     self.config = config or {}
     self.serve = True
     self.castfilter = []
     if autojson and dumps:
         self.add_filter(dict, dumps)
Beispiel #48
0
class Application(object):
    """WSGI-application.

    :param root_factory: callable which returns a root object

    The application passes ``environ`` and ``start_response`` to the
    controller and expects an iterable as return value (or generator).

    If traversal is used, the result is passed on to the controller as
    the first argument.
    """

    def __init__(self, root_factory=None):
        self._router = Router()
        self._root_factories = {}
        self._root_factory = root_factory

    def __call__(self, environ, start_response):
        path = environ['PATH_INFO']
        controller = self.match(path)
        return controller(environ, start_response)

    def match(self, path):
        match = self._router(path)
        if match is None:
            return self.not_found
        route = match.route
        if match.path is not None:
            root_factory = self._root_factories[route]
            root = root_factory()
            context = self.traverse(root, match.path)
            controller = route.get(type(context))
            return partial(controller, context, **match.dict)
        else:
            controller = route.get()
            return partial(controller, **match.dict)

    def not_found(self, environ, start_response):
        start_response("404 Not Found", [('Content-type', 'text/plain')])
        return 'Page not found',

    def route(self, path, root_factory=None):
        if root_factory is None:
            root_factory = self._root_factory
        route = self._router.new(path)
        self._root_factories[route] = root_factory
        return route

    def traverse(self, root, path):
        segments = path.split('/')
        context = root
        for segment in segments:
            context = context[segment]
        return context
Beispiel #49
0
 def test3(self):
     r = Router()
     r.route("/pages/", target="a")
     r.route(Rule("/pages/"), target="b")
     
     matches = r.matches("/pages/")
     self.assertEqual(matches.next().param("target"), "a")
     self.assertEqual(matches.next().param("target"), "b")
Beispiel #50
0
class System:

	def __init__(self):
		logger.info('System starting')
		self.state = State()
		self.task_scheduler = TaskScheduler()
		self.router = Router()
		self.condition_engine = ConditionEngine()

		self.router.init(self.state, self.condition_engine)
		self.task_scheduler.init(self.condition_engine)
		self.condition_engine.init(self, self.state, self.router, self.task_scheduler)
		logger.info('System started successfully')

	def stop(self):
		logger.info('Stopping system')
		self.router.stop()
		self.task_scheduler.stop()
		self.condition_engine.stop()
		logger.info('System stopped successfully')

	def send(self, node_label, message):
		if 'stop' in message:
			self.stop()
Beispiel #51
0
    def __init__(self, uri, port):
        
        self.LOG_DTFORMAT = "%H:%M:%S"
        self.channel = settings['bot_name']
        self.uuid = SKYNET_UUID
        self.token = SKYNET_TOKEN
        # set the name to MAC address if not found.
        self.bot_name = settings['bot_name']
        self.bot_roles = settings['bot_roles']

        self.core = Core()
        self.router = Router()

        self.connect(uri, port)
        print "[__init__()] Finished connecting"
Beispiel #52
0
    def setUp(self):
        # localhost:6379 and localhost:6390 must be accessible redis instances for testing.
        self.valid_list_file = os.tmpnam()
        self.valid_list = file(self.valid_list_file, "w")
        self.valid_list.write("127.0.0.1:6379\t600\n")
        self.valid_list.write("127.0.0.1:6380\t400\n")
        self.valid_list.flush()

        self.invalid_list_file = os.tmpnam()
        self.invalid_list = file(self.invalid_list_file, "w")
        self.invalid_list.write("127.0.0.1:11211 600\n")
        self.invalid_list.write("127.0.0.1:11212 foo\n")
        self.invalid_list.flush()

        self.router = Router(self.valid_list_file)
Beispiel #53
0
    def __init__(self, protocols, uri='ws://173.255.213.55:9093/ws?'):
        rs = super(ArdyhClient, self).__init__(uri, protocols)
        

        self.ARDYH_URI = uri
        self.LOG_DTFORMAT = "%H:%M:%S"
        self.CTENOPHORE = CTENOPHORE
        

        self.channel = settings['bot_name']

        # set the name to MAC address if not found.
        self.bot_name = settings['bot_name']
        self.bot_roles = settings['bot_roles']

        self.core = Core()
        self.router = Router()
Beispiel #54
0
    def __init__(self, config):
        self.config = config
        self.refdes = config.get('refdes', config['type'])
        self.ttl = config['ttl']
        self.num_connections = 0
        self.disconnect_notification_id = None

        self.router = Router(self)
        self.stats_publisher = StatisticsPublisher()
        self.stats_publisher.connect()
        self.connections = set()
        self.clients = set()

        self._register_loggers()
        self._create_routes()
        self._start_servers()
        self.get_consul_host()

        heartbeat_task = task.LoopingCall(self._heartbeat)
        heartbeat_task.start(interval=HEARTBEAT_INTERVAL)

        log.msg('Base PortAgent initialization complete')
Beispiel #55
0
    def _worker(self):
        router = Router()

        for mountpoint, conf in self.config.get("locations", {}).items():
            conf.update(self.config)
            router.use(mountpoint, static(conf.get("root")))

        for code, page in self.config.get("error_pages", {}).items():
            def handler(err, req, res):
                if type(err) == HTTPError and err.code == code:
                    res.send_file(page)
                else: return True
            router.handler(handler)

        router.use(not_found)

        while True:
            req = Request(self)
            if not req or self.closed: break

            err = router(req, req.response)
            if err: break

        return self.close()
Beispiel #56
0
            
            if menu.page.message_cover:
                data['pic_url'] = menu.page.message_cover.url
            else:
                data['pic_url'] = settings.SITE_URL + settings.STATIC_URL + get_default_cover(menu.page)
            data['url'] = cls.get_url() + "?user=%s&wx=%s" % (info.user, info.wx)
            return BuildConfig(MessageBuilder.TYPE_WEB_APP, None, data)
        else:
            return BuildConfig(MessageBuilder.TYPE_RAW_TEXT, None, u'非常抱歉')
    except:
        logger.error(traceback.format_exc())
        return BuildConfig(MessageBuilder.TYPE_RAW_TEXT, None, u'非常抱歉')

Router.get_instance().set({
        'name' : u'关注',
        'pattern' : match_subscribe_event,
        'handler' : micro_site 
    })
Router.get_instance().set({
        'name' : u'取消关注',
        'pattern' : match_unsubscribe_event,
        'handler' : unsubscribe
    })
Router.get_instance().set({
        'name' : u'验证绑定',
        'pattern' : u'rocket',
        'handler' : check_bind_state
    })
Router.get_instance().set({
        'name' : u'microsite',
        'pattern' : u'(官网|网站|你好|hi|hello|你是谁)',
Beispiel #57
0
def create_zip_files_final_callback(r):
    Router.send(Router.State.create_zip_files_done)
        sys.stdout.write(body)
    else:
        print res_status
        for k, v in res_headers:
            print k + ': ' + v
        print
        sys.stdout.write(body)
        sent_header=True

def start_response(status, response_headers):
    global res_status
    global res_headers
    res_status=status
    res_headers=response_headers

router = Router()

#here is the application
@router('/hello')
def hello(environ, start_response):
    status = '200 OK'
    output = 'Hello'
    response_headers = [('Content-type', 'text/plain'),
                        ('Content-Length', str(len(output)))]
    write = start_response(status, response_headers)
    return [output]

@router('/world')
def world(environ, start_response):
    status = '200 OK'
    output = 'World!'
Beispiel #59
0
import wsgiref.validate

from conteroller import index
from router import Router
from utils import parse_http_x_www_form_urlencoded_post_data, \
    parse_http_get_data, parse_http_headers, \
    parse_http_content_type, parse_http_uri


DEBUG = True
STATIC_URL = '/static/'
STATIC_ROOT = 'data'

router = Router()
router.register_controller('/', index)


@wsgiref.validate.validator
def application(environ, start_response):
    # https://www.python.org/dev/peps/pep-3333/#environ-variables
    REQUEST_METHOD = environ['REQUEST_METHOD']
    CONTENT_TYPE, CONTENT_TYPE_KWARGS = parse_http_content_type(environ)
    SERVER_PROTOCOL = environ['SERVER_PROTOCOL']
    HEADERS = parse_http_headers(environ)
    URI_PATH = environ['PATH_INFO']
    URI_QUERY = environ['QUERY_STRING']
    URI = parse_http_uri(environ)
    POST = parse_http_x_www_form_urlencoded_post_data(environ)
    GET = parse_http_get_data(environ)

    headers = [('Content-type', 'text/html; charset=utf-8')]
Beispiel #60
0
    def route (self, conf, *args):
        router = Router()
        router.set_logger(conf["log"]["level"], conf["log"]["file"])
        router.info("RapidSMS Server started up")
        import_i18n_sms_settings(conf)
        
        # add each application from conf
        for app_conf in conf["rapidsms"]["apps"]:
            router.add_app(app_conf)

        # add each backend from conf
        for backend_conf in conf["rapidsms"]["backends"]:
            router.add_backend(backend_conf)

        # wait for incoming messages
        router.start()
        
        # TODO: Had to explicitly do this to end the script. Will need a fix.
        sys.exit(0)