depot.py revision 466
290N/A#!/usr/bin/python2.4
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#
290N/A# Copyright 2008 Sun Microsystems, Inc. All rights reserved.
290N/A# Use is subject to license terms.
290N/A#
290N/A
290N/A# pkg.depotd - package repository daemon
290N/A
383N/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
383N/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
290N/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
290N/A# only a basic HTTP/HTTPS server in place.
383N/A
290N/A# XXX We should support simple "last-modified" operations via HEAD queries.
290N/A
290N/A# XXX Although we pushed the evaluation of next-version, etc. to the pull
290N/A# client, we should probably provide a query API to do same on the server, for
290N/A# dumb clients (like a notification service).
290N/A
290N/A# The default authority for the depot.
290N/AAUTH_DEFAULT = "opensolaris.org"
290N/A# The default repository path.
290N/AREPO_PATH_DEFAULT = "/var/pkg/repo"
290N/A# The default port to serve data from.
290N/APORT_DEFAULT = 80
290N/A# The minimum number of threads allowed.
290N/ATHREADS_MIN = 1
290N/A# The default number of threads to start.
290N/ATHREADS_DEFAULT = 10
290N/A# The maximum number of threads that can be started.
290N/ATHREADS_MAX = 100
290N/A# The default server socket timeout in seconds. We want this to be longer than
290N/A# the normal default of 10 seconds to accommodate clients with poor quality
290N/A# connections.
290N/ASOCKET_TIMEOUT_DEFAULT = 60
290N/A# Whether modify operations should be allowed.
290N/AREADONLY_DEFAULT = False
290N/A# Whether the repository catalog should be rebuilt on startup.
290N/AREBUILD_DEFAULT = False
290N/A# Whether the indexes should be rebuilt
290N/AREINDEX_DEFAULT = False
290N/A# Not in mirror mode by default
290N/AMIRROR_DEFAULT = False
290N/A
290N/Aimport getopt
290N/Aimport logging
290N/Aimport os
290N/Aimport sys
290N/Aimport urlparse
290N/A
290N/Atry:
290N/A import cherrypy
290N/A version = cherrypy.__version__.split('.')
290N/A if map(int, version) < [3, 1, 0]:
290N/A raise ImportError
290N/A elif map(int, version) >= [3, 2, 0]:
290N/A raise ImportError
290N/Aexcept ImportError:
290N/A print """cherrypy 3.1.0 or greater (but less than 3.2.0) is """ \
290N/A """required to use this program."""
290N/A sys.exit(2)
290N/A
290N/Aimport pkg.server.face as face
290N/Aimport pkg.server.config as config
290N/Aimport pkg.server.depot as depot
290N/Aimport pkg.server.repository as repo
290N/Aimport pkg.server.repositoryconfig as rc
290N/Afrom pkg.misc import port_available, msg, emsg
290N/A
290N/Aclass LogSink(object):
290N/A """This is a dummy object that we can use to discard log entries
290N/A without relying on non-portable interfaces such as /dev/null."""
290N/A
290N/A def write(self, *args, **kwargs):
290N/A """Discard the bits."""
290N/A pass
290N/A
290N/A def flush(self, *args, **kwargs):
290N/A """Discard the bits."""
290N/A pass
290N/A
290N/Adef usage(text):
290N/A if text:
290N/A emsg(text)
290N/A
290N/A print """\
290N/AUsage: /usr/lib/pkg.depotd [--readonly] [--rebuild] [--mirror] [--proxy-base url]
290N/A [--log-access dest] [--log-errors dest] [-d repo_dir] [-p port]
290N/A [-s threads] [-t socket_timeout]
290N/A
290N/A --readonly Read-only operation; modifying operations disallowed
290N/A --rebuild Re-build the catalog from pkgs in depot
290N/A Cannot be used with --readonly or --mirror
290N/A --mirror Content mirror mode. Publishing and metadata operations
290N/A disabled
290N/A --proxy-base The url to use as the base for generating internal
290N/A redirects and content.
290N/A --log-access The destination for any access related information
290N/A logged by the depot process. Possible values are:
290N/A stderr, stdout, none, or an absolute pathname. The
290N/A default value is stdout if stdout is a tty; otherwise
290N/A the default value is none.
290N/A --log-errors The destination for any errors or other information
290N/A logged by the depot process. Possible values are:
290N/A stderr, stdout, none, or an absolute pathname. The
290N/A default value is stderr.
290N/A"""
290N/A sys.exit(2)
290N/A
290N/Aclass OptionError(Exception):
290N/A """Option exception. """
290N/A
290N/A def __init__(self, *args):
290N/A Exception.__init__(self, *args)
290N/A
290N/Aif __name__ == "__main__":
290N/A
290N/A port = PORT_DEFAULT
290N/A threads = THREADS_DEFAULT
290N/A socket_timeout = SOCKET_TIMEOUT_DEFAULT
290N/A readonly = READONLY_DEFAULT
290N/A rebuild = REBUILD_DEFAULT
290N/A reindex = REINDEX_DEFAULT
290N/A proxy_base = None
290N/A mirror = MIRROR_DEFAULT
290N/A
290N/A if "PKG_REPO" in os.environ:
290N/A repo_path = os.environ["PKG_REPO"]
290N/A else:
290N/A repo_path = REPO_PATH_DEFAULT
290N/A
290N/A # By default, if the destination for a particular log type is not
290N/A # specified, this is where we will send the output.
290N/A log_routes = {
290N/A "access": "none",
290N/A "errors": "stderr"
290N/A }
290N/A log_opts = ["--log-%s" % log_type for log_type in log_routes]
290N/A
290N/A # If stdout is a tty, then send access output there by default instead
290N/A # of discarding it.
290N/A if os.isatty(sys.stdout.fileno()):
290N/A log_routes["access"] = "stdout"
290N/A
290N/A opt = None
290N/A try:
290N/A long_opts = ["readonly", "rebuild", "mirror", "refresh-index",
290N/A "proxy-base="]
290N/A for opt in log_opts:
290N/A long_opts.append("%s=" % opt.lstrip('--'))
290N/A opts, pargs = getopt.getopt(sys.argv[1:], "d:np:s:t:",
290N/A long_opts)
290N/A for opt, arg in opts:
290N/A if opt == "-n":
290N/A sys.exit(0)
290N/A elif opt == "-d":
290N/A repo_path = arg
290N/A elif opt == "-p":
290N/A port = int(arg)
290N/A elif opt == "-s":
290N/A threads = int(arg)
290N/A if threads < THREADS_MIN:
290N/A raise OptionError, \
290N/A "minimum value is %d" % THREADS_MIN
290N/A if threads > THREADS_MAX:
290N/A raise OptionError, \
290N/A "maximum value is %d" % THREADS_MAX
290N/A elif opt == "-t":
290N/A socket_timeout = int(arg)
290N/A elif opt in log_opts:
290N/A if arg is None or arg == "":
290N/A raise OptionError, \
290N/A "You must specify a log " \
290N/A "destination."
290N/A log_routes[opt.lstrip("--log-")] = arg
290N/A elif opt == "--readonly":
290N/A readonly = True
290N/A elif opt == "--rebuild":
290N/A rebuild = True
290N/A elif opt == "--refresh-index":
290N/A # Note: This argument is for internal use
290N/A # only. It's used when pkg.depotd is reexecing
290N/A # itself and needs to know that's the case.
290N/A # This flag is purposefully omitted in usage.
290N/A # The supported way to forcefully reindex is to
290N/A # kill any pkg.depot using that directory,
290N/A # remove the index directory, and restart the
290N/A # pkg.depot process. The index will be rebuilt
290N/A # automatically on startup.
290N/A reindex = True
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
290N/A # don't need it.
290N/A scheme, netloc, path, params, query, \
290N/A fragment = urlparse.urlparse(arg,
290N/A allow_fragments=0)
290N/A
290N/A # Rebuild the url without the scheme and
290N/A # remove the leading // urlunparse adds.
290N/A proxy_base = urlparse.urlunparse(("", netloc,
290N/A path, params, query, fragment)
290N/A ).lstrip("//")
290N/A
290N/A elif opt == "--mirror":
290N/A mirror = True
290N/A except getopt.GetoptError, e:
290N/A usage("pkg.depotd: %s" % e.msg)
290N/A except OptionError, e:
290N/A usage("pkg.depotd: option: %s -- %s" % (opt, e))
290N/A except (ArithmeticError, ValueError):
290N/A usage("pkg.depotd: illegal option value: %s specified " \
290N/A "for option: %s" % (arg, opt))
290N/A
290N/A if rebuild and reindex:
290N/A usage("--refresh-index cannot be used with --rebuild")
290N/A if rebuild and (readonly or mirror):
290N/A usage("--readonly and --mirror cannot be used with --rebuild")
290N/A if reindex and (readonly or mirror):
290N/A usage("--readonly and --mirror cannot be used with " \
290N/A "--refresh-index")
290N/A
290N/A # If the program is going to reindex, the port is irrelevant since
290N/A # the program will not bind to a port.
290N/A if not reindex:
290N/A available, msg = port_available(None, port)
290N/A if not available:
290N/A print "pkg.depotd: unable to bind to the specified " \
290N/A "port: %d. Reason: %s" % (port, msg)
290N/A sys.exit(1)
290N/A
290N/A try:
290N/A face.set_content_root(os.environ["PKG_DEPOT_CONTENT"])
290N/A except KeyError:
290N/A pass
290N/A
290N/A scfg = config.SvrConfig(repo_path, AUTH_DEFAULT)
290N/A
290N/A if rebuild:
290N/A scfg.destroy_catalog()
290N/A
290N/A if readonly:
290N/A scfg.set_read_only()
290N/A
290N/A if mirror:
290N/A scfg.set_mirror()
290N/A
290N/A try:
290N/A scfg.init_dirs()
290N/A except EnvironmentError, e:
290N/A print "pkg.depotd: an error occurred while trying to " \
290N/A "initialize the depot repository directory " \
290N/A "structures:\n%s" % e
290N/A sys.exit(1)
290N/A
290N/A # Setup our global configuration.
290N/A # Global cherrypy configuration
290N/A gconf = {
290N/A "environment": "production",
290N/A "checker.on": True,
290N/A "log.screen": False,
290N/A "server.socket_host": "0.0.0.0",
290N/A "server.socket_port": port,
290N/A "server.thread_pool": threads,
290N/A "server.socket_timeout": socket_timeout,
290N/A "tools.log_headers.on": True
290N/A }
290N/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
290N/A for log_type in log_type_map:
290N/A dest = log_routes[log_type]
290N/A if dest in ("stdout", "stderr", "none"):
290N/A if dest == "none":
290N/A h = logging.StreamHandler(LogSink())
290N/A else:
290N/A h = logging.StreamHandler(eval("sys.%s" % \
290N/A dest))
290N/A
290N/A h.setLevel(logging.DEBUG)
290N/A h.setFormatter(cherrypy._cplogging.logfmt)
290N/A log_obj = eval("cherrypy.log.%s" % \
290N/A log_type_map[log_type]["attr"])
290N/A log_obj.addHandler(h)
290N/A # Since we've replaced cherrypy's log handler with our
290N/A # own, we don't want the output directed to a file.
290N/A dest = ""
290N/A
290N/A gconf[log_type_map[log_type]["param"]] = dest
290N/A
290N/A # Now build our site configuration.
290N/A conf = {
290N/A "/": {
290N/A # We have to override cherrypy's default response_class so that
290N/A # we have access to the write() callable to stream data
290N/A # directly to the client.
290N/A "wsgi.response_class": depot.DepotResponse,
290N/A },
290N/A "/robots.txt": {
290N/A "tools.staticfile.on": True,
290N/A "tools.staticfile.filename": os.path.join(face.content_root,
290N/A "robots.txt")
290N/A },
290N/A "/static": {
290N/A "tools.staticdir.on": True,
290N/A "tools.staticdir.root": face.content_root,
290N/A "tools.staticdir.dir": ""
290N/A }
290N/A }
290N/A
290N/A if proxy_base:
290N/A # This changes the base URL for our server, and is primarily
383N/A # intended to allow our depot process to operate behind Apache
383N/A # or some other webserver process.
383N/A #
383N/A # Visit the following URL for more information:
383N/A # http://cherrypy.org/wiki/BuiltinTools#tools.proxy
383N/A proxy_conf = {
383N/A "tools.proxy.on": True,
383N/A "tools.proxy.local": "",
383N/A "tools.proxy.base": proxy_base
383N/A }
383N/A
383N/A if "/" not in conf:
383N/A conf["/"] = {}
383N/A
383N/A # Now merge or add our proxy configuration information into the
383N/A # existing configuration.
383N/A for entry in proxy_conf:
383N/A conf["/"][entry] = proxy_conf[entry]
383N/A
383N/A cherrypy.config.update(gconf)
383N/A
383N/A # Now that our logging, etc. has been setup, it's safe to perform any
383N/A # remaining preparation.
383N/A if reindex:
290N/A scfg.acquire_catalog(rebuild=False)
290N/A scfg.catalog.run_update_index()
290N/A sys.exit(0)
290N/A
290N/A scfg.acquire_in_flight()
290N/A scfg.acquire_catalog()
290N/A
290N/A try:
290N/A root = cherrypy.Application(repo.Repository(scfg))
290N/A except rc.InvalidAttributeValueError, e:
290N/A emsg("pkg.depotd: repository.conf error: %s" % e)
290N/A sys.exit(1)
290N/A
290N/A try:
290N/A cherrypy.quickstart(root, config=conf)
290N/A except:
290N/A usage("pkg.depotd: unknown error starting depot, illegal " \
290N/A "option value specified?")
290N/A
290N/A