# Path: ravel/app.py
# class Application(object):
#     """A Ravel application.  In Ravel, an application contains a SQL
#        implementation and, optionally, a sub-shell implemented in Python to
#        monitor and control the application.  Application sub-shells are accesible
#        from the main Ravel CLI by loading the application and typing its name
#        or shortcut."""
# 
#     def __init__(self, name):
#         "name: the name of the application"
#         self.name = name
#         self.shortcut = None
#         self.description = ""
#         self.pyfile = None
#         self.sqlfile = None
#         self.module = None
#         self.components = []
#         self.console = None
# 
#     def link(self, filename):
#         """Link a resource or implementation file to the application
#            filename: path to the file containing an application's resource"""
#         if filename.endswith(".py"):
#             self.pyfile = filename
#         elif filename.endswith(".sql"):
#             self.sqlfile = filename
# 
#     def is_loadable(self):
#         """returns: true if the application's Python component (it's sub-shell)
#            can be imported and instantiated"""
#         return self.module is not None
# 
#     def load(self, db):
#         """Load the application from the specified database
#            db: a ravel.db.RavelDb instance into which the application will be loaded"""
#         if self.sqlfile is None:
#             logger.debug("loaded application %s with no SQL file", self.name)
#             return
# 
#         with open(self.sqlfile) as f:
#             try:
#                 db.cursor.execute(f.read())
#             except psycopg2.ProgrammingError, e:
#                 print "Error loading app {0}: {1}".format(self.name, e)
# 
#         logger.debug("loaded application %s", self.name)
# 
#     def unload(self, db):
#         """Unload the application from the specified database
#            db: a ravel.db.RavelDb instance containing the application"""
#         for component in self.components:
#             component.drop(db)
# 
#         logger.debug("unloaded application %s", self.name)
# 
#     def init(self, db, env):
#         """Initialize the application without loading it into the database.
#            db: a ravel.db.RavelDb instance to be passed to the application's
#            sub-shell
#            env: a ravel.env.Environment instance of the CLI's executing
#            environment to be passed to the application's sub-shell"""
#         if not self.pyfile:
#             return
# 
#         # discover sql components (tables, views, functions)
#         if self.sqlfile is not None:
#             with open(self.sqlfile) as f:
#                 self.components = discoverComponents(f.read())
# 
#         logger.debug("discovered {0} components: {1}"
#                      .format(self.name, self.components))
# 
#         # if needed, add path
#         filepath = os.path.dirname(self.pyfile)
#         ravel.util.append_path(filepath)
# 
#         try:
#             self.module = importlib.import_module(self.name)
#             self.console =  self.module.console(db, env, self.components)
# 
#             # force module prompt to app name
#             self.console.prompt = self.name + "> "
#             self.console.doc_header = self.name + \
#                                       " commands (type help <topic>):"
#         except BaseException, e:
#             errstr = "{0}: {1}".format(type(e).__name__, str(e))
#             logger.warning("error loading %s console: %s",
#                            self.name, e)
# 
#         try:
#             self.shortcut = self.module.shortcut
#             self.description = self.module.description
#         except BaseException:
#             pass
# 
#     def cmd(self, line):
#         """Execute a command in the application's sub-shell.  If an empty
#            command is passed, start the application's sub-shell in a cmdloop
#            line: a command in the application's sub-shell, or an empty
#            string"""
#         if self.console:
#             if line:
#                 self.console.onecmd(line)
#             else:
#                 self.console.cmdloop()
# 
# 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
# class ConnectionType:
# class ConfigParameters(object):
# def update_trigger_path(filename, path):
# def append_path(path):
# def resource_string(name):
# def resource_file(name=None):
# def splitArgs( argstr ):
#     def makeNumeric( s ):
#     def __init__(self):
#     def read(self, cfg):


import os
import subprocess
import ravel.db
import ravel.messaging
import ravel.util
from ravel.app import Application
from ravel.log import logger
from ravel.util import Config
            self.db.load_schema(ravel.db.AUXILIARY_FUN_SQL)
        else:
            logger.debug("connecting to existing db, skipping load_topo()")

        # if running onlydb mode, remove network flow triggers
        if self.opts.onlydb:
            self.db.load_schema(ravel.db.NOFLOW_SQL)

        self.provider.cacheNodes()

        core_shortcuts = []
        for app in self.coreapps:
            self.load_app(app)
            if self.loaded[app].shortcut is not None:
                core_shortcuts.append(self.loaded[app].shortcut)
        self.coreapps.extend(core_shortcuts)

    def stop(self):
        "Stop the environment, including the database and network provider"
        self.provider.stop()
        if len(self.xterms) > 0:
            logger.debug("waiting for xterms")

        for t in self.xterms:
            t.wait()

        # delete xterm temp files
        for f in self.xterm_files:
            os.unlink(f)


# Path: ravel/app.py
# class Application(object):
#     """A Ravel application.  In Ravel, an application contains a SQL
#        implementation and, optionally, a sub-shell implemented in Python to
#        monitor and control the application.  Application sub-shells are accesible
#        from the main Ravel CLI by loading the application and typing its name
#        or shortcut."""
# 
#     def __init__(self, name):
#         "name: the name of the application"
#         self.name = name
#         self.shortcut = None
#         self.description = ""
#         self.pyfile = None
#         self.sqlfile = None
#         self.module = None
#         self.components = []
#         self.console = None
# 
#     def link(self, filename):
#         """Link a resource or implementation file to the application
#            filename: path to the file containing an application's resource"""
#         if filename.endswith(".py"):
#             self.pyfile = filename
#         elif filename.endswith(".sql"):
#             self.sqlfile = filename
# 
#     def is_loadable(self):
#         """returns: true if the application's Python component (it's sub-shell)
#            can be imported and instantiated"""
#         return self.module is not None
# 
#     def load(self, db):
#         """Load the application from the specified database
#            db: a ravel.db.RavelDb instance into which the application will be loaded"""
#         if self.sqlfile is None:
#             logger.debug("loaded application %s with no SQL file", self.name)
#             return
# 
#         with open(self.sqlfile) as f:
#             try:
#                 db.cursor.execute(f.read())
#             except psycopg2.ProgrammingError, e:
#                 print "Error loading app {0}: {1}".format(self.name, e)
# 
#         logger.debug("loaded application %s", self.name)
# 
#     def unload(self, db):
#         """Unload the application from the specified database
#            db: a ravel.db.RavelDb instance containing the application"""
#         for component in self.components:
#             component.drop(db)
# 
#         logger.debug("unloaded application %s", self.name)
# 
#     def init(self, db, env):
#         """Initialize the application without loading it into the database.
#            db: a ravel.db.RavelDb instance to be passed to the application's
#            sub-shell
#            env: a ravel.env.Environment instance of the CLI's executing
#            environment to be passed to the application's sub-shell"""
#         if not self.pyfile:
#             return
# 
#         # discover sql components (tables, views, functions)
#         if self.sqlfile is not None:
#             with open(self.sqlfile) as f:
#                 self.components = discoverComponents(f.read())
# 
#         logger.debug("discovered {0} components: {1}"
#                      .format(self.name, self.components))
# 
#         # if needed, add path
#         filepath = os.path.dirname(self.pyfile)
#         ravel.util.append_path(filepath)
# 
#         try:
#             self.module = importlib.import_module(self.name)
#             self.console =  self.module.console(db, env, self.components)
# 
#             # force module prompt to app name
#             self.console.prompt = self.name + "> "
#             self.console.doc_header = self.name + \
#                                       " commands (type help <topic>):"
#         except BaseException, e:
#             errstr = "{0}: {1}".format(type(e).__name__, str(e))
#             logger.warning("error loading %s console: %s",
#                            self.name, e)
# 
#         try:
#             self.shortcut = self.module.shortcut
#             self.description = self.module.description
#         except BaseException:
#             pass
# 
#     def cmd(self, line):
#         """Execute a command in the application's sub-shell.  If an empty
#            command is passed, start the application's sub-shell in a cmdloop
#            line: a command in the application's sub-shell, or an empty
#            string"""
#         if self.console:
#             if line:
#                 self.console.onecmd(line)
#             else:
#                 self.console.cmdloop()
# 
# 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
# class ConnectionType:
# class ConfigParameters(object):
# def update_trigger_path(filename, path):
# def append_path(path):
# def resource_string(name):
# def resource_file(name=None):
# def splitArgs( argstr ):
#     def makeNumeric( s ):
#     def __init__(self):
#     def read(self, cfg):


# Path: ravel/env.py
import os
import subprocess
import ravel.db
import ravel.messaging
import ravel.util
from ravel.app import Application
from ravel.log import logger
from ravel.util import Config

            self.db.load_schema(ravel.db.AUXILIARY_FUN_SQL)
        else:
            logger.debug("connecting to existing db, skipping load_topo()")

        # if running onlydb mode, remove network flow triggers
        if self.opts.onlydb:
            self.db.load_schema(ravel.db.NOFLOW_SQL)

        self.provider.cacheNodes()

        core_shortcuts = []
        for app in self.coreapps:
            self.load_app(app)
            if self.loaded[app].shortcut is not None:
                core_shortcuts.append(self.loaded[app].shortcut)
        self.coreapps.extend(core_shortcuts)

    def stop(self):
        "Stop the environment, including the database and network provider"
        self.provider.stop()
        if len(self.xterms) > 0:
            logger.debug("waiting for xterms")

        for t in self.xterms:
            t.wait()

        # delete xterm temp files
        for f in self.xterm_files:
            os.unlink(f)


        ravel.messaging.clear_queue(Config.QueueId)