depot.py revision 689
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"
382N/A# The default path for static and other web content.
382N/ACONTENT_PATH_DEFAULT = "/usr/share/lib/pkg"
382N/A# The default port to serve data from.
382N/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
429N/A# Whether the repository catalog should be rebuilt on startup.
429N/AREBUILD_DEFAULT = False
461N/A# Whether the indexes should be rebuilt
461N/AREINDEX_DEFAULT = False
382N/A# Not in mirror mode by default
26N/AMIRROR_DEFAULT = False
466N/A
0N/Aimport getopt
468N/Aimport gettext
52N/Aimport locale
451N/Aimport logging
0N/Aimport os
382N/Aimport os.path
382N/Aimport sys
382N/Aimport urlparse
452N/A
382N/Atry:
452N/A import cherrypy
382N/A version = cherrypy.__version__.split('.')
382N/A if map(int, version) < [3, 1, 0]:
452N/A raise ImportError
382N/A elif map(int, version) >= [3, 2, 0]:
382N/A raise ImportError
22N/Aexcept ImportError:
114N/A print """cherrypy 3.1.0 or greater (but less than 3.2.0) is """ \
26N/A """required to use this program."""
382N/A sys.exit(2)
382N/A
428N/Aimport pkg.server.face as face
466N/Aimport pkg.server.config as config
466N/Aimport pkg.server.depot as depot
466N/Aimport pkg.server.repository as repo
466N/Aimport pkg.server.repositoryconfig as rc
466N/Aimport pkg.search_errors as search_errors
23N/Afrom pkg.misc import port_available, msg, emsg
466N/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."""
466N/A
466N/A def write(self, *args, **kwargs):
466N/A """Discard the bits."""
466N/A pass
466N/A
466N/A def flush(self, *args, **kwargs):
466N/A """Discard the bits."""
466N/A pass
26N/A
461N/Adef usage(text):
466N/A if text:
466N/A emsg(text)
382N/A
135N/A print """\
157N/AUsage: /usr/lib/pkg.depotd [-d repo_dir] [-p port] [-s threads]
461N/A [-t socket_timeout] [--content-root] [--log-access dest]
461N/A [--log-errors dest] [--mirror] [--proxy-base url] [--readonly]
461N/A [--rebuild]
451N/A
451N/A --content-root The file system path to the directory containing the
466N/A the static and other web content used by the depot's
466N/A browser user interface. The default value is
466N/A '/usr/share/lib/pkg'.
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
26N/A logged by the depot process. Possible values are:
135N/A stderr, stdout, none, or an absolute pathname. The
14N/A default value is stderr.
382N/A --mirror Package mirror mode; publishing and metadata operations
429N/A disallowed. Cannot be used with --readonly or
14N/A --rebuild.
404N/A --proxy-base The url to use as the base for generating internal
404N/A redirects and content.
30N/A --readonly Read-only operation; modifying operations disallowed.
382N/A Cannot be used with --mirror or --rebuild.
30N/A --rebuild Re-build the catalog from pkgs in depot. Cannot be
382N/A used with --mirror or --readonly.
382N/A"""
382N/A sys.exit(2)
382N/A
382N/Aclass OptionError(Exception):
429N/A """Option exception. """
451N/A
461N/A def __init__(self, *args):
258N/A Exception.__init__(self, *args)
382N/A
382N/Aif __name__ == "__main__":
382N/A
382N/A locale.setlocale(locale.LC_ALL, "")
30N/A gettext.install("pkg", "/usr/share/locale")
466N/A
466N/A port = PORT_DEFAULT
466N/A threads = THREADS_DEFAULT
466N/A socket_timeout = SOCKET_TIMEOUT_DEFAULT
466N/A readonly = READONLY_DEFAULT
466N/A rebuild = REBUILD_DEFAULT
466N/A reindex = REINDEX_DEFAULT
466N/A proxy_base = None
466N/A mirror = MIRROR_DEFAULT
466N/A
466N/A if "PKG_REPO" in os.environ:
466N/A repo_path = os.environ["PKG_REPO"]
466N/A else:
466N/A repo_path = REPO_PATH_DEFAULT
54N/A
466N/A try:
466N/A content_root = os.environ["PKG_DEPOT_CONTENT"]
466N/A except KeyError:
466N/A try:
382N/A content_root = os.path.join(os.environ['PKG_HOME'],
466N/A 'share/lib/pkg')
135N/A except KeyError:
135N/A content_root = CONTENT_PATH_DEFAULT
135N/A
135N/A # By default, if the destination for a particular log type is not
382N/A # specified, this is where we will send the output.
135N/A log_routes = {
135N/A "access": "none",
382N/A "errors": "stderr"
382N/A }
382N/A log_opts = ["--log-%s" % log_type for log_type in log_routes]
382N/A
382N/A # If stdout is a tty, then send access output there by default instead
382N/A # of discarding it.
382N/A if os.isatty(sys.stdout.fileno()):
382N/A log_routes["access"] = "stdout"
382N/A
382N/A opt = None
466N/A try:
466N/A long_opts = ["content-root=", "mirror", "proxy-base=",
466N/A "readonly", "rebuild", "refresh-index"]
466N/A for opt in log_opts:
466N/A long_opts.append("%s=" % opt.lstrip('--'))
466N/A opts, pargs = getopt.getopt(sys.argv[1:], "d:np:s:t:",
135N/A long_opts)
382N/A for opt, arg in opts:
157N/A if opt == "-n":
382N/A sys.exit(0)
429N/A elif opt == "-d":
429N/A repo_path = arg
429N/A elif opt == "-p":
429N/A port = int(arg)
429N/A elif opt == "-s":
429N/A threads = int(arg)
429N/A if threads < THREADS_MIN:
429N/A raise OptionError, \
429N/A "minimum value is %d" % THREADS_MIN
429N/A if threads > THREADS_MAX:
429N/A raise OptionError, \
451N/A "maximum value is %d" % THREADS_MAX
451N/A elif opt == "-t":
451N/A socket_timeout = int(arg)
451N/A elif opt == "--content-root":
451N/A if arg == "":
451N/A raise OptionError, "You must specify " \
451N/A "a directory path."
451N/A content_root = arg
451N/A elif opt in log_opts:
451N/A if arg is None or arg == "":
451N/A raise OptionError, \
451N/A "You must specify a log " \
451N/A "destination."
451N/A log_routes[opt.lstrip("--log-")] = arg
451N/A elif opt == "--mirror":
461N/A mirror = True
461N/A elif opt == "--proxy-base":
135N/A # Attempt to decompose the url provided into
466N/A # its base parts. This is done so we can
382N/A # remove any scheme information since we
466N/A # don't need it.
382N/A scheme, netloc, path, params, query, \
466N/A fragment = urlparse.urlparse(arg,
466N/A allow_fragments=0)
451N/A
445N/A # Rebuild the url without the scheme and
466N/A # remove the leading // urlunparse adds.
461N/A proxy_base = urlparse.urlunparse(("", netloc,
466N/A path, params, query, fragment)
461N/A ).lstrip("//")
466N/A elif opt == "--readonly":
466N/A readonly = True
451N/A elif opt == "--rebuild":
429N/A rebuild = True
429N/A elif opt == "--refresh-index":
429N/A # Note: This argument is for internal use
429N/A # only. It's used when pkg.depotd is reexecing
429N/A # itself and needs to know that's the case.
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,
386N/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 except getopt.GetoptError, e:
382N/A usage("pkg.depotd: %s" % e.msg)
468N/A except OptionError, e:
382N/A usage("pkg.depotd: option: %s -- %s" % (opt, e))
382N/A except (ArithmeticError, ValueError):
382N/A usage("pkg.depotd: illegal option value: %s specified " \
382N/A "for option: %s" % (arg, opt))
382N/A
382N/A if rebuild and reindex:
382N/A usage("--refresh-index cannot be used with --rebuild")
461N/A if rebuild and (readonly or mirror):
461N/A usage("--readonly and --mirror cannot be used with --rebuild")
461N/A if reindex and (readonly or mirror):
382N/A usage("--readonly and --mirror cannot be used with " \
382N/A "--refresh-index")
382N/A
382N/A # If the program is going to reindex, the port is irrelevant since
382N/A # the program will not bind to a port.
382N/A if not reindex:
382N/A available, msg = port_available(None, port)
382N/A if not available:
452N/A print "pkg.depotd: unable to bind to the specified " \
466N/A "port: %d. Reason: %s" % (port, msg)
466N/A sys.exit(1)
382N/A else:
382N/A # Not applicable for reindexing operations.
466N/A content_root = None
452N/A
382N/A scfg = config.SvrConfig(repo_path, content_root, AUTH_DEFAULT)
382N/A
466N/A if rebuild:
466N/A scfg.destroy_catalog()
466N/A
466N/A if readonly:
466N/A scfg.set_read_only()
466N/A
466N/A if mirror:
466N/A scfg.set_mirror()
466N/A
466N/A try:
466N/A scfg.init_dirs()
466N/A except (RuntimeError, EnvironmentError), e:
466N/A print "pkg.depotd: an error occurred while trying to " \
466N/A "initialize the depot repository directory " \
466N/A "structures:\n%s" % e
466N/A sys.exit(1)
466N/A
466N/A # Setup our global configuration.
466N/A # Global cherrypy configuration
466N/A gconf = {
466N/A "environment": "production",
466N/A "checker.on": True,
466N/A "log.screen": False,
466N/A "server.socket_host": "0.0.0.0",
466N/A "server.socket_port": port,
466N/A "server.thread_pool": threads,
466N/A "server.socket_timeout": socket_timeout,
466N/A "tools.log_headers.on": True
466N/A }
466N/A
466N/A log_type_map = {
466N/A "errors": {
466N/A "param": "log.error_file",
466N/A "attr": "error_log"
382N/A },
451N/A "access": {
382N/A "param": "log.access_file",
452N/A "attr": "access_log"
452N/A }
452N/A }
452N/A
452N/A for log_type in log_type_map:
452N/A dest = log_routes[log_type]
382N/A if dest in ("stdout", "stderr", "none"):
382N/A if dest == "none":
382N/A h = logging.StreamHandler(LogSink())
382N/A else:
382N/A h = logging.StreamHandler(eval("sys.%s" % \
382N/A dest))
382N/A
382N/A h.setLevel(logging.DEBUG)
382N/A h.setFormatter(cherrypy._cplogging.logfmt)
382N/A log_obj = eval("cherrypy.log.%s" % \
382N/A log_type_map[log_type]["attr"])
145N/A log_obj.addHandler(h)
451N/A # Since we've replaced cherrypy's log handler with our
451N/A # own, we don't want the output directed to a file.
451N/A dest = ""
451N/A
451N/A gconf[log_type_map[log_type]["param"]] = dest
451N/A
451N/A cherrypy.config.update(gconf)
451N/A
451N/A # Now that our logging, etc. has been setup, it's safe to perform any
451N/A # remaining preparation.
451N/A if reindex:
451N/A scfg.acquire_catalog(rebuild=False)
451N/A try:
451N/A scfg.catalog.run_update_index()
451N/A except search_errors.IndexingException, e:
451N/A cherrypy.log(str(e), "INDEX")
451N/A sys.exit(1)
451N/A sys.exit(0)
451N/A
451N/A # Now build our site configuration.
451N/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(scfg.web_static_root,
466N/A "robots.txt")
466N/A },
466N/A "/static": {
217N/A "tools.staticdir.on": True,
466N/A "tools.staticdir.root": scfg.web_static_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
382N/A # intended to allow our depot process to operate behind Apache
466N/A # or some other webserver process.
466N/A #
217N/A # Visit the following URL for more information:
# http://cherrypy.org/wiki/BuiltinTools#tools.proxy
proxy_conf = {
"tools.proxy.on": True,
"tools.proxy.local": "",
"tools.proxy.base": proxy_base
}
if "/" not in conf:
conf["/"] = {}
# Now merge or add our proxy configuration information into the
# existing configuration.
for entry in proxy_conf:
conf["/"][entry] = proxy_conf[entry]
scfg.acquire_in_flight()
scfg.acquire_catalog()
try:
root = cherrypy.Application(repo.Repository(scfg))
except rc.InvalidAttributeValueError, e:
emsg("pkg.depotd: repository.conf error: %s" % e)
sys.exit(1)
try:
cherrypy.quickstart(root, config=conf)
except:
usage("pkg.depotd: unknown error starting depot, illegal " \
"option value specified?")