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