depot.py revision 2951
1516N/A#!/usr/bin/python2.6
290N/A#
290N/A# CDDL HEADER START
290N/A#
290N/A# The contents of this file are subject to the terms of the
290N/A# Common Development and Distribution License (the "License").
290N/A# You may not use this file except in compliance with the License.
290N/A#
290N/A# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
290N/A# or http://www.opensolaris.org/os/licensing.
290N/A# See the License for the specific language governing permissions
290N/A# and limitations under the License.
290N/A#
290N/A# When distributing Covered Code, include this CDDL HEADER in each
290N/A# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
290N/A# If applicable, add the following below this CDDL HEADER, with the
290N/A# fields enclosed by brackets "[]" replaced with your own identifying
290N/A# information: Portions Copyright [yyyy] [name of copyright owner]
290N/A#
290N/A# CDDL HEADER END
290N/A#
1660N/A# Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
395N/A#
395N/A
290N/A# pkg.depotd - package repository daemon
883N/A
454N/A# XXX The prototype pkg.depotd combines both the version management server that
290N/A# answers to pkgsend(1) sessions and the HTTP file server that answers to the
448N/A# various GET operations that a pkg(1) client makes. This split is expected to
290N/A# be made more explicit, by constraining the pkg(1) operations such that they
290N/A# can be served as a typical HTTP/HTTPS session. Thus, pkg.depotd will reduce
290N/A# to a special purpose HTTP/HTTPS server explicitly for the version management
383N/A# operations, and must manipulate the various state files--catalogs, in
290N/A# particular--such that the pkg(1) pull client can operately accurately with
395N/A# only a basic HTTP/HTTPS server in place.
290N/A
395N/A# XXX Although we pushed the evaluation of next-version, etc. to the pull
849N/A# client, we should probably provide a query API to do same on the server, for
1516N/A# dumb clients (like a notification service).
290N/A
849N/A# The default path for static and other web content.
290N/ACONTENT_PATH_DEFAULT = "/usr/share/lib/pkg"
290N/A# cherrypy has a max_request_body_size parameter that determines whether the
290N/A# server should abort requests with REQUEST_ENTITY_TOO_LARGE when the request
290N/A# body is larger than the specified size (in bytes). The maximum size supported
383N/A# by cherrypy is 2048 * 1024 * 1024 - 1 (just short of 2048MB), but the default
290N/A# here is purposefully conservative.
290N/AMAX_REQUEST_BODY_SIZE = 512 * 1024 * 1024
290N/A# The default host/port(s) to serve data from.
290N/AHOST_DEFAULT = "0.0.0.0"
290N/APORT_DEFAULT = 80
290N/ASSL_PORT_DEFAULT = 443
290N/A# The minimum number of threads allowed.
290N/ATHREADS_MIN = 1
1660N/A# The default number of threads to start.
1660N/ATHREADS_DEFAULT = 60
1660N/A# The maximum number of threads that can be started.
1660N/ATHREADS_MAX = 5000
1660N/A# The default server socket timeout in seconds. We want this to be longer than
1660N/A# the normal default of 10 seconds to accommodate clients with poor quality
1660N/A# connections.
1660N/ASOCKET_TIMEOUT_DEFAULT = 60
1660N/A
1660N/Aimport getopt
1660N/Aimport gettext
1660N/Aimport locale
1660N/Aimport logging
1660N/Aimport os
1660N/Aimport os.path
1660N/Aimport OpenSSL.crypto as crypto
1660N/Aimport subprocess
1660N/Aimport sys
465N/Aimport tempfile
465N/Aimport urlparse
465N/A
1516N/Atry:
465N/A import cherrypy
465N/A version = cherrypy.__version__.split('.')
465N/A if map(int, version) < [3, 1, 0]:
1516N/A raise ImportError
465N/A elif map(int, version) >= [3, 2, 0]:
465N/A raise ImportError
465N/Aexcept ImportError:
465N/A print >> sys.stderr, """cherrypy 3.1.0 or greater (but less than """ \
465N/A """3.2.0) is required to use this program."""
465N/A sys.exit(2)
465N/A
1099N/Aimport cherrypy.process.servers
465N/Afrom cherrypy.process.plugins import Daemonizer
1513N/A
1513N/Afrom pkg.misc import msg, emsg, setlocale
1514N/Aimport pkg.client.api_errors as api_errors
1513N/Aimport pkg.config as cfg
1513N/Aimport pkg.portable.util as os_util
1513N/Aimport pkg.search_errors as search_errors
1099N/Aimport pkg.server.depot as ds
1513N/Aimport pkg.server.depotresponse as dr
708N/Aimport pkg.server.repository as sr
1391N/A
1391N/A
1391N/Aclass LogSink(object):
1391N/A """This is a dummy object that we can use to discard log entries
1391N/A without relying on non-portable interfaces such as /dev/null."""
1391N/A
1391N/A def write(self, *args, **kwargs):
1391N/A """Discard the bits."""
1391N/A pass
1391N/A
1391N/A def flush(self, *args, **kwargs):
742N/A """Discard the bits."""
742N/A pass
742N/A
742N/A
742N/Adef usage(text=None, retcode=2, full=False):
742N/A """Optionally emit a usage message and then exit using the specified
1099N/A exit code."""
742N/A
941N/A if text:
941N/A emsg(text)
941N/A
941N/A if not full:
941N/A # The full usage message isn't desired.
941N/A emsg(_("Try `pkg.depotd --help or -?' for more "
1099N/A "information."))
941N/A sys.exit(retcode)
1191N/A
1513N/A print """\
1191N/AUsage: /usr/lib/pkg.depotd [-a address] [-d inst_root] [-p port] [-s threads]
1191N/A [-t socket_timeout] [--cfg] [--content-root]
1191N/A [--disable-ops op[/1][,...]] [--debug feature_list]
1191N/A [--image-root dir] [--log-access dest] [--log-errors dest]
1191N/A [--mirror] [--nasty] [--nasty-sleep] [--proxy-base url]
1660N/A [--readonly] [--ssl-cert-file] [--ssl-dialog] [--ssl-key-file]
1660N/A [--sort-file-max-size size] [--writable-root dir]
1660N/A
290N/A -a address The IP address on which to listen for connections. The
448N/A default value is 0.0.0.0 (INADDR_ANY) which will listen
448N/A on all active interfaces. To listen on all active IPv6
534N/A interfaces, use '::'.
534N/A -d inst_root The file system path at which the server should find its
534N/A repository data. Required unless PKG_REPO has been set
534N/A in the environment.
534N/A -p port The port number on which the instance should listen for
534N/A incoming package requests. The default value is 80 if
534N/A ssl certificate and key information has not been
290N/A provided; otherwise, the default value is 443.
290N/A -s threads The number of threads that will be started to serve
954N/A requests. The default value is 10.
954N/A -t timeout The maximum number of seconds the server should wait for
954N/A a response from a client before closing a connection.
954N/A The default value is 60.
534N/A --cfg The pathname of the file to use when reading and writing
1099N/A depot configuration data, or a fully qualified service
290N/A fault management resource identifier (FMRI) of the SMF
1191N/A service or instance to read configuration data from.
1191N/A --content-root The file system path to the directory containing the
1191N/A the static and other web content used by the depot's
1516N/A browser user interface. The default value is
290N/A '/usr/share/lib/pkg'.
290N/A --disable-ops A comma separated list of operations that the depot
290N/A should not configure. If, for example, you wanted
661N/A to omit loading search v1, 'search/1' should be
290N/A provided as an argument, or to disable all search
290N/A operations, simply 'search'.
290N/A --debug The name of a debug feature to enable; or a whitespace
395N/A or comma separated list of features to enable.
290N/A Possible values are: headers.
290N/A --image-root The path to the image whose file information will be
290N/A used as a cache for file data.
1483N/A --log-access The destination for any access related information
290N/A logged by the depot process. Possible values are:
1498N/A stderr, stdout, none, or an absolute pathname. The
1498N/A default value is stdout if stdout is a tty; otherwise
290N/A the default value is none.
395N/A --log-errors The destination for any errors or other information
430N/A logged by the depot process. Possible values are:
395N/A stderr, stdout, none, or an absolute pathname. The
1544N/A default value is stderr.
1557N/A --mirror Package mirror mode; publishing and metadata operations
1506N/A disallowed. Cannot be used with --readonly or
395N/A --rebuild.
395N/A --nasty Instruct the server to misbehave. At random intervals
424N/A it will time-out, send bad responses, hang up on
1024N/A clients, and generally be hostile. The option
395N/A takes a value (1 to 100) for how nasty the server
395N/A should be.
395N/A --nasty-sleep In nasty mode (see --nasty), how many seconds to
578N/A randomly sleep when a random sleep occurs.
1228N/A --proxy-base The url to use as the base for generating internal
1172N/A redirects and content.
395N/A --readonly Read-only operation; modifying operations disallowed.
661N/A Cannot be used with --mirror or --rebuild.
1099N/A --ssl-cert-file The absolute pathname to a PEM-encoded Certificate file.
661N/A This option must be used with --ssl-key-file. Usage of
395N/A this option will cause the depot to only respond to SSL
849N/A requests on the provided port.
290N/A --ssl-dialog Specifies what method should be used to obtain the
395N/A passphrase needed to decrypt the file specified by
395N/A --ssl-key-file. Supported values are: builtin,
395N/A exec:/path/to/program, smf, or an SMF FMRI. The
395N/A default value is builtin. If smf is specified, an
395N/A SMF FMRI must be provided using the --cfg option.
395N/A --ssl-key-file The absolute pathname to a PEM-encoded Private Key file.
395N/A This option must be used with --ssl-cert-file. Usage of
395N/A this option will cause the depot to only respond to SSL
395N/A requests on the provided port.
395N/A --sort-file-max-size
395N/A The maximum size of the indexer sort file. Used to
395N/A limit the amount of RAM the depot uses for indexing,
395N/A or increase it for speed.
290N/A --writable-root The path to a directory to which the program has write
290N/A access. Used with --readonly to allow server to
395N/A create needed files, such as search indices, without
395N/A needing write access to the package information.
1231N/AOptions:
1557N/A --help or -?
1557N/A
395N/AEnvironment:
395N/A PKG_REPO Used as default inst_root if -d not provided.
395N/A PKG_DEPOT_CONTENT Used as default content_root if --content-root
395N/A not provided."""
395N/A sys.exit(retcode)
395N/A
395N/Aclass OptionError(Exception):
395N/A """Option exception. """
395N/A
395N/A def __init__(self, *args):
395N/A Exception.__init__(self, *args)
290N/A
290N/Aif __name__ == "__main__":
430N/A
395N/A setlocale(locale.LC_ALL, "")
395N/A gettext.install("pkg", "/usr/share/locale",
395N/A codeset=locale.getpreferredencoding())
395N/A
1302N/A add_content = False
395N/A exit_ready = False
395N/A rebuild = False
290N/A reindex = False
395N/A nasty = False
1024N/A
413N/A # Track initial configuration values.
1544N/A ivalues = { "pkg": {}, "nasty": {} }
1557N/A if "PKG_REPO" in os.environ:
1506N/A ivalues["pkg"]["inst_root"] = os.environ["PKG_REPO"]
413N/A
413N/A try:
1024N/A content_root = os.environ["PKG_DEPOT_CONTENT"]
395N/A ivalues["pkg"]["content_root"] = content_root
395N/A except KeyError:
413N/A try:
395N/A content_root = os.path.join(os.environ['PKG_HOME'],
395N/A 'share/lib/pkg')
413N/A ivalues["pkg"]["content_root"] = content_root
395N/A except KeyError:
395N/A pass
395N/A
395N/A opt = None
395N/A addresses = set()
395N/A debug_features = []
1191N/A disable_ops = []
1452N/A repo_props = {}
1231N/A socket_path = ""
395N/A user_cfg = None
395N/A try:
424N/A long_opts = ["add-content", "cfg=", "cfg-file=",
395N/A "content-root=", "debug=", "disable-ops=", "exit-ready",
742N/A "help", "image-root=", "log-access=", "log-errors=",
742N/A "llmirror", "mirror", "nasty=", "nasty-sleep=",
742N/A "proxy-base=", "readonly", "rebuild", "refresh-index",
742N/A "set-property=", "ssl-cert-file=", "ssl-dialog=",
742N/A "ssl-key-file=", "sort-file-max-size=", "writable-root="]
742N/A
742N/A opts, pargs = getopt.getopt(sys.argv[1:], "a:d:np:s:t:?",
742N/A long_opts)
742N/A
742N/A show_usage = False
742N/A for opt, arg in opts:
395N/A if opt == "-a":
395N/A addresses.add(arg)
395N/A elif opt == "-n":
395N/A sys.exit(0)
395N/A elif opt == "-d":
954N/A ivalues["pkg"]["inst_root"] = arg
954N/A elif opt == "-p":
954N/A ivalues["pkg"]["port"] = arg
954N/A elif opt == "-s":
954N/A threads = int(arg)
954N/A if threads < THREADS_MIN:
954N/A raise OptionError, \
395N/A "minimum value is %d" % THREADS_MIN
1483N/A if threads > THREADS_MAX:
1483N/A raise OptionError, \
1483N/A "maximum value is %d" % THREADS_MAX
1483N/A ivalues["pkg"]["threads"] = threads
395N/A elif opt == "-t":
1099N/A ivalues["pkg"]["socket_timeout"] = arg
1099N/A elif opt == "--add-content":
395N/A add_content = True
1498N/A elif opt == "--cfg":
1498N/A user_cfg = arg
691N/A elif opt == "--cfg-file":
691N/A ivalues["pkg"]["cfg_file"] = arg
691N/A elif opt == "--content-root":
395N/A ivalues["pkg"]["content_root"] = arg
395N/A elif opt == "--debug":
395N/A if arg is None or arg == "":
395N/A continue
395N/A
290N/A # A list of features can be specified using a
395N/A # "," or any whitespace character as separators.
395N/A if "," in arg:
591N/A features = arg.split(",")
591N/A else:
591N/A features = arg.split()
1505N/A debug_features.extend(features)
1505N/A elif opt == "--disable-ops":
1505N/A if arg is None or arg == "":
1505N/A raise OptionError, \
1632N/A "An argument must be specified."
1632N/A
1632N/A disableops = arg.split(",")
1632N/A for s in disableops:
395N/A if "/" in s:
395N/A op, ver = s.rsplit("/", 1)
290N/A else:
290N/A op = s
290N/A ver = "*"
290N/A
290N/A if op not in \
290N/A ds.DepotHTTP.REPO_OPS_DEFAULT:
290N/A raise OptionError(
290N/A "Invalid operation "
290N/A "'%s'." % s)
290N/A disable_ops.append(s)
290N/A elif opt == "--exit-ready":
290N/A exit_ready = True
290N/A elif opt == "--image-root":
290N/A ivalues["pkg"]["image_root"] = arg
395N/A elif opt.startswith("--log-"):
395N/A prop = "log_%s" % opt.lstrip("--log-")
290N/A ivalues["pkg"][prop] = arg
290N/A elif opt in ("--help", "-?"):
290N/A show_usage = True
290N/A elif opt == "--mirror":
290N/A ivalues["pkg"]["mirror"] = True
395N/A elif opt == "--llmirror":
395N/A ivalues["pkg"]["mirror"] = True
395N/A ivalues["pkg"]["ll_mirror"] = True
290N/A ivalues["pkg"]["readonly"] = True
395N/A elif opt == "--nasty":
395N/A # ValueError is caught by caller.
395N/A nasty_value = int(arg)
395N/A if (nasty_value > 100 or nasty_value < 1):
591N/A raise OptionError, "Invalid value " \
591N/A "for nasty option.\n Please " \
591N/A "choose a value between 1 and 100."
591N/A nasty = True
691N/A ivalues["nasty"]["nasty_level"] = nasty_value
691N/A elif opt == "--nasty-sleep":
691N/A # ValueError is caught by caller.
691N/A sleep_value = int(arg)
290N/A ivalues["nasty"]["nasty_sleep"] = sleep_value
290N/A elif opt == "--proxy-base":
290N/A # Attempt to decompose the url provided into
290N/A # its base parts. This is done so we can
290N/A # remove any scheme information since we
591N/A # don't need it.
591N/A scheme, netloc, path, params, query, \
691N/A fragment = urlparse.urlparse(arg,
691N/A "http", allow_fragments=0)
290N/A
395N/A if not netloc:
395N/A raise OptionError, "Unable to " \
290N/A "determine the hostname from " \
395N/A "the provided URL; please use a " \
395N/A "fully qualified URL."
395N/A
395N/A scheme = scheme.lower()
290N/A if scheme not in ("http", "https"):
290N/A raise OptionError, "Invalid URL; http " \
290N/A "and https are the only supported " \
395N/A "schemes."
395N/A
395N/A # Rebuild the url with the sanitized components.
395N/A ivalues["pkg"]["proxy_base"] = \
395N/A urlparse.urlunparse((scheme, netloc, path,
395N/A params, query, fragment))
290N/A elif opt == "--readonly":
290N/A ivalues["pkg"]["readonly"] = True
290N/A elif opt == "--rebuild":
290N/A rebuild = True
290N/A elif opt == "--refresh-index":
430N/A # Note: This argument is for internal use
290N/A # only.
290N/A #
395N/A # This flag is purposefully omitted in usage.
290N/A # The supported way to forcefully reindex is to
395N/A # kill any pkg.depot using that directory,
506N/A # remove the index directory, and restart the
506N/A # pkg.depot process. The index will be rebuilt
506N/A # automatically on startup.
506N/A reindex = True
506N/A exit_ready = True
506N/A elif opt == "--set-property":
506N/A try:
506N/A prop, p_value = arg.split("=", 1)
834N/A p_sec, p_name = prop.split(".", 1)
506N/A except ValueError:
506N/A usage(_("property arguments must be of "
506N/A "the form '<section.property>="
513N/A "<value>'."))
506N/A repo_props.setdefault(p_sec, {})
506N/A repo_props[p_sec][p_name] = p_value
506N/A elif opt == "--ssl-cert-file":
506N/A if arg == "none" or arg == "":
290N/A # Assume this is an override to clear
290N/A # the value.
395N/A arg = ""
395N/A elif not os.path.isabs(arg):
849N/A raise OptionError, "The path to " \
849N/A "the Certificate file must be " \
883N/A "absolute."
883N/A elif not os.path.exists(arg):
395N/A raise OptionError, "The specified " \
413N/A "file does not exist."
413N/A elif not os.path.isfile(arg):
413N/A raise OptionError, "The specified " \
395N/A "pathname is not a file."
290N/A ivalues["pkg"]["ssl_cert_file"] = arg
395N/A elif opt == "--ssl-key-file":
395N/A if arg == "none" or arg == "":
506N/A # Assume this is an override to clear
506N/A # the value.
395N/A arg = ""
395N/A elif not os.path.isabs(arg):
395N/A raise OptionError, "The path to " \
395N/A "the Private Key file must be " \
430N/A "absolute."
849N/A elif not os.path.exists(arg):
834N/A raise OptionError, "The specified " \
290N/A "file does not exist."
1191N/A elif not os.path.isfile(arg):
1191N/A raise OptionError, "The specified " \
1191N/A "pathname is not a file."
1191N/A ivalues["pkg"]["ssl_key_file"] = arg
1391N/A elif opt == "--ssl-dialog":
1391N/A if arg != "builtin" and \
1401N/A arg != "smf" and not \
1391N/A arg.startswith("exec:/") and not \
1391N/A arg.startswith("svc:"):
1391N/A raise OptionError, "Invalid value " \
1391N/A "specified. Expected: builtin, " \
1391N/A "exec:/path/to/program, smf, or " \
1391N/A "an SMF FMRI."
1391N/A
1391N/A if arg.startswith("exec:"):
836N/A if os_util.get_canonical_os_type() != \
836N/A "unix":
849N/A # Don't allow a somewhat
849N/A # insecure authentication method
849N/A # on some platforms.
849N/A raise OptionError, "exec is " \
849N/A "not a supported dialog " \
849N/A "type for this operating " \
849N/A "system."
849N/A
849N/A f = os.path.abspath(arg.split(
849N/A "exec:")[1])
849N/A if not os.path.isfile(f):
849N/A raise OptionError, "Invalid " \
1513N/A "file path specified for " \
1391N/A "exec."
849N/A ivalues["pkg"]["ssl_dialog"] = arg
1513N/A elif opt == "--sort-file-max-size":
1391N/A ivalues["pkg"]["sort_file_max_size"] = arg
1513N/A elif opt == "--writable-root":
1391N/A ivalues["pkg"]["writable_root"] = arg
1391N/A
1660N/A # Set accumulated values.
1513N/A if debug_features:
1513N/A ivalues["pkg"]["debug"] = debug_features
290N/A if disable_ops:
883N/A ivalues["pkg"]["disable_ops"] = disable_ops
883N/A if addresses:
883N/A ivalues["pkg"]["address"] = list(addresses)
883N/A
883N/A # Build configuration object.
883N/A dconf = ds.DepotConfig(target=user_cfg, overrides=ivalues)
883N/A except getopt.GetoptError, _e:
883N/A usage("pkg.depotd: %s" % _e.msg)
883N/A except api_errors.ApiException, _e:
883N/A usage("pkg.depotd: %s" % str(_e))
883N/A except OptionError, _e:
883N/A usage("pkg.depotd: option: %s -- %s" % (opt, _e))
883N/A except (ArithmeticError, ValueError):
883N/A usage("pkg.depotd: illegal option value: %s specified " \
883N/A "for option: %s" % (arg, opt))
883N/A
1099N/A if show_usage:
1099N/A usage(retcode=0, full=True)
1099N/A
1099N/A if not dconf.get_property("pkg", "log_errors"):
1099N/A dconf.set_property("pkg", "log_errors", "stderr")
1516N/A
1265N/A # If stdout is a tty, then send access output there by default instead
1099N/A # of discarding it.
1099N/A if not dconf.get_property("pkg", "log_access"):
1099N/A if os.isatty(sys.stdout.fileno()):
1099N/A dconf.set_property("pkg", "log_access", "stdout")
1099N/A else:
1099N/A dconf.set_property("pkg", "log_access", "none")
1099N/A
1099N/A # Check for invalid option combinations.
1099N/A image_root = dconf.get_property("pkg", "image_root")
1099N/A inst_root = dconf.get_property("pkg", "inst_root")
1208N/A mirror = dconf.get_property("pkg", "mirror")
1208N/A ll_mirror = dconf.get_property("pkg", "ll_mirror")
1099N/A readonly = dconf.get_property("pkg", "readonly")
1099N/A writable_root = dconf.get_property("pkg", "writable_root")
1191N/A if rebuild and add_content:
1191N/A usage("--add-content cannot be used with --rebuild")
1191N/A if rebuild and reindex:
1191N/A usage("--refresh-index cannot be used with --rebuild")
1191N/A if (rebuild or add_content) and (readonly or mirror):
1191N/A usage("--readonly and --mirror cannot be used with --rebuild "
1191N/A "or --add-content")
1191N/A if reindex and mirror:
1191N/A usage("--mirror cannot be used with --refresh-index")
1191N/A if reindex and readonly and not writable_root:
1191N/A usage("--readonly can only be used with --refresh-index if "
1191N/A "--writable-root is used")
1191N/A if image_root and not ll_mirror:
1191N/A usage("--image-root can only be used with --llmirror.")
1265N/A if image_root and writable_root:
1191N/A usage("--image_root and --writable-root cannot be used "
1191N/A "together.")
1191N/A if image_root and inst_root:
1191N/A usage("--image-root and -d cannot be used together.")
1191N/A
1191N/A # If the image format changes this may need to be reexamined.
1191N/A if image_root:
1191N/A inst_root = os.path.join(image_root, "var", "pkg")
1191N/A
1191N/A # Set any values using defaults if they weren't provided.
1191N/A
1191N/A # Only use the first value for now; multiple bind addresses may be
1265N/A # supported later.
1265N/A address = dconf.get_property("pkg", "address")
1265N/A if address:
1265N/A address = address[0]
1099N/A elif not address:
1391N/A dconf.set_property("pkg", "address", [HOST_DEFAULT])
1099N/A address = dconf.get_property("pkg", "address")[0]
1099N/A
1099N/A if not inst_root:
1099N/A usage("Either PKG_REPO or -d must be provided")
1099N/A
465N/A content_root = dconf.get_property("pkg", "content_root")
465N/A if not content_root:
395N/A dconf.set_property("pkg", "content_root", CONTENT_PATH_DEFAULT)
465N/A content_root = dconf.get_property("pkg", "content_root")
395N/A
395N/A port = dconf.get_property("pkg", "port")
465N/A ssl_cert_file = dconf.get_property("pkg", "ssl_cert_file")
465N/A ssl_key_file = dconf.get_property("pkg", "ssl_key_file")
465N/A if (ssl_cert_file and not ssl_key_file) or (ssl_key_file and not
1208N/A ssl_cert_file):
1208N/A usage("The --ssl-cert-file and --ssl-key-file options must "
465N/A "must both be provided when using either option.")
395N/A elif not port:
465N/A if ssl_cert_file and ssl_key_file:
395N/A dconf.set_property("pkg", "port", SSL_PORT_DEFAULT)
465N/A else:
1099N/A dconf.set_property("pkg", "port", PORT_DEFAULT)
1099N/A port = dconf.get_property("pkg", "port")
1099N/A
465N/A socket_timeout = dconf.get_property("pkg", "socket_timeout")
465N/A if not socket_timeout:
395N/A dconf.set_property("pkg", "socket_timeout",
395N/A SOCKET_TIMEOUT_DEFAULT)
1099N/A socket_timeout = dconf.get_property("pkg", "socket_timeout")
395N/A
1191N/A threads = dconf.get_property("pkg", "threads")
1191N/A if not threads:
1191N/A dconf.set_property("pkg", "threads", THREADS_DEFAULT)
1191N/A threads = dconf.get_property("pkg", "threads")
1191N/A
1191N/A # If the program is going to reindex, the port is irrelevant since
1191N/A # the program will not bind to a port.
1191N/A if not exit_ready:
1191N/A try:
1191N/A cherrypy.process.servers.check_port(address, port)
1265N/A except Exception, e:
1265N/A emsg("pkg.depotd: unable to bind to the specified "
1265N/A "port: %d. Reason: %s" % (port, e))
1208N/A sys.exit(1)
1208N/A else:
1208N/A # Not applicable if we're not going to serve content
1208N/A dconf.set_property("pkg", "content_root", "")
1208N/A
1208N/A # Any relative paths should be made absolute using pkg_root. 'pkg_root'
1208N/A # is a special property that was added to enable internal deployment of
1191N/A # multiple disparate versions of the pkg.depotd software.
1191N/A pkg_root = dconf.get_property("pkg", "pkg_root")
1391N/A
1391N/A repo_config_file = dconf.get_property("pkg", "cfg_file")
1391N/A if repo_config_file and not os.path.isabs(repo_config_file):
1391N/A repo_config_file = os.path.join(pkg_root, repo_config_file)
1391N/A
1391N/A if content_root and not os.path.isabs(content_root):
1391N/A content_root = os.path.join(pkg_root, content_root)
1394N/A
1394N/A if inst_root and not os.path.isabs(inst_root):
1391N/A inst_root = os.path.join(pkg_root, inst_root)
1391N/A
1391N/A if ssl_cert_file:
1391N/A if ssl_cert_file == "none":
1391N/A ssl_cert_file = None
1391N/A elif not os.path.isabs(ssl_cert_file):
1391N/A ssl_cert_file = os.path.join(pkg_root, ssl_cert_file)
1660N/A
1391N/A if ssl_key_file:
465N/A if ssl_key_file == "none":
1660N/A ssl_key_file = None
1660N/A elif not os.path.isabs(ssl_key_file):
1660N/A ssl_key_file = os.path.join(pkg_root, ssl_key_file)
1660N/A
465N/A if writable_root and not os.path.isabs(writable_root):
465N/A writable_root = os.path.join(pkg_root, writable_root)
1516N/A
498N/A # Setup SSL if requested.
498N/A key_data = None
849N/A ssl_dialog = dconf.get_property("pkg", "ssl_dialog")
1660N/A if not exit_ready and ssl_cert_file and ssl_key_file and \
1391N/A ssl_dialog != "builtin":
1660N/A cmdline = None
1660N/A def get_ssl_passphrase(*ignored):
1660N/A p = None
1660N/A try:
849N/A p = subprocess.Popen(cmdline, shell=True,
1208N/A stdout=subprocess.PIPE,
1208N/A stderr=None)
1208N/A p.wait()
1208N/A except Exception, __e:
849N/A emsg("pkg.depotd: an error occurred while "
290N/A "executing [%s]; unable to obtain the "
465N/A "passphrase needed to decrypt the SSL "
465N/A "private key file: %s" % (cmdline, __e))
1099N/A sys.exit(1)
465N/A return p.stdout.read().strip("\n")
1099N/A
1099N/A if ssl_dialog.startswith("exec:"):
1099N/A exec_path = ssl_dialog.split("exec:")[1]
454N/A if not os.path.isabs(exec_path):
1099N/A exec_path = os.path.join(pkg_root, exec_path)
849N/A cmdline = "%s %s %d" % (exec_path, "''", port)
290N/A elif ssl_dialog == "smf" or ssl_dialog.startswith("svc:"):
430N/A if ssl_dialog == "smf":
395N/A # Assume the configuration target was an SMF
395N/A # FMRI and let svcprop fail with an error if
290N/A # it wasn't.
383N/A svc_fmri = dconf.target
383N/A else:
395N/A svc_fmri = ssl_dialog
383N/A cmdline = "/usr/bin/svcprop -p " \
383N/A "pkg_secure/ssl_key_passphrase %s" % svc_fmri
384N/A
383N/A # The key file requires decryption, but the user has requested
849N/A # exec-based authentication, so it will have to be decoded first
849N/A # to an un-named temporary file.
849N/A try:
849N/A with file(ssl_key_file, "rb") as key_file:
849N/A pkey = crypto.load_privatekey(
849N/A crypto.FILETYPE_PEM, key_file.read(),
849N/A get_ssl_passphrase)
849N/A
849N/A key_data = tempfile.TemporaryFile()
849N/A key_data.write(crypto.dump_privatekey(
849N/A crypto.FILETYPE_PEM, pkey))
849N/A key_data.seek(0)
849N/A except EnvironmentError, _e:
383N/A emsg("pkg.depotd: unable to read the SSL private key "
383N/A "file: %s" % _e)
383N/A sys.exit(1)
849N/A except crypto.Error, _e:
383N/A emsg("pkg.depotd: authentication or cryptography "
422N/A "failure while attempting to decode\nthe SSL "
422N/A "private key file: %s" % _e)
422N/A sys.exit(1)
422N/A else:
422N/A # Redirect the server to the decrypted key file.
422N/A ssl_key_file = "/dev/fd/%d" % key_data.fileno()
422N/A
422N/A # Setup our global configuration.
422N/A gconf = {
422N/A "checker.on": True,
422N/A "environment": "production",
422N/A "log.screen": False,
422N/A "server.max_request_body_size": MAX_REQUEST_BODY_SIZE,
422N/A "server.shutdown_timeout": 0,
422N/A "server.socket_host": address,
422N/A "server.socket_port": port,
422N/A "server.socket_timeout": socket_timeout,
383N/A "server.ssl_certificate": ssl_cert_file,
422N/A "server.ssl_private_key": ssl_key_file,
383N/A "server.thread_pool": threads,
383N/A "tools.log_headers.on": True,
383N/A "tools.encode.on": True
383N/A }
383N/A
383N/A if "headers" in dconf.get_property("pkg", "debug"):
383N/A # Despite its name, this only logs headers when there is an
422N/A # error; it's redundant with the debug feature enabled.
849N/A gconf["tools.log_headers.on"] = False
849N/A
849N/A # Causes the headers of every request to be logged to the error
383N/A # log; even if an exception occurs.
383N/A gconf["tools.log_headers_always.on"] = True
290N/A cherrypy.tools.log_headers_always = cherrypy.Tool(
430N/A "on_start_resource",
395N/A cherrypy.lib.cptools.log_request_headers)
395N/A
290N/A log_type_map = {
290N/A "errors": {
290N/A "param": "log.error_file",
290N/A "attr": "error_log"
290N/A },
290N/A "access": {
290N/A "param": "log.access_file",
290N/A "attr": "access_log"
290N/A }
290N/A }
290N/A
395N/A for log_type in log_type_map:
290N/A dest = dconf.get_property("pkg", "log_%s" % log_type)
395N/A if dest in ("stdout", "stderr", "none"):
290N/A if dest == "none":
395N/A h = logging.StreamHandler(LogSink())
290N/A else:
534N/A h = logging.StreamHandler(eval("sys.%s" % \
534N/A dest))
1099N/A
1099N/A h.setLevel(logging.DEBUG)
290N/A h.setFormatter(cherrypy._cplogging.logfmt)
290N/A log_obj = eval("cherrypy.log.%s" % \
1101N/A log_type_map[log_type]["attr"])
1101N/A log_obj.addHandler(h)
1101N/A # Since we've replaced cherrypy's log handler with our
1513N/A # own, we don't want the output directed to a file.
1513N/A dest = ""
1513N/A elif dest:
448N/A if not os.path.isabs(dest):
1513N/A dest = os.path.join(pkg_root, dest)
448N/A gconf[log_type_map[log_type]["param"]] = dest
1101N/A
1513N/A cherrypy.config.update(gconf)
1513N/A
290N/A # Now that our logging, etc. has been setup, it's safe to perform any
290N/A # remaining preparation.
290N/A
448N/A # Initialize repository state.
448N/A if not readonly:
430N/A # Not readonly, so assume a new repository should be created.
448N/A try:
430N/A sr.repository_create(inst_root, properties=repo_props)
1101N/A except sr.RepositoryExistsError:
1513N/A # Already exists, nothing to do.
1101N/A pass
290N/A except (api_errors.ApiException, sr.RepositoryError), _e:
290N/A emsg("pkg.depotd: %s" % _e)
1101N/A sys.exit(1)
290N/A
1101N/A try:
290N/A sort_file_max_size = dconf.get_property("pkg",
290N/A "sort_file_max_size")
290N/A
448N/A repo = sr.Repository(cfgpathname=repo_config_file,
448N/A log_obj=cherrypy, mirror=mirror, properties=repo_props,
448N/A read_only=readonly, root=inst_root,
448N/A sort_file_max_size=sort_file_max_size,
448N/A writable_root=writable_root)
430N/A except (RuntimeError, sr.RepositoryError), _e:
448N/A emsg("pkg.depotd: %s" % _e)
290N/A sys.exit(1)
290N/A except search_errors.IndexingException, _e:
290N/A emsg("pkg.depotd: %s" % str(_e), "INDEX")
430N/A sys.exit(1)
395N/A except api_errors.ApiException, _e:
290N/A emsg("pkg.depotd: %s" % str(_e))
290N/A sys.exit(1)
290N/A
290N/A if not rebuild and not add_content and not repo.mirror and \
1637N/A not (repo.read_only and not repo.writable_root):
1637N/A # Automatically update search indexes on startup if not already
290N/A # told to, and not in readonly/mirror mode.
613N/A reindex = True
613N/A
613N/A if reindex:
613N/A try:
613N/A # Only execute a index refresh here if --exit-ready was
613N/A # requested; it will be handled later in the setup
613N/A # process for other cases.
613N/A if repo.root and exit_ready:
1632N/A repo.refresh_index()
1632N/A except (sr.RepositoryError, search_errors.IndexingException,
1632N/A api_errors.ApiException), e:
1632N/A emsg(str(e), "INDEX")
1632N/A sys.exit(1)
1632N/A elif rebuild:
1632N/A try:
1632N/A repo.rebuild(build_index=True)
613N/A except sr.RepositoryError, e:
290N/A emsg(str(e), "REBUILD")
742N/A sys.exit(1)
395N/A except (search_errors.IndexingException,
395N/A api_errors.UnknownErrors,
395N/A api_errors.PermissionsException), e:
395N/A emsg(str(e), "INDEX")
395N/A sys.exit(1)
395N/A elif add_content:
395N/A try:
395N/A repo.add_content()
395N/A repo.refresh_index()
395N/A except sr.RepositoryError, e:
290N/A emsg(str(e), "ADD_CONTENT")
383N/A sys.exit(1)
395N/A except (search_errors.IndexingException,
395N/A api_errors.UnknownErrors,
395N/A api_errors.PermissionsException), e:
395N/A emsg(str(e), "INDEX")
395N/A sys.exit(1)
290N/A
290N/A # Ready to start depot; exit now if requested.
395N/A if exit_ready:
395N/A sys.exit(0)
395N/A
395N/A # Next, initialize depot.
1483N/A if nasty:
395N/A depot = ds.NastyDepotHTTP(repo, dconf)
1498N/A else:
1498N/A depot = ds.DepotHTTP(repo, dconf)
395N/A
290N/A # Now build our site configuration.
290N/A conf = {
395N/A "/": {
395N/A # We have to override cherrypy's default response_class so that
395N/A # we have access to the write() callable to stream data
613N/A # directly to the client.
290N/A "wsgi.response_class": dr.DepotResponse,
395N/A },
395N/A "/robots.txt": {
395N/A "tools.staticfile.on": True,
395N/A "tools.staticfile.filename": os.path.join(depot.web_root,
395N/A "robots.txt")
395N/A },
395N/A }
395N/A
290N/A proxy_base = dconf.get_property("pkg", "proxy_base")
395N/A if proxy_base:
395N/A # This changes the base URL for our server, and is primarily
395N/A # intended to allow our depot process to operate behind Apache
395N/A # or some other webserver process.
395N/A #
395N/A # Visit the following URL for more information:
430N/A # http://cherrypy.org/wiki/BuiltinTools#tools.proxy
395N/A proxy_conf = {
395N/A "tools.proxy.on": True,
395N/A "tools.proxy.local": "",
395N/A "tools.proxy.base": proxy_base
395N/A }
395N/A
691N/A # Now merge or add our proxy configuration information into the
691N/A # existing configuration.
691N/A for entry in proxy_conf:
691N/A conf["/"][entry] = proxy_conf[entry]
691N/A
691N/A if ll_mirror:
691N/A ds.DNSSD_Plugin(cherrypy.engine, gconf).subscribe()
691N/A
395N/A if reindex:
395N/A # Tell depot to update search indexes when possible;
395N/A # this is done as a background task so that packages
395N/A # can be served immediately while search indexes are
395N/A # still being updated.
1516N/A depot._queue_refresh_index()
1516N/A
395N/A # If stdin is not a tty and the pkgdepot controller isn't being used,
395N/A # then assume process should be daemonized.
395N/A if not os.environ.get("PKGDEPOT_CONTROLLER") and \
395N/A not os.isatty(sys.stdin.fileno()):
395N/A Daemonizer(cherrypy.engine).subscribe()
395N/A
try:
root = cherrypy.Application(depot)
cherrypy.quickstart(root, config=conf)
except Exception, _e:
emsg("pkg.depotd: unknown error starting depot server, " \
"illegal option value specified?")
emsg(_e)
sys.exit(1)