Source

CherryPy Recipes / web / websockets / http_traffic / __init__.py

# -*- coding: utf-8 -*-
import json
import logging
import os
import random

import cherrypy
from cherrypy.lib import cpstats
from cherrypy.process import plugins

from ws4py.server.cherrypyserver import WebSocketPlugin, WebSocketTool
from ws4py.websocket import WebSocket
from ws4py.messaging import TextMessage

base_dir = os.path.abspath(os.path.dirname(__file__))

class MetricsWebSocketHandler(WebSocket):
    def received_message(self, m):
        pass

class MetricsBroadcaster(plugins.Monitor):
    def __init__(self, bus):
        plugins.Monitor.__init__(self, bus, callback=self.broadcast, frequency=0.2)

    def broadcast(self):
        s = cpstats.extrapolate_statistics(logging.statistics)
        data = []
        for k in s:
            if k.startswith("CherryPy HTTPServer"):
                for w in s[k]["Worker Threads"]:
                    data.append(s[k]["Worker Threads"][w])
                break
            
        data = json.dumps(data, sort_keys=True, indent=4)
        cherrypy.engine.publish('websocket-broadcast', TextMessage(data))
        
class Root(object):
    @cherrypy.expose
    def index(self):
        return file(os.path.join(base_dir, 'index.html'))

    @cherrypy.expose
    def dummy(self):
        return '*' * random.randint(1, 256)

    @cherrypy.expose
    def metrics(self):
        cherrypy.log("Handler created: %s" % repr(cherrypy.request.ws_handler))
        
if __name__ == '__main__':
    
    root = Root()
    root.cpstats = cpstats.StatsPage()
    
    cherrypy.config.update({'server.socket_port': 8090,
                            'server.statistics': True,
                            'server.thread_pool': 3})

    WebSocketPlugin(cherrypy.engine).subscribe()
    cherrypy.tools.websocket = WebSocketTool()

    MetricsBroadcaster(cherrypy.engine).subscribe()
    
    cherrypy.quickstart(root, '/', {
        '/': {
            'tools.cpstats.on': True
            },
        '/metrics': {
            'tools.cpstats.on': False,
            'tools.websocket.on': True,
            'tools.websocket.handler_cls': MetricsWebSocketHandler
            }
        }
    )
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.