Esempio n. 1
0
def spreadConfigsFromFile(options, config_file_path):
    if not os.path.isfile(config_file_path):
        log.warning("Can't find config file at {}".format(config_file_path))
        return options
    with open(config_file_path, "r") as config_file:
        try:
            config = json.loads(config_file.read())
        except:
            log.critical("Looks like i could not parse the config file!")
            raise
    common.updateConfigOverwrite(config)
    # TODO: create a XDM name space in config and use these as args
    # if they have not been set by args
    pre_run_system_settings_fields = ("port", "api_port", "socket_host",
        "dont_open_browser", "login_user", "login_password", "datadir")
    if options.systemIdentifer in config and "Default" in config[options.systemIdentifer]:
        pre_run_system_settings = config[options.systemIdentifer]["Default"]
        for field in pre_run_system_settings_fields:
            if field in pre_run_system_settings:
                setattr(options, field, pre_run_system_settings[field])
    return options
Esempio n. 2
0
def spreadConfigsFromFile(options, config_file_path):
    if not os.path.isfile(config_file_path):
        log.warning("Can't find config file at {}".format(config_file_path))
        return options
    with open(config_file_path, "r") as config_file:
        try:
            config = json.loads(config_file.read())
        except:
            log.critical("Looks like i could not parse the config file!")
            raise
    common.updateConfigOverwrite(config)
    # TODO: create a XDM name space in config and use these as args
    # if they have not been set by args
    pre_run_system_settings_fields = ("port", "api_port", "socket_host",
                                      "dont_open_browser", "login_user",
                                      "login_password", "datadir")
    if options.systemIdentifer in config and "Default" in config[
            options.systemIdentifer]:
        pre_run_system_settings = config[options.systemIdentifer]["Default"]
        for field in pre_run_system_settings_fields:
            if field in pre_run_system_settings:
                setattr(options, field, pre_run_system_settings[field])
    return options
Esempio n. 3
0
File: XDM.py Progetto: Trixter69/XDM
    def __init__(self, args=None):

        if args is None:
            args = sys.argv[1:]

        p = argparse.ArgumentParser(prog="XDM")
        p.add_argument("-d", "--daemonize", action="store_true", dest="daemonize", help="Run the server as a daemon.")
        p.add_argument("-v", "--version", action="version", version="%s" % common.getVersionHuman())
        p.add_argument("-D", "--debug", action="store_true", dest="debug", help="Print debug log to screen.")
        p.add_argument("-p", "--pidfile", dest="pidfile", default=None, help="Store the process id in the given file.")
        p.add_argument(
            "-P", "--port", dest="port", type=int, default=None, help="Force webinterface to listen on this port."
        )
        p.add_argument("-n", "--nolaunch", action="store_true", dest="nolaunch", help="Don't start the browser.")
        p.add_argument("-b", "--datadir", dest="datadir", default=None, help="Set the directory for created data.")
        p.add_argument(
            "--configJSON",
            dest="configJSON",
            default=None,
            help="Set the path to the config JSON file (or folder with then) to read from",
        )
        p.add_argument(
            "--systemIdentifer",
            dest="systemIdentifer",
            default="de.lad1337.systemconfig",
            help="Set the identifier for the system plugin",
        )
        p.add_argument("--resetWizard", dest="reset_wizard", action="store_true", help="reset the wizard state")

        p.add_argument("--config_db", dest="config_db", default=None, help="Path to config database")
        p.add_argument("--data_db", dest="data_db", default=None, help="Path to data database")
        p.add_argument("--history_db", dest="history_db", default=None, help="Path to history database")
        p.add_argument(
            "--dev",
            action="store_true",
            dest="dev",
            default=None,
            help="Developer mode. Disables the censoring during log and the plugin manager follows symlinks",
        )
        p.add_argument("--noApi", action="store_true", dest="noApi", default=None, help="Disable the api")
        p.add_argument("--apiPort", dest="apiPort", type=int, default=None, help="Port the api runs on")
        p.add_argument("--noWebServer", action="store_true", dest="noWebServer", help="Don't start the webserver")
        p.add_argument(
            "--pluginImportDebug",
            action="store_true",
            dest="pluginImportDebug",
            help="Extra verbosy debug during plugin import is printed.",
        )
        p.add_argument(
            "--profile",
            dest="profile",
            nargs="*",
            default=None,
            help="Wrap a decorated(!) function in a profiler. By default all decorated functions are profiled. Decorate your function with @profileMeMaybe",
        )
        p.add_argument("--installType", dest="installType", default=None, type=int, help="Force the install type")
        p.add_argument(
            "--config", dest="config", default=None, type=json.loads, help="Update the config with this json object"
        )

        options = p.parse_args(args)
        self.options = options
        common.STARTOPTIONS = options

        log.info("Starting XDM %s" % common.getVersionHuman())

        if options.configJSON:
            config_files = []
            if os.path.isdir(options.configJSON):
                import glob

                config_files = [os.path.abspath(p) for p in glob.glob(os.path.join(options.configJSON, "*.json"))]
            else:
                config_files.append(os.path.abspath(options.configJSON))
            for config_file in config_files:
                log.info("Loading config from file {}".format(config_file))
                options = helper.spreadConfigsFromFile(options, config_file)

        if options.config:
            common.updateConfigOverwrite(options.config)

        # Set the Paths
        if options.datadir:
            datadir = options.datadir
            if not os.path.isdir(datadir):
                os.makedirs(datadir)
        elif hasattr(sys, "frozen"):
            datadir = helper.getSystemDataDir(app_path)
            if not os.path.isdir(datadir):
                os.makedirs(datadir)
        else:
            datadir = app_path
        datadir = os.path.abspath(datadir)

        if not os.access(datadir, os.W_OK):
            raise SystemExit("Data dir must be writeable '" + datadir + "'")

        # setup file logger with datadir
        xdm.LOGPATH = os.path.join(datadir, xdm.LOGFILE)
        hdlr = logging.handlers.RotatingFileHandler(xdm.LOGPATH, maxBytes=10 * 1024 * 1024, backupCount=5)
        xdm.logger.fLogger.addHandler(hdlr)

        # Daemonize
        if options.daemonize:
            if sys.platform == "win32":
                log.error("Daemonize not supported under Windows, starting normally")
            else:
                log.info("Preparing to run in daemon mode")
                logger.cLogger.setLevel(logging.CRITICAL)
                daemonize()

        # Debug
        if options.debug:
            logger.cLogger.setLevel(logging.DEBUG)
            log.info("XDM Debug mode ON")
        # Profile
        if options.profile is not None:
            log.info("XDM profiling mode ON")
            common.RUNPROFILER = True

        # PIDfile
        if options.pidfile:
            log.info("Set PIDfile to %s" % options.pidfile)
            PIDFile(cherrypy.engine, options.pidfile).subscribe()
            pid = str(os.getpid())
            log(u"Writing PID %s to %s" % (pid, options.pidfile))
            file(os.path.abspath(options.pidfile), "w").write("%s\n" % pid)

        init.preDB(app_path, datadir)
        log.info("Logfile path is %s" % xdm.LOGPATH)
        init.db()
        init.postDB()
        init.schedule()

        if options.reset_wizard:
            common.SYSTEM.hc.setup_wizard_step = 0

        # Set port
        if options.port:
            log.info("Port manual set to %d" % (options.port))
            port = options.port
            server.socket_port = port
        else:
            port = common.SYSTEM.c.port
            server.socket_port = port
        self.port = server.socket_port
        # Set api port
        if options.apiPort:
            log.info("Api port manual set to %d" % (options.apiPort))
            self.port_api = options.apiPort
        else:
            self.port_api = common.SYSTEM.c.port_api

        # update config for cherrypy
        cherrypy.config.update({"global": {"server.socket_port": port}})
Esempio n. 4
0
    def __init__(self, args=None):

        if args is None:
            args = sys.argv[1:]

        p = argparse.ArgumentParser(prog='XDM')
        p.add_argument('-d',
                       '--daemonize',
                       action="store_true",
                       dest='daemonize',
                       help="Run the server as a daemon.")
        p.add_argument('-v',
                       '--version',
                       action="version",
                       version='%s' % common.getVersionHuman())
        p.add_argument('-D',
                       '--debug',
                       action="store_true",
                       dest='debug',
                       help="Print debug log to screen.")
        p.add_argument('-p',
                       '--pidfile',
                       dest='pidfile',
                       default=None,
                       help="Store the process id in the given file.")
        p.add_argument('-P',
                       '--port',
                       dest='port',
                       type=int,
                       default=None,
                       help="Force webinterface to listen on this port.")
        p.add_argument('-n',
                       '--nolaunch',
                       action="store_true",
                       dest='nolaunch',
                       help="Don't start the browser.")
        p.add_argument('-b',
                       '--datadir',
                       dest='datadir',
                       default=None,
                       help="Set the directory for created data.")
        p.add_argument(
            '--configJSON',
            dest='configJSON',
            default=None,
            help=
            "Set the path to the config JSON file (or folder with then) to read from"
        )
        p.add_argument('--systemIdentifer',
                       dest='systemIdentifer',
                       default="de.lad1337.systemconfig",
                       help="Set the identifier for the system plugin")
        p.add_argument('--resetWizard',
                       dest='reset_wizard',
                       action="store_true",
                       help="reset the wizard state")

        p.add_argument('--config_db',
                       dest='config_db',
                       default=None,
                       help="Path to config database")
        p.add_argument('--data_db',
                       dest='data_db',
                       default=None,
                       help="Path to data database")
        p.add_argument('--history_db',
                       dest='history_db',
                       default=None,
                       help="Path to history database")
        p.add_argument(
            '--dev',
            action="store_true",
            dest='dev',
            default=None,
            help=
            "Developer mode. Disables the censoring during log and the plugin manager follows symlinks"
        )
        p.add_argument('--noApi',
                       action="store_true",
                       dest='noApi',
                       default=None,
                       help="Disable the api")
        p.add_argument('--apiPort',
                       dest='apiPort',
                       type=int,
                       default=None,
                       help="Port the api runs on")
        p.add_argument('--noWebServer',
                       action="store_true",
                       dest='noWebServer',
                       help="Don't start the webserver")
        p.add_argument(
            '--pluginImportDebug',
            action="store_true",
            dest='pluginImportDebug',
            help="Extra verbosy debug during plugin import is printed.")
        p.add_argument(
            '--profile',
            dest='profile',
            nargs='*',
            default=None,
            help=
            "Wrap a decorated(!) function in a profiler. By default all decorated functions are profiled. Decorate your function with @profileMeMaybe"
        )
        p.add_argument('--installType',
                       dest='installType',
                       default=None,
                       type=int,
                       help="Force the install type")
        p.add_argument('--config',
                       dest='config',
                       default=None,
                       type=json.loads,
                       help="Update the config with this json object")

        options = p.parse_args(args)
        self.options = options
        common.STARTOPTIONS = options

        log.info('Starting XDM %s' % common.getVersionHuman())

        if options.configJSON:
            config_files = []
            if os.path.isdir(options.configJSON):
                import glob
                config_files = [
                    os.path.abspath(p) for p in glob.glob(
                        os.path.join(options.configJSON, '*.json'))
                ]
            else:
                config_files.append(os.path.abspath(options.configJSON))
            for config_file in config_files:
                log.info('Loading config from file {}'.format(config_file))
                options = helper.spreadConfigsFromFile(options, config_file)

        if options.config:
            common.updateConfigOverwrite(options.config)

        # Set the Paths
        if options.datadir:
            datadir = options.datadir
            if not os.path.isdir(datadir):
                os.makedirs(datadir)
        elif hasattr(sys, 'frozen'):
            datadir = helper.getSystemDataDir(app_path)
            if not os.path.isdir(datadir):
                os.makedirs(datadir)
        else:
            datadir = app_path
        datadir = os.path.abspath(datadir)

        if not os.access(datadir, os.W_OK):
            raise SystemExit("Data dir must be writeable '" + datadir + "'")

        # setup file logger with datadir
        xdm.LOGPATH = os.path.join(datadir, xdm.LOGFILE)
        hdlr = logging.handlers.RotatingFileHandler(xdm.LOGPATH,
                                                    maxBytes=10 * 1024 * 1024,
                                                    backupCount=5)
        xdm.logger.fLogger.addHandler(hdlr)

        # Daemonize
        if options.daemonize:
            if sys.platform == 'win32':
                log.error(
                    "Daemonize not supported under Windows, starting normally")
            else:
                log.info("Preparing to run in daemon mode")
                logger.cLogger.setLevel(logging.CRITICAL)
                daemonize()

        # Debug
        if options.debug:
            logger.cLogger.setLevel(logging.DEBUG)
            log.info('XDM Debug mode ON')
        # Profile
        if options.profile is not None:
            log.info('XDM profiling mode ON')
            common.RUNPROFILER = True

        # PIDfile
        if options.pidfile:
            log.info("Set PIDfile to %s" % options.pidfile)
            PIDFile(cherrypy.engine, options.pidfile).subscribe()
            pid = str(os.getpid())
            log(u"Writing PID %s to %s" % (pid, options.pidfile))
            file(os.path.abspath(options.pidfile), 'w').write("%s\n" % pid)

        init.preDB(app_path, datadir)
        log.info("Logfile path is %s" % xdm.LOGPATH)
        init.db()
        init.postDB()
        init.schedule()

        if options.reset_wizard:
            common.SYSTEM.hc.setup_wizard_step = 0

        # Set port
        if options.port:
            log.info("Port manual set to %d" % (options.port))
            port = options.port
            server.socket_port = port
        else:
            port = common.SYSTEM.c.port
            server.socket_port = port
        self.port = server.socket_port
        # Set api port
        if options.apiPort:
            log.info("Api port manual set to %d" % (options.apiPort))
            self.port_api = options.apiPort
        else:
            self.port_api = common.SYSTEM.c.port_api

        # update config for cherrypy
        cherrypy.config.update({'global': {'server.socket_port': port}})