Пример #1
0
 def __init__(self):
     """Initialize application."""
     super(Application, self).__init__()
     self.acl = acl.load()
     storage.load()
     self.encoding = config.get("encoding", "request")
     if config.getboolean('logging', 'full_environment'):
         self.headers_log = lambda environ: environ
Пример #2
0
 def __init__(self):
     """Initialize application."""
     super(Application, self).__init__()
     self.acl = acl.load()
     storage.load()
     self.encoding = config.get("encoding", "request")
     if config.getboolean("logging", "full_environment"):
         self.headers_log = lambda environ: environ
Пример #3
0
 def __init__(self, configuration):
     """Initialize application."""
     super().__init__()
     self.configuration = configuration
     self.Auth = auth.load(configuration)
     self.Collection = storage.load(configuration)
     self.Rights = rights.load(configuration)
     self.Web = web.load(configuration)
     self.encoding = configuration.get("encoding", "request")
Пример #4
0
 def __init__(self, configuration):
     """Initialize application."""
     super().__init__()
     self.configuration = configuration
     self.Auth = auth.load(configuration)
     self.Collection = storage.load(configuration)
     self.Rights = rights.load(configuration)
     self.Web = web.load(configuration)
     self.encoding = configuration.get("encoding", "request")
Пример #5
0
    def __init__(self, configuration):
        """Initialize application.

        ``configuration`` see ``radicale.config`` module.

        """
        super().__init__()
        self.configuration = configuration
        self.auth = auth.load(configuration)
        self.storage = storage.load(configuration)
        self.rights = rights.load(configuration)
        self.Web = web.load(configuration)
        self.encoding = configuration.get("encoding", "request")
Пример #6
0
    def __init__(self, configuration):
        """Initialize Application.

        ``configuration`` see ``radicale.config`` module.
        The ``configuration`` must not change during the lifetime of
        this object, it is kept as an internal reference.

        """
        super().__init__()
        self.configuration = configuration
        self._auth = auth.load(configuration)
        self._storage = storage.load(configuration)
        self._rights = rights.load(configuration)
        self._web = web.load(configuration)
        self._encoding = configuration.get("encoding", "request")
Пример #7
0
 def __init__(self, configuration, logger):
     super().__init__(configuration, logger)
     self.filename = os.path.expanduser(configuration.get("rights", "file"))
     self.Storeclass = storage.load(configuration, logger)
Пример #8
0
def run():
    """Run Radicale as a standalone server."""
    log.setup()

    # Get command-line arguments
    parser = argparse.ArgumentParser(usage="radicale [OPTIONS]")

    parser.add_argument("--version", action="version", version=VERSION)
    parser.add_argument("--verify-storage", action="store_true",
                        help="check the storage for errors and exit")
    parser.add_argument(
        "-C", "--config", help="use a specific configuration file")
    parser.add_argument("-D", "--debug", action="store_true",
                        help="print debug information")

    groups = {}
    for section, values in config.DEFAULT_CONFIG_SCHEMA.items():
        if values.get("_internal", False):
            continue
        group = parser.add_argument_group(section)
        groups[group] = []
        for option, data in values.items():
            if option.startswith("_"):
                continue
            kwargs = data.copy()
            long_name = "--{0}-{1}".format(
                section, option.replace("_", "-"))
            args = kwargs.pop("aliases", [])
            args.append(long_name)
            kwargs["dest"] = "{0}_{1}".format(section, option)
            groups[group].append(kwargs["dest"])
            del kwargs["value"]
            if "internal" in kwargs:
                del kwargs["internal"]

            if kwargs["type"] == bool:
                del kwargs["type"]
                kwargs["action"] = "store_const"
                kwargs["const"] = "True"
                opposite_args = kwargs.pop("opposite", [])
                opposite_args.append("--no{0}".format(long_name[1:]))
                group.add_argument(*args, **kwargs)

                kwargs["const"] = "False"
                kwargs["help"] = "do not {0} (opposite of {1})".format(
                    kwargs["help"], long_name)
                group.add_argument(*opposite_args, **kwargs)
            else:
                del kwargs["type"]
                group.add_argument(*args, **kwargs)

    args = parser.parse_args()

    # Preliminary configure logging
    if args.debug:
        args.logging_level = "debug"
    with contextlib.suppress(ValueError):
        log.set_level(config.DEFAULT_CONFIG_SCHEMA["logging"]["level"]["type"](
            args.logging_level))

    # Update Radicale configuration according to arguments
    arguments_config = {}
    for group, actions in groups.items():
        section = group.title
        section_config = {}
        for action in actions:
            value = getattr(args, action)
            if value is not None:
                section_config[action.split('_', 1)[1]] = value
        if section_config:
            arguments_config[section] = section_config

    try:
        configuration = config.load(config.parse_compound_paths(
            config.DEFAULT_CONFIG_PATH,
            os.environ.get("RADICALE_CONFIG"),
            args.config))
        if arguments_config:
            configuration.update(
                arguments_config, "arguments", internal=False)
    except Exception as e:
        logger.fatal("Invalid configuration: %s", e, exc_info=True)
        exit(1)

    # Configure logging
    log.set_level(configuration.get("logging", "level"))

    # Inspect configuration after logger is configured
    configuration.inspect()

    if args.verify_storage:
        logger.info("Verifying storage")
        try:
            Collection = storage.load(configuration)
            with Collection.acquire_lock("r"):
                if not Collection.verify():
                    logger.fatal("Storage verifcation failed")
                    exit(1)
        except Exception as e:
            logger.fatal("An exception occurred during storage verification: "
                         "%s", e, exc_info=True)
            exit(1)
        return

    # Create a socket pair to notify the server of program shutdown
    shutdown_socket, shutdown_socket_out = socket.socketpair()

    # SIGTERM and SIGINT (aka KeyboardInterrupt) shutdown the server
    def shutdown(*args):
        shutdown_socket.sendall(b" ")
    signal.signal(signal.SIGTERM, shutdown)
    signal.signal(signal.SIGINT, shutdown)

    try:
        server.serve(configuration, shutdown_socket_out)
    except Exception as e:
        logger.fatal("An exception occurred during server startup: %s", e,
                     exc_info=True)
        exit(1)
Пример #9
0
def run():
    """Run Radicale as a standalone server."""
    # Get command-line arguments
    parser = argparse.ArgumentParser(usage="radicale [OPTIONS]")

    parser.add_argument("--version", action="version", version=VERSION)
    parser.add_argument("--verify-storage",
                        action="store_true",
                        help="check the storage for errors and exit")
    parser.add_argument("-C",
                        "--config",
                        help="use a specific configuration file")

    groups = {}
    for section, values in config.INITIAL_CONFIG.items():
        group = parser.add_argument_group(section)
        groups[group] = []
        for option, data in values.items():
            kwargs = data.copy()
            long_name = "--{0}-{1}".format(section, option.replace("_", "-"))
            args = kwargs.pop("aliases", [])
            args.append(long_name)
            kwargs["dest"] = "{0}_{1}".format(section, option)
            groups[group].append(kwargs["dest"])
            del kwargs["value"]
            if "internal" in kwargs:
                del kwargs["internal"]

            if kwargs["type"] == bool:
                del kwargs["type"]
                kwargs["action"] = "store_const"
                kwargs["const"] = "True"
                opposite_args = kwargs.pop("opposite", [])
                opposite_args.append("--no{0}".format(long_name[1:]))
                group.add_argument(*args, **kwargs)

                kwargs["const"] = "False"
                kwargs["help"] = "do not {0} (opposite of {1})".format(
                    kwargs["help"], long_name)
                group.add_argument(*opposite_args, **kwargs)
            else:
                group.add_argument(*args, **kwargs)

    args = parser.parse_args()
    if args.config is not None:
        config_paths = [args.config] if args.config else []
        ignore_missing_paths = False
    else:
        config_paths = [
            "/etc/radicale/config",
            os.path.expanduser("~/.config/radicale/config")
        ]
        if "RADICALE_CONFIG" in os.environ:
            config_paths.append(os.environ["RADICALE_CONFIG"])
        ignore_missing_paths = True
    try:
        configuration = config.load(config_paths,
                                    ignore_missing_paths=ignore_missing_paths)
    except Exception as e:
        print("ERROR: Invalid configuration: %s" % e, file=sys.stderr)
        if args.logging_debug:
            raise
        exit(1)

    # Update Radicale configuration according to arguments
    for group, actions in groups.items():
        section = group.title
        for action in actions:
            value = getattr(args, action)
            if value is not None:
                configuration.set(section, action.split("_", 1)[1], value)

    if args.verify_storage:
        # Write to stderr when storage verification is requested
        configuration["logging"]["config"] = ""

    # Start logging
    filename = os.path.expanduser(configuration.get("logging", "config"))
    debug = configuration.getboolean("logging", "debug")
    try:
        logger = log.start("radicale", filename, debug)
    except Exception as e:
        print("ERROR: Failed to start logger: %s" % e, file=sys.stderr)
        if debug:
            raise
        exit(1)

    if args.verify_storage:
        logger.info("Verifying storage")
        try:
            Collection = storage.load(configuration, logger)
            if not Collection.verify():
                logger.error("Storage verifcation failed")
                exit(1)
        except Exception as e:
            logger.error(
                "An exception occurred during storage verification: "
                "%s",
                e,
                exc_info=True)
            exit(1)
        return

    try:
        serve(configuration, logger)
    except Exception as e:
        logger.error("An exception occurred during server startup: %s",
                     e,
                     exc_info=True)
        exit(1)
Пример #10
0
def start_web_server():
    storage.load()

    run(host='localhost', port=8080)
Пример #11
0
def run():
    """Run Radicale as a standalone server."""
    # Get command-line arguments
    parser = argparse.ArgumentParser(usage="radicale [OPTIONS]")

    parser.add_argument("--version", action="version", version=VERSION)
    parser.add_argument("--verify-storage", action="store_true",
                        help="check the storage for errors and exit")
    parser.add_argument(
        "-C", "--config", help="use a specific configuration file")

    groups = {}
    for section, values in config.INITIAL_CONFIG.items():
        group = parser.add_argument_group(section)
        groups[group] = []
        for option, data in values.items():
            kwargs = data.copy()
            long_name = "--{0}-{1}".format(
                section, option.replace("_", "-"))
            args = kwargs.pop("aliases", [])
            args.append(long_name)
            kwargs["dest"] = "{0}_{1}".format(section, option)
            groups[group].append(kwargs["dest"])
            del kwargs["value"]
            if "internal" in kwargs:
                del kwargs["internal"]

            if kwargs["type"] == bool:
                del kwargs["type"]
                kwargs["action"] = "store_const"
                kwargs["const"] = "True"
                opposite_args = kwargs.pop("opposite", [])
                opposite_args.append("--no{0}".format(long_name[1:]))
                group.add_argument(*args, **kwargs)

                kwargs["const"] = "False"
                kwargs["help"] = "do not {0} (opposite of {1})".format(
                    kwargs["help"], long_name)
                group.add_argument(*opposite_args, **kwargs)
            else:
                group.add_argument(*args, **kwargs)

    args = parser.parse_args()
    if args.config is not None:
        config_paths = [args.config] if args.config else []
        ignore_missing_paths = False
    else:
        config_paths = ["/etc/radicale/config",
                        os.path.expanduser("~/.config/radicale/config")]
        if "RADICALE_CONFIG" in os.environ:
            config_paths.append(os.environ["RADICALE_CONFIG"])
        ignore_missing_paths = True
    try:
        configuration = config.load(config_paths,
                                    ignore_missing_paths=ignore_missing_paths)
    except Exception as e:
        print("ERROR: Invalid configuration: %s" % e, file=sys.stderr)
        if args.logging_debug:
            raise
        exit(1)

    # Update Radicale configuration according to arguments
    for group, actions in groups.items():
        section = group.title
        for action in actions:
            value = getattr(args, action)
            if value is not None:
                configuration.set(section, action.split('_', 1)[1], value)

    if args.verify_storage:
        # Write to stderr when storage verification is requested
        configuration["logging"]["config"] = ""

    # Start logging
    filename = os.path.expanduser(configuration.get("logging", "config"))
    debug = configuration.getboolean("logging", "debug")
    try:
        logger = log.start("radicale", filename, debug)
    except Exception as e:
        print("ERROR: Failed to start logger: %s" % e, file=sys.stderr)
        if debug:
            raise
        exit(1)

    if args.verify_storage:
        logger.info("Verifying storage")
        try:
            Collection = storage.load(configuration, logger)
            with Collection.acquire_lock("r"):
                if not Collection.verify():
                    logger.error("Storage verifcation failed")
                    exit(1)
        except Exception as e:
            logger.error("An exception occurred during storage verification: "
                         "%s", e, exc_info=True)
            exit(1)
        return

    try:
        serve(configuration, logger)
    except Exception as e:
        logger.error("An exception occurred during server startup: %s", e,
                     exc_info=True)
        exit(1)
Пример #12
0
def run():
    """Run Radicale as a standalone server."""
    log.setup()

    # Get command-line arguments
    parser = argparse.ArgumentParser(usage="radicale [OPTIONS]")

    parser.add_argument("--version", action="version", version=VERSION)
    parser.add_argument("--verify-storage",
                        action="store_true",
                        help="check the storage for errors and exit")
    parser.add_argument("-C",
                        "--config",
                        help="use a specific configuration file")
    parser.add_argument("-D",
                        "--debug",
                        action="store_true",
                        help="print debug information")

    groups = {}
    for section, values in config.INITIAL_CONFIG.items():
        group = parser.add_argument_group(section)
        groups[group] = []
        for option, data in values.items():
            kwargs = data.copy()
            long_name = "--{0}-{1}".format(section, option.replace("_", "-"))
            args = kwargs.pop("aliases", [])
            args.append(long_name)
            kwargs["dest"] = "{0}_{1}".format(section, option)
            groups[group].append(kwargs["dest"])
            del kwargs["value"]
            if "internal" in kwargs:
                del kwargs["internal"]

            if kwargs["type"] == bool:
                del kwargs["type"]
                kwargs["action"] = "store_const"
                kwargs["const"] = "True"
                opposite_args = kwargs.pop("opposite", [])
                opposite_args.append("--no{0}".format(long_name[1:]))
                group.add_argument(*args, **kwargs)

                kwargs["const"] = "False"
                kwargs["help"] = "do not {0} (opposite of {1})".format(
                    kwargs["help"], long_name)
                group.add_argument(*opposite_args, **kwargs)
            else:
                group.add_argument(*args, **kwargs)

    args = parser.parse_args()

    # Preliminary configure logging
    if args.debug:
        args.logging_level = "debug"
    if args.logging_level is not None:
        log.set_level(args.logging_level)

    if args.config is not None:
        config_paths = [args.config] if args.config else []
        ignore_missing_paths = False
    else:
        config_paths = [
            "/etc/radicale/config",
            os.path.expanduser("~/.config/radicale/config")
        ]
        if "RADICALE_CONFIG" in os.environ:
            config_paths.append(os.environ["RADICALE_CONFIG"])
        ignore_missing_paths = True
    try:
        configuration = config.load(config_paths,
                                    ignore_missing_paths=ignore_missing_paths)
    except Exception as e:
        logger.fatal("Invalid configuration: %s", e, exc_info=True)
        exit(1)

    # Update Radicale configuration according to arguments
    for group, actions in groups.items():
        section = group.title
        for action in actions:
            value = getattr(args, action)
            if value is not None:
                configuration.set(section, action.split('_', 1)[1], value)

    # Configure logging
    log.set_level(configuration.get("logging", "level"))

    if args.verify_storage:
        logger.info("Verifying storage")
        try:
            Collection = storage.load(configuration)
            with Collection.acquire_lock("r"):
                if not Collection.verify():
                    logger.fatal("Storage verifcation failed")
                    exit(1)
        except Exception as e:
            logger.fatal(
                "An exception occurred during storage verification: "
                "%s",
                e,
                exc_info=True)
            exit(1)
        return

    # Create a socket pair to notify the server of program shutdown
    shutdown_socket, shutdown_socket_out = socket.socketpair()

    # SIGTERM and SIGINT (aka KeyboardInterrupt) shutdown the server
    def shutdown(*args):
        shutdown_socket.sendall(b" ")

    signal.signal(signal.SIGTERM, shutdown)
    signal.signal(signal.SIGINT, shutdown)

    try:
        server.serve(configuration, shutdown_socket_out)
    except Exception as e:
        logger.fatal("An exception occurred during server startup: %s",
                     e,
                     exc_info=True)
        exit(1)
Пример #13
0
def run():
    """Run Radicale as a standalone server."""

    # Raise SystemExit when signal arrives to run cleanup code
    # (like destructors, try-finish etc.), otherwise the process exits
    # without running any of them
    def signal_handler(signal_number, stack_frame):
        sys.exit(1)

    signal.signal(signal.SIGTERM, signal_handler)
    signal.signal(signal.SIGINT, signal_handler)
    if os.name == "posix":
        signal.signal(signal.SIGHUP, signal_handler)

    log.setup()

    # Get command-line arguments
    parser = argparse.ArgumentParser(prog="radicale",
                                     usage="%(prog)s [OPTIONS]")

    parser.add_argument("--version", action="version", version=VERSION)
    parser.add_argument("--verify-storage",
                        action="store_true",
                        help="check the storage for errors and exit")
    parser.add_argument("-C",
                        "--config",
                        help="use specific configuration files",
                        nargs="*")
    parser.add_argument("-D",
                        "--debug",
                        action="store_true",
                        help="print debug information")

    groups = {}
    for section, values in config.DEFAULT_CONFIG_SCHEMA.items():
        if section.startswith("_"):
            continue
        group = parser.add_argument_group(section)
        groups[group] = []
        for option, data in values.items():
            if option.startswith("_"):
                continue
            kwargs = data.copy()
            long_name = "--%s-%s" % (section, option.replace("_", "-"))
            args = kwargs.pop("aliases", [])
            args.append(long_name)
            kwargs["dest"] = "%s_%s" % (section, option)
            groups[group].append(kwargs["dest"])
            del kwargs["value"]
            with contextlib.suppress(KeyError):
                del kwargs["internal"]

            if kwargs["type"] == bool:
                del kwargs["type"]
                kwargs["action"] = "store_const"
                kwargs["const"] = "True"
                opposite_args = kwargs.pop("opposite", [])
                opposite_args.append("--no%s" % long_name[1:])
                group.add_argument(*args, **kwargs)

                kwargs["const"] = "False"
                kwargs["help"] = "do not %s (opposite of %s)" % (
                    kwargs["help"], long_name)
                group.add_argument(*opposite_args, **kwargs)
            else:
                del kwargs["type"]
                group.add_argument(*args, **kwargs)

    args = parser.parse_args()

    # Preliminary configure logging
    if args.debug:
        args.logging_level = "debug"
    with contextlib.suppress(ValueError):
        log.set_level(config.DEFAULT_CONFIG_SCHEMA["logging"]["level"]["type"](
            args.logging_level))

    # Update Radicale configuration according to arguments
    arguments_config = {}
    for group, actions in groups.items():
        section = group.title
        section_config = {}
        for action in actions:
            value = getattr(args, action)
            if value is not None:
                section_config[action.split('_', 1)[1]] = value
        if section_config:
            arguments_config[section] = section_config

    try:
        configuration = config.load(
            config.parse_compound_paths(
                config.DEFAULT_CONFIG_PATH, os.environ.get("RADICALE_CONFIG"),
                os.pathsep.join(args.config) if args.config else None))
        if arguments_config:
            configuration.update(arguments_config, "arguments")
    except Exception as e:
        logger.fatal("Invalid configuration: %s", e, exc_info=True)
        sys.exit(1)

    # Configure logging
    log.set_level(configuration.get("logging", "level"))

    # Log configuration after logger is configured
    for source, miss in configuration.sources():
        logger.info("%s %s", "Skipped missing" if miss else "Loaded", source)

    if args.verify_storage:
        logger.info("Verifying storage")
        try:
            storage_ = storage.load(configuration)
            with storage_.acquire_lock("r"):
                if not storage_.verify():
                    logger.fatal("Storage verifcation failed")
                    sys.exit(1)
        except Exception as e:
            logger.fatal(
                "An exception occurred during storage verification: "
                "%s",
                e,
                exc_info=True)
            sys.exit(1)
        return

    try:
        server.serve(configuration)
    except Exception as e:
        logger.fatal("An exception occurred during server startup: %s",
                     e,
                     exc_info=True)
        sys.exit(1)