Viewing file: wrapper.py (44.19 KB) -rwxr-xr-x Select action/file-type: (+) | (+) | (+) | Code (+) | Session (+) | (+) | SDB (+) | (+) | (+) | (+) | (+) | (+) |
#!/usr/bin/python -u # # Command line wrapper for Update Agent # Copyright (c) 1999-2002 Red Hat, Inc. Distributed under GPL. # # Authors: # Adrian Likins <alikins@redhat.com> # Preston Brown <pbrown@redhat.com>
import sys, os import rpm import string try: # Optik is deprecated since it is part of python (but it is called # optparse) from optparse import OptionParser, Option except ImportError: from optik import OptionParser, Option from types import StringType sys.path.insert(0, "/usr/share/rhn/") #from up2date_client import timeoutsocket #timeoutsocket.setDefaultSocketTimeout(10) from up2date_client import up2dateErrors
# try to catch abuseErrors gracefully try: from up2date_client import repoDirector except up2dateErrors.AbuseError, e: print e.errmsg sys.exit(1)
from up2date_client import wrapperUtils from up2date_client import up2date
from up2date_client import up2dateMessages from up2date_client import rpcServer from up2date_client import rhnChannel from up2date_client import packageList from up2date_client import up2dateBatch from up2date_client import gpgUtils from up2date_client import rhnHardware from up2date_client import depSolver from up2date_client import rpmUtils from up2date_client import rollbacks from up2date_client import up2dateUtils #from up2date_client import rhnLockfile #from up2date_client import timeoutsocket from up2date_client import rhnPackageInfo from up2date_client import config from up2date_client import sourcesConfig from up2date_client import up2dateComps from up2date_client import up2dateLog
from up2date_client import up2dateAuth #registered = up2dateAuth.getSystemId()
# for ssl exceptions from OpenSSL import SSL from OpenSSL import crypto
from rhpl.translate import _, N_ from rhpl.comps import Comps
from rhpl.translate import py_bind_textdomain_codeset py_bind_textdomain_codeset("redhat-dist", "UTF-8")
from rhn import rpclib
try: from up2date_client import lilocfg except ImportError: lilocfg = None
# XXX: Shouldn't these excpetions be in up2dateErrors? class DaemonReturnError(Exception): pass
class CLIOptionParser(OptionParser): def __init__(self, from_daemon=0, *args, **kwargs): apply(OptionParser.__init__, (self, ) + args, kwargs) # We need a different way to get out for daemon mode self.from_daemon = from_daemon
def print_help(self, filed=None): OptionParser.print_help(self, filed)
if not filed: filed = sys.stdout filed.write(_(""" When operating in command line mode, specifying package names as arguments to the program will attempt to retrieve (and possibly install, based on your configuration) those packages. Version, release, and architecture details will be determined by the Update Agent automatically. """))
def error(self, msg): self.print_usage(sys.stderr) sys.stderr.write("%s: error: %s\n" % (sys.argv[0], msg)) # If ran by the daemon, raise an exception if self.from_daemon: raise DaemonReturnError # Otherwise, just exit sys.exit(1)
optionsTable = [ Option( "--configure", action="store_true", help=_("configure Update Agent options")), Option("-d", "--download", action="store_true", help=_("download packages only, even if configuration says to install")), Option("-i", "--install", action="store_true", help=_("install packages, even if configuration says to download only")), Option( "--src", action="store_true", help=_("Download src packages as well as binary rpms")), Option( "--nosrc", action="store_true", help=_("Do not download src packages (overrides config setting if set)")), Option( "--dbpath", action="store", metavar="<dir>", help=_("Specify a path where an alternate rpm db is found")), Option("-f", "--force", action="store_true", help=_("Force package installation, overriding package and file skip list")), Option( "--justdb", action="store_true", help=_("Only add packages to database, do not install to the filesystem")), Option("-l", "--list", action="store_true", help=_("list packages available for retrieval")), Option( "--dry-run", action="store_true", help=_("Do everything but download and install packages (show dependencies needed, etc)")), Option("-?", "--usage", action="store_true", help=_("Briefly describe the options")), Option("-k", "--packagedir", action="store", metavar="<dir>", help=_("colon separated path of directories to look in for packages")), Option( "--nosig", action="store_true", help=_("do not use GPG to check package signatures")), Option( "--nox", action="store_true", help=_("do not attempt to use X")), Option("-p", "--packages", action="store_true", help=_("update packages associated with this System Profile on Red Hat Network")), Option( "--hardware", action="store_true", help=_("up2date hardware profile associated with this System Profile on Red Hat Network")), Option( "--register", action="store_true", help=_("register the system (or reregister it, if need be)")), Option( "--showall", action="store_true", help=_("List all packages available for download")), Option( "--show-available", action="store_true", help=_("List all packages available that are not currently installed")), Option( "--show-orphans", action="store_true", help=_("List all packages currently installed that are not in channels the system is subscribed to")), Option( "--show-groups", action="store_true", help=_("List all the install components available to install")), Option( "--solvedeps", action="store", metavar="<deps>", help=_("finds, downloads, and installs the packages needed to solve the list of dependencies")), Option( "--tmpdir", action="store", metavar="<temp-dir>", help=_("where to store temporary files / RPMs")), Option( "--undo", action="store_true", help=("undo the last package set update")), Option("-u", "--update", action="store_true", help=_("update system with all relevant packages")), Option( "--version", action="store_true", help=_("show program version information")), Option("-v", "--verbose", action="count", help=_("Show additional output")), Option( "--show-channels", action="store_true", dest="show_channels", help=_("Show the channel names along with the package name where approriate")), Option( "--list-rollbacks", action="store_true", help=_("Show the rpm rollbacks available")), Option( "--whatprovides", action="store", metavar="<deps>", help=_("Show the packages which solve the comma separated list of dependencies")), Option( "--installall", action="store_true", help=_("Install all available packages. Used with --channel")), Option( "--exclude", action="append", metavar="<pkg>", help=_("List of packages to exlude from being installed or updated")), Option( "--channel", action="append", metavar="<channel>", help=_("Specify which channels to use by channel label")), Option( "--gpg-flags", action="store_true", dest="gpg_flags", help=_("Show the flags that gpg will be invoked with (the keyring, etc)")), Option( "--nodownload", action="store_true", help=_("Do not download packages at all. For testing purposes")), Option( "--uuid", action="store", metavar="<uuid>", help=_("Pass in a uuid that the applet generates")), Option( "--proxy", action="store", metavar="<proxyurl>", help=_("Specify an http proxy to use")), Option( "--proxyUser", action="store", metavar="<proxy userid>", help=_("Specify a username to use with an authenticated http proxy")), Option( "--proxyPassword", action="store", metavar="<proxy password>", help=_("Specify a password to use with an authenticated http proxy")), Option( "--serverUrl", action="store", metavar="<url>", help=_("Specify what server url to use")), # Option( "--local-pkgs", action="append", metavar="<filename>", # help=_("Specify local rpm packages to install via up2date")), Option( "--show-package-dialog", action="store_true", help=_("Show the package installation dialog in gui mode")), Option( "--get", action="store_true", help=_("Fetch the package specified without resolving dependencies")), Option( "--get-source", action="store_true", help=_("Fetch the source package for the specified package without resolving dependencies")), Option( "--arch", action="append", help=_("Force up2date to install this arch of the package. Not valid with -u, --list, or --dry-run")), Option( "--upgrade-to-release", action="store", metavar="<release-version>", help=_("Upgrade to the channel specified")), ]
def printUsage(poptContext, stream = sys.stdout): poptContext.printUsage(stream)
def gpgWarning2(hasGui): guiErrMsg = up2dateMessages.gpgWarningGuiMsg keyBlurb = "" for key in gpgUtils.keysToImport(): keyBlurb = keyBlurb + " rpm --import %s\n" % key errMsg = "" errMsg = up2dateMessages.gpgWarningMsg + keyBlurb if hasGui: try: from up2date_client import messageWindow dlg = messageWindow.QuestionDialog( guiErrMsg + _("\n\nInstall key?") )
if dlg.getrc(): dlg.hide() try: if gpgUtils.importRedHatGpgKeys(): dlg = messageWindow.ErrorDialog(_(""" Some sort of error occurred adding the Red Hat GPG key to your keyring.""")) return 1 except up2dateErrors.RpmError, e: print e.errmsg return 1 dlg.hide() return 0 except (ImportError, RuntimeError) : print _("Unable to open gui. Try `up2date --nox`") print errMsg print return 1 else: print errMsg print return 1
def sslWarning(hasGui): errMsg = _(""" Your system libraries do not support SSL (secure) connections. Any data that you send or receive from redhat.com will be transmitted in the clear. """)
if hasGui: try: from up2date_client import messageWindow dlg = messageWindow.QuestionDialog(errMsg + _("Continue anyway?")) if not dlg.get_rc(): return 1 else: return 0 except (ImportError, RuntimeError): print _("Unable to open gui. Try `up2date --nox`") print errMsg return 1 else: print errMsg return 1
def addChannelPkgsTopkgNames(pkgNames, channels): pkgs = rhnPackageInfo.getAvailablePackageList() channelHash = {} for pkg in pkgs: if channelHash.has_key(pkg[6]): channelHash[pkg[6]].append(pkg[0]) else: channelHash[pkg[6]] = [pkg[0]]
for channel in channels: try: pkgsPerChannel = channelHash[channel] except KeyError: # no packages from that channel pkgsPerChannel = [] for pkg in pkgsPerChannel: pkgNames.append(pkg)
return pkgNames
def sanityChecks(fromDaemon, hasGui): cfg = config.initUp2dateConfig() # see if /var/spool/up2date exists if up2date.checkForStorageDir(): wrapperUtils.warningDialog(up2dateMessages.storageDirWarningMsg,hasGui) if not fromDaemon: sys.exit(1) return 1
if cfg["useGPG"] and gpgUtils.checkGPGInstallation() == 2: ret = gpgWarning2(hasGui) if ret: return 1
if not rpcServer.hasSSL(): if sslWarning(hasGui): if not fromDaemon: sys.exit(1) return 1 # to shut up pychecker return None
# the world's ugliest function... def main(arglist = sys.argv, fromDaemon = 0): hasGui = 0 nox = 0 nogui = 0 configure = 0 continuePostConfigure = 0
# to shut up pychecker (we don't actually use arglist currently) arglist = arglist
#capabilities.Capabilities() cfg = config.initUp2dateConfig()
# lets try parsing the sources config file # lets see if were talking to rhn or not, # and if not, lets set a config variable so # everyone knows sources = sourcesConfig.getSources() useRhn = 0 for source in sources: if source['type'] == "up2date": useRhn = 1 cfg['useRhn'] = useRhn
# see what we got called as if os.path.basename(sys.argv[0]) == "up2date-nox": nox = 1
if os.path.basename(sys.argv[0]) == "up2date-config": configure = 1
if not cfg["networkSetup"]: configure = 1 continuePostConfigure = 1
global optionsTable optparser = CLIOptionParser(option_list=optionsTable, usage="usage: %prog [OPTIONS] [<packages>]", from_daemon=fromDaemon)
try: (options, pkgNames) = optparser.parse_args() except DaemonReturnError: return 1
nox = nox or options.nox
# figure out if were entering a differnt "mode" or if we # want to open the gui app refreshmodes = ["packages", "hardware"] refreshmode = None for mode in refreshmodes: if hasattr(options,mode) and getattr(options,mode): refreshmode = 1 continue
# if any of the non gui mode options are specified, set guimode to None modes = ["showall", "update", "list", "dry_run", "show_channels", "list_rollbacks","whatprovides", "solvedeps", "configure", "register", "installall", "show_available", "show_orphans", "get", "get_source", "show_comps"] guimode = 1 for mode in modes: if hasattr(options,mode) and getattr(options,mode): guimode = None continue
# whether or not to show the available packages screen... # could be a commandline option or a pref... cfg["showAvailablePackages"] = 0 if options.show_package_dialog: cfg["showAvailablePackages"] = 1
if options.exclude: cfg['pkgSkipList'] = cfg['pkgSkipList'] + options.exclude
# Easy mapping of flags # Syntax: # l[0] == name of the option # l[1] == name in the config object # l[2] == value to set in the config object flags = [ # XXX ["download", "retrieveOnly", 1], ["install", "retrieveOnly", 0], ["nodownload", "noDownload", 1], ["force", "forceInstall", 1], # XXX ["src", "retrieveSource", 1], ["nosrc", "retrieveSource", 0], ["tmpdir", "storageDir", options.tmpdir], ["nosig", "useGPG", 0], ["dbpath", "dbpath", options.dbpath], ["justdb", "justdb", 1], ["show_channels", "showChannels", 1], ["serverUrl", "serverURL", options.serverUrl], ['uuid', "uuid", options.uuid], ['arch', "forcedArch", options.arch] # ["gpg_flags", "gpg-flags", 1], ]
for flag in flags: if getattr(options, flag[0]): cfg[flag[1]] = flag[2]
if len(pkgNames): guimode = None
try: if os.access("/usr/share/rhn/up2date_client/gui.py", os.R_OK): if os.environ["DISPLAY"] != "": if not nox: hasGui = 1 except: pass
if options.usage: optparser.print_usage() if fromDaemon: return 1 sys.exit(0) if options.version: showVersion(hasGui) if fromDaemon: return 1 sys.exit(0)
if options.upgrade_to_release and not options.dry_run: cfg["versionOverride"] = options.upgrade_to_release
if cfg['dbpath']: rpm.addMacro("_dbpath", cfg['dbpath'])
# figure out the debug level debug = options.verbose or 0 cfg["debug"] = cfg["debug"] + debug if cfg["debug"] > 2: # Set rpm's verbosity mode try: rpm.setVerbosity(rpm.RPMLOG_DEBUG) except AttributeError: print "extra verbosity not supported in this version of rpm"
if options.gpg_flags: try: print rpmUtils.getGPGflags() except up2dateErrors.RpmError, e: print e.errmsg sys.exit(1) if fromDaemon: return 1 sys.exit(0)
if options.list_rollbacks: _rollback = rollbacks.Rollback() print _rollback.printTransactions() sys.exit(1) if options.undo and not options.dry_run: try: ret = up2date.undo() except up2dateErrors.RpmInstallError, e: print e.errmsg ret = 1 sys.exit(ret)
# set a default warning message callback, the gui version # should reset this wrapperUtils.warningCallback = wrapperUtils.printit
registered = 1 if cfg['useRhn']: registered = up2dateAuth.getSystemId()
# hmm, if were configured not to use rhn, but someone # calls it as rhn_register, lets assume that means they # want to use RHN afterall if os.path.basename(sys.argv[0]) == "rhn_register": registered = 0 if not cfg['useRhn']: sourcesFile = sourcesConfig.SourcesConfigFile(filename="/etc/sysconfig/rhn/sources") sourcesFile.writeUp2date() cfg['useRhn'] = 1
# these modes only really make sense for rhn mode... # so turn them off if not cfg['useRhn'] and refreshmode: print _("Package and Hardware refresh not applicable when not using Red Hat Network") sys.exit(1) if refreshmode and not options.dry_run: if options.packages: if not registered: print up2dateMessages.needToRegister sys.exit(1) try: up2dateAuth.updateLoginInfo() except rpclib.Fault, f: faultError(hasGui,f.faultString) sys.exit(1) except up2dateErrors.ServerCapabilityError, e: print e sys.exit(1) except up2dateErrors.CommunicationError, e: print e sys.exit(1)
print _("Updating package profile...") rhnPackageInfo.updatePackageProfile() print _("Updating transaction history...") rhnPackageInfo.updateTransactions()
if options.hardware: if not registered: print up2dateMessages.needToRegister sys.exit(1) try: up2dateAuth.updateLoginInfo() except rpclib.Fault, f: faultError(hasGui,f.faultString) sys.exit(1) except up2dateErrors.ServerCapabilityError, e: print e sys.exit(1) except up2dateErrors.CommunicationError, e: print e sys.exit(1) print _("Updating hardware profile...") rhnHardware.updateHardware() # if we didnt get any other mode arguments, exit # if we did, keep chugging and run those as well if guimode: return 0 # might as well save the proxy info we get for the next useage save_cfg = 0 # hmm, well, some of the non rhn modes dont really understand this, # but alas... if options.proxy: cfg.set("httpProxy", options.proxy) cfg.set("enableProxy", 1) save_cfg = 1 if options.proxyUser: cfg.set("proxyUser", options.proxyUser) cfg.set("enableProxyAuth", 1) save_cfg = 1 if options.proxyPassword: cfg.set("proxyPassword", options.proxyPassword) cfg.set("enableProxyAuth", 1) save_cfg = 1 if save_cfg: cfg.save()
packagedir = options.packagedir if packagedir: cfg["packageDir"] = packagedir # for path in packagedir: # fullpath = os.path.normpath( # os.path.abspath(os.path.expanduser(path))) # paths.append(fullpath) # cfg["packageDir"] = paths
# Done with the flags processing
tempchannels = options.channel or [] if len(tempchannels): if not registered and cfg['useRhn']: print up2dateMessages.needToRegister sys.exit(1) if cfg['useRhn']: try: up2dateAuth.updateLoginInfo() except rpclib.Fault, f: faultError(hasGui,f.faultString) sys.exit(1) except up2dateErrors.CommunicationError, e: print e sys.exit(1) rhnChannel.updateChannels(tempchannels)
if options.showall: if not registered and cfg['useRhn']: print up2dateMessages.needToRegister sys.exit(1) # FIXME: hack, should set a variable here and then run it later if cfg['useRhn']: try: up2dateAuth.updateLoginInfo() except rpclib.Fault, f: faultError(hasGui,f.faultString) sys.exit(1) except up2dateErrors.CommunicationError, e: print e sys.exit(1) printList(rhnPackageInfo.getAvailableAllArchPackageList(), cfg['showChannels']) return 0
if options.show_groups: comps = up2dateComps.initComps() compsList = comps.group_by_name.keys() compsList.sort() for comp in compsList: print comp return 0
fullUpdate = options.update configure = configure or options.configure
# see if were running as root, before running configure if os.geteuid() != 0: wrapperUtils.warningDialog(up2dateMessages.rootWarningMsg, hasGui) if not fromDaemon: sys.exit(1)
if configure: if hasGui: try: from up2date_client import configdlg except: hasGui = 0 if hasGui: ret = configdlg.main() if fromDaemon: return 0 elif continuePostConfigure and ret: cfg.set("networkSetup", 1) cfg.save() else: sys.exit(0) else: from up2date_client import text_config text_config.main() if fromDaemon: return 1 elif continuePostConfigure: cfg.set("networkSetup", 1) cfg.save() else: sys.exit(1)
depslist = options.whatprovides or [] # XXX: what is this used for? if depslist: cfg["depslist"] = depslist else: cfg["depslist"] = [] # detect if were running on a tty or not cfg["isatty"] = 0 if sys.stdout.isatty(): cfg["isatty"] = 1
# run all the sanity checks (gpg key, paths, etc) ret = sanityChecks(fromDaemon, hasGui) if ret: return ret
# force a registration if we specify it on the commandline if options.register: registered = 0
if registered and cfg['useRhn']: try: up2dateAuth.updateLoginInfo() except rpclib.Fault, f: faultError(hasGui,f.faultString) sys.exit(1) except up2dateErrors.ServerCapabilityError, e: print e sys.exit(1) except up2dateErrors.CommunicationError, e: print e sys.exit(1)
if len(cfg["depslist"]): return whatprovides(cfg["depslist"]) if options.get: return getPackages(pkgNames) if options.get_source: return getPackages(pkgNames, source=1)
#FIXME: this stuff needs to move to post registration if options.solvedeps: # maybe this will handle comboa cases of packages and deps # specified?? NEEDSTEST extraPackages = whatprovides(options.solvedeps, 1) if extraPackages: pkgNames = pkgNames + extraPackages else: print _("No packages were found that satisfy those dependencies.") sys.exit(1)
if not registered and cfg['useRhn']: if hasGui: try: from up2date_client import gui nogui = 0 except RuntimeError: # if we fail to initialize the interface, fall back to tui nogui = 1
if not nogui: wrapperUtils.warningCallback = gui.errorWindow if not registered: gui.forceRegister = 1 gui.main() sys.exit(0) else: # call the registration client first... from up2date_client import tui tui.main()
# if we dont have loginingo because we needed # to register, login now if cfg['useRhn'] and not up2dateAuth.getLoginInfo(): try: up2dateAuth.updateLoginInfo() except rpclib.Fault, f: faultError(hasGui,f.faultString) sys.exit(1) except up2dateErrors.ServerCapabilityError, e: print e sys.exit(1) except up2dateErrors.AuthenticationError, e: sys.exit(1) except up2dateErrors.CommunicationError, e: print e sys.exit(1)
if options.installall: if options.channel: pkgNames = addChannelPkgsTopkgNames(pkgNames, options.channel) else: print _("A channel name must be specified with --installall") sys.exit(1)
if options.show_available: availablePackages = up2date.computeAvailablePackages() if availablePackages: printList(availablePackages, cfg['showChannels']) sys.exit(0) if options.show_orphans: unAvailablePackages = up2date.computeUnavailablePackages() if unAvailablePackages: printList(unAvailablePackages) sys.exit(0)
if cfg["showChannels"]: # nothing else that uses showChannel follows, so we can exit here if not (options.list or len(pkgNames) or fullUpdate or options.dry_run): channels = rhnChannel.getChannels().channels() for channel in channels: print "%s" % channel['label'] sys.exit(0)
if options.list or len(pkgNames) or fullUpdate or options.dry_run: # continue on in batch mode if fromDaemon: return batchRun(options.list, pkgNames, fullUpdate, fromDaemon) try: sys.exit(batchRun(options.list, pkgNames, fullUpdate, dryRun=options.dry_run)) # we need a new up2date... go fetch it except up2dateErrors.Up2dateNeedsUpdateError: if cfg['updateUp2date']: cfg['forceInstall'] = 1 try: ret = batchRun(0, ["up2date"], 0, fromDaemon, dryRun=options.dry_run, updateUp2date=None) up2dateUtils.restartUp2date() sys.exit() except (up2dateErrors.GPGVerificationError, up2dateErrors.GPGVerificationUnsignedPackageError, up2dateErrors.GPGVerificationUnknownKeyError), e: # yeah, thats a little hokey, but this is a rare case, and # it's better than a traceback print "There was a gpg problem with the up2date package. "\ "Check that the proper gpg keys are installed.: \n %s" % e except up2dateErrors.GPGVerificationError, e: # might as well be annoying and loud about it print print "************ GPG VERIFICATION ERROR ****************" print e print "****************************************************" print sys.exit(1) except up2dateErrors.FileNotFoundError, e: print e.errmsg sys.exit(1) except up2dateErrors.GPGVerificationUnsignedPackageError,e: print e, "Aborting..." sys.exit(1) except up2dateErrors.GPGVerificationUnknownKeyError, e: print e, "Aborting..." sys.exit(1) except up2dateErrors.GPGVerificationUntrustedKeyError, e: print e, "Aborting..." sys.exit(1) except up2dateErrors.GPGKeyringError,e: print e sys.exit(1) except up2dateErrors.CommunicationError, e: print _("There was a fatal error communicating with the server. "\ "The message was:\n") + e.errmsg sys.exit(1) except up2dateErrors.RpmError, e: print _("There was a fatal RPM error. "\ "The message was:\n") + e.errmsg sys.exit(1) except up2dateErrors.RpmInstallError, e: print _("There was a fatal RPM install error. "\ "The message was:\n") + e.errmsg sys.exit(1) except up2dateErrors.DependencyError, e: print _("There was a package dependency problem. "\ "The message was:\n") + e.errmsg sys.exit(1) except up2dateErrors.UnsolvedDependencyError, e: print _("There was a package dependency problem. "\ "The message was:\n") + e.errmsg sys.exit(1) except up2dateErrors.OutOfSpaceError, e: print _("There was an error installing the packages. "\ "The message was:\n") + e.errmsg sys.exit(1) except up2dateErrors.ConflictError, e: print e sys.exit(1) except up2dateErrors.NoChannelsError, e: print e sys.exit(1)
elif not registered: sys.exit(0) else: # no --list if hasGui: try: from up2date_client import gui nogui = 0 except RuntimeError: # if we fail to initialize the interface, fall back to tui nogui = 1
if not nogui: wrapperUtils.warningCallback = gui.errorWindow gui.main() sys.exit(0)
print _("No interactive mode available") print _("Please specify either -l, -u, --nox, or package names "\ "as command line arguments.") optparser.print_help() if fromDaemon: return 1 else: sys.exit(1) # to shut up pychecker return None
def ReportError(*args): sys.stderr.write("%s\n" % string.join(map(str, args)))
def showVersion(hasGui): if hasGui: try: from up2date_client import gui gui.showAbout() except: print _("Unable to open gui. Try specifying \"--nox\" "\ "as an option") else: print "Red Hat Update Agent v%s" % up2dateUtils.version() print "Copyright (C) 1999-2002 Red Hat, Inc." print _("Licensed under terms of the GPL.")
def faultError(hasGui,msg): errMsg = msg
if hasGui: try: from up2date_client import gui gui.errorWindow(errMsg) except: print _("Unable to open gui. Try `up2date --nox`") print errMsg else: print errMsg
def whatprovides(depslist, returnlist=None): tmp_list = string.split(depslist, ",") deps_list=[] cfg = config.initUp2dateConfig() availlist = rhnPackageInfo.getAvailablePackageList() # a little text munging to make this commandline friendlier for i in tmp_list: i=string.strip(i) deps_list.append(i) solveDep = depSolver.SolveDep() try: (provides, depToPkg) = solveDep.solveDep(deps_list,availlist) except up2dateErrors.DependencyError: print "Unable to solve dependencies for %s" % deps_list return None if returnlist: pkgnames = [] for provide in provides: pkgnames.append(provide[0]) return pkgnames pkgDict = up2date.avail_package_dict() for provide in provides: pkgString = "%s-%s-%s" % (provide[0], provide[1],provide[2]) if cfg["showChannels"]: # print the channel name channelName = pkgDict["%s-%s-%s.%s" % ( provide[0], provide[1],provide[2], provide[4])][6] print "%-40s%-30s" % (pkgString, channelName) else: print "%s" % pkgString # to shut up pychecker return None
def splitGlobsAndComps(pkgNames): # pkgnames can include globs and @foo comp style names
comps = [] globs = [] tmpPkgNames = [] for token in pkgNames: if token[0] == '@': comps.append(token[1:]) continue if (string.find(token, '?') != -1) or (string.find(token, '*') != -1) or \ (string.find(token, '[') != -1) or (string.find(token, ']') != -1): globs.append(token) else: tmpPkgNames.append(token) return (comps, globs, tmpPkgNames)
def getPackages(filenames, source=None): allAvailList = rhnPackageInfo.getAllAvailableAllArchPackageList(msgCallback = wrapperUtils.printit, progressCallback = wrapperUtils.percent) pkgNamesDict = {}
for i in range(len(allAvailList)): pkg = allAvailList[i] nvra = "%s-%s-%s.%s" % (pkg[0], pkg[1], pkg[2], pkg[4]) nvr = "%s-%s-%s" % (pkg[0], pkg[1], pkg[2]) nv = "%s-%s" % (pkg[0], pkg[1]) if pkgNamesDict.has_key(nvra): pkgNamesDict[nvra].append(("all", i)) else: pkgNamesDict[nvra] = [("all", i)] if pkgNamesDict.has_key(nvr): pkgNamesDict[nvr].append(("all", i)) else: pkgNamesDict[nvr] = [("all", i)] if pkgNamesDict.has_key(nv): pkgNamesDict[nv].append(("all", i)) else: pkgNamesDict[nv] = [("all", i)] availList = rhnPackageInfo.getAvailablePackageList(msgCallback=wrapperUtils.printit, progressCallback=wrapperUtils.percent)
for i in range(len(availList)): pkg = availList[i] pkgNamesDict["%s" % pkg[0]] = [("latest", i)]
packages = [] missingPackages = [] for filename in filenames: if filename[-4:] == ".rpm": filename = filename[:-4]
if pkgNamesDict.has_key(filename): listindexlist = pkgNamesDict[filename]
# sort the list by rpm version, use the latest if len(listindexlist) > 1: pkgList = [] for i in listindexlist: plist, index = i if plist == "all": pkgList.append(allAvailList[index]) else: pkgList.append(availList[index]) pkgList.sort(up2dateUtils.comparePackages) pkgList.reverse() packages.append(pkgList[0])
else: plist, index = listindexlist[0] if plist == "all": packages.append(allAvailList[index]) else: packages.append(availList[index]) else: missingPackages.append(filename)
for packages in packages: try: up2date.getPackage(packages, msgCallback = wrapperUtils.printit, progressCallback = wrapperUtils.percent, onlySource = source) except up2dateErrors.FileNotFoundError, e: print e continue exitcode = 0 if missingPackages: print _("The following packages are not available:") for mp in missingPackages: print "%s" % mp exitcode = 1
return exitcode
def printList(packageList, showChannels=None): packageList.sort() for pkg in packageList: pkgString = "%s-%s-%s.%s" % (pkg[0], pkg[1],pkg[2], pkg[4]) if showChannels: #clabel = "%s-%s-%s.%s" % (pkg[0], pkg[1], pkg[2], pkg[4]) channelName = pkg[6] print "%-40s%-30s" % (pkgString, channelName) else: print "%s" % (pkgString)
def batchRun(onlyList, pkgNames, fullUpdate = 0, fromDaemon = 0, actionPkgs=None, dryRun=None, returnInfo=0, updateUp2date=1):
cfg = config.initUp2dateConfig() rpmCallback = wrapperUtils.RpmCallback()
batch = up2dateBatch.BatchRun() batch.onlyList = onlyList batch.dryRunFlag = dryRun
# quiet mode for rhn_check if fromDaemon: batch.printCallback = None batch.percentCallback = None else: batch.printCallback = wrapperUtils.printit batch.percentCallback = wrapperUtils.percent
(comps, globs, pkgNames) = splitGlobsAndComps(pkgNames) batch.listOfPkgNames = pkgNames batch.listOfComps = comps batch.listOfGlobs = globs batch.onlyList = onlyList batch.fromDaemon = fromDaemon batch.actionPkgs = actionPkgs batch.rpmCallback = rpmCallback.callback
# fix bz #152523, calc the needed packages first to # see if we should call up2date up2date batch.init() # dont update up2date if were only downloading or listing # fix for #152523, don't try to update up2date in daemon mode if updateUp2date and not onlyList and not dryRun \ and not cfg['retrieveOnly'] and not fromDaemon: if batch.packagesToInstall: for i in batch.packagesToInstall: if i[0] == "up2date": channelName = i[6] channels = rhnChannel.getChannels() channel = channels.getByName(channelName) # only update up2date if it's from an RHN source if channel['type'] == 'up2date': raise up2dateErrors.Up2dateNeedsUpdateError try: batch.run() except (lilocfg.LiloConfError, lilocfg.LiloInstallError), info: print info return 1 # cases... # case 1: I specify a package to install, the package is availa # I want the dep list, and the warning if it's found, but # not the info about packages that were skipped unless it was # one of the cmdline packages or it's deps
# case 2: a full update... I want all the info # # case 3: actions... not sure...
if len(batch.applicableSkippedPackages): wrapperUtils.printSkippedPackages(batch.skippedPackages)
if len(batch.obsoletedPackages) and ( onlyList or dryRun): wrapperUtils.printObsoletedPackages(batch.obsoletedPackages)
if len(batch.installedObsoletingPackages): wrapperUtils.printInstalledObsoletingPackages(batch.installedObsoletingPackages)
if batch.listOfComps and batch.noMatchesForComps: wrapperUtils.printEmptyCompsWarning(batch.noMatchesForComps)
if batch.listOfGlobs and batch.noMatchesForGlobs: wrapperUtils.printEmptyGlobsWarning(batch.noMatchesForGlobs)
if not batch.packagesToInstall: # if we got no updates, but packages we skipped, raise an # exception indicating that
# FIXME: insert code here to determine if packages were on # package skip, file skip, or skipped because of config # stuff... probabaly need to add code to PackageList to expose # that info individually and then make BatchRun know that... if fromDaemon: if len(batch.applicableSkippedPackages): raise up2dateErrors.SkipListError( "The following packages were on your skip list "\ "and could not be installed: %s" % batch.applicableSkippedPackages, batch.applicableSkippedPackages)
# case 1: install a package and it's already installed and up2date # case 2: update all packages but your up2date if fullUpdate: print _("All packages are currently up to date") if returnInfo: # return the batch object so we can dissect it for # more useful error messages return batch return 0 else: tmpPkgNames = pkgNames[:] if batch.packagesNotFound: print print _("The following packages you requested were not found:") for pkgname in pkgNames: if pkgname in batch.packagesNotFound: print pkgname del tmpPkgNames[tmpPkgNames.index(pkgname)]
if tmpPkgNames: print print _("The following packages you requested are already updated:") for pkgname in tmpPkgNames: print pkgname return 0
## if len(skippedPackagesFileConfigSkipList): ## raise up2dateErrors.FileConfigSkipListError( ## "The following packages were on your skip list "\ ## "and could not be installed: %s" % ## skippedPackagesFileConfigSkipList, ## skippedPackagesFileConfigSkipList)
return 0
#FIXME:? should batch run do this itself? if len(batch.depPackages): wrapperUtils.printDepPackages(batch.depPackages)
# we're fine up to this point... if returnInfo: return batch return 0
def exceptionHandler(type, value, tb): log = up2dateLog.initLog() print _("An error has occurred:") if hasattr(value, "errmsg"): print value.errmsg log.log_exception(type, value, tb) else: print type log.log_exception(type, value, tb)
print _("See /var/log/up2date for more information")
if __name__ == "__main__": # quick check for other instances of up2date/rhn_check # lock = None # try: # lock = rhnLockfile.Lockfile('/var/run/up2date.pid') # except rhnLockfile.LockfileLockedException, e: # sys.stderr.write("Attempting to run more than one instance of up2date/rhn_check. Exiting.\n") # sys.exit(0)
# quick check for other instances of up2date/rhn_check # stdout = os.popen('ps --no-headers -C up2date -C rhn_check', 'r') # lines = stdout.readlines() # stdout.close() # if len(lines) > 1: # sys.stderr.write(_("Attempting to run more than one instance of up2date/rhn_check. Exiting.\n")) # sys.exit(0)
# catch any uncaught exceptions and handle them nicely sys.excepthook = exceptionHandler # main loop call try: sys.exit(main() or 0) except KeyboardInterrupt: sys.stderr.write(_("\nAborted.\n")) sys.exit(1) except OSError, e: sys.stderr.write(_("An unexpected OS error occurred: %s\n") % e) sys.exit(1) except IOError, e: sys.stderr.write(_("There was some sort of I/O error: %s\n") % e) sys.exit(1) except SSL.Error, e: sys.stderr.write(_("There was an SSL error: %s\n") % e) sys.stderr.write(_("A common cause of this error is the system time being incorrect. " \ "Verify that the time on this system is correct.\n")) sys.exit(1) except crypto.Error, e: sys.stderr.write(_("There was a SSL crypto error: %s\n") % e) except SystemExit, e: raise e except up2dateErrors.AuthenticationError, e: sys.stderr.write(_("There was an authentication error: %s\n") % e) sys.exit(1) except up2dateErrors.RpmError, e: sys.stderr.write("%s\n" % e) sys.exit(1) # except Exception, e: # sys.stderr.write(_("\nERROR: unhandled exception occurred:\n %s -- %s.\n") % (repr(e), e)) # raise e
# if lock: # lock.release()
|