# Path: ravel/app.py
# class AppConsole(cmd.Cmd):
#     "Superclass for an application's sub-shell"
# 
#     def __init__(self, db, env, components):
#         """db: a ravel.db.RavelDb instance
#            env: a ravel.env.Environment instance of the CLI's executing environment
#            components: list of the app's SQL components (tables, view, etc.)"""
#         self.db = db
#         self.env = env
#         self.components = components
#         self.logOn = False
#         cmd.Cmd.__init__(self)
# 
#     def emptyline(self):
#         "Don't repeat the last line when hitting return on empty line"
#         return
# 
#     def onecmd(self, line):
#         "Run command and report execution time for each execution line"  
#         if line:
#             if self.logOn:
#                 startTime = time.time()
#                 stop = cmd.Cmd.onecmd(self, line)
#                 endTime = time.time()
#                 elapsed = round((endTime - startTime)*1000, 3)
#                 cmdLogger.logline('cmd: '+line)
#                 logger.info("Execution time: {0}ms".format(elapsed))
#                 cmdLogger.logline('start time: {0}'.format(time.asctime(time.localtime(startTime))))
#                 cmdLogger.logline('time span: {0}ms'.format(elapsed))
#                 return stop
#             else:
#                 return cmd.Cmd.onecmd(self, line)
# 
#     def do_cmdlogger(self, line):
#         if str(line).lower() == 'on':
#             self.logOn = True
#             logger.info('Cmd logger on.')
#         elif str(line).lower() == 'off':
#             self.logOn = False
#             logger.info('Cmd logger off.')
#         else:
#             logger.info("Input 'on' to turn on cmd logger and 'off' to turn it off.")
# 
#     def do_list(self, line):
#         "List application components"
#         print self.name, "components:"
#         for comp in self.components:
#             print "   ", comp
# 
#     def do_watch(self, line):
#         "Watch application components"
#         w = [c.name for c in self.components if c.watchable]
#         cmd, cmdfile = mk_watchcmd(self.db, w)
#         self.env.mkterm(cmd, cmdfile)
# 
#     def do_EOF(self, line):
#         "Quit application console"
#         sys.stdout.write("\n")
#         return True
# 
#     def do_exit(self, line):
#         "Quit application console"
#         return True
# 
# def discoverComponents(sql):
#     """Search for installable/removable components within a string containing
#        one or more SQL statemnets"""
#     components = []
#     parsed = sqlparse.parse(sql)
#     for statement in parsed:
#         for token in statement.tokens:
#             name = None
#             typ = None
# 
#             # remove newlines, extra spaces for regex
#             stmt = str(statement).replace("\n", " ")
#             stmt = " ".join(stmt.split())
# 
#             for comp in sqlComponents:
#                 if token.match(Keyword, comp.typ):
#                     name = comp.match(stmt)
#                     typ = comp.typ
# 
#             if name is not None:
#                 component = AppComponent(name, typ)
#                 if component not in components:
#                     components.append(component)
# 
#     # sort alphabetically, should fix drop issues when 'rule on table'
#     # is dropped before 'table'
#     return sorted(components, key=lambda x: x.typ)
# 
# Path: ravel/log.py
# LEVELS = { "debug" : logging.DEBUG,
#            "info" : logging.INFO,
#            "warning" : logging.WARNING,
#            "error" : logging.ERROR,
#            "critical" : logging.CRITICAL
#        }
# DEFAULT_LEVEL = logging.ERROR
# MSG_FORMAT = "%(levelname)s:%(funcName)s: %(message)s"
# class Singleton(type):
# class RavelLogger(Logger, object):
#     def __init__(cls, name, bases, dict_):
#     def __call__(cls, *args, **kw):
#     def __init__(self):
#     def setLogLevel(self, levelname=None):
# 
# Path: ravel/util.py
# def resource_file(name=None):
#     """Search for a file within the distribution and return its absolute path.
#        If no name is passed, returns the absolute path to the distribution's
#        top-level directory
#        name: the name of the file
#        returns: absolute path to the file"""
#     install_path = os.path.dirname(os.path.abspath(__file__))
#     install_path = os.path.normpath(
#         os.path.join(install_path, ".."))
# 
#     if name is None:
#         return install_path
# 
#     return os.path.abspath(os.path.join(install_path, name))


import os
from itertools import tee, izip
from ravel.app import AppConsole, discoverComponents
from ravel.log import logger
from ravel.util import resource_file
            sql += ptable_template.format(app)
            try:
                self.db.cursor.execute("SELECT violation FROM app_violation WHERE app = '{0}';".format(app))
                violations = self.db.cursor.fetchall()
                if len(violations) > 0:
                    vtable = violations[0][0]
                    for v in violations[1:]:
                        vtable += "; DELETE FROM {0}".format(v[0])
                else:
                    vtable = "{0}_violation".format(app)
            except Exception, e:
                print e
            sql += runrule_template.format(app, vtable)

        if "routing" in ordering:
            sql += routing

        for app1, app2 in pairwise(ordering):
            sql += orderrule_template.format(app1, app2)

        sql += clock_template.format(ordering[-1])

        self.ordering = [x for x in reversed(ordering)]
        self.sql = sql

        log = resource_file("orch_log.sql")
        f = open(log, 'w')
        f.write(self.sql)
        f.close()


# Path: ravel/app.py
# class AppConsole(cmd.Cmd):
#     "Superclass for an application's sub-shell"
# 
#     def __init__(self, db, env, components):
#         """db: a ravel.db.RavelDb instance
#            env: a ravel.env.Environment instance of the CLI's executing environment
#            components: list of the app's SQL components (tables, view, etc.)"""
#         self.db = db
#         self.env = env
#         self.components = components
#         self.logOn = False
#         cmd.Cmd.__init__(self)
# 
#     def emptyline(self):
#         "Don't repeat the last line when hitting return on empty line"
#         return
# 
#     def onecmd(self, line):
#         "Run command and report execution time for each execution line"  
#         if line:
#             if self.logOn:
#                 startTime = time.time()
#                 stop = cmd.Cmd.onecmd(self, line)
#                 endTime = time.time()
#                 elapsed = round((endTime - startTime)*1000, 3)
#                 cmdLogger.logline('cmd: '+line)
#                 logger.info("Execution time: {0}ms".format(elapsed))
#                 cmdLogger.logline('start time: {0}'.format(time.asctime(time.localtime(startTime))))
#                 cmdLogger.logline('time span: {0}ms'.format(elapsed))
#                 return stop
#             else:
#                 return cmd.Cmd.onecmd(self, line)
# 
#     def do_cmdlogger(self, line):
#         if str(line).lower() == 'on':
#             self.logOn = True
#             logger.info('Cmd logger on.')
#         elif str(line).lower() == 'off':
#             self.logOn = False
#             logger.info('Cmd logger off.')
#         else:
#             logger.info("Input 'on' to turn on cmd logger and 'off' to turn it off.")
# 
#     def do_list(self, line):
#         "List application components"
#         print self.name, "components:"
#         for comp in self.components:
#             print "   ", comp
# 
#     def do_watch(self, line):
#         "Watch application components"
#         w = [c.name for c in self.components if c.watchable]
#         cmd, cmdfile = mk_watchcmd(self.db, w)
#         self.env.mkterm(cmd, cmdfile)
# 
#     def do_EOF(self, line):
#         "Quit application console"
#         sys.stdout.write("\n")
#         return True
# 
#     def do_exit(self, line):
#         "Quit application console"
#         return True
# 
# def discoverComponents(sql):
#     """Search for installable/removable components within a string containing
#        one or more SQL statemnets"""
#     components = []
#     parsed = sqlparse.parse(sql)
#     for statement in parsed:
#         for token in statement.tokens:
#             name = None
#             typ = None
# 
#             # remove newlines, extra spaces for regex
#             stmt = str(statement).replace("\n", " ")
#             stmt = " ".join(stmt.split())
# 
#             for comp in sqlComponents:
#                 if token.match(Keyword, comp.typ):
#                     name = comp.match(stmt)
#                     typ = comp.typ
# 
#             if name is not None:
#                 component = AppComponent(name, typ)
#                 if component not in components:
#                     components.append(component)
# 
#     # sort alphabetically, should fix drop issues when 'rule on table'
#     # is dropped before 'table'
#     return sorted(components, key=lambda x: x.typ)
# 
# Path: ravel/log.py
# LEVELS = { "debug" : logging.DEBUG,
#            "info" : logging.INFO,
#            "warning" : logging.WARNING,
#            "error" : logging.ERROR,
#            "critical" : logging.CRITICAL
#        }
# DEFAULT_LEVEL = logging.ERROR
# MSG_FORMAT = "%(levelname)s:%(funcName)s: %(message)s"
# class Singleton(type):
# class RavelLogger(Logger, object):
#     def __init__(cls, name, bases, dict_):
#     def __call__(cls, *args, **kw):
#     def __init__(self):
#     def setLogLevel(self, levelname=None):
# 
# Path: ravel/util.py
# def resource_file(name=None):
#     """Search for a file within the distribution and return its absolute path.
#        If no name is passed, returns the absolute path to the distribution's
#        top-level directory
#        name: the name of the file
#        returns: absolute path to the file"""
#     install_path = os.path.dirname(os.path.abspath(__file__))
#     install_path = os.path.normpath(
#         os.path.join(install_path, ".."))
# 
#     if name is None:
#         return install_path
# 
#     return os.path.abspath(os.path.join(install_path, name))


# Path: apps/orch.py
import os
from itertools import tee, izip
from ravel.app import AppConsole, discoverComponents
from ravel.log import logger
from ravel.util import resource_file

            sql += ptable_template.format(app)
            try:
                self.db.cursor.execute("SELECT violation FROM app_violation WHERE app = '{0}';".format(app))
                violations = self.db.cursor.fetchall()
                if len(violations) > 0:
                    vtable = violations[0][0]
                    for v in violations[1:]:
                        vtable += "; DELETE FROM {0}".format(v[0])
                else:
                    vtable = "{0}_violation".format(app)
            except Exception, e:
                print e
            sql += runrule_template.format(app, vtable)

        if "routing" in ordering:
            sql += routing

        for app1, app2 in pairwise(ordering):
            sql += orderrule_template.format(app1, app2)

        sql += clock_template.format(ordering[-1])

        self.ordering = [x for x in reversed(ordering)]
        self.sql = sql

        log = resource_file("orch_log.sql")
        f = open(log, 'w')
        f.write(self.sql)
        f.close()


        logger.debug("logged orchestration protocol to %s", log)