Source

flowrate / flowrate / run.py

Full commit
Robert Brewer 2ef30a2 
Robert Brewer 9ebbb12 

Robert Brewer 2ef30a2 
Robert Brewer 9ebbb12 


Robert Brewer f63ee0e 
Robert Brewer 9ebbb12 

Robert Brewer 6eaa905 
Robert Brewer c557000 
Robert Brewer 4681778 

































































Robert Brewer 9ebbb12 

Robert Brewer 6eaa905 
Robert Brewer f63ee0e 




Robert Brewer 6eaa905 
Robert Brewer f63ee0e 

Robert Brewer c557000 



Robert Brewer f63ee0e 
Robert Brewer c557000 


Robert Brewer f63ee0e 
Robert Brewer 6eaa905 














Robert Brewer f63ee0e 


Robert Brewer 9ebbb12 

Robert Brewer 4681778 
Robert Brewer 6eaa905 
Robert Brewer 4681778 


Robert Brewer 9ebbb12 

Robert Brewer 2ef30a2 


Robert Brewer 9ebbb12 
Robert Brewer 2ef30a2 






Robert Brewer 9ebbb12 
import optparse
import os
thisdir = os.path.abspath(os.path.dirname(__file__))
import sys

import cherrypy
from cherrypy.process import plugins
import simplejson

import flowrate
from flowrate import dbutil, ledger, flows
from flowrate.variables import environment as env


class Postgres(plugins.SimplePlugin):

    def __init__(self, bus, config):
        self.bus = bus
        self.config = config

    def start(self):
        self.bus.log("Connecting to Postgres database...")
        flowrate.set_db(
            'postgresql://%(user)s:%(password)s@%(host)s:%(port)s/%(database)s' %
            self.config, echo=False, max_overflow=10,
            strategy='threadlocal')
        self.bus.log("Connected to Postgres database.")
    start.priority = 30

    def recreate(self):
        d = dbutil.PgDatabase(**self.config)
        self.bus.log("Dropping Postgres database %s..." %
                     self.config['database'])
        d.drop_if_exists()
        self.bus.log("Creating Postgres database %s..." %
                     self.config['database'])
        d.create('flowrate.sql')
        self.bus.log("Postgres database created.")


class FlowrateApp(plugins.SimplePlugin):

    def __init__(self, bus, config):
        self.bus = bus
        self.config = config

    def start(self):
        self.bus.log("Mounting Flowrate application...")
        
        cherrypy.config.update({
            'server.socket_port': self.config['port'],
            'server.socket_host': self.config['host'],
            })
        appconf = {
            '/': {
                'tools.cpstats.on': True,
                'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
                'tools.trailing_slash.status': 307,
            },
            "/okapi": {
                "tools.staticdir.on": True,
                "tools.staticdir.dir": os.path.join(thisdir, 'okapi'),
            },
            "/cpstats": {
                'request.dispatch': cherrypy.dispatch.Dispatcher(),
            },
            "/manager": {
                'request.dispatch': cherrypy.dispatch.Dispatcher(),
            },
        }
        cpenv = self.config.get('environment', 'development')
        if cpenv != 'development':
            appconf['global']['environment'] = cpenv

        cherrypy.server.statistics = True

        self.app = cherrypy.tree.mount(flowrate.root, '/', appconf)
    start.priority = 70


class DataLoader(plugins.SimplePlugin):

    def __init__(self, bus):
        self.bus = bus

    def start(self):
        # Do this before flows since they need variables to obligate/fulfill.
        self.bus.log("Loading Flowrate variables...")

        for row in flowrate.db.execute("SELECT * FROM variables;"
                                       ).fetchall():
            env.bind(row['name'], row['source'])
        env.calc_all()

        #print "Environment:"
        #for name, source in env.variables.iteritems():
        #    print name, source, '=>', env.locals[name]

        self.bus.log("Loading Flowrate accounts...")
        ledger.Account.load_all()

        # Do this first because Flow.load_all tries to obligate
        self.bus.log("Loading Flowrate transactions...")
        ledger.Transaction.load_all()

        self.bus.log("Loading Flowrate flows...")
        flows.Flow.load_all()

        self.bus.log("Calculating Flowrate obligations...")
        for flow in flows.flows.itervalues():
            self.bus.log(flow['description'])
            flow.obligate()

    start.priority = Postgres.start.priority + 5


def run(config):
    cherrypy.engine.timeout_monitor.unsubscribe()
    Postgres(cherrypy.engine, config['db_info']).subscribe()
    DataLoader(cherrypy.engine).subscribe()
    FlowrateApp(cherrypy.engine, config).subscribe()
    cherrypy.engine.start()
    cherrypy.engine.block()


usage = 'flowrate/run.py <config>'


if __name__ == '__main__':
    parser = optparse.OptionParser(prog='flowrate/run.py', usage=usage)
    options, args = parser.parse_args(sys.argv[1:])

    if len(args) != 1:
        parser.error("You must supply a config file path.")

    config = simplejson.loads(open(args[0], 'rb').read())
    run(config)