depot.py revision 2507
1516N/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#
2230N/A# Copyright (c) 2007, 2011 Oracle and/or its affiliates. All rights reserved.
20N/A#
20N/A
22N/A# pkg.depotd - package repository daemon
0N/A
50N/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
589N/A# The default path for static and other web content.
589N/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
965N/A# here is purposefully conservative.
965N/AMAX_REQUEST_BODY_SIZE = 128 * 1024 * 1024
1836N/A# The default host/port(s) to serve data from.
1836N/AHOST_DEFAULT = "0.0.0.0"
382N/APORT_DEFAULT = 80
812N/ASSL_PORT_DEFAULT = 443
382N/A# The minimum number of threads allowed.
382N/ATHREADS_MIN = 1
382N/A# The default number of threads to start.
1963N/ATHREADS_DEFAULT = 60
382N/A# The maximum number of threads that can be started.
1963N/ATHREADS_MAX = 5000
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
382N/A
26N/Aimport getopt
689N/Aimport gettext
689N/Aimport locale
466N/Aimport logging
0N/Aimport os
468N/Aimport os.path
812N/Aimport OpenSSL.crypto as crypto
812N/Aimport subprocess
52N/Aimport sys
812N/Aimport tempfile
451N/Aimport urlparse
0N/A
382N/Atry:
382N/A import cherrypy
382N/A version = cherrypy.__version__.split('.')
452N/A if map(int, version) < [3, 1, 0]:
382N/A raise ImportError
452N/A elif map(int, version) >= [3, 2, 0]:
382N/A raise ImportError
382N/Aexcept ImportError:
751N/A print >> sys.stderr, """cherrypy 3.1.0 or greater (but less than """ \
751N/A """3.2.0) is required to use this program."""
382N/A sys.exit(2)
22N/A
1836N/Aimport cherrypy.process.servers
2507N/Afrom cherrypy.process.plugins import Daemonizer
1836N/A
1836N/Afrom pkg.misc import msg, emsg, setlocale
1431N/Aimport pkg.client.api_errors as api_errors
1968N/Aimport pkg.config as cfg
873N/Aimport pkg.portable.util as os_util
812N/Aimport pkg.search_errors as search_errors
1431N/Aimport pkg.server.depot as ds
873N/Aimport pkg.server.depotresponse as dr
1431N/Aimport pkg.server.repository as sr
466N/A
1431N/A
466N/Aclass LogSink(object):
466N/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."""
23N/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."""
466N/A pass
466N/A
1431N/A
1633N/Adef usage(text=None, retcode=2, full=False):
1633N/A """Optionally emit a usage message and then exit using the specified
1633N/A exit code."""
1633N/A
466N/A if text:
466N/A emsg(text)
466N/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."))
1633N/A sys.exit(retcode)
1633N/A
26N/A print """\
2230N/AUsage: /usr/lib/pkg.depotd [-a address] [-d inst_root] [-p port] [-s threads]
1968N/A [-t socket_timeout] [--cfg] [--content-root]
1633N/A [--disable-ops op[/1][,...]] [--debug feature_list]
1902N/A [--file-root dir] [--log-access dest] [--log-errors dest]
1968N/A [--mirror] [--nasty] [--proxy-base url] [--readonly]
2100N/A [--ssl-cert-file] [--ssl-dialog] [--ssl-key-file]
1937N/A [--sort-file-max-size size] [--writable-root dir]
382N/A
2230N/A -a address The IP address on which to listen for connections. The
2230N/A default value is 0.0.0.0 (INADDR_ANY) which will listen
2230N/A on all active interfaces. To listen on all active IPv6
2230N/A interfaces, use '::'.
2028N/A -d inst_root The file system path at which the server should find its
1968N/A repository data. Required unless PKG_REPO has been set
1968N/A in the environment.
2028N/A -p port The port number on which the instance should listen for
1968N/A incoming package requests. The default value is 80 if
1968N/A ssl certificate and key information has not been
1968N/A provided; otherwise, the default value is 443.
2028N/A -s threads The number of threads that will be started to serve
2028N/A requests. The default value is 10.
2028N/A -t timeout The maximum number of seconds the server should wait for
1968N/A a response from a client before closing a connection.
1968N/A The default value is 60.
1968N/A --cfg The pathname of the file to use when reading and writing
1968N/A depot configuration data, or a fully qualified service
1968N/A fault management resource identifier (FMRI) of the SMF
1968N/A service or instance to read configuration data from.
589N/A --content-root The file system path to the directory containing the
589N/A the static and other web content used by the depot's
589N/A browser user interface. The default value is
589N/A '/usr/share/lib/pkg'.
1431N/A --disable-ops A comma separated list of operations that the depot
1431N/A should not configure. If, for example, you wanted
1431N/A to omit loading search v1, 'search/1' should be
1431N/A provided as an argument, or to disable all search
1431N/A operations, simply 'search'.
858N/A --debug The name of a debug feature to enable; or a whitespace
1633N/A or comma separated list of features to enable.
1633N/A Possible values are: headers.
1902N/A --file-root The path to the root of the file content for a given
1902N/A repository. This is used to override the default,
2028N/A <inst_root>/file or <inst_root>/publisher/<prefix>/file.
466N/A --log-access The destination for any access related information
466N/A logged by the depot process. Possible values are:
466N/A stderr, stdout, none, or an absolute pathname. The
466N/A default value is stdout if stdout is a tty; otherwise
466N/A the default value is none.
466N/A --log-errors The destination for any errors or other information
466N/A logged by the depot process. Possible values are:
466N/A stderr, stdout, none, or an absolute pathname. The
466N/A default value is stderr.
589N/A --mirror Package mirror mode; publishing and metadata operations
589N/A disallowed. Cannot be used with --readonly or
589N/A --rebuild.
1191N/A --nasty Instruct the server to misbehave. At random intervals
1191N/A it will time-out, send bad responses, hang up on
1191N/A clients, and generally be hostile. The option
1191N/A takes a value (1 to 100) for how nasty the server
1191N/A should be.
589N/A --proxy-base The url to use as the base for generating internal
589N/A redirects and content.
589N/A --readonly Read-only operation; modifying operations disallowed.
589N/A Cannot be used with --mirror or --rebuild.
812N/A --ssl-cert-file The absolute pathname to a PEM-encoded Certificate file.
812N/A This option must be used with --ssl-key-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 --ssl-dialog Specifies what method should be used to obtain the
812N/A passphrase needed to decrypt the file specified by
812N/A --ssl-key-file. Supported values are: builtin,
1968N/A exec:/path/to/program, smf, or an SMF FMRI. The
1968N/A default value is builtin. If smf is specified, an
1968N/A SMF FMRI must be provided using the --cfg option.
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.
1475N/A --sort-file-max-size
1475N/A The maximum size of the indexer sort file. Used to
1475N/A limit the amount of RAM the depot uses for indexing,
1475N/A or increase it for speed.
975N/A --writable-root The path to a directory to which the program has write
975N/A access. Used with --readonly to allow server to
975N/A create needed files, such as search indices, without
975N/A needing write access to the package information.
1633N/AOptions:
1633N/A --help or -?
1633N/A
1633N/AEnvironment:
2028N/A PKG_REPO Used as default inst_root if -d not provided.
1633N/A PKG_DEPOT_CONTENT Used as default content_root if --content-root
1633N/A not provided."""
1633N/A sys.exit(retcode)
14N/A
382N/Aclass OptionError(Exception):
429N/A """Option exception. """
14N/A
404N/A def __init__(self, *args):
404N/A Exception.__init__(self, *args)
30N/A
382N/Aif __name__ == "__main__":
30N/A
791N/A setlocale(locale.LC_ALL, "")
689N/A gettext.install("pkg", "/usr/share/locale")
689N/A
1968N/A add_content = False
1968N/A exit_ready = False
1968N/A rebuild = False
1968N/A reindex = False
1191N/A nasty = False
1191N/A nasty_value = 0
258N/A
1968N/A # Track initial configuration values.
1968N/A ivalues = { "pkg": {} }
382N/A if "PKG_REPO" in os.environ:
1968N/A ivalues["pkg"]["inst_root"] = os.environ["PKG_REPO"]
30N/A
589N/A try:
589N/A content_root = os.environ["PKG_DEPOT_CONTENT"]
1968N/A ivalues["pkg"]["content_root"] = content_root
589N/A except KeyError:
589N/A try:
589N/A content_root = os.path.join(os.environ['PKG_HOME'],
589N/A 'share/lib/pkg')
1968N/A ivalues["pkg"]["content_root"] = content_root
589N/A except KeyError:
1968N/A pass
466N/A
466N/A opt = None
2230N/A addresses = set()
1968N/A debug_features = []
1968N/A disable_ops = []
1431N/A repo_props = {}
1968N/A socket_path = ""
1968N/A user_cfg = None
54N/A try:
1968N/A long_opts = ["add-content", "cfg=", "cfg-file=",
1968N/A "content-root=", "debug=", "disable-ops=", "exit-ready",
1968N/A "file-root=", "help", "log-access=", "log-errors=",
1968N/A "llmirror", "mirror", "nasty=", "proxy-base=", "readonly",
2100N/A "rebuild", "refresh-index", "set-property=",
1968N/A "ssl-cert-file=", "ssl-dialog=", "ssl-key-file=",
1968N/A "sort-file-max-size=", "writable-root="]
1475N/A
2230N/A opts, pargs = getopt.getopt(sys.argv[1:], "a:d:np:s:t:?",
466N/A long_opts)
1633N/A
1633N/A show_usage = False
135N/A for opt, arg in opts:
2230N/A if opt == "-a":
2230N/A addresses.add(arg)
2230N/A elif opt == "-n":
135N/A sys.exit(0)
135N/A elif opt == "-d":
1968N/A ivalues["pkg"]["inst_root"] = arg
135N/A elif opt == "-p":
1968N/A ivalues["pkg"]["port"] = arg
382N/A elif opt == "-s":
382N/A threads = int(arg)
382N/A if threads < THREADS_MIN:
382N/A raise OptionError, \
382N/A "minimum value is %d" % THREADS_MIN
382N/A if threads > THREADS_MAX:
382N/A raise OptionError, \
382N/A "maximum value is %d" % THREADS_MAX
1968N/A ivalues["pkg"]["threads"] = threads
382N/A elif opt == "-t":
1968N/A ivalues["pkg"]["socket_timeout"] = arg
1542N/A elif opt == "--add-content":
1542N/A add_content = True
1968N/A elif opt == "--cfg":
1968N/A user_cfg = arg
812N/A elif opt == "--cfg-file":
1968N/A ivalues["pkg"]["cfg_file"] = arg
589N/A elif opt == "--content-root":
1968N/A ivalues["pkg"]["content_root"] = arg
858N/A elif opt == "--debug":
858N/A if arg is None or arg == "":
1968N/A continue
858N/A
858N/A # A list of features can be specified using a
858N/A # "," or any whitespace character as separators.
858N/A if "," in arg:
858N/A features = arg.split(",")
858N/A else:
858N/A features = arg.split()
1968N/A debug_features.extend(features)
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:
1431N/A op, ver = s.rsplit("/", 1)
1431N/A else:
1431N/A op = s
1431N/A ver = "*"
1431N/A
1431N/A if op not in \
1431N/A ds.DepotHTTP.REPO_OPS_DEFAULT:
1431N/A raise OptionError(
1431N/A "Invalid operation "
1431N/A "'%s'." % s)
1968N/A disable_ops.append(s)
1542N/A elif opt == "--exit-ready":
1542N/A exit_ready = True
1968N/A elif opt == "--file-root":
1968N/A ivalues["pkg"]["file_root"] = arg
1968N/A elif opt.startswith("--log-"):
1968N/A prop = "log_%s" % opt.lstrip("--log-")
1968N/A ivalues["pkg"][prop] = arg
1633N/A elif opt in ("--help", "-?"):
1633N/A show_usage = True
589N/A elif opt == "--mirror":
1968N/A ivalues["pkg"]["mirror"] = True
1902N/A elif opt == "--llmirror":
1968N/A ivalues["pkg"]["mirror"] = True
1968N/A ivalues["pkg"]["ll_mirror"] = True
1968N/A ivalues["pkg"]["readonly"] = True
1191N/A elif opt == "--nasty":
1191N/A value_err = None
1191N/A try:
1191N/A nasty_value = int(arg)
1191N/A except ValueError, e:
1191N/A value_err = e
1191N/A
1191N/A if value_err or (nasty_value > 100 or
1191N/A nasty_value < 1):
1191N/A raise OptionError, "Invalid value " \
1191N/A "for nasty option.\n Please " \
1191N/A "choose a value between 1 and 100."
1191N/A nasty = True
589N/A elif opt == "--proxy-base":
589N/A # Attempt to decompose the url provided into
589N/A # its base parts. This is done so we can
589N/A # remove any scheme information since we
589N/A # don't need it.
589N/A scheme, netloc, path, params, query, \
589N/A fragment = urlparse.urlparse(arg,
765N/A "http", allow_fragments=0)
765N/A
765N/A if not netloc:
765N/A raise OptionError, "Unable to " \
765N/A "determine the hostname from " \
765N/A "the provided URL; please use a " \
765N/A "fully qualified URL."
589N/A
765N/A scheme = scheme.lower()
765N/A if scheme not in ("http", "https"):
765N/A raise OptionError, "Invalid URL; http " \
765N/A "and https are the only supported " \
765N/A "schemes."
765N/A
765N/A # Rebuild the url with the sanitized components.
1968N/A ivalues["pkg"]["proxy_base"] = \
1968N/A urlparse.urlunparse((scheme, netloc, path,
1968N/A params, query, fragment))
135N/A elif opt == "--readonly":
1968N/A ivalues["pkg"]["readonly"] = True
157N/A elif opt == "--rebuild":
382N/A rebuild = True
429N/A elif opt == "--refresh-index":
429N/A # Note: This argument is for internal use
2028N/A # only.
2028N/A #
429N/A # This flag is purposefully omitted in usage.
429N/A # The supported way to forcefully reindex is to
429N/A # kill any pkg.depot using that directory,
429N/A # remove the index directory, and restart the
429N/A # pkg.depot process. The index will be rebuilt
429N/A # automatically on startup.
429N/A reindex = True
2028N/A exit_ready = True
1968N/A elif opt == "--set-property":
1968N/A try:
1968N/A prop, p_value = arg.split("=", 1)
1968N/A p_sec, p_name = prop.split(".", 1)
1968N/A except ValueError:
1968N/A usage(_("property arguments must be of "
1968N/A "the form '<section.property>="
1968N/A "<value>'."))
1968N/A repo_props.setdefault(p_sec, {})
1968N/A repo_props[p_sec][p_name] = p_value
812N/A elif opt == "--ssl-cert-file":
1968N/A if arg == "none" or arg == "":
1968N/A # Assume this is an override to clear
1968N/A # the value.
1968N/A arg = ""
1968N/A elif not os.path.isabs(arg):
812N/A raise OptionError, "The path to " \
812N/A "the Certificate file must be " \
812N/A "absolute."
1968N/A elif not os.path.exists(arg):
812N/A raise OptionError, "The specified " \
812N/A "file does not exist."
1968N/A elif not os.path.isfile(arg):
812N/A raise OptionError, "The specified " \
812N/A "pathname is not a file."
1968N/A ivalues["pkg"]["ssl_cert_file"] = arg
812N/A elif opt == "--ssl-key-file":
1968N/A if arg == "none" or arg == "":
1968N/A # Assume this is an override to clear
1968N/A # the value.
1968N/A arg = ""
1968N/A elif not os.path.isabs(arg):
812N/A raise OptionError, "The path to " \
812N/A "the Private Key file must be " \
812N/A "absolute."
1968N/A elif not os.path.exists(arg):
812N/A raise OptionError, "The specified " \
812N/A "file does not exist."
1968N/A elif not os.path.isfile(arg):
812N/A raise OptionError, "The specified " \
812N/A "pathname is not a file."
1968N/A ivalues["pkg"]["ssl_key_file"] = arg
812N/A elif opt == "--ssl-dialog":
1968N/A if arg != "builtin" and \
1968N/A arg != "smf" and not \
812N/A arg.startswith("exec:/") and not \
1968N/A arg.startswith("svc:"):
812N/A raise OptionError, "Invalid value " \
812N/A "specified. Expected: builtin, " \
1968N/A "exec:/path/to/program, smf, or " \
1968N/A "an SMF FMRI."
812N/A
1968N/A if arg.startswith("exec:"):
812N/A if os_util.get_canonical_os_type() != \
812N/A "unix":
873N/A # Don't allow a somewhat
873N/A # insecure authentication method
873N/A # on some platforms.
873N/A raise OptionError, "exec is " \
873N/A "not a supported dialog " \
873N/A "type for this operating " \
873N/A "system."
812N/A
1968N/A f = os.path.abspath(arg.split(
812N/A "exec:")[1])
812N/A if not os.path.isfile(f):
812N/A raise OptionError, "Invalid " \
812N/A "file path specified for " \
812N/A "exec."
1968N/A ivalues["pkg"]["ssl_dialog"] = arg
1475N/A elif opt == "--sort-file-max-size":
1968N/A ivalues["pkg"]["sort_file_max_size"] = arg
975N/A elif opt == "--writable-root":
1968N/A ivalues["pkg"]["writable_root"] = arg
1968N/A
1968N/A # Set accumulated values.
1968N/A if debug_features:
1968N/A ivalues["pkg"]["debug"] = debug_features
1968N/A if disable_ops:
1968N/A ivalues["pkg"]["disable_ops"] = disable_ops
2230N/A if addresses:
2230N/A ivalues["pkg"]["address"] = list(addresses)
1968N/A
1968N/A # Build configuration object.
1968N/A dconf = ds.DepotConfig(target=user_cfg, overrides=ivalues)
873N/A except getopt.GetoptError, _e:
873N/A usage("pkg.depotd: %s" % _e.msg)
1968N/A except api_errors.ApiException, _e:
1968N/A usage("pkg.depotd: %s" % str(_e))
873N/A except OptionError, _e:
873N/A usage("pkg.depotd: option: %s -- %s" % (opt, _e))
382N/A except (ArithmeticError, ValueError):
466N/A usage("pkg.depotd: illegal option value: %s specified " \
466N/A "for option: %s" % (arg, opt))
451N/A
1633N/A if show_usage:
1633N/A usage(retcode=0, full=True)
1633N/A
1968N/A if not dconf.get_property("pkg", "log_errors"):
1968N/A dconf.set_property("pkg", "log_errors", "stderr")
1968N/A
1968N/A # If stdout is a tty, then send access output there by default instead
1968N/A # of discarding it.
1968N/A if not dconf.get_property("pkg", "log_access"):
1968N/A if os.isatty(sys.stdout.fileno()):
1968N/A dconf.set_property("pkg", "log_access", "stdout")
1968N/A else:
1968N/A dconf.set_property("pkg", "log_access", "none")
1968N/A
1968N/A # Check for invalid option combinations.
1968N/A mirror = dconf.get_property("pkg", "mirror")
2230N/A ll_mirror = dconf.get_property("pkg", "ll_mirror")
1968N/A readonly = dconf.get_property("pkg", "readonly")
1968N/A writable_root = dconf.get_property("pkg", "writable_root")
1542N/A if rebuild and add_content:
1542N/A usage("--add-content cannot be used with --rebuild")
445N/A if rebuild and reindex:
466N/A usage("--refresh-index cannot be used with --rebuild")
1542N/A if (rebuild or add_content) and (readonly or mirror):
1633N/A usage("--readonly and --mirror cannot be used with --rebuild "
1633N/A "or --add-content")
1020N/A if reindex and mirror:
1020N/A usage("--mirror cannot be used with --refresh-index")
1020N/A if reindex and readonly and not writable_root:
1020N/A usage("--readonly can only be used with --refresh-index if "
1020N/A "--writable-root is used")
451N/A
1968N/A # Set any values using defaults if they weren't provided.
2230N/A
2230N/A # Only use the first value for now; multiple bind addresses may be
2230N/A # supported later.
2230N/A address = dconf.get_property("pkg", "address")
2230N/A if address:
2230N/A address = address[0]
2230N/A elif not address:
2230N/A dconf.set_property("pkg", "address", [HOST_DEFAULT])
2230N/A address = dconf.get_property("pkg", "address")[0]
2230N/A
1968N/A inst_root = dconf.get_property("pkg", "inst_root")
1968N/A file_root = dconf.get_property("pkg", "file_root")
1968N/A if not inst_root and not file_root:
1902N/A usage("At least one of PKG_REPO, -d, or --file-root"
1902N/A " must be provided")
1902N/A
1968N/A content_root = dconf.get_property("pkg", "content_root")
1968N/A if not content_root:
1968N/A dconf.set_property("pkg", "content_root", CONTENT_PATH_DEFAULT)
1968N/A content_root = dconf.get_property("pkg", "content_root")
1968N/A
1968N/A port = dconf.get_property("pkg", "port")
1968N/A ssl_cert_file = dconf.get_property("pkg", "ssl_cert_file")
1968N/A ssl_key_file = dconf.get_property("pkg", "ssl_key_file")
812N/A if (ssl_cert_file and not ssl_key_file) or (ssl_key_file and not
812N/A ssl_cert_file):
812N/A usage("The --ssl-cert-file and --ssl-key-file options must "
812N/A "must both be provided when using either option.")
1968N/A elif not port:
1968N/A if ssl_cert_file and ssl_key_file:
1968N/A dconf.set_property("pkg", "port", SSL_PORT_DEFAULT)
1968N/A else:
1968N/A dconf.set_property("pkg", "port", PORT_DEFAULT)
1968N/A port = dconf.get_property("pkg", "port")
1968N/A
1968N/A socket_timeout = dconf.get_property("pkg", "socket_timeout")
1968N/A if not socket_timeout:
1968N/A dconf.set_property("pkg", "socket_timeout",
1968N/A SOCKET_TIMEOUT_DEFAULT)
1968N/A socket_timeout = dconf.get_property("pkg", "socket_timeout")
1968N/A
1968N/A threads = dconf.get_property("pkg", "threads")
1968N/A if not threads:
1968N/A dconf.set_property("pkg", "threads", THREADS_DEFAULT)
1968N/A threads = dconf.get_property("pkg", "threads")
812N/A
429N/A # If the program is going to reindex, the port is irrelevant since
429N/A # the program will not bind to a port.
2028N/A if not exit_ready:
1836N/A try:
2230N/A cherrypy.process.servers.check_port(address, port)
1836N/A except Exception, e:
1836N/A emsg("pkg.depotd: unable to bind to the specified "
1836N/A "port: %d. Reason: %s" % (port, e))
429N/A sys.exit(1)
612N/A else:
1542N/A # Not applicable if we're not going to serve content
1968N/A dconf.set_property("pkg", "content_root", "")
1968N/A
1968N/A # Any relative paths should be made absolute using pkg_root. 'pkg_root'
1968N/A # is a special property that was added to enable internal deployment of
1968N/A # multiple disparate versions of the pkg.depotd software.
1968N/A pkg_root = dconf.get_property("pkg", "pkg_root")
1968N/A
1968N/A repo_config_file = dconf.get_property("pkg", "cfg_file")
1968N/A if repo_config_file and not os.path.isabs(repo_config_file):
1968N/A repo_config_file = os.path.join(pkg_root, repo_config_file)
1968N/A
1968N/A if content_root and not os.path.isabs(content_root):
1968N/A content_root = os.path.join(pkg_root, content_root)
1968N/A
1968N/A if file_root and not os.path.isabs(file_root):
1968N/A file_root = os.path.join(pkg_root, file_root)
386N/A
1968N/A if inst_root and not os.path.isabs(inst_root):
1968N/A inst_root = os.path.join(pkg_root, inst_root)
1968N/A
1968N/A if ssl_cert_file:
1968N/A if ssl_cert_file == "none":
1968N/A ssl_cert_file = None
1968N/A elif not os.path.isabs(ssl_cert_file):
1968N/A ssl_cert_file = os.path.join(pkg_root, ssl_cert_file)
1968N/A
1968N/A if ssl_key_file:
1968N/A if ssl_key_file == "none":
1968N/A ssl_key_file = None
1968N/A elif not os.path.isabs(ssl_key_file):
1968N/A ssl_key_file = os.path.join(pkg_root, ssl_key_file)
1968N/A
1968N/A if writable_root and not os.path.isabs(writable_root):
1968N/A writable_root = os.path.join(pkg_root, writable_root)
1968N/A
1968N/A # Setup SSL if requested.
812N/A key_data = None
1968N/A ssl_dialog = dconf.get_property("pkg", "ssl_dialog")
2028N/A if not exit_ready and ssl_cert_file and ssl_key_file and \
812N/A ssl_dialog != "builtin":
812N/A cmdline = None
812N/A def get_ssl_passphrase(*ignored):
812N/A p = None
812N/A try:
812N/A p = subprocess.Popen(cmdline, shell=True,
812N/A stdout=subprocess.PIPE,
812N/A stderr=None)
812N/A p.wait()
873N/A except Exception, __e:
1836N/A emsg("pkg.depotd: an error occurred while "
1836N/A "executing [%s]; unable to obtain the "
1836N/A "passphrase needed to decrypt the SSL "
1836N/A "private key file: %s" % (cmdline, __e))
812N/A sys.exit(1)
812N/A return p.stdout.read().strip("\n")
812N/A
812N/A if ssl_dialog.startswith("exec:"):
1968N/A exec_path = ssl_dialog.split("exec:")[1]
1968N/A if not os.path.isabs(exec_path):
1968N/A exec_path = os.path.join(pkg_root, exec_path)
1968N/A cmdline = "%s %s %d" % (exec_path, "''", port)
1968N/A elif ssl_dialog == "smf" or ssl_dialog.startswith("svc:"):
1968N/A if ssl_dialog == "smf":
1968N/A # Assume the configuration target was an SMF
1968N/A # FMRI and let svcprop fail with an error if
1968N/A # it wasn't.
1968N/A svc_fmri = dconf.target
1968N/A else:
1968N/A svc_fmri = ssl_dialog
812N/A cmdline = "/usr/bin/svcprop -p " \
1968N/A "pkg_secure/ssl_key_passphrase %s" % svc_fmri
812N/A
812N/A # The key file requires decryption, but the user has requested
812N/A # exec-based authentication, so it will have to be decoded first
812N/A # to an un-named temporary file.
812N/A try:
1968N/A with file(ssl_key_file, "rb") as key_file:
1968N/A pkey = crypto.load_privatekey(
1968N/A crypto.FILETYPE_PEM, key_file.read(),
1968N/A get_ssl_passphrase)
812N/A
812N/A key_data = tempfile.TemporaryFile()
812N/A key_data.write(crypto.dump_privatekey(
812N/A crypto.FILETYPE_PEM, pkey))
812N/A key_data.seek(0)
873N/A except EnvironmentError, _e:
1836N/A emsg("pkg.depotd: unable to read the SSL private key "
1836N/A "file: %s" % _e)
812N/A sys.exit(1)
873N/A except crypto.Error, _e:
1836N/A emsg("pkg.depotd: authentication or cryptography "
1836N/A "failure while attempting to decode\nthe SSL "
1836N/A "private key file: %s" % _e)
812N/A sys.exit(1)
812N/A else:
812N/A # Redirect the server to the decrypted key file.
812N/A ssl_key_file = "/dev/fd/%d" % key_data.fileno()
1968N/A key_data.close()
812N/A
452N/A # Setup our global configuration.
466N/A gconf = {
858N/A "checker.on": True,
382N/A "environment": "production",
466N/A "log.screen": False,
965N/A "server.max_request_body_size": MAX_REQUEST_BODY_SIZE,
858N/A "server.shutdown_timeout": 0,
2230N/A "server.socket_host": address,
382N/A "server.socket_port": port,
858N/A "server.socket_timeout": socket_timeout,
858N/A "server.ssl_certificate": ssl_cert_file,
858N/A "server.ssl_private_key": ssl_key_file,
382N/A "server.thread_pool": threads,
742N/A "tools.log_headers.on": True,
858N/A "tools.encode.on": True
466N/A }
466N/A
1968N/A if "headers" in dconf.get_property("pkg", "debug"):
858N/A # Despite its name, this only logs headers when there is an
858N/A # error; it's redundant with the debug feature enabled.
858N/A gconf["tools.log_headers.on"] = False
858N/A
858N/A # Causes the headers of every request to be logged to the error
858N/A # log; even if an exception occurs.
858N/A gconf["tools.log_headers_always.on"] = True
858N/A cherrypy.tools.log_headers_always = cherrypy.Tool(
858N/A "on_start_resource",
858N/A cherrypy.lib.cptools.log_request_headers)
858N/A
466N/A log_type_map = {
466N/A "errors": {
466N/A "param": "log.error_file",
466N/A "attr": "error_log"
466N/A },
466N/A "access": {
466N/A "param": "log.access_file",
466N/A "attr": "access_log"
466N/A }
466N/A }
466N/A
466N/A for log_type in log_type_map:
1968N/A dest = dconf.get_property("pkg", "log_%s" % log_type)
466N/A if dest in ("stdout", "stderr", "none"):
466N/A if dest == "none":
466N/A h = logging.StreamHandler(LogSink())
466N/A else:
466N/A h = logging.StreamHandler(eval("sys.%s" % \
466N/A dest))
466N/A
466N/A h.setLevel(logging.DEBUG)
466N/A h.setFormatter(cherrypy._cplogging.logfmt)
466N/A log_obj = eval("cherrypy.log.%s" % \
466N/A log_type_map[log_type]["attr"])
466N/A log_obj.addHandler(h)
466N/A # Since we've replaced cherrypy's log handler with our
466N/A # own, we don't want the output directed to a file.
466N/A dest = ""
1968N/A elif dest:
1968N/A if not os.path.isabs(dest):
1968N/A dest = os.path.join(pkg_root, dest)
466N/A gconf[log_type_map[log_type]["param"]] = dest
382N/A
612N/A cherrypy.config.update(gconf)
612N/A
612N/A # Now that our logging, etc. has been setup, it's safe to perform any
612N/A # remaining preparation.
1431N/A
1431N/A # Initialize repository state.
2028N/A if not readonly:
2028N/A # Not readonly, so assume a new repository should be created.
2028N/A try:
2028N/A sr.repository_create(inst_root, properties=repo_props)
2028N/A except sr.RepositoryExistsError:
2028N/A # Already exists, nothing to do.
2028N/A pass
2028N/A except (api_errors.ApiException, sr.RepositoryError), _e:
2028N/A emsg("pkg.depotd: %s" % _e)
2028N/A sys.exit(1)
2028N/A
1431N/A try:
1968N/A sort_file_max_size = dconf.get_property("pkg",
1968N/A "sort_file_max_size")
1968N/A
2028N/A repo = sr.Repository(cfgpathname=repo_config_file,
2028N/A file_root=file_root, log_obj=cherrypy, mirror=mirror,
2028N/A properties=repo_props, read_only=readonly,
2028N/A root=inst_root, sort_file_max_size=sort_file_max_size,
1431N/A writable_root=writable_root)
1895N/A except (RuntimeError, sr.RepositoryError), _e:
1431N/A emsg("pkg.depotd: %s" % _e)
1431N/A sys.exit(1)
1672N/A except search_errors.IndexingException, _e:
1672N/A emsg("pkg.depotd: %s" % str(_e), "INDEX")
1672N/A sys.exit(1)
1968N/A except api_errors.ApiException, _e:
1672N/A emsg("pkg.depotd: %s" % str(_e))
1431N/A sys.exit(1)
1431N/A
2028N/A if not rebuild and not add_content and not repo.mirror and \
2028N/A not (repo.read_only and not repo.writable_root):
2028N/A # Automatically update search indexes on startup if not already
2028N/A # told to, and not in readonly/mirror mode.
2028N/A reindex = True
2028N/A
612N/A if reindex:
617N/A try:
2065N/A # Only execute a index refresh here if --exit-ready was
2065N/A # requested; it will be handled later in the setup
2065N/A # process for other cases.
2065N/A if repo.root and exit_ready:
2028N/A repo.refresh_index()
2028N/A except (sr.RepositoryError, search_errors.IndexingException,
2028N/A api_errors.ApiException), e:
2028N/A emsg(str(e), "INDEX")
2028N/A sys.exit(1)
2028N/A elif rebuild:
2028N/A try:
2028N/A repo.rebuild(build_index=True)
1431N/A except sr.RepositoryError, e:
1431N/A emsg(str(e), "REBUILD")
1431N/A sys.exit(1)
975N/A except (search_errors.IndexingException,
1779N/A api_errors.UnknownErrors,
1431N/A api_errors.PermissionsException), e:
1431N/A emsg(str(e), "INDEX")
617N/A sys.exit(1)
1542N/A elif add_content:
1542N/A try:
1542N/A repo.add_content()
2028N/A repo.refresh_index()
1542N/A except sr.RepositoryError, e:
1542N/A emsg(str(e), "ADD_CONTENT")
1542N/A sys.exit(1)
1542N/A except (search_errors.IndexingException,
1779N/A api_errors.UnknownErrors,
1542N/A api_errors.PermissionsException), e:
1542N/A emsg(str(e), "INDEX")
1542N/A sys.exit(1)
1542N/A
2028N/A # Ready to start depot; exit now if requested.
1542N/A if exit_ready:
1542N/A sys.exit(0)
1542N/A
1431N/A # Next, initialize depot.
1431N/A if nasty:
1968N/A depot = ds.NastyDepotHTTP(repo, dconf)
1968N/A depot.set_nasty(nasty_value)
1431N/A else:
1968N/A depot = ds.DepotHTTP(repo, dconf)
612N/A
451N/A # Now build our site configuration.
382N/A conf = {
452N/A "/": {
452N/A # We have to override cherrypy's default response_class so that
452N/A # we have access to the write() callable to stream data
452N/A # directly to the client.
873N/A "wsgi.response_class": dr.DepotResponse,
452N/A },
382N/A "/robots.txt": {
382N/A "tools.staticfile.on": True,
1431N/A "tools.staticfile.filename": os.path.join(depot.web_root,
382N/A "robots.txt")
382N/A },
382N/A }
145N/A
1968N/A proxy_base = dconf.get_property("pkg", "proxy_base")
451N/A if proxy_base:
451N/A # This changes the base URL for our server, and is primarily
451N/A # intended to allow our depot process to operate behind Apache
451N/A # or some other webserver process.
451N/A #
451N/A # Visit the following URL for more information:
451N/A # http://cherrypy.org/wiki/BuiltinTools#tools.proxy
451N/A proxy_conf = {
451N/A "tools.proxy.on": True,
451N/A "tools.proxy.local": "",
451N/A "tools.proxy.base": proxy_base
451N/A }
451N/A
451N/A # Now merge or add our proxy configuration information into the
451N/A # existing configuration.
451N/A for entry in proxy_conf:
451N/A conf["/"][entry] = proxy_conf[entry]
451N/A
1902N/A if ll_mirror:
2230N/A ds.DNSSD_Plugin(cherrypy.engine, gconf).subscribe()
1902N/A
2065N/A if reindex:
2065N/A # Tell depot to update search indexes when possible;
2065N/A # this is done as a background task so that packages
2065N/A # can be served immediately while search indexes are
2065N/A # still being updated.
2065N/A depot._queue_refresh_index()
2065N/A
2507N/A # If stdin is not a tty and the pkgdepot controller isn't being used,
2507N/A # then assume process should be daemonized.
2507N/A if not os.environ.get("PKGDEPOT_CONTROLLER") and \
2507N/A not os.isatty(sys.stdin.fileno()):
2507N/A Daemonizer(cherrypy.engine).subscribe()
2507N/A
814N/A try:
1431N/A root = cherrypy.Application(depot)
466N/A cherrypy.quickstart(root, config=conf)
873N/A except Exception, _e:
812N/A emsg("pkg.depotd: unknown error starting depot server, " \
812N/A "illegal option value specified?")
873N/A emsg(_e)
812N/A sys.exit(1)