Source

gevent_cometd / gevent_cometd / start.py

Full commit
from gevent import monkey, pywsgi; monkey.patch_all()
import datetime
import gevent
import gevent_cometd.app_views as app_views
import logging
import optparse

from gevent_cometd import config
from webob import Request, exc


log = logging.getLogger(__name__)


class WSGIHandler(object):
        
    def __call__(self, environ, start_response):
        """ try to find the right request"""
        req = Request(environ)

        #pop the / from path
        query_parts = req.path[1:].split('/')
        action = query_parts[0]
        if not action:
            action = 'index'

        #try to find the action
        try:
            method = getattr(app_views, action)
        except AttributeError:
            raise exc.HTTPBadRequest('No such action %r' % action)

        try:
            res = method(req, *query_parts[1:])
        except exc.HTTPException, e:
            # The exception object itself is a WSGI application/response:
            res = e

        #return proper response
        return res(environ, start_response)
    
    
def garbage_control():
    """garbage control loop"""
    while True:
        gevent.sleep(10)
        curr_time = datetime.datetime.utcnow()
        #garbage control connections/users
        to_remove = []
        for key, client in app_views.clients.iteritems():
            delta = curr_time - client.last_active
            if delta.seconds >= config['gc_conns_after']:
                to_remove.append(key)
        for key in to_remove:
            app_views.clients.pop(key, None)
        removed_total = len(to_remove)
        # we salvaged clients, now also delete copies
        for channel in app_views.channels.itervalues():
            for x in range(len(channel.clients) - 1, -1, -1):
                if channel.clients[x].conn_id in to_remove:
                    del channel.clients[x]
        if removed_total:
            print "GC'd %i users" % removed_total
        

def cli_start():
    parser = optparse.OptionParser()
    parser.add_option("-s", "--secret", dest="secret",
                  help="secret used to secure your requests",
                  default='secret'
                  )
    parser.add_option("-a", "--admin_secret", dest="admin_secret",
                  help="secret used to secure your admin_panel",
                  default='admin_secret'
                  )
    parser.add_option("-p", "--port", dest="port",
                  help="port on which the server listens to",
                  default=8088
                  )
    parser.add_option("-x", "--allowed_post_ip", dest="allow_posting_from",
                  help="comma separated list of ip's that can post to server",
                  default="127.0.0.1"
                  )
    (options, args) = parser.parse_args()
    config['port'] = int(options.port)
    config['secret'] = options.secret
    config['admin_secret'] = options.admin_secret
    config['allow_posting_from'] = [ip.strip() for ip in options.allow_posting_from.split(',')]
    print 'Serving on 0.0.0.0:%s' % config['port'] 
    app = WSGIHandler()
    gevent.spawn(garbage_control)
    pywsgi.WSGIServer(('', config['port']), app).serve_forever()