Exemple #1
0
def default_start():
    """
    Use `sys.argv` for starting parameters. This is the entry-point of `vlcp-start`
    """
    (config, daemon, pidfile, startup, fork) = parsearg()
    if config is None:
        if os.path.isfile('/etc/vlcp.conf'):
            config = '/etc/vlcp.conf'
        else:
            print('/etc/vlcp.conf is not found; start without configurations.')
    elif not config:
        config = None
    main(config, startup, daemon, pidfile, fork)
Exemple #2
0
        action = parser.ofp_action_output(port=output)

        packetoutMessage.actions.append(action)

        log.debug("packet to %r", output)
        openflow_reply, _ = await proto.batch([packetoutMessage], connection,
                                              self)

        for reply in openflow_reply:
            #if reply['type'] == common.OFPET_BAD_REQUEST:
            log.debug(common.dump(reply))

    async def main(self):
        connectEventMatcher = OpenflowConnectionStateEvent.createMatcher()
        while True:
            ev = await connectEventMatcher
            # here event must be connect event
            # handle this connection in an subroutine
            self.connectStateHandler(ev)


if __name__ == '__main__':

    #logging.basicConfig(format='%(asctime)s-%(name)s-%(levelname)s : %(message)s',level=logging.DEBUG)
    log = logging.getLogger('l2switch')
    log.setLevel(logging.DEBUG)
    manager['module.OpenflowServer.urls'] = ['ltcp://127.0.0.1:6653']

    main(None, ())
Exemple #3
0
        '''
        Constructor
        '''
        Module.__init__(self, server)
        self._ce_matcher = ConsoleEvent.createMatcher()
        self.apiroutine = RoutineContainer(self.scheduler)
        self.apiroutine.main = self._service_routine
        self._restore_console_event = threading.Event()
        @generator_to_async(True, False)
        def proxy(event, matcher):
            while True:
                events = self.sendEventQueue.get()
                if events is None:
                    break
                yield events
        @async_to_async(True, False)
        @async_processor
        def processor(event, matcher, queueout):
            if event.type == 'initproxy':
                proxy(event, matcher, queueout)
        self.connector = Connector(processor, (self._ce_matcher,), self.scheduler, False)
        self.routines.append(self.apiroutine)
        self.routines.append(self.connector)

if __name__ == '__main__':
    from vlcp.server import main
    import sys
    manager['module.console.startinconsole'] = True
    modules = list(sys.argv[1:]) + ['__main__.Console']
    main(None, modules)
Exemple #4
0
            # here will call test the event cause
            if timeout:
                env.outputjson(dict(messages=[]))
            else:
                # the event will store self.event
                # we can get the message form it

                #self.logger.info(self.event)
                #self.logger.info(self.event.id)
                #self.logger.info(self.event.message)

                array = []
                data = {"id": ev.id, "message": ev.message}
                array.append(data)
                env.outputjson(dict(messages=array))


if __name__ == '__main__':

    conf = "./app.conf"

    parsers = OptionParser()
    parsers.add_option('-d',
                       dest='daemon',
                       help='run as daemon',
                       action='store_true',
                       metavar='Daemon')
    (options, args) = parsers.parse_args()

    main(conf, (), options.daemon)
Exemple #5
0
            await env.rewrite(b'/?test=a&test2=b')
            return
        elif 'redirect' in env.args:
            await env.redirect(b'/?test3=b&test4=c')
            return
        elif 'redirect2' in env.args:
            await env.redirect(b'http://www.baidu.com/')
            return
        if 'download' in env.args:
            env.header('Content-Disposition', 'attachment; filename="a:b.txt"')
        await env.write(
            self.formatstr(
                self.document,
                (env.escape(env.host), env.escape(env.fullpath),
                 env.escape(repr(env.headers)), env.escape(env.path),
                 env.escape(env.originalpath), env.escape(repr(env.cookies)),
                 env.escape(repr(env.args)), env.escape(repr(env.form)))))


if __name__ == '__main__':
    #s.scheduler.debugging = True
    #s.scheduler.logger.setLevel(logging.DEBUG)
    #Http.debugging = True
    #Http._logger.setLevel(logging.DEBUG)
    #manager['server.debugging'] = True
    manager['module.httpserver.url'] = None
    manager['module.httpserver.urls'] = ['ltcp://0.0.0.0:8080']
    manager['protocol.http.showerrorinfo'] = True
    manager['module.console.startinconsole'] = False
    main(None, ('__main__.TestHttpServer', ))
Exemple #6
0
            pm_key = PhysicalNetworkMap.default_key(physicalnetwork)
            with request_context(reqid, self.apiroutine):
                keys, result = await call_api(
                    self.apiroutine, 'objectdb', 'walk', {
                        'keys': [pm_key],
                        'walkerdict': {
                            pm_key: walker_func(lambda x: x.networks)
                        },
                        'requestid': reqid
                    })
                return [dump(r) for r in result]
        else:
            self._reqid += 1
            reqid = ('testobjectdb', self._reqid)
            ns_key = LogicalNetworkSet.default_key()
            with request_context(reqid, self.apiroutine):
                keys, result = await call_api(
                    self.apiroutine, 'objectdb', 'walk', {
                        'keys': [ns_key],
                        'walkerdict': {
                            ns_key: walker_func(lambda x: x.set)
                        },
                        'requestid': reqid
                    })
                return [dump(r) for r in result]


if __name__ == '__main__':
    main("/etc/vlcp.conf",
         ("__main__.TestObjectDB", "vlcp.service.manage.webapi.WebAPI"))
Exemple #7
0
        self.apiroutine = RoutineContainer(self.scheduler)
        self.apiroutine.main = self._service_routine
        self._restore_console_event = threading.Event()

        @generator_to_async(True, False)
        def proxy(event, matcher):
            while True:
                events = self.sendEventQueue.get()
                if events is None:
                    break
                yield events

        @async_to_async(True, False)
        @async_processor
        def processor(event, matcher, queueout):
            if event.type == 'initproxy':
                proxy(event, matcher, queueout)

        self.connector = Connector(processor, (self._ce_matcher, ),
                                   self.scheduler, False)
        self.routines.append(self.apiroutine)
        self.routines.append(self.connector)


if __name__ == '__main__':
    from vlcp.server import main
    import sys
    manager['module.console.startinconsole'] = True
    modules = list(sys.argv[1:]) + ['__main__.Console']
    main(None, modules)
Exemple #8
0
            env.header("Content-Disposition", 'attachment; filename="a:b.txt"')
        for m in env.write(
            self.formatstr(
                self.document,
                (
                    env.escape(env.host),
                    env.escape(env.fullpath),
                    env.escape(repr(env.headers)),
                    env.escape(env.path),
                    env.escape(env.originalpath),
                    env.escape(repr(env.cookies)),
                    env.escape(repr(env.args)),
                    env.escape(repr(env.form)),
                ),
            )
        ):
            yield m


if __name__ == "__main__":
    # s.scheduler.debugging = True
    # s.scheduler.logger.setLevel(logging.DEBUG)
    # Http.debugging = True
    # Http._logger.setLevel(logging.DEBUG)
    # manager['server.debugging'] = True
    manager["module.httpserver.url"] = None
    manager["module.httpserver.urls"] = ["ltcp://0.0.0.0:8080"]
    manager["protocol.http.showerrorinfo"] = True
    manager["module.console.startinconsole"] = False
    main(None, ("__main__.TestHttpServer",))
Exemple #9
0
        action = parser.ofp_action_output(port = output)
        
        packetoutMessage.actions.append(action)
    
        log.debug("packet to %r",output)
        for m in proto.batch([packetoutMessage],connection,self):
            yield m

        for reply in self.openflow_reply:
            #if reply['type'] == common.OFPET_BAD_REQUEST:
            log.debug(common.dump(self.openflow_reply))

    def main(self):
        while True:

            connectEventMatcher = OpenflowConnectionStateEvent.createMatcher()
            yield (connectEventMatcher,)
           
            # here event must be connect event
            # handle this connection in an subroutine
            self.connectStateHandler(self.event)

if __name__ == '__main__':

    #logging.basicConfig(format='%(asctime)s-%(name)s-%(levelname)s : %(message)s',level=logging.DEBUG)
    log = logging.getLogger('l2switch')
    log.setLevel(logging.DEBUG)
    manager['module.OpenflowServer.urls'] = ['ltcp://127.0.0.1:6653']

    main(None,())
Exemple #10
0
                    if getattr(result, k, None) != v:
                        self.apiroutine.retvalue = []
                        return
                self.apiroutine.retvalue = [dump(result)]
        elif physicalnetwork is not None:
            self._reqid += 1
            reqid = ('testobjectdb', self._reqid)
            pm_key = PhysicalNetworkMap.default_key(physicalnetwork)
            for m in callAPI(self.apiroutine, 'objectdb', 'walk', {'keys': [pm_key],
                                                                   'walkerdict': {pm_key: walker_func(lambda x: x.networks)},
                                                                   'requestid': reqid}):
                yield m
            keys, result = self.apiroutine.retvalue
            with watch_context(keys, result, reqid, self.apiroutine):
                self.apiroutine.retvalue = [dump(r) for r in result]
        else:
            self._reqid += 1
            reqid = ('testobjectdb', self._reqid)
            ns_key = LogicalNetworkSet.default_key()
            for m in callAPI(self.apiroutine, 'objectdb', 'walk', {'keys': [ns_key],
                                                                   'walkerdict': {ns_key: walker_func(lambda x: x.set)},
                                                                   'requestid': reqid}):
                yield m
            keys, result = self.apiroutine.retvalue
            with watch_context(keys, result, reqid, self.apiroutine):
                self.apiroutine.retvalue = [dump(r) for r in result]
    
if __name__ == '__main__':
    main("/etc/vlcp.conf", ("__main__.TestObjectDB", "vlcp.service.manage.webapi.WebAPI"))
    
Exemple #11
0
    def main(self):
        clients = [ZooKeeperClient(self.apiroutine, self.serverlist) for _ in range(0,10)]
        for c in clients:
            c.start()
        def test_loop(number):
            maindir = ('vlcptest_' + str(number)).encode('utf-8')
            client = clients[number % len(clients)]
            for _ in range(0, 100):
                for m in client.requests([zk.multi(
                                                zk.multi_create(maindir, b'test'),
                                                zk.multi_create(maindir + b'/subtest', 'test2')
                                            ),
                                          zk.getchildren2(maindir, True)], self.apiroutine):
                    yield m
                for m in client.requests([zk.multi(
                                                zk.multi_delete(maindir + b'/subtest'),
                                                zk.multi_delete(maindir)),
                                          zk.getchildren2(maindir, True)], self.apiroutine):
                    yield m
        from time import time
        starttime = time()
        for m in self.apiroutine.executeAll([test_loop(i) for i in range(0, 100)]):
            yield m
        print('10000 loops in %r seconds, with %d connections' % (time() - starttime, len(clients)))
        for c in clients:
            for m in c.shutdown():
                yield m
        
if __name__ == '__main__':
    main()
    
Exemple #12
0
'''
Created on 2016/1/29

:author: hubo
'''

from vlcp.server import main
from vlcp.config.config import manager

if __name__ == '__main__':
    manager['module.httpserver.url'] = ''
    manager['module.httpserver.vhost.api.url'] = 'ltcp://localhost:8081/'
    main(None, ('vlcp.service.manage.webapi.WebAPI', 'vlcp.service.manage.modulemanager.Manager',
                'vlcp.service.utils.knowledge.Knowledge'))
Exemple #13
0
'''
Created on 2015/12/30

@author: hubo
'''
from vlcp.server import main
from vlcp.config.config import manager

if __name__ == '__main__':
    #manager['module.console.startinconsole'] = True
    main(None, ('vlcp.service.debugging.console.Console',))
Exemple #14
0
        for k, v in options:
            if k == '--help' or k == '-?' or k == '-h':
                usage()
            elif k == '-f':
                configfile = v
            elif k == '-p':
                pidfile = v
            elif k == '-d':
                daemon = True
            elif k == '-F':
                fork = int(v)
        startup = None
        if args:
            startup = args
        return (configfile, daemon, pidfile, startup, fork)
    except getopt.GetoptError as exc:
        print(exc)
        usage()


if __name__ == '__main__':
    (config, daemon, pidfile, startup, fork) = parsearg()
    if config is None:
        if os.path.isfile('/etc/vlcp.conf'):
            config = '/etc/vlcp.conf'
        else:
            print('/etc/vlcp.conf is not found; start without configurations.')
    elif not config:
        config = None
    main(config, startup, daemon, pidfile, fork)
Exemple #15
0
'''
Created on 2016/1/29

:author: hubo
'''

from vlcp.server import main
from vlcp.config.config import manager

if __name__ == '__main__':
    manager['module.httpserver.url'] = ''
    manager['module.httpserver.vhost.api.url'] = 'ltcp://localhost:8081/'
    main(None, ('vlcp.service.manage.webapi.WebAPI',
                'vlcp.service.manage.modulemanager.Manager',
                'vlcp.service.utils.knowledge.Knowledge'))
Exemple #16
0
        for k,v in options:
            if k == '--help' or k == '-?' or k == '-h':
                usage()
            elif k == '-f':
                configfile = v
            elif k == '-p':
                pidfile = v
            elif k == '-d':
                daemon = True
            elif k == '-F':
                fork = int(v)
        startup = None
        if args:
            startup = args
        return (configfile, daemon, pidfile, startup, fork)
    except getopt.GetoptError as exc:
        print(exc)
        usage()
        

if __name__ == '__main__':
    (config, daemon, pidfile, startup, fork) = parsearg()
    if config is None:
        if os.path.isfile('/etc/vlcp.conf'):
            config = '/etc/vlcp.conf'
        else:
            print('/etc/vlcp.conf is not found; start without configurations.')
    elif not config:
        config = None
    main(config, startup, daemon, pidfile, fork)
Exemple #17
0
                                                        passwd = b'\x00' * 16,      # Why is it necessary...
                                                    ), self.apiroutine, []):
            yield m
        for m in self.protocol.requests(self.client, [zk.create(b'/vlcptest', b'test'),
                                                      zk.getdata(b'/vlcptest', True)], self.apiroutine):
            yield m
        pprint(dump(self.apiroutine.retvalue[0]))
        for m in self.apiroutine.waitWithTimeout(0.2):
            yield m
        for m in self.protocol.requests(self.client, [zk.delete(b'/vlcptest'),
                                                      zk.getdata(b'/vlcptest', watch = True)], self.apiroutine):
            yield m
        pprint(dump(self.apiroutine.retvalue[0]))
        for m in self.protocol.requests(self.client, [zk.multi(
                                                            zk.multi_create(b'/vlcptest2', b'test'),
                                                            zk.multi_create(b'/vlcptest2/subtest', 'test2')
                                                        ),
                                                      zk.getchildren2(b'/vlcptest2', True)], self.apiroutine):
            yield m
        pprint(dump(self.apiroutine.retvalue[0]))
        for m in self.protocol.requests(self.client, [zk.multi(
                                                            zk.multi_delete(b'/vlcptest2/subtest'),
                                                            zk.multi_delete(b'/vlcptest2')),
                                                      zk.getchildren2(b'/vlcptest2', True)], self.apiroutine):
            yield m
        pprint(dump(self.apiroutine.retvalue[0]))
        
        
if __name__ == '__main__':
    main()
    
Exemple #18
0
            #self.logger.info(self.timeout)

            # here will call test the event cause
            if(self.timeout):
                    env.outputjson(dict(messages=[]))
            else:
                    # the event will store self.event
                    # we can get the message form it

                    #self.logger.info(self.event)
                    #self.logger.info(self.event.id)
                    #self.logger.info(self.event.message)

                    array = []
                    data = {"id":self.event.id,"message":self.event.message}
                    array.append(data)
                    env.outputjson(dict(messages=array))


if __name__ == '__main__':

    conf = "./app.conf"

    parsers = OptionParser()
    parsers.add_option('-d',dest='daemon',help='run as daemon',action='store_true',metavar='Daemon')
    (options,args) = parsers.parse_args()

    main(conf,(),options.daemon)