depot.py revision 1836
3177N/A#!/usr/bin/python2.6
20N/A#
20N/A# CDDL HEADER START
20N/A#
20N/A# The contents of this file are subject to the terms of the
20N/A# Common Development and Distribution License (the "License").
20N/A# You may not use this file except in compliance with the License.
20N/A#
20N/A# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
20N/A# or http://www.opensolaris.org/os/licensing.
20N/A# See the License for the specific language governing permissions
20N/A# and limitations under the License.
20N/A#
20N/A# When distributing Covered Code, include this CDDL HEADER in each
20N/A# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
20N/A# If applicable, add the following below this CDDL HEADER, with the
20N/A# fields enclosed by brackets "[]" replaced with your own identifying
20N/A# information: Portions Copyright [yyyy] [name of copyright owner]
20N/A#
20N/A# CDDL HEADER END
20N/A#
3158N/A# Copyright 2010 Sun Microsystems, Inc. All rights reserved.
20N/A# Use is subject to license terms.
20N/A#
3143N/A
3143N/A# pkg.depotd - package repository daemon
22N/A
0N/A# XXX The prototype pkg.depotd combines both the version management server that
50N/A# answers to pkgsend(1) sessions and the HTTP file server that answers to the
50N/A# various GET operations that a pkg(1) client makes. This split is expected to
50N/A# be made more explicit, by constraining the pkg(1) operations such that they
50N/A# can be served as a typical HTTP/HTTPS session. Thus, pkg.depotd will reduce
50N/A# to a special purpose HTTP/HTTPS server explicitly for the version management
50N/A# operations, and must manipulate the various state files--catalogs, in
50N/A# particular--such that the pkg(1) pull client can operately accurately with
50N/A# only a basic HTTP/HTTPS server in place.
50N/A
50N/A# XXX Although we pushed the evaluation of next-version, etc. to the pull
50N/A# client, we should probably provide a query API to do same on the server, for
50N/A# dumb clients (like a notification service).
50N/A
50N/A# The default repository path.
589N/AREPO_PATH_DEFAULT = "/var/pkg/repo"
589N/A# The default path for static and other web content.
965N/ACONTENT_PATH_DEFAULT = "/usr/share/lib/pkg"
965N/A# cherrypy has a max_request_body_size parameter that determines whether the
965N/A# server should abort requests with REQUEST_ENTITY_TOO_LARGE when the request
965N/A# body is larger than the specified size (in bytes). The maximum size supported
965N/A# by cherrypy is 2048 * 1024 * 1024 - 1 (just short of 2048MB), but the default
2951N/A# here is purposefully conservative.
1836N/AMAX_REQUEST_BODY_SIZE = 128 * 1024 * 1024
1836N/A# The default host/port(s) to serve data from.
382N/AHOST_DEFAULT = "0.0.0.0"
812N/APORT_DEFAULT = 80
382N/ASSL_PORT_DEFAULT = 443
382N/A# The minimum number of threads allowed.
382N/ATHREADS_MIN = 1
1963N/A# The default number of threads to start.
382N/ATHREADS_DEFAULT = 10
1963N/A# The maximum number of threads that can be started.
382N/ATHREADS_MAX = 500
382N/A# The default server socket timeout in seconds. We want this to be longer than
382N/A# the normal default of 10 seconds to accommodate clients with poor quality
382N/A# connections.
382N/ASOCKET_TIMEOUT_DEFAULT = 60
26N/A# Whether modify operations should be allowed.
689N/AREADONLY_DEFAULT = False
689N/A# Whether the repository catalog should be rebuilt on startup.
466N/AREBUILD_DEFAULT = False
0N/A# Whether the indexes should be rebuilt
468N/AREINDEX_DEFAULT = False
812N/A# Not in mirror mode by default
3273N/AMIRROR_DEFAULT = False
812N/A
52N/Aimport getopt
812N/Aimport gettext
0N/Aimport locale
3194N/Aimport logging
3234N/Aimport os
3194N/Aimport os.path
382N/Aimport OpenSSL.crypto as crypto
382N/Aimport subprocess
382N/Aimport sys
3234N/Aimport tempfile
3234N/Aimport urlparse
382N/A
3234N/Atry:
382N/A import cherrypy
382N/A version = cherrypy.__version__.split('.')
3143N/A if map(int, version) < [3, 1, 0]:
3194N/A raise ImportError
382N/A elif map(int, version) >= [3, 2, 0]:
22N/A raise ImportError
1836N/Aexcept ImportError:
2507N/A print >> sys.stderr, """cherrypy 3.1.0 or greater (but less than """ \
1836N/A """3.2.0) is required to use this program."""
1836N/A sys.exit(2)
2962N/A
2962N/Aimport cherrypy.process.servers
2962N/A
1431N/Afrom pkg.misc import msg, emsg, setlocale
1968N/Aimport pkg.client.api_errors as api_errors
873N/Aimport pkg.indexer as indexer
812N/Aimport pkg.portable.util as os_util
1431N/Aimport pkg.search_errors as search_errors
873N/Aimport pkg.server.depot as ds
1431N/Aimport pkg.server.depotresponse as dr
466N/Aimport pkg.server.repository as sr
1431N/Aimport pkg.server.repositoryconfig as rc
466N/A
466N/A
466N/Aclass LogSink(object):
23N/A """This is a dummy object that we can use to discard log entries
466N/A without relying on non-portable interfaces such as /dev/null."""
466N/A
466N/A def write(self, *args, **kwargs):
466N/A """Discard the bits."""
466N/A pass
466N/A
466N/A def flush(self, *args, **kwargs):
466N/A """Discard the bits."""
1431N/A pass
1633N/A
1633N/A
1633N/Adef usage(text=None, retcode=2, full=False):
1633N/A """Optionally emit a usage message and then exit using the specified
466N/A exit code."""
466N/A
466N/A if text:
1633N/A emsg(text)
1633N/A
1633N/A if not full:
1633N/A # The full usage message isn't desired.
1633N/A emsg(_("Try `pkg.depotd --help or -?' for more "
1633N/A "information."))
3143N/A sys.exit(retcode)
2230N/A
1968N/A print """\
1633N/AUsage: /usr/lib/pkg.depotd [-d repo_dir] [-p port] [-s threads]
2515N/A [-t socket_timeout] [--cfg-file] [--content-root]
2816N/A [--disable-ops op[/1][,...]] [--debug feature_list]
2816N/A [--log-access dest] [--log-errors dest] [--mirror] [--nasty]
1937N/A [--set-property <section.property>=<value>]
382N/A [--proxy-base url] [--readonly] [--rebuild] [--ssl-cert-file]
2230N/A [--ssl-dialog] [--ssl-key-file] [--sort-file-max-size size]
2230N/A [--writable-root dir]
2230N/A
2230N/A --add-content Check the repository on startup and add any new
2028N/A packages found. Cannot be used with --mirror or
1968N/A --readonly.
1968N/A --cfg-file The pathname of the file from which to read and to
2028N/A write configuration information.
1968N/A --content-root The file system path to the directory containing the
1968N/A the static and other web content used by the depot's
1968N/A browser user interface. The default value is
2028N/A '/usr/share/lib/pkg'.
2028N/A --disable-ops A comma separated list of operations that the depot
2028N/A should not configure. If, for example, you wanted
1968N/A to omit loading search v1, 'search/1' should be
1968N/A provided as an argument, or to disable all search
1968N/A operations, simply 'search'.
1968N/A --debug The name of a debug feature to enable; or a whitespace
1968N/A or comma separated list of features to enable.
1968N/A Possible values are: headers.
589N/A --exit-ready Perform startup processing (including rebuilding
589N/A catalog or indices, if requested) and exit when
589N/A ready to start serving packages.
589N/A --log-access The destination for any access related information
1431N/A logged by the depot process. Possible values are:
1431N/A stderr, stdout, none, or an absolute pathname. The
1431N/A default value is stdout if stdout is a tty; otherwise
1431N/A the default value is none.
1431N/A --log-errors The destination for any errors or other information
858N/A logged by the depot process. Possible values are:
1633N/A stderr, stdout, none, or an absolute pathname. The
2962N/A default value is stderr.
3053N/A --mirror Package mirror mode; publishing and metadata operations
2515N/A disallowed. Cannot be used with --readonly or
2515N/A --rebuild.
466N/A --nasty Instruct the server to misbehave. At random intervals
466N/A it will time-out, send bad responses, hang up on
466N/A clients, and generally be hostile. The option
466N/A takes a value (1 to 100) for how nasty the server
466N/A should be.
466N/A --proxy-base The url to use as the base for generating internal
466N/A redirects and content.
466N/A --readonly Read-only operation; modifying operations disallowed.
466N/A Cannot be used with --mirror or --rebuild.
589N/A --rebuild Re-build the catalog from pkgs in depot. Cannot be
589N/A used with --mirror or --readonly.
589N/A --set-property Used to specify initial repository configuration
1191N/A property values or to update existing ones; can
1191N/A be specified multiple times. If used with --readonly
1191N/A this acts as a temporary override.
1191N/A --ssl-cert-file The absolute pathname to a PEM-encoded Certificate file.
1191N/A This option must be used with --ssl-key-file. Usage of
2816N/A this option will cause the depot to only respond to SSL
2816N/A requests on the provided port.
589N/A --ssl-dialog Specifies what method should be used to obtain the
589N/A passphrase needed to decrypt the file specified by
589N/A --ssl-key-file. Supported values are: builtin,
589N/A exec:/path/to/program, or smf:fmri. The default value
812N/A is builtin.
812N/A --ssl-key-file The absolute pathname to a PEM-encoded Private Key file.
812N/A This option must be used with --ssl-cert-file. Usage of
812N/A this option will cause the depot to only respond to SSL
812N/A requests on the provided port.
812N/A --sort-file-max-size
812N/A The maximum size of the indexer sort file. Used to
1968N/A limit the amount of RAM the depot uses for indexing,
1968N/A or increase it for speed.
1968N/A --writable-root The path to a directory to which the program has write
812N/A access. Used with --readonly to allow server to
812N/A create needed files, such as search indices, without
812N/A needing write access to the package information.
812N/A
1475N/AOptions:
1475N/A --help or -?
1475N/A
1475N/AEnvironment:
975N/A PKG_REPO Used as default repo_dir if -d not provided.
975N/A PKG_DEPOT_CONTENT Used as default content_root if --content-root
975N/A not provided."""
975N/A sys.exit(retcode)
1633N/A
1633N/Aclass OptionError(Exception):
1633N/A """Option exception. """
1633N/A
2028N/A def __init__(self, *args):
1633N/A Exception.__init__(self, *args)
3143N/A
1633N/Aif __name__ == "__main__":
14N/A
382N/A setlocale(locale.LC_ALL, "")
429N/A gettext.install("pkg", "/usr/share/locale")
14N/A
404N/A debug_features = {
404N/A "headers": False,
30N/A }
382N/A disable_ops = {}
30N/A port = PORT_DEFAULT
791N/A port_provided = False
2728N/A threads = THREADS_DEFAULT
2728N/A socket_timeout = SOCKET_TIMEOUT_DEFAULT
689N/A readonly = READONLY_DEFAULT
1968N/A rebuild = REBUILD_DEFAULT
1968N/A reindex = REINDEX_DEFAULT
1968N/A proxy_base = None
1968N/A mirror = MIRROR_DEFAULT
1191N/A nasty = False
258N/A nasty_value = 0
1968N/A repo_config_file = None
2816N/A sort_file_max_size = indexer.SORT_FILE_MAX_SIZE
382N/A ssl_cert_file = None
1968N/A ssl_key_file = None
30N/A ssl_dialog = "builtin"
589N/A writable_root = None
589N/A add_content = False
1968N/A exit_ready = False
589N/A
589N/A if "PKG_REPO" in os.environ:
589N/A repo_path = os.environ["PKG_REPO"]
589N/A else:
1968N/A repo_path = REPO_PATH_DEFAULT
589N/A
1968N/A try:
466N/A content_root = os.environ["PKG_DEPOT_CONTENT"]
466N/A except KeyError:
2230N/A try:
1968N/A content_root = os.path.join(os.environ['PKG_HOME'],
1968N/A 'share/lib/pkg')
1431N/A except KeyError:
1968N/A content_root = CONTENT_PATH_DEFAULT
1968N/A
54N/A # By default, if the destination for a particular log type is not
1968N/A # specified, this is where we will send the output.
1968N/A log_routes = {
2515N/A "access": "none",
2816N/A "errors": "stderr"
2816N/A }
2816N/A log_opts = ["--log-%s" % log_type for log_type in log_routes]
2816N/A
1475N/A # If stdout is a tty, then send access output there by default instead
2230N/A # of discarding it.
466N/A if os.isatty(sys.stdout.fileno()):
1633N/A log_routes["access"] = "stdout"
1633N/A
135N/A opt = None
2230N/A repo_props = {}
2230N/A try:
2230N/A long_opts = ["add-content", "cfg-file=", "content-root=",
135N/A "debug=", "disable-ops=", "exit-ready", "help", "mirror",
135N/A "nasty=", "set-property=", "proxy-base=", "readonly",
1968N/A "rebuild", "refresh-index", "ssl-cert-file=", "ssl-dialog=",
135N/A "ssl-key-file=", "sort-file-max-size=", "writable-root="]
1968N/A
382N/A for opt in log_opts:
382N/A long_opts.append("%s=" % opt.lstrip('--'))
382N/A opts, pargs = getopt.getopt(sys.argv[1:], "d:np:s:t:?",
3194N/A long_opts)
3158N/A
3194N/A show_usage = False
382N/A for opt, arg in opts:
3194N/A if opt == "-n":
3158N/A sys.exit(0)
3194N/A elif opt == "-d":
1968N/A repo_path = arg
382N/A elif opt == "-p":
1968N/A port = int(arg)
1542N/A port_provided = True
1542N/A elif opt == "-s":
1968N/A threads = int(arg)
1968N/A if threads < THREADS_MIN:
812N/A raise OptionError, \
1968N/A "minimum value is %d" % THREADS_MIN
589N/A if threads > THREADS_MAX:
1968N/A raise OptionError, \
858N/A "maximum value is %d" % THREADS_MAX
858N/A elif opt == "-t":
1968N/A socket_timeout = int(arg)
858N/A elif opt == "--add-content":
858N/A add_content = True
858N/A elif opt == "--cfg-file":
858N/A repo_config_file = os.path.abspath(arg)
858N/A elif opt == "--content-root":
858N/A if arg == "":
858N/A raise OptionError, "You must specify " \
1968N/A "a directory path."
2962N/A content_root = arg
2962N/A elif opt == "--debug":
2962N/A if arg is None or arg == "":
2962N/A raise OptionError, \
2962N/A "A debug feature must be specified."
2962N/A
2962N/A # A list of features can be specified using a
2962N/A # "," or any whitespace character as separators.
2962N/A if "," in arg:
2962N/A features = arg.split(",")
1431N/A else:
1431N/A features = arg.split()
3194N/A
3194N/A for f in features:
1431N/A if f not in debug_features:
1431N/A raise OptionError, \
1431N/A "Invalid debug feature: " \
1431N/A "%s." % f
1431N/A debug_features[f] = True
1431N/A elif opt == "--disable-ops":
1431N/A if arg is None or arg == "":
1431N/A raise OptionError, \
1431N/A "An argument must be specified."
1431N/A
1431N/A disableops = arg.split(",")
1431N/A for s in disableops:
1431N/A if "/" in s:
3158N/A op, ver = s.rsplit("/", 1)
1968N/A else:
1542N/A op = s
1542N/A ver = "*"
2515N/A
2515N/A if op not in \
1968N/A ds.DepotHTTP.REPO_OPS_DEFAULT:
3158N/A raise OptionError(
1968N/A "Invalid operation "
1633N/A "'%s'." % s)
1633N/A
589N/A disable_ops.setdefault(op, [])
1968N/A disable_ops[op].append(ver)
1902N/A elif opt == "--exit-ready":
1968N/A exit_ready = True
1968N/A elif opt in log_opts:
1968N/A if arg is None or arg == "":
1191N/A raise OptionError, \
2816N/A "You must specify a log " \
2816N/A "destination."
2816N/A log_routes[opt.lstrip("--log-")] = arg
3194N/A elif opt in ("--help", "-?"):
3194N/A show_usage = True
3194N/A elif opt == "--mirror":
1191N/A mirror = True
2816N/A elif opt == "--nasty":
2816N/A value_err = None
2816N/A try:
2816N/A nasty_value = int(arg)
2816N/A except ValueError, e:
589N/A value_err = e
589N/A
589N/A if value_err or (nasty_value > 100 or
589N/A nasty_value < 1):
589N/A raise OptionError, "Invalid value " \
589N/A "for nasty option.\n Please " \
3234N/A "choose a value between 1 and 100."
765N/A nasty = True
765N/A elif opt == "--set-property":
765N/A try:
3194N/A prop, p_value = arg.split("=", 1)
3194N/A p_sec, p_name = prop.split(".", 1)
3194N/A except ValueError:
3194N/A usage(_("property arguments must be of "
589N/A "the form '<section.property>="
765N/A "<value>'."))
765N/A repo_props.setdefault(p_sec, {})
3194N/A repo_props[p_sec][p_name] = p_value
3194N/A elif opt == "--proxy-base":
3194N/A # Attempt to decompose the url provided into
765N/A # its base parts. This is done so we can
765N/A # remove any scheme information since we
1968N/A # don't need it.
3234N/A scheme, netloc, path, params, query, \
1968N/A fragment = urlparse.urlparse(arg,
135N/A "http", allow_fragments=0)
1968N/A
157N/A if not netloc:
382N/A raise OptionError, "Unable to " \
429N/A "determine the hostname from " \
429N/A "the provided URL; please use a " \
2028N/A "fully qualified URL."
2028N/A
429N/A scheme = scheme.lower()
429N/A if scheme not in ("http", "https"):
429N/A raise OptionError, "Invalid URL; http " \
429N/A "and https are the only supported " \
429N/A "schemes."
429N/A
429N/A # Rebuild the url with the sanitized components.
2028N/A proxy_base = urlparse.urlunparse((scheme,
1968N/A netloc, path, params, query, fragment))
1968N/A elif opt == "--readonly":
1968N/A readonly = True
1968N/A elif opt == "--rebuild":
1968N/A rebuild = True
1968N/A elif opt == "--refresh-index":
1968N/A # Note: This argument is for internal use
1968N/A # only. It's used when pkg.depotd is reexecing
1968N/A # itself and needs to know that's the case.
1968N/A # This flag is purposefully omitted in usage.
812N/A # The supported way to forcefully reindex is to
1968N/A # kill any pkg.depot using that directory,
1968N/A # remove the index directory, and restart the
1968N/A # pkg.depot process. The index will be rebuilt
1968N/A # automatically on startup.
1968N/A reindex = True
3194N/A elif opt == "--ssl-cert-file":
3194N/A if arg == "none":
3194N/A continue
1968N/A
3194N/A ssl_cert_file = arg
3194N/A if not os.path.isabs(ssl_cert_file):
1968N/A raise OptionError, "The path to " \
3194N/A "the Certificate file must be " \
3194N/A "absolute."
1968N/A elif not os.path.exists(ssl_cert_file):
812N/A raise OptionError, "The specified " \
1968N/A "file does not exist."
1968N/A elif not os.path.isfile(ssl_cert_file):
1968N/A raise OptionError, "The specified " \
1968N/A "pathname is not a file."
1968N/A elif opt == "--ssl-key-file":
3194N/A if arg == "none":
3194N/A continue
3194N/A
1968N/A ssl_key_file = arg
3194N/A if not os.path.isabs(ssl_key_file):
3194N/A raise OptionError, "The path to " \
1968N/A "the Private Key file must be " \
3194N/A "absolute."
3194N/A elif not os.path.exists(ssl_key_file):
1968N/A raise OptionError, "The specified " \
812N/A "file does not exist."
1968N/A elif not os.path.isfile(ssl_key_file):
1968N/A raise OptionError, "The specified " \
812N/A "pathname is not a file."
1968N/A elif opt == "--ssl-dialog":
3194N/A if arg != "builtin" and not \
3194N/A arg.startswith("exec:/") and not \
3194N/A arg.startswith("smf:"):
3194N/A raise OptionError, "Invalid value " \
812N/A "specified. Expected: builtin, " \
1968N/A "exec:/path/to/program, or " \
812N/A "smf:fmri."
812N/A
873N/A f = arg
873N/A if f.startswith("exec:"):
873N/A if os_util.get_canonical_os_type() != \
3194N/A "unix":
3194N/A # Don't allow a somewhat
3194N/A # insecure authentication method
3194N/A # on some platforms.
812N/A raise OptionError, "exec is " \
1968N/A "not a supported dialog " \
812N/A "type for this operating " \
812N/A "system."
3194N/A
3194N/A f = os.path.abspath(f.split(
3194N/A "exec:")[1])
1968N/A
1475N/A if not os.path.isfile(f):
1968N/A raise OptionError, "Invalid " \
975N/A "file path specified for " \
1968N/A "exec."
1968N/A
1968N/A f = "exec:%s" % f
1968N/A
1968N/A ssl_dialog = f
1968N/A elif opt == "--sort-file-max-size":
1968N/A if arg == "":
2230N/A raise OptionError, "You must specify " \
2230N/A "a maximum sort file size."
1968N/A sort_file_max_size = arg
2962N/A elif opt == "--writable-root":
2962N/A if arg == "":
2962N/A raise OptionError, "You must specify " \
1968N/A "a directory path."
1968N/A writable_root = arg
3171N/A except getopt.GetoptError, _e:
3158N/A usage("pkg.depotd: %s" % _e.msg)
3171N/A except OptionError, _e:
3158N/A usage("pkg.depotd: option: %s -- %s" % (opt, _e))
3171N/A except (ArithmeticError, ValueError):
3158N/A usage("pkg.depotd: illegal option value: %s specified " \
382N/A "for option: %s" % (arg, opt))
3158N/A
3158N/A if show_usage:
451N/A usage(retcode=0, full=True)
1633N/A
1633N/A if rebuild and add_content:
1633N/A usage("--add-content cannot be used with --rebuild")
1968N/A if rebuild and reindex:
1968N/A usage("--refresh-index cannot be used with --rebuild")
1968N/A if (rebuild or add_content) and (readonly or mirror):
1968N/A usage("--readonly and --mirror cannot be used with --rebuild "
1968N/A "or --add-content")
1968N/A if reindex and mirror:
1968N/A usage("--mirror cannot be used with --refresh-index")
1968N/A if reindex and readonly and not writable_root:
1968N/A usage("--readonly can only be used with --refresh-index if "
1968N/A "--writable-root is used")
1968N/A
1968N/A if (ssl_cert_file and not ssl_key_file) or (ssl_key_file and not
2515N/A ssl_cert_file):
2515N/A usage("The --ssl-cert-file and --ssl-key-file options must "
1968N/A "must both be provided when using either option.")
2230N/A elif ssl_cert_file and ssl_key_file and not port_provided:
1968N/A # If they didn't already specify a particular port, use the
1968N/A # default SSL port instead.
1542N/A port = SSL_PORT_DEFAULT
1542N/A
445N/A # If the program is going to reindex, the port is irrelevant since
466N/A # the program will not bind to a port.
1542N/A if not reindex and not exit_ready:
1633N/A try:
1633N/A cherrypy.process.servers.check_port(HOST_DEFAULT, port)
1020N/A except Exception, e:
1020N/A emsg("pkg.depotd: unable to bind to the specified "
1020N/A "port: %d. Reason: %s" % (port, e))
1020N/A sys.exit(1)
1020N/A else:
2515N/A # Not applicable if we're not going to serve content
2515N/A content_root = None
2515N/A
2515N/A key_data = None
2515N/A if not reindex and ssl_cert_file and ssl_key_file and \
2515N/A ssl_dialog != "builtin":
2515N/A cmdline = None
2515N/A def get_ssl_passphrase(*ignored):
2515N/A p = None
2515N/A try:
2515N/A p = subprocess.Popen(cmdline, shell=True,
451N/A stdout=subprocess.PIPE,
1968N/A stderr=None)
2230N/A p.wait()
2230N/A except Exception, __e:
2230N/A emsg("pkg.depotd: an error occurred while "
2230N/A "executing [%s]; unable to obtain the "
2230N/A "passphrase needed to decrypt the SSL "
2230N/A "private key file: %s" % (cmdline, __e))
2230N/A sys.exit(1)
2230N/A return p.stdout.read().strip("\n")
2230N/A
2230N/A if ssl_dialog.startswith("exec:"):
2515N/A cmdline = "%s %s %d" % (ssl_dialog.split("exec:")[1],
2515N/A "''", port)
1902N/A elif ssl_dialog.startswith("smf:"):
1968N/A cmdline = "/usr/bin/svcprop -p " \
1968N/A "pkg_secure/ssl_key_passphrase %s" % (
1968N/A ssl_dialog.split("smf:")[1])
1968N/A
1968N/A # The key file requires decryption, but the user has requested
1968N/A # exec-based authentication, so it will have to be decoded first
1968N/A # to an un-named temporary file.
1968N/A try:
812N/A key_file = file(ssl_key_file, "rb")
812N/A pkey = crypto.load_privatekey(crypto.FILETYPE_PEM,
812N/A key_file.read(), get_ssl_passphrase)
812N/A
1968N/A key_data = tempfile.TemporaryFile()
1968N/A key_data.write(crypto.dump_privatekey(
1968N/A crypto.FILETYPE_PEM, pkey))
1968N/A key_data.seek(0)
1968N/A except EnvironmentError, _e:
1968N/A emsg("pkg.depotd: unable to read the SSL private key "
1968N/A "file: %s" % _e)
1968N/A sys.exit(1)
1968N/A except crypto.Error, _e:
1968N/A emsg("pkg.depotd: authentication or cryptography "
1968N/A "failure while attempting to decode\nthe SSL "
1968N/A "private key file: %s" % _e)
1968N/A sys.exit(1)
1968N/A else:
1968N/A # Redirect the server to the decrypted key file.
1968N/A ssl_key_file = "/dev/fd/%d" % key_data.fileno()
1968N/A
812N/A # Setup our global configuration.
429N/A gconf = {
429N/A "checker.on": True,
2028N/A "environment": "production",
1836N/A "log.screen": False,
2230N/A "server.max_request_body_size": MAX_REQUEST_BODY_SIZE,
3171N/A "server.shutdown_timeout": 0,
1836N/A "server.socket_host": HOST_DEFAULT,
3158N/A "server.socket_port": port,
429N/A "server.socket_timeout": socket_timeout,
612N/A "server.ssl_certificate": ssl_cert_file,
1542N/A "server.ssl_private_key": ssl_key_file,
1968N/A "server.thread_pool": threads,
1968N/A "tools.log_headers.on": True,
1968N/A "tools.encode.on": True
1968N/A }
1968N/A
1968N/A if debug_features["headers"]:
1968N/A # Despite its name, this only logs headers when there is an
1968N/A # error; it's redundant with the debug feature enabled.
1968N/A gconf["tools.log_headers.on"] = False
1968N/A
1968N/A # Causes the headers of every request to be logged to the error
1968N/A # log; even if an exception occurs.
1968N/A gconf["tools.log_headers_always.on"] = True
1968N/A cherrypy.tools.log_headers_always = cherrypy.Tool(
1968N/A "on_start_resource",
1968N/A cherrypy.lib.cptools.log_request_headers)
1968N/A
1968N/A log_type_map = {
1968N/A "errors": {
1968N/A "param": "log.error_file",
1968N/A "attr": "error_log"
1968N/A },
1968N/A "access": {
1968N/A "param": "log.access_file",
1968N/A "attr": "access_log"
1968N/A }
1968N/A }
1968N/A
1968N/A for log_type in log_type_map:
1968N/A dest = log_routes[log_type]
1968N/A if dest in ("stdout", "stderr", "none"):
1968N/A if dest == "none":
1968N/A h = logging.StreamHandler(LogSink())
812N/A else:
1968N/A h = logging.StreamHandler(eval("sys.%s" % \
2028N/A dest))
812N/A
812N/A h.setLevel(logging.DEBUG)
812N/A h.setFormatter(cherrypy._cplogging.logfmt)
812N/A log_obj = eval("cherrypy.log.%s" % \
812N/A log_type_map[log_type]["attr"])
3273N/A log_obj.addHandler(h)
3273N/A # Since we've replaced cherrypy's log handler with our
3273N/A # own, we don't want the output directed to a file.
3273N/A dest = ""
3273N/A gconf[log_type_map[log_type]["param"]] = dest
812N/A
812N/A cherrypy.config.update(gconf)
812N/A
3171N/A # Now that our logging, etc. has been setup, it's safe to perform any
1836N/A # remaining preparation.
3158N/A
1836N/A # Initialize repository state.
3158N/A fork_allowed = not reindex and not exit_ready
3158N/A try:
812N/A repo = sr.Repository(auto_create=not readonly,
812N/A cfgpathname=repo_config_file, fork_allowed=fork_allowed,
812N/A log_obj=cherrypy, mirror=mirror, properties=repo_props,
812N/A read_only=readonly, refresh_index=not add_content,
1968N/A repo_root=repo_path, sort_file_max_size=sort_file_max_size,
1968N/A writable_root=writable_root)
1968N/A except sr.RepositoryError, _e:
3158N/A emsg("pkg.depotd: %s" % _e)
1968N/A sys.exit(1)
1968N/A except rc.RequiredPropertyValueError, _e:
1968N/A emsg("pkg.depotd: repository configuration error: %s" % _e)
1968N/A emsg("Please use the --set-property option to provide a value, "
1968N/A "or update the cfg_cache file for the repository to "
1968N/A "correct this.")
1968N/A sys.exit(1)
1968N/A except rc.PropertyError, _e:
812N/A emsg("pkg.depotd: repository configuration error: %s" % _e)
3158N/A sys.exit(1)
812N/A except search_errors.IndexingException, _e:
812N/A emsg("pkg.depotd: %s" % str(_e), "INDEX")
812N/A sys.exit(1)
812N/A except (api_errors.UnknownErrors, api_errors.PermissionsException), _e:
812N/A emsg("pkg.depotd: %s" % str(_e))
3234N/A sys.exit(1)
1968N/A
1968N/A if reindex:
1968N/A # Initializing the repository above updated search indices
812N/A # as needed; nothing left to do, so exit.
812N/A sys.exit(0)
812N/A
812N/A if nasty:
812N/A repo.cfg.set_nasty(nasty_value)
3171N/A
1836N/A if rebuild:
3158N/A try:
812N/A repo.rebuild()
3171N/A except sr.RepositoryError, e:
1836N/A emsg(str(e), "REBUILD")
1836N/A sys.exit(1)
3158N/A except (search_errors.IndexingException,
812N/A api_errors.UnknownErrors,
812N/A api_errors.PermissionsException), e:
812N/A emsg(str(e), "INDEX")
3158N/A sys.exit(1)
812N/A
452N/A elif add_content:
466N/A try:
858N/A repo.add_content()
382N/A except sr.RepositoryError, e:
466N/A emsg(str(e), "ADD_CONTENT")
965N/A sys.exit(1)
858N/A except (search_errors.IndexingException,
2230N/A api_errors.UnknownErrors,
382N/A api_errors.PermissionsException), e:
858N/A emsg(str(e), "INDEX")
858N/A sys.exit(1)
858N/A
382N/A # ready to start depot; exit now if requested
742N/A if exit_ready:
858N/A sys.exit(0)
466N/A
466N/A # Next, initialize depot.
1968N/A if nasty:
858N/A depot = ds.NastyDepotHTTP(repo, content_root,
858N/A disable_ops=disable_ops)
858N/A else:
858N/A depot = ds.DepotHTTP(repo, content_root,
858N/A disable_ops=disable_ops)
858N/A
858N/A # Now build our site configuration.
858N/A conf = {
858N/A "/": {
858N/A # We have to override cherrypy's default response_class so that
858N/A # we have access to the write() callable to stream data
2992N/A # directly to the client.
2992N/A "wsgi.response_class": dr.DepotResponse,
2992N/A },
2992N/A "/robots.txt": {
2992N/A "tools.staticfile.on": True,
2992N/A "tools.staticfile.filename": os.path.join(depot.web_root,
2992N/A "robots.txt")
2992N/A },
2992N/A }
2992N/A
2992N/A if proxy_base:
2992N/A # This changes the base URL for our server, and is primarily
2992N/A # intended to allow our depot process to operate behind Apache
3158N/A # or some other webserver process.
3158N/A #
2992N/A # Visit the following URL for more information:
3158N/A # http://cherrypy.org/wiki/BuiltinTools#tools.proxy
3158N/A proxy_conf = {
2992N/A "tools.proxy.on": True,
2992N/A "tools.proxy.local": "",
2992N/A "tools.proxy.base": proxy_base
2992N/A }
3158N/A
3158N/A # Now merge or add our proxy configuration information into the
2992N/A # existing configuration.
3158N/A for entry in proxy_conf:
3158N/A conf["/"][entry] = proxy_conf[entry]
2992N/A
2992N/A try:
2992N/A root = cherrypy.Application(depot)
466N/A cherrypy.quickstart(root, config=conf)
466N/A except Exception, _e:
466N/A emsg("pkg.depotd: unknown error starting depot server, " \
466N/A "illegal option value specified?")
466N/A emsg(_e)
466N/A sys.exit(1)
466N/A