#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License (the "License").
# You may not use this file except in compliance with the License.
#
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# See the License for the specific language governing permissions
# and limitations under the License.
#
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
# If applicable, add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your own identifying
# information: Portions Copyright [yyyy] [name of copyright owner]
#
# CDDL HEADER END
#
#
#
import calendar
import errno
import getopt
import gettext
import locale
import os
import shutil
import sys
import tempfile
import traceback
import warnings
# Globals
cache_dir = None
src_cat = None
tmpdirs = []
temp_root = None
xport = None
xport_cfg = None
dest_xport = None
targ_pub = None
target = None
"""Emit an error message prefixed by the command name """
# If we get passed something like an Exception, we can convert
# it down to a string.
# If the message starts with whitespace, assume that it should come
# *before* the command-name prefix.
# This has to be a constant value as we can't reliably get our actual
# program name on all platforms.
"""Emit a usage message and optionally prefix it with a more specific
error message. Causes program to exit."""
if usage_error:
msg(_("""\
Usage:
pkgrecv [-aknrv] [-s src_uri] [-d (path|dest_uri)] [-c cache_dir]
[-m match] [--mog-file file_path ...] [--raw]
[--key src_key --cert src_cert]
[--dkey dest_key --dcert dest_cert]
(fmri|pattern) ...
pkgrecv [-s src_repo_uri] --newest
pkgrecv [-nv] [-s src_repo_uri] [-d path] [-p publisher ...]
[--key src_key --cert src_cert] --clone
Options:
-a Store the retrieved package data in a pkg(7) archive
at the location specified by -d. The file may not
already exist, and this option may only be used with
filesystem-based destinations.
-c cache_dir The path to a directory that will be used to cache
downloaded content. If one is not supplied, the
client will automatically pick a cache directory.
In the case where a download is interrupted, and a
cache directory was automatically chosen, use this
option to resume the download.
-d path_or_uri The filesystem path or URI of the target repository to
republish packages to. The target must already exist.
New repositories can be created using pkgrepo(1).
-h Display this usage message.
-k Keep the retrieved package content compressed, ignored
when republishing. Should not be used with pkgsend.
-m match Controls matching behaviour using the following values:
all-timestamps (default)
includes all matching timestamps (implies
all-versions)
all-versions
includes all matching versions
latest
includes only the latest version of each package
-n Perform a trial run with no changes made.
-v Display verbose output.
-p publisher Only clone the given publisher. Can be specified
multiple times. Only valid with --clone.
-r Recursively evaluates all dependencies for the provided
list of packages and adds them to the list.
-s src_repo_uri A URI representing the location of a pkg(7)
repository to retrieve package data from.
--clone Make an exact copy of the source repository. By default,
the clone operation will only succeed if publishers in
the source repository are also present in the
destination. By using -p, the operation can be limited
to specific publishers which will be added to the
destination repository if not already present.
Packages in the destination repository which are not in
the source will be removed.
Cloning will leave the destination repository altered in
case of an error.
--mog-file Specifies the path to a file containing pkgmogrify(1)
transforms to be applied to every package before it is
copied to the destination. A path of '-' can be
specified to use stdin. This option can be specified
multiple times. This option can not be combined with
--clone.
--newest List the most recent versions of the packages available
from the specified repository and exit. (All other
options except -s will be ignored.)
--raw Retrieve and store the raw package data in a set of
directory structures by stem and version at the location
specified by -d. May only be used with filesystem-
based destinations.
--key src_key Specify a client SSL key file to use for pkg retrieval.
--cert src_cert Specify a client SSL certificate file to use for pkg
retrieval.
--dkey dest_key Specify a client SSL key file to use for pkg
publication.
--dcert dest_cert Specify a client SSL certificate file to use for pkg
publication.
Environment:
PKG_DEST Destination directory or URI
PKG_SRC Source URI or path"""))
"""To be called at program finish."""
for d in tmpdirs:
# If the cache_dir is in the list of directories that should
# be cleaned up, but we're exiting with an error, then preserve
# the directory so downloads may be resumed.
error(_("\n\nCached files were preserved in the "
"following directory:\n\t{0}\nUse pkgrecv -c "
"to resume the interrupted download.").format(
continue
try:
except apx.TransportError:
# If this fails, ignore it as this was a last ditch
# attempt anyway.
pass
"""To be called when a fatal error is encountered."""
if err:
# Clear any possible output first.
msg("")
def get_tracker():
try:
progresstracker = \
except progress.ProgressTrackerException:
return progresstracker
m = None
else:
# A FactoredManifest is used here to reduce peak memory
# usage (notably when -r was specified).
try:
except:
if validate:
errors = []
for a in m.gen_actions():
try:
except Exception as e:
if errors:
return m
"""Find matching fmri using CONSTRAINT_AUTO cache for performance.
Returns None if no matching fmri is found."""
# Iterate in reverse so newest version is evaluated first.
for f in fmris:
return f
return
# The user may be recursing 'entire' or 'redistributable'.
s = set()
for f in fmri_list:
# Restore the previous default.
return list(s)
"""Expand all dependencies."""
# XXX???
# tracker.evaluate_progress(pkgfmri=pfmri)
for a in m.gen_actions_by_type("depend"):
return s
"""Takes a manifest and return
(get_bytes, get_files, send_bytes, send_comp_bytes) tuple."""
getb = 0
getf = 0
sendb = 0
sendcb = 0
for a in mfst.gen_actions():
getb += get_pkg_otw_size(a)
getf += 1
if a.name == "signature":
getb += a.get_action_chain_csize()
"""Takes a manifest and a multi object and adds the hashes to the multi
object."""
for a in mfst.gen_actions():
multi.add_action(a)
"""Returns a filtered version of fmri_list based on the provided
parameters."""
if all_timestamps:
pass
elif all_versions:
dedup = {}
for f in fmri_list:
else:
dedup = {}
for f in fmri_list:
return fmri_list
"""Fetch the catalog from src_uri.
target_catalog is a hint about whether this is a destination catalog,
which helps the progress tracker render the refresh output properly."""
# Create a temporary directory for catalog.
try:
except apx.TransportError as e:
# Assume that a catalog doesn't exist for the target publisher,
# and drive on. If there was an actual failure due to a
# transport issue, let the failure happen whenever some other
# operation is attempted later.
finally:
def main_func():
src_uri = None
incoming_dir = None
src_pub = None
key = None
cert = None
dkey = None
dcert = None
mog_files = []
publishers = []
# set process limits for memory consumption to 8GB
try:
["cert=", "key=", "dcert=", "dkey=", "mog-file=", "newest",
"raw", "debug=", "clone"])
except getopt.GetoptError as e:
if opt == "-a":
elif opt == "-c":
elif opt == "--clone":
elif opt == "-d":
value = "True"
else:
try:
except (AttributeError, ValueError):
usage(_("{opt} takes argument of form "
"name=value, not {arg}").format(
elif opt == "-h":
elif opt == "-k":
elif opt == "-m":
if arg == "all-timestamps":
elif arg == "all-versions":
elif arg == "latest":
else:
arg))
elif opt == "-n":
elif opt == "-p":
elif opt == "-r":
elif opt == "-s":
elif opt == "-v":
elif opt == "--mog-file":
elif opt == "--newest":
elif opt == "--raw":
elif opt == "--key":
elif opt == "--cert":
elif opt == "--dkey":
elif opt == "--dcert":
if not list_newest and not target:
usage(_("a destination must be provided"))
if not src_uri:
usage(_("a source repository must be provided"))
else:
if not cache_dir:
# Only clean-up cache dir if implicitly created by pkgrecv.
# User's cache-dirs should be preserved
else:
if clone:
usage(_("--clone can not be used with -c.\n"
"Content will be downloaded directly to the "
"destination repository and re-downloading after a "
"pkgrecv failure will not be required."))
usage(_("--clone can not be used with --raw.\n"))
usage(_("--clone can not be used with -a.\n"))
if clone and list_newest:
usage(_("--clone can not be used with --newest.\n"))
usage(_("--clone does not support FMRI patterns"))
if publishers and not clone:
usage(_("-p can only be used with --clone.\n"))
usage(_("--mog-file can not be used with --clone.\n"))
# Create transport and transport config
# Since publication destinations may only have one repository configured
# per publisher, create destination as separate transport in case source
# and destination have identical publisher configuration but different
# repository endpoints.
# Configure src publisher(s).
if clone:
args += (publishers,)
return clone_repo(*args)
if archive:
# Retrieving package data for archival requires a different mode
# of operation so gets its own routine. Notably, it requires
# that all package data be retrieved before the archival process
# is started.
return archive_pkgs(*args)
# Normal package transfer allows operations on a per-package basis.
return transfer_pkgs(*args)
# Reduce unmatched patterns to those that were unmatched for all
# publishers.
if not unmatched:
return
# If any match failures remain, abort with an error.
rval = 1
if total_processed > 0:
rval = 3
"""Returns the set of matching FMRIs for the given arguments."""
global src_cat
# Avoid overhead of going through matching if user requested all
# packages.
try:
except apx.PackageMatchErrors as e:
# Track anything that failed to match.
else:
if not matches:
# No matches at all; nothing to do for this publisher.
return matches
if recursive:
msg(_("Retrieving manifests for dependency "
"evaluation ..."))
return matches
"""Helper routine for mogrifying manifest. Precondition: mog_files
has at least one element."""
includes = []
macros = {}
printinfo = []
output = []
line_buffer = []
# Set mogrify in verbose mode for debugging.
# Take out "-" symbol. If the only one element is "-", input_files
# will be empty, then stdin is used. If more than elements, the
# effect of "-" will be ignored, and system only takes input from
# real files provided.
try:
for p in printinfo:
except IOError as e:
# Collect new contents of mogrified manifest.
# emitted tracks output so far to avoid duplicates.
if comment:
for l in comment:
.format(l))
if action is None:
continue
if prepended_macro is None:
else:
s = "{0}{1}".format(
# The first action is the original
# action and should be collected;
# later actions are all emitted and
# should only be collected if not
# duplicates.
if i == 0:
elif s not in emitted:
# Print the mogrified result for debugging purpose.
if mog_verbose:
for line in line_buffer:
# Find the mogrified fmri. Make it equal to the old fmri first just
# to make sure it always has a value.
new_lines = []
for al in line_buffer:
continue
continue
try:
except Exception as e:
# If any exception encoutered here, that means the
# action is corrupted with mogrify.
abort(e)
# Construct mogrified new fmri.
try:
abort("Invalid FMRI for set action:\n{0}"
# Drop the signature.
continue
# Check whether new contents such as files and licenses
# was added via mogrify. This should not be allowed.
abort("Adding new hashable content {0} is not "
try:
for f in fmris:
abort("Invalid FMRI(s) for depend action:\n{0}"
# pkg_parentdir is the actual pkg_name directory.
# If the parent directory become empty,
# remove it as well.
"""Retrieve source package data completely and then archive it."""
if mog_files:
error(_("Target archive '{0}' already "
abort()
# Open the archive early so that permissions failures, etc. can be
# detected before actual work is started.
if not dry_run:
# Retrieve package data for all publishers.
any_unmatched = []
any_matched = []
invalid_manifests = []
total_processed = 0
arc_bytes = 0
archive_list = []
# Root must be per publisher on the off chance that multiple
# publishers have the same package.
tracker = get_tracker()
usage(_("must specify at least one pkgfmri"))
if not matches:
# No matches at all; nothing to do for this publisher.
continue
# First, retrieve the manifests and calculate package transfer
# sizes.
get_bytes = 0
get_files = 0
if not recursive:
npkgs))
fmappings = {}
good_matches = []
for f in matches:
try:
except apx.InvalidPackageErrors as e:
continue
nf = f
if do_mog:
try:
f, m.pathname)
# Create mogrified manifest.
# Remove the old raw pkg data first.
except EnvironmentError as e:
raise apx._convert_error(e)
except Exception as e:
abort(_("Creating mogrified "
"manifest failed: {0}"
else:
# Use the original manifest if no
# mogrify is done.
nm = m
# Store a mapping between new fmri and new manifest for
# future use.
# Since files are going into the archive, progress
# can be tracked in terms of compressed bytes for
# the package files themselves.
# Also include the the manifest file itself in the
# amount of bytes to archive.
try:
except EnvironmentError as e:
raise apx._convert_error(e)
# Next, retrieve the content for this publisher's packages.
if verbose:
if not dry_run:
msg(_("\nArchiving packages ..."))
else:
msg(_("\nArchiving packages (dry-run) ..."))
status = []
for s in status:
msg(_("\nPackages to archive:"))
msg()
if dry_run:
# Don't call download_done here; it would cause an
# assertion failure since nothing was downloaded.
# Instead, call the method that simply finishes
# up the progress output.
cleanup()
continue
if mfile:
if not dry_run:
# Nothing more to do for this package.
total_processed += 1
# Check processed patterns and abort with failure if some were
# unmatched.
if not dry_run:
# Now create archive and then archive retrieved package data.
while archive_list:
# Dump all temporary data.
cleanup()
error(_("One or more packages could not be retrieved:\n\n{0}").
if invalid_manifests and total_processed:
return pkgdefs.EXIT_PARTIAL
invalid_manifests = []
total_processed = 0
modified_pubs = set()
old_c_root = {}
del_search_index = set()
# Turn target into a valid URI.
"filesystem-based."))
# Initialize the target repo.
try:
except sr.RepositoryInvalidError as e:
txt += _("To create a repository, use the pkgrepo command.")
# Copy catalog files.
try:
# We just use mkdtemp() to find ourselves a directory
# which does not already exist. The created dir is not
# used.
prefix='catalog-')
except Exception as e:
e))
return old_c_root
# Check if all publishers in src are also in target. If not, add
# depending on what publishers were specified by user.
pubs_to_sync = []
pubs_to_add = []
src_pubs = {}
unknown_pubs = []
for p in publishers:
if p not in src_pubs and p != '*':
"source repository.".format(p)))
'*' in publishers):
or not pubs_specified):
elif not pubs_specified:
# We only print warning if the user didn't specify any valid publishers
if len(unknown_pubs):
txt = _("\nThe following publishers are present in the "
"source repository but not in the target repository.\n"
"Please use -p to specify which publishers need to be "
"cloned or -p '*' to clone all publishers.")
for p in unknown_pubs:
# Create non-existent publishers.
for p in pubs_to_add:
if not dry_run:
# add_publisher() will create a p5i file in the repo
# store, containing origin and possible mirrors from
# the src repo. These may not be valid for the new repo
# so skip creation of this file.
else:
p.prefix))
for src_pub in pubs_to_sync:
tracker = get_tracker()
# We make the destination repo our cache directory to save on
# IOPs. Have to remove all the old caches first.
if not dry_run:
# Retrieve src and dest catalog for comparison.
try:
except sr.RepositoryUnknownPublisher:
del src_cat
del targ_cat
to_add = []
to_rm = []
# We use bulk prefetching for faster transport of the manifests.
# Prefetch requires an intent which it sends to the server. Here
# we just use operation=clone for all FMRIs.
intent = "operation=clone;"
for f in to_add_set:
del src_fmris
del targ_fmris
del to_add_set
# We have to do package removal first because after the sync we
# don't have the old catalog anymore and if we delete packages
# after the sync based on the current catalog we might delete
# files required by packages still in the repo.
msg(_("Packages to remove:"))
for f in to_rm:
if not dry_run:
msg(_("Removing packages ..."))
if repo.get_pub_rstore(
msg(_("No packages to add."))
if deleted_pkgs:
continue
get_bytes = 0
get_files = 0
# Retrieve manifests.
# Try prefetching manifests in bulk first for faster, parallel
# transport. Retryable errors during prefetch are ignored and
# manifests are retrieved again during the "Reading" phase.
# Need to change the output of mfst_fetch since otherwise we
# would see "Download Manifests x/y" twice, once from the
# prefetch and once from the actual manifest analysis.
_("Reading Manifests"))
for f, i in to_add:
try:
except apx.InvalidPackageErrors as e:
continue
if dry_run:
continue
# Move manifest into dest repo.
try:
except Exception as e:
# Restore old GoalTrackerItem for manifest download.
if verbose:
if not dry_run:
msg(_("\nRetrieving packages ..."))
else:
msg(_("\nRetrieving packages (dry-run) ..."))
status = []
for s in status:
msg(_("\nPackages to transfer:"))
msg()
if dry_run:
continue
# Retrieve package files.
for f, i in to_add:
m = get_manifest(f, xport_cfg)
if mfile:
total_processed += 1
error(_("One or more packages could not be retrieved:\n\n{0}").
ret = 0
# Run pkgrepo verify to check repo.
if total_processed:
msg(_("\n\nVerifying repository contents."))
"pkgrepo")
try:
except OSError as e:
args, e))
# Cleanup. If verification was ok, remove backup copy of old catalog.
# If not, move old catalog back into place and remove messed up catalog.
for pub in modified_pubs:
try:
if ret:
else:
except Exception as e:
# We don't abort here to make sure we can
continue
if ret:
txt = _("Pkgrepo verify found errors in the updated repository."
"\nThe original package catalog has been restored.\n")
if deleted_pkgs:
txt += _("Deleted packages can not be restored.\n")
txt += _("The clone operation can be retried; package content "
"that has already been retrieved will not be downloaded "
"again.")
if del_search_index:
txt = _("\nThe search index for the following publishers has "
"been removed due to package removals.\n")
for p in del_search_index:
txt += _("\nTo restore the search index for all publishers run"
"\n'pkgrepo refresh --no-catalog -s {0}'.\n").format(
cleanup()
if invalid_manifests and total_processed:
return pkgdefs.EXIT_PARTIAL
"""Retrieve source package data and optionally republish it as each
package is retrieved.
"""
any_unmatched = []
any_matched = []
invalid_manifests = []
total_processed = 0
if mog_files:
tracker = get_tracker()
if list_newest:
# Make sure the prog tracker knows we're doing a listing
# operation so that it suppresses irrelevant output.
usage(_("--newest takes no options"))
continue
usage(_("must specify at least one pkgfmri"))
if not raw:
# Turn target into a valid URI.
# Setup target for transport.
# Files have to be decompressed for republishing.
# Check to see if the repository exists first.
try:
except trans.TransactionRepositoryInvalidError as e:
txt += _("To create a repository, use "
"the pkgrepo command.")
except trans.TransactionRepositoryConfigError as e:
txt += _("The repository configuration "
"for the repository located at "
"'{0}' is not valid or the "
"specified path does not exist. "
"Please correct the configuration "
"of the repository or create a new "
except trans.TransactionError as e:
else:
try:
except Exception as e:
error(_("Unable to create basedir "
"'{dir}': {err}").format(
abort()
if not matches:
# No matches at all; nothing to do for this publisher.
continue
return "{0:d}_{1}".format(
# First, retrieve the manifests and calculate package transfer
# sizes.
get_bytes = 0
get_files = 0
send_bytes = 0
if not recursive:
npkgs))
pkgs_to_get = []
new_targ_cats = {}
new_targ_pubs = {}
fmappings = {}
while matches:
try:
except apx.InvalidPackageErrors as e:
continue
nf = f
if do_mog:
try:
f, m.pathname)
except Exception as e:
# Figure out whether the package is already in
# the target repository or not.
if republish:
# Check whether the fmri already exists in the
# target repository.
# If no publisher transport
# established. That means it is a
# remote host. set remote prefix
# equal to True.
if not newpub:
continue
# If we already have a catalog in the
# cache, use it.
continue
if do_mog:
# We have examined which packge to
# republish. Then we need store the
# mogrified manifest for future use.
try:
# Create mogrified manifest.
# Remove the old raw pkg data first.
except EnvironmentError as e:
raise apx._convert_error(e)
except Exception as e:
abort(_("Creating mogrified "
"manifest failed: {0}"
else:
# Use the original manifest if no
# mogrify is done.
nm = m
if republish:
nm.gen_actions())
# Store a mapping between new fmri and new manifest for
# future use.
if dry_run:
# Next, retrieve and store the content for each package.
if verbose:
if not dry_run:
msg(_("\nRetrieving packages ..."))
else:
msg(_("\nRetrieving packages (dry-run) ..."))
status = []
for s in status:
msg(_("\nPackages to transfer:"))
for f in sorted(pkgs_to_get):
msg()
if dry_run:
cleanup()
continue
processed = 0
if republish and pkgs_to_get:
# If files can be transferred compressed, keep them
# compressed in the source.
for nf in pkgs_to_get:
# Processing republish.
not keep_compressed, tracker)
if mfile:
if not republish:
# Nothing more to do for this package.
continue
# Check whether to include scheme based on new
# manifest.
for a in nm.gen_actions()):
# Use the new fmri for constructing a transaction id.
# This is needed so any previous failures for a package
# can be aborted.
try:
# Remove any previous failed attempt to
# to republish this package.
try:
except:
# It might not exist already.
pass
t.open()
for a in nm.gen_actions():
if a.name == "set" and \
"pkg.fmri"):
# To be consistent with the
# server, the fmri can't be
# added to the manifest.
continue
fname = None
fhash = None
if a.has_payload:
"rb")
# If the payload will be
# transferred and not have been
# uploaded, upload it...
else:
# ...otherwise, just add the
# action to the transaction.
if a.name == "signature" and \
not do_mog:
# We always store content in the
# repository by the least-
# preferred hash.
for fp in a.get_chain_certs(
if keep_compressed:
else:
# Always defer catalog update.
except trans.TransactionError as e:
# Dump data retrieved so far after each successful
# republish to conserve space.
try:
# If cache_dir is listed in tmpdirs,
# then it's safe to dump cache contents.
# Otherwise, it's a user cache directory
# and shouldn't be dumped.
except EnvironmentError as e:
raise apx._convert_error(e)
processed += 1
if processed > 0:
# If any packages were published, trigger an update of
# the catalog.
# Prevent further use.
targ_pub = None
# Check processed patterns and abort with failure if some were
# unmatched.
# Dump all temporary data.
cleanup()
error(_("One or more packages could not be retrieved:\n\n{0}").
if invalid_manifests and total_processed:
return pkgdefs.EXIT_PARTIAL
if __name__ == "__main__":
# Make all warnings be errors.
import six
# disable ResourceWarning: unclosed file
try:
try:
except:
__ret = 99
else:
__ret = 1
try:
except:
__ret = 99
else:
__ret = 1
except PipeError:
# We don't want to display any messages here to prevent
# possible further broken pipe (EPIPE) errors.
try:
except:
__ret = 99
else:
__ret = 1
except SystemExit as _e:
try:
except:
__ret = 99
raise _e
except EnvironmentError as _e:
raise
txt += _("Storage space quota exceeded.")
else:
txt += _("No storage space left.")
# Only include in message if user specified.
txt += "\n"
"the following directories has enough space available:\n"
try:
cleanup()
except:
__ret = 99
else:
__ret = 1
try:
cleanup()
except:
__ret = 99
else:
__ret = 1
except:
# Cleanup must be called *after* error messaging so that
# exceptions processed during cleanup don't cause the wrong
# traceback to be printed.
try:
except:
pass