示例#1
0
文件: yic.py 项目: ryanyard/yic
def yumInstall(pkgname):
    ybc = cli.YumBaseCli()
    ybc.doConfigSetup()
    ybc.doTsSetup()
    ybc.doRpmDBSetup()
    ybc.installPkgs(pkgname)
    ybc.buildTransaction()
    ybc.doTransaction()
示例#2
0
文件: yic.py 项目: ryanyard/yic
def yumRemove(pkgname):
    ybc = cli.YumBaseCli()
    ybc.doConfigSetup()
    ybc.doTsSetup()
    ybc.doRpmDBSetup()
    ybc.removePkgs(pkgname)
    ybc.buildTransaction()
    ybc.doTransaction()
示例#3
0
def main(args):
    base = cli.YumBaseCli()
    base.yum_cli_commands.clear()
    base.registerCommand(GroupsCompletionCommand())
    base.registerCommand(ListCompletionCommand())
    base.registerCommand(RepoListCompletionCommand())
    base.getOptionsConfig(args)
    base.parseCommands()
    try:
        for repo in base.repos.listEnabled():
            repo.skip_if_unavailable = True
        base.doCommands()
    except (GroupsError, ConfigError), e:
        base.logger.error(e)
示例#4
0
def main(args):
    base = cli.YumBaseCli()
    base.setCacheDir = lambda *x: True  # use the system cachedir
    base.yum_cli_commands.clear()
    base.registerCommand(GroupsCompletionCommand())
    base.registerCommand(ListCompletionCommand())
    base.registerCommand(RepoListCompletionCommand())
    base.getOptionsConfig(args)
    base.parseCommands()
    try:
        for repo in base.repos.listEnabled():
            repo.skip_if_unavailable = True
        base.doCommands()
    except (GroupsError, ConfigError, RepoError), e:
        # Any reason to not just catch YumBaseError ?
        base.logger.error(e)
示例#5
0
    def configure_yum_packages(self):
        """Configure package resources."""
        print("- Configuring Packages")
        runtime_start = time.time()
        nsync = 0
        osync = 0
        fail = 0
        packages = self.config['packages']

        yb = yum.YumBase()
        yb.preconf.debuglevel = 0
        yb.preconf.errorlevel = 0
        yb.doTsSetup()
        yb.doRpmDBSetup()

        ybc = cli.YumBaseCli()
        ybc.preconf.debuglevel = 0
        ybc.preconf.errorlevel = 0
        ybc.conf.assumeyes = True
        ybc.doTsSetup()
        ybc.doRpmDBSetup()

        create_pkg_list = []
        remove_pkg_list = []
        for package in packages:
            action = packages[package]['action']
            # In the near future, will use install_name vs package
            # as it includes a more specific package name: "package-version"
            # install_name = packages[package]['install_name']
            if yb.isPackageInstalled(package):
                if action == 'create':
                    nsync += 1
                if action == 'remove':
                    remove_pkg_list.append(package)
            if not yb.isPackageInstalled(package):
                if action == 'create':
                    create_pkg_list.append(package)
                if action == 'remove':
                    nsync += 1

        # Don't waste time with YUM if there is nothing to do.
        doTransaction = False

        if create_pkg_list:
            print("  Packages out of sync: %s" % create_pkg_list)
            ybc.installPkgs(create_pkg_list)
            osync += len(create_pkg_list)
            doTransaction = True
        if remove_pkg_list:
            print("  Packages out of sync: %s" % remove_pkg_list)
            ybc.erasePkgs(remove_pkg_list)
            osync += len(remove_pkg_list)
            doTransaction = True
        if doTransaction:
            ybc.buildTransaction()
            ybc.doTransaction()

        runtime_end = time.time()
        runtime = (runtime_end - runtime_start)
        self.stats['pkg'] = {
            'runtime': runtime,
            'nsync': nsync,
            'osync': osync,
            'fail': fail
        }
示例#6
0
        try:
            probs = base._rpmdb_warn_checks(out=verbose_logger.info,
                                            warn=False)
        except Errors.YumBaseError, e:
            # This is mainly for PackageSackError from rpmdb.
            verbose_logger.info(_(" Yum checks failed: %s"), exception2msg(e))
            probs = []
        if not probs:
            verbose_logger.info(
                _(" You could try running: rpm -Va --nofiles --nodigest"))

    logger = logging.getLogger("yum.main")
    verbose_logger = logging.getLogger("yum.verbose.main")

    # our core object for the cli
    base = cli.YumBaseCli()

    # do our cli parsing and config file setup
    # also sanity check the things being passed on the cli
    try:
        base.getOptionsConfig(args)
    except plugins.PluginYumExit, e:
        return exPluginExit(e)
    except Errors.YumBaseError, e:
        return exFatal(e)

    # Try to open the current directory to see if we have
    # read and execute access. If not, chdir to /
    try:
        f = open(".")
    except IOError, e:
示例#7
0
文件: yummain.py 项目: Python3pkg/yum
def main(args):
    """Run the yum program from a command line interface."""

    yum.misc.setup_locale(override_time=True)

    def exUserCancel():
        logger.critical(_('\n\nExiting on user cancel'))
        if unlock(): return 200
        return 1

    def exIOError(e):
        if e.errno == 32:
            logger.critical(_('\n\nExiting on Broken Pipe'))
        else:
            logger.critical(_('\n\n%s') % exception2msg(e))
        if unlock(): return 200
        return 1

    def exPluginExit(e):
        '''Called when a plugin raises PluginYumExit.

        Log the plugin's exit message if one was supplied.
        ''' # ' xemacs hack
        exitmsg = exception2msg(e)
        if exitmsg:
            logger.warn('\n\n%s', exitmsg)
        if unlock(): return 200
        return 1

    def exFatal(e):
        logger.critical('\n\n%s', exception2msg(e.value))
        if unlock(): return 200
        return 1

    def exRepoError(e):
        # For RepoErrors ... help out by forcing new repodata next time.
        # XXX: clean only the repo that has failed?
        try:
            base.cleanExpireCache()
        except Errors.YumBaseError:
            # Let's not confuse the user further (they don't even know we tried
            # the clean).
            pass

        msg = _("""\
 One of the configured repositories failed (%(repo)s),
 and yum doesn't have enough cached data to continue. At this point the only
 safe thing yum can do is fail. There are a few ways to work "fix" this:

     1. Contact the upstream for the repository and get them to fix the problem.

     2. Reconfigure the baseurl/etc. for the repository, to point to a working
        upstream. This is most often useful if you are using a newer
        distribution release than is supported by the repository (and the
        packages for the previous distribution release still work).

     3. Run the command with the repository temporarily disabled
            yum --disablerepo=%(repoid)s ...

     4. Disable the repository permanently, so yum won't use it by default. Yum
        will then just ignore the repository until you permanently enable it
        again or use --enablerepo for temporary usage:

            yum-config-manager --disable %(repoid)s
        or
            subscription-manager repos --disable=%(repoid)s

     5. Configure the failing repository to be skipped, if it is unavailable.
        Note that yum will try to contact the repo. when it runs most commands,
        so will have to try and fail each time (and thus. yum will be be much
        slower). If it is a very temporary problem though, this is often a nice
        compromise:

            yum-config-manager --save --setopt=%(repoid)s.skip_if_unavailable=true
""")

        repoui = _('Unknown')
        repoid = _('<repoid>')
        try:
            repoid = e.repo.id
            repoui = e.repo.name
        except AttributeError:
            pass

        msg = msg % {'repoid': repoid, 'repo': repoui}

        logger.critical('\n\n%s\n%s', msg, exception2msg(e))

        if unlock(): return 200
        return 1

    def unlock():
        try:
            base.closeRpmDB()
            base.doUnlock()
        except Errors.LockError as e:
            return 200
        return 0

    def rpmdb_warn_checks():
        try:
            probs = base._rpmdb_warn_checks(out=verbose_logger.info,
                                            warn=False)
        except Errors.YumBaseError as e:
            # This is mainly for PackageSackError from rpmdb.
            verbose_logger.info(_(" Yum checks failed: %s"), exception2msg(e))
            probs = []
        if not probs:
            verbose_logger.info(
                _(" You could try running: rpm -Va --nofiles --nodigest"))

    logger = logging.getLogger("yum.main")
    verbose_logger = logging.getLogger("yum.verbose.main")

    # Try to open the current directory to see if we have
    # read and execute access. If not, chdir to /
    try:
        f = open(".")
    except IOError as e:
        if e.errno == errno.EACCES:
            logger.critical(
                _('No read/execute access in current directory, moving to /'))
            os.chdir("/")
    else:
        f.close()
    try:
        os.getcwd()
    except OSError as e:
        if e.errno == errno.ENOENT:
            logger.critical(
                _('No getcwd() access in current directory, moving to /'))
            os.chdir("/")

    # our core object for the cli
    base = cli.YumBaseCli()

    # do our cli parsing and config file setup
    # also sanity check the things being passed on the cli
    try:
        base.getOptionsConfig(args)
    except plugins.PluginYumExit as e:
        return exPluginExit(e)
    except Errors.YumBaseError as e:
        return exFatal(e)
    except (OSError, IOError) as e:
        return exIOError(e)

    try:
        base.waitForLock()
    except Errors.YumBaseError as e:
        return exFatal(e)

    try:
        result, resultmsgs = base.doCommands()
    except plugins.PluginYumExit as e:
        return exPluginExit(e)
    except Errors.RepoError as e:
        return exRepoError(e)
    except Errors.YumBaseError as e:
        result = 1
        resultmsgs = [exception2msg(e)]
    except KeyboardInterrupt:
        return exUserCancel()
    except IOError as e:
        return exIOError(e)

    # Act on the command/shell result
    if result == 0:
        # Normal exit
        for msg in resultmsgs:
            verbose_logger.log(logginglevels.INFO_2, '%s', msg)
        if unlock(): return 200
        return base.exit_code
    elif result == 1:
        # Fatal error
        for msg in resultmsgs:
            logger.critical(_('Error: %s'), msg)
        if unlock(): return 200
        return 1
    elif result == 2:
        # Continue on
        pass
    elif result == 100:
        if unlock(): return 200
        return 100
    else:
        logger.critical(_('Unknown Error(s): Exit Code: %d:'), result)
        for msg in resultmsgs:
            logger.critical(msg)
        if unlock(): return 200
        return 3

    # Mainly for ostree, but might be useful for others.
    if base.conf.usr_w_check:
        usrinstpath = base.conf.installroot + "/usr"
        usrinstpath = usrinstpath.replace('//', '/')
        if (os.path.exists(usrinstpath)
                and not os.access(usrinstpath, os.W_OK)):
            logger.critical(_('No write access to %s directory') % usrinstpath)
            logger.critical(_('  Maybe this is an ostree image?'))
            logger.critical(
                _('  To disable you can use --setopt=usr_w_check=false'))
            if unlock(): return 200
            return 1

    # Depsolve stage
    verbose_logger.log(logginglevels.INFO_2, _('Resolving Dependencies'))

    try:
        (result, resultmsgs) = base.buildTransaction()
    except plugins.PluginYumExit as e:
        return exPluginExit(e)
    except Errors.RepoError as e:
        return exRepoError(e)
    except Errors.YumBaseError as e:
        result = 1
        resultmsgs = [exception2msg(e)]
    except KeyboardInterrupt:
        return exUserCancel()
    except IOError as e:
        return exIOError(e)

    # Act on the depsolve result
    if result == 0:
        # Normal exit
        if unlock(): return 200
        return base.exit_code
    elif result == 1:
        # Fatal error
        for prefix, msg in base.pretty_output_restring(resultmsgs):
            logger.critical(prefix, msg)
        if base._depsolving_failed:
            if not base.conf.skip_broken:
                verbose_logger.info(
                    _(" You could try using --skip-broken to work around the problem"
                      ))
            rpmdb_warn_checks()
        if unlock(): return 200
        return 1
    elif result == 2:
        # Continue on
        pass
    else:
        logger.critical(_('Unknown Error(s): Exit Code: %d:'), result)
        for msg in resultmsgs:
            logger.critical(msg)
        if unlock(): return 200
        return 3

    verbose_logger.log(logginglevels.INFO_2, _('\nDependencies Resolved'))

    # Run the transaction
    try:
        inhibit = {
            'what': 'shutdown:idle',
            'who': 'yum cli',
            'why': 'Running transaction',  # i18n?
            'mode': 'block'
        }
        return_code = base.doTransaction(inhibit=inhibit)
    except plugins.PluginYumExit as e:
        return exPluginExit(e)
    except Errors.RepoError as e:
        return exRepoError(e)
    except Errors.YumBaseError as e:
        return exFatal(e)
    except KeyboardInterrupt:
        return exUserCancel()
    except IOError as e:
        return exIOError(e)

    # rpm ts.check() failed.
    if type(return_code) == type((0, )) and len(return_code) == 2:
        (result, resultmsgs) = return_code
        for msg in resultmsgs:
            logger.critical("%s", msg)
        rpmdb_warn_checks()
        return_code = result
        if base._ts_save_file:
            verbose_logger.info(
                _("Your transaction was saved, rerun it with:\n yum load-transaction %s"
                  ) % base._ts_save_file)
    elif return_code < 0:
        return_code = 1  # Means the pre-transaction checks failed...
        #  This includes:
        # . No packages.
        # . Hitting N at the prompt.
        # . GPG check failures.
        if base._ts_save_file:
            verbose_logger.info(
                _("Your transaction was saved, rerun it with:\n yum load-transaction %s"
                  ) % base._ts_save_file)
    else:
        verbose_logger.log(logginglevels.INFO_2, _('Complete!'))

    if unlock(): return 200
    return return_code or base.exit_code
import yum
import cli
import json
import urllib
import re
import xml.etree.ElementTree as ET

# Get verions of all installed packages
base = yum.YumBase()
base.conf.cache = 1
versions = dict()
for pkg in base.rpmdb.returnPackages():
    versions[pkg.name] = pkg.printVer()

# Get list of packages available for update
base_cli = cli.YumBaseCli()
try:
    base_cli.getOptionsConfig(["list", "updates"])
    base_cli.doLock()
    base_cli.doCommands()
    updates = base_cli.doPackageLists(pkgnarrow="updates").updates
finally:
    base_cli.closeRpmDB()
    base_cli.doUnlock()

# Get list of rpms of security updates
ERRATA_URL = "http://cefs.steve-meier.de/errata.latest.xml"

#errataxml = urllib.urlopen(ERRATA_URL).read()
#root = ET.fromstring(errataxml)