示例#1
0
文件: launcher.py 项目: ri0t/isomer
    def _start_frontend(self, restart=False):
        """Check if it is enabled and start the frontend http & websocket"""

        self.log(self.config, self.config.frontendenabled, lvl=verbose)
        if self.config.frontendenabled and not self.frontend_running or restart:
            self.log("Restarting webfrontend services on",
                     self.frontend_target)

            self.static = Static("/",
                                 docroot=self.frontend_target).register(self)
            self.websocket = WebSocketsDispatcher("/websocket").register(self)
            self.frontend_running = True

            if self.development:
                self.frontend_watch_manager = pyinotify.WatchManager()
                self.frontend_watcher = pyinotify.ThreadedNotifier(
                    self.frontend_watch_manager, FrontendHandler(self))
                self.frontend_watcher.start()
                # noinspection PyUnresolvedReferences
                mask = (pyinotify.IN_DELETE | pyinotify.IN_CREATE
                        | pyinotify.IN_CLOSE_WRITE)
                self.log("Frontend root:", self.frontend_root, lvl=debug)
                self.frontend_watch_manager.add_watch(self.module_root,
                                                      mask,
                                                      rec=True)
    def __init__(self, engine_cls, debug=False, force_snmp_init=True):
        super(RedisStateHandler, self).__init__()

        self._state_tracker = EngineStateTracker()

        logger.info("Initializing websocket server...")
        # set up a web socket server
        socket_conf = {
            "host": os.environ.get("SIMENGINE_SOCKET_HOST"),
            "port": int(os.environ.get("SIMENGINE_SOCKET_PORT")),
        }
        self._server = Server(
            (socket_conf["host"], socket_conf["port"])).register(self)

        # Worker(process=False).register(self)
        Static().register(self._server)
        Logger().register(self._server)

        if debug:
            Debugger(events=False).register(self)
        self._ws = WebSocket().register(self._server)

        WebSocketsDispatcher("/simengine").register(self._server)

        logger.info("Initializing engine...")
        self._engine = engine_cls(
            force_snmp_init=force_snmp_init).register(self)
        self._engine.subscribe_tracker(self._ws)
        self._engine.subscribe_tracker(self._state_tracker)

        # Use redis pub/sub communication
        logger.info("Initializing redis connection...")
        self._redis_store = redis.StrictRedis(host="localhost", port=6379)
示例#3
0
def main():
    opts, args = parse_options()

    bind = parse_bind(opts.bind)

    if opts.validate:
        application = (Application() + Root())
        app = validator(application)

        httpd = make_server(bind[0], bind[1], app)
        httpd.serve_forever()

        raise SystemExit(0)

    manager = Manager()

    opts.debug and Debugger().register(manager)

    Poller = select_poller(opts.poller.lower())
    Poller().register(manager)

    if opts.server.lower() == "base":
        BaseServer(bind).register(manager)
        HelloWorld().register(manager)
    else:
        Server(bind).register(manager)
        Root().register(manager)

    docroot = os.getcwd() if not args else args[0]

    Static(docroot=docroot, dirlisting=True).register(manager)

    opts.passwd and Authentication(passwd=opts.passwd).register(manager)

    opts.logging and Logger().register(manager)

    if opts.profile and hotshot:
        profiler = hotshot.Profile(".profile")
        profiler.start()

    if opts.debug:
        print(graph(manager, name="circuits.web"))
        print()
        print(inspect(manager))

    for i in range(opts.jobs):
        manager.start(process=True)

    manager.run()

    if opts.profile and hotshot:
        profiler.stop()
        profiler.close()

        stats = hotshot.stats.load(".profile")
        stats.strip_dirs()
        stats.sort_stats("time", "calls")
        stats.print_stats(20)
示例#4
0
文件: launcher.py 项目: addy2342/hfos
def construct_graph(dodebug=False, dograph=False, dogui=False):
    """Preliminary HFOS application Launcher"""

    if dodebug:
        from circuits import Debugger

    server = Server(("0.0.0.0", 8055))
    setup_root(server)
    Logger().register(server)
    hfoslog("[HFOS] Beginning graph assembly.")

    HFDebugger().register(server)

    app = App().register(server)

    # Machineroom().register(app)

    navdata = NavData().register(server)
    NMEAParser('localhost', 2222).register(navdata)

    TileCache().register(server)
    Static("/", docroot="/var/lib/hfos/static").register(server)
    WebSocketsDispatcher("/websocket").register(server)

    clientmanager = ClientManager().register(server)
    AlertManager().register(clientmanager)
    SchemaManager().register(clientmanager)
    ObjectManager().register(clientmanager)
    Authenticator().register(clientmanager)
    Chat().register(clientmanager)
    MapViewManager().register(clientmanager)
    LayerManager().register(clientmanager)
    RemoteControlManager().register(clientmanager)
    WebDemo().register(clientmanager)
    Wiki().register(clientmanager)
    # CameraManager().register(clientmanager)

    # Logger().register(server)

    if dodebug:
        dbg = Debugger()
        dbg.IgnoreEvents.extend(["write", "_write", "streamsuccess"])
        # dbg.register(lm)

    if dograph:
        from circuits.tools import graph

        graph(server)

    if dogui:
        import webbrowser

        webbrowser.open("http://127.0.0.1:8055")

    hfoslog("[HFOS] Graph assembly done.")

    return server
示例#5
0
文件: launcher.py 项目: ri0t/hfos
    def _start_frontend(self, restart=False):
        self.log(self.config, self.config.frontendenabled, lvl=verbose)
        if self.config.frontendenabled and not self.frontendrunning \
                or restart:
            self.log("Restarting webfrontend services on",
                     self.config.frontendtarget)

            self.static = Static("/",
                                 docroot=self.config.frontendtarget).register(
                self)
            self.websocket = WebSocketsDispatcher("/websocket").register(self)
            self.frontendrunning = True
示例#6
0
    def GET(self, name="FrontPage", action="view"):
        environ = self.environ.copy()
        environ["page.name"] = name
        environ["parser"] = text2html

        d = {}
        d["title"] = name
        d["version"] = circuits.__version__
        d["menu"] = text2html(self.db.get("SiteMenu", ""), environ=environ)

        text = self.db.get(name, "")
        s = open("tpl/%s.html" % action, "r").read()

        if action == "view":
            d["text"] = text2html(text, environ=environ)
        else:
            d["text"] = text

        return s % d

    def POST(self, name="FrontPage", **form):
        self.db.save(name, form.get("text", ""))
        return self.redirect(name)


app = Server(("0.0.0.0", 8000))
Static(docroot="static").register(app)
Root().register(app)
Logger().register(app)
app.run()
示例#7
0
        form_out = DynamicForm.get_form().render()

        return render_template('dynamic.html', form=form_out)

    def piecewise(self, *args, **kwargs):
        # Generate a regular form via a classmethod to provide easy access to extra
        # functionality
        form = JsonForm()

        # Handle regular submission of the form
        if self.request.method == 'POST':
            success, out = form.json_validate(kwargs, piecewise=True)
            if success:
                print "Whoo! We should do some sort of database stuff here..."

            return out
        else:
            out = form.render()

        return render_template('piecewise.html', form=out)

app = Server(("0.0.0.0", 5000))

from circuits import Debugger
Debugger().register(app)

Static(docroot=template_path + "../").register(app)
Root().register(app)

app.run()
示例#8
0
#!/usr/bin/env python
from circuits import Debugger
from circuits.web import Controller, Server, Static


class Root(Controller):
    def index(self):
        """Index Request Handler

        Controller(s) expose implicitly methods as request handlers.
        Request Handlers can still be customized by using the ``@expose``
        decorator. For example exposing as a different path.
        """

        return "Hello World!"


app = Server(("0.0.0.0", 9000))
Debugger().register(app)
Static().register(app)
Root().register(app)
app.run()
示例#9
0
    def init(self):
        self.closed = False

        self.server = Server(0).register(self)
        Static("/static", DOCROOT, dirlisting=True).register(self)
示例#10
0
 def __init__(self):
     Server.__init__(self, "0.0.0.0:%d" % PORT)  #"localhost", PORT)
     self + WebController() + Static(docroot=SHOTPATH)
示例#11
0
        EntityAnalyserComponent(),
        EntityPreprocessorComponent(),
        DialogGeneratorComponent()
    ],
    "jobRunnerComponents": [
        TimeJobRunnerComponent(),
        GreetJobRunnerComponent(),
        ComplimentJobRunnerComponent(),
        QuestionJobRunnerComponent(),
        SearchGeneralJobRunnerComponent()
    ],
    "gateways": [WSGateway(), Root()],
    "dispatchers": [WebSocketsDispatcher("/websocket")],
    "circuitComponents": [
        Debugger(),
        Static(),
        Logger(),
    ]
}


def bootstrapAppComponents(app, appComponents):
    for appComponent in appComponents:
        appComponent.register(app)


def bootstrapJobRunnerComponents(app, jobRunnerComponents):
    for jobRunnerComponent in jobRunnerComponents:
        jobRunnerComponent.register(app)

示例#12
0
def main():
    config = Config()

    manager = Manager()

    if config.get("debug"):
        manager += Debugger(
            events=config.get("verbose"),
            file=config.get("errorlog"),
        )

    environ = Environment(config)

    SignalHandler(environ).register(environ)

    manager += environ

    if config.get("sock") is not None:
        bind = config.get("sock")
    elif ":" in config.get("bind"):
        address, port = config.get("bind").split(":")
        bind = (
            address,
            int(port),
        )
    else:
        bind = (
            config.get("bind"),
            config.get("port"),
        )

    server = (Server(bind) + Sessions() + Root(environ) +
              CacheControl(environ) + ErrorHandler(environ))

    if MemoryMonitor is not None:
        MemoryMonitor(channel="/memory").register(server)

    if not config.get("disable-logging"):
        server += Logger(file=config.get("accesslog", sys.stdout))

    if not config.get("disable-static"):
        server += Static(docroot=os.path.join(config.get("theme"), "htdocs"))

    if not config.get("disable-hgweb"):
        baseui = ui()
        baseui.setconfig("web", "prefix", "/+hg")
        baseui.setconfig("web", "style", "gitweb")
        baseui.setconfig("web", "allow_push", "*")
        baseui.setconfig("web", "push_ssl", False)
        baseui.setconfig("web", "allow_archive", ["bz2", "gz", "zip"])
        baseui.setconfig("web", "description", config.get("description"))

        server += Gateway({
            "/+hg":
            hgweb(environ.storage.repo_path, config.get("name"), baseui)
        })

    if not config.get("disable-compression"):
        server += Compression(environ)

    if config.get("daemon"):
        manager += Daemon(config.get("pidfile"))

    server.register(manager)

    manager.run()
示例#13
0
def main():
    opts, args = parse_options()

    if opts.jit and psyco:
        psyco.full()

    if ":" in opts.bind:
        address, port = opts.bind.split(":")
        port = int(port)
    else:
        address, port = opts.bind, 8000

    bind = (address, port)

    if opts.validate:
        application = (wsgi.Application() + Root())
        app = validator(application)

        httpd = make_server(address, port, app)
        httpd.serve_forever()
        
        raise SystemExit, 0

    manager = Manager()

    if opts.debug:
        manager += Debugger()

    poller = opts.type.lower()
    if poller == "poll":
        if Poll is None:
            print "No poll support available - defaulting to Select..."
            Poller = Select
        else:
            Poller = Poll
    elif poller == "epoll":
        if EPoll is None:
            print "No epoll support available - defaulting to Select..."
            Poller = Select
        else:
            Poller = EPoll
    else:
        Poller = Select

    if opts.server.lower() == "base":
        BaseServer(bind, poller=Poller).register(manager)
        HelloWorld().register(manager)
    else:
        Server(bind, poller=Poller).register(manager)
        Root().register(manager)

    docroot = os.getcwd() if not args else args[0]

    Static(docroot=docroot, dirlisting=True).register(manager)

    if opts.profile:
        if hotshot:
            profiler = hotshot.Profile(".profile")
            profiler.start()

    if opts.debug:
        print graph(manager, name="circuits.web")
        print
        print inspect(manager)

    if opts.mp:
        from circuits.core.workers import cpus
        for i in xrange(cpus() - 1):
            manager.start(process=True)

    manager.run()

    if opts.profile and hotshot:
        profiler.stop()
        profiler.close()

        stats = hotshot.stats.load(".profile")
        stats.strip_dirs()
        stats.sort_stats("time", "calls")
        stats.print_stats(20)
示例#14
0
    def GET(self, *args, **kwargs):
        self.expires(60 * 60 * 24 * 30)
        return self.serve_file(os.path.abspath("static/index.xhtml"))

    def POST(self, input=None):
        if not input:
            return ""

        self.response.headers["Content-Type"] = "text/plain"

        if input.strip() == "inspect":
            return inspect(self)

        self.response.stream = True

        sid = self.request.sid
        self += Command(self.request, self.response, input, channel=sid)

        return self.response


app = Server(("0.0.0.0", 8000))
Debugger().register(app)
Static("/js", docroot="static/js").register(app)
Static("/css", docroot="static/css").register(app)
Sessions().register(app)
Logger().register(app)
Root().register(app)
app.run()
示例#15
0
 def __init__(self):
     Server.__init__(self, PORT)  #"localhost", PORT)
     self + WebController() + Static(docroot=PATH)
示例#16
0
 def __init__(self):
     log("RaspuinoDartServer::__init__")
     Server.__init__(self, ("0.0.0.0", 8000))
     Static(docroot=".", defaults=['RaspuinoDart.html']).register(self)
     RaspuinoDartEcho().register(self)
     WebSocketsDispatcher("/websocket").register(self)