Your IP : 216.73.216.209


Current Path : /bin/
Upload File :
Current File : //bin/package-cleanup

#!/usr/bin/python
#
# (C) 2005 Gijs Hollestelle, released under the GPL
# Copyright 2009 Red Hat
# Rewritten 2009 - Seth Vidal
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
#


import sys
sys.path.insert(0,'/usr/share/yum-cli')

from yum.misc import setup_locale
from utils import YumUtilBase
import logging
import os
import re
import yum.depsolve # For flags

from yum.Errors import YumBaseError
from rpmUtils import miscutils, arch
from optparse import OptionGroup

def exactlyOne(l):
    return len(filter(None, l)) == 1


class PackageCleanup(YumUtilBase):
    NAME = 'package-cleanup'
    VERSION = '1.0'
    USAGE = """
    package-cleanup: helps find problems in the rpmdb of system and correct them

    usage: package-cleanup --problems or --leaves or --orphans or --oldkernels
    """
    def __init__(self):
        YumUtilBase.__init__(self,
                             PackageCleanup.NAME,
                             PackageCleanup.VERSION,
                             PackageCleanup.USAGE)
        self.logger = logging.getLogger("yum.verbose.cli.packagecleanup")
        # Add util commandline options to the yum-cli ones
        self.optparser = self.getOptionParser()
        self.optparser_grp = self.getOptionGroup()
        self.addCmdOptions()
        self.main()

    def addCmdOptions(self):
        self.optparser_grp.add_option("--problems", default=False, 
                    dest="problems", action="store_true",
                    help='List dependency problems in the local RPM database')
        self.optparser_grp.add_option("--qf", "--queryformat", dest="qf", 
                    action="store",
                    default='%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}',
                    help="Query format to use for output.")
        self.optparser_grp.add_option("--orphans", default=False, 
                    dest="orphans",action="store_true",
                    help='List installed packages which are not available from'\
                         ' currently configured repositories')

        dupegrp = OptionGroup(self.optparser, 'Duplicate Package Options')
        dupegrp.add_option("--dupes", default=False, 
                    dest="dupes", action="store_true",
                    help='Scan for duplicates in your rpmdb')
        dupegrp.add_option("--cleandupes", default=False, 
                    dest="cleandupes", action="store_true",
                    help='Scan for duplicates in your rpmdb and remove older ')
        dupegrp.add_option("--removenewestdupes", default=False, 
                    dest="removenewestdupes", action="store_true",
                    help='Remove the newest dupes instead of the oldest dupes when cleaning duplicates.')
        dupegrp.add_option("--noscripts", default=False,
                    dest="noscripts", action="store_true",
                    help="disable rpm scriptlets from running when cleaning duplicates")
        self.optparser.add_option_group(dupegrp)
        
        leafgrp = OptionGroup(self.optparser, 'Leaf Node Options')
        leafgrp.add_option("--leaves", default=False, dest="leaves",
                    action="store_true",
                    help='List leaf nodes in the local RPM database')
        leafgrp.add_option("--all", default=False, dest="all_nodes",
                    action="store_true",
                    help='list all packages leaf nodes that do not match'\
                         ' leaf-regex')
        leafgrp.add_option("--leaf-regex", 
                    default="(^(compat-)?lib(?!reoffice).+|.*libs?[\d-]*|.*-data$)",
                    help='A package name that matches this regular expression' \
                         ' (case insensitively) is a leaf')
        leafgrp.add_option("--exclude-devel", default=False, 
                    action="store_true",
                    help='do not list development packages as leaf nodes')
        leafgrp.add_option("--exclude-bin", default=False, 
                    action="store_true",
                    help='do not list packages with files in a bin dirs as'\
                         'leaf nodes')
        self.optparser.add_option_group(leafgrp)        
        
        kernelgrp = OptionGroup(self.optparser, 'Old Kernel Options')
        kernelgrp.add_option("--oldkernels", default=False, 
                    dest="kernels",action="store_true",
                    help="Remove old kernel and kernel-devel packages")
        kernelgrp.add_option("--count",default=2,dest="kernelcount",
                             action="store",
                             help='Number of kernel packages to keep on the '\
                                  'system (default 2)')
        kernelgrp.add_option("--keepdevel", default=False, dest="keepdevel",
                             action="store_true",
                             help='Do not remove kernel-devel packages when '
                                 'removing kernels')
        self.optparser.add_option_group(kernelgrp)
    
    def _find_installed_duplicates(self, ignore_kernel=True):
        """find installed duplicate packages returns a dict of 
           pkgname = [[dupe1, dupe2], [dupe3, dupe4]] """
           
        # XXX - this should move to be a method of rpmsack
        
        multipkgs = {}
        singlepkgs = {}
        results = {}
        
        for pkg in self.rpmdb.returnPackages():
            # just skip kernels and everyone is happier
            if ignore_kernel:
                if 'kernel' in pkg.provides_names:
                    continue
                if pkg.name.startswith('kernel'):
                    continue

            name = pkg.name                
            if name in multipkgs or name in singlepkgs:
                continue

            pkgs = self.rpmdb.searchNevra(name=name)
            if len(pkgs)  <= 1:
                continue
            
            for po in pkgs:
                if name not in multipkgs:
                    multipkgs[name] = []
                if name not in singlepkgs:
                    singlepkgs[name] = []
                    
                if arch.isMultiLibArch(arch=po.arch):
                    multipkgs[name].append(po)
                elif po.arch == 'noarch':
                    multipkgs[name].append(po)
                    singlepkgs[name].append(po)
                elif not arch.isMultiLibArch(arch=po.arch):
                    singlepkgs[name].append(po)
                else:
                    print "Warning: neither single nor multi lib arch: %s " % po
            
        for (name, pkglist) in multipkgs.items() + singlepkgs.items():
            if len(pkglist) <= 1:
                continue
                
            if name not in results:
                results[name] = []
            if pkglist not in results[name]:
                results[name].append(pkglist)
            
        return results

    def _remove_dupes(self, newest=False):
        """add duplicate pkgs to be removed in the transaction,
           return a dict of excluded dupes and their requiring packages"""

        # Find dupes
        dupedict = self._find_installed_duplicates()
        removedupes = set()
        for (name,dupelists) in dupedict.items():
            for dupelist in dupelists:
                dupelist.sort()
                if newest:
                    plist = dupelist[1:]
                else:
                    plist = dupelist[0:-1]
                for lowpo in plist:
                    removedupes.add(lowpo)

        # Exclude any such dupes that would pull other installed packages into
        # the removal transaction (to prevent us from accidentally removing a
        # huge part of a working system) by performing a dry transaction(s)
        # first.
        excluded = {}
        while True:
            for po in removedupes:
                self.remove(po)
            changed = False
            for txmbr in self.tsInfo.getMembers():
                requiredby = self._checkRemove(txmbr)
                if requiredby:
                    removedupes.remove(txmbr.po)
                    excluded[txmbr.po] = requiredby
                    # Do another round, to cover any transitive deps within
                    # removedupes, for example: if foo requires bar requires
                    # baz and removedupes contains bar and baz, then
                    # _checkRemove(baz) won't return bar.
                    changed = True
            del self.tsInfo
            if not changed:
                break

        # Mark the dupes for removal
        for po in removedupes:
            self.remove(po)

        return excluded


    def _should_show_leaf(self, po, leaf_regex, exclude_devel, exclude_bin):
        """
        Determine if the given pkg should be displayed as a leaf or not.

        Return True if the pkg should be shown, False if not.
        """
        if po.name == 'gpg-pubkey':
            return False
        name = po.name
        if exclude_devel and name.endswith('devel'):
            return False
        if exclude_bin:
            for file_name in po.filelist:
                if file_name.find('bin') != -1:
                    return False
        if leaf_regex.match(name):
            return True
        return False

    def _get_kernels(self):
        """return a list of all installed kernels, sorted newest to oldest"""

        kernlist =  self.rpmdb.searchProvides(name='kernel')
        kernlist.sort()
        kernlist.reverse()
        return kernlist

    def _get_old_kernel_devel(self, kernels, removelist):
    # List all kernel devel packages that either belong to kernel versions that
    # are no longer installed or to kernel version that are in the removelist
        
        devellist = []
        for po in self.rpmdb.searchProvides(name='kernel-devel'):
            # For all kernel-devel packages see if there is a matching kernel
            # in kernels but not in removelist
            keep = False
            for kernel in kernels:
                if kernel in removelist:
                    continue
                (kname,karch,kepoch,kver,krel) = kernel.pkgtup
                (dname,darch,depoch,dver,drel) = po.pkgtup
                if (karch,kepoch,kver,krel) == (darch,depoch,dver,drel):
                    keep = True
            if not keep:
                devellist.append(po)
        return devellist
        
    def _remove_old_kernels(self, count, keepdevel):
        """Remove old kernels, keep at most count kernels (and always keep the running
         kernel"""

        count = int(count)
        kernels = self._get_kernels()
        runningkernel = os.uname()[2]
        # Vanilla kernels dont have a release, only a version
        if '-' in runningkernel:
            splt = runningkernel.split('-')
            if len(splt) == 2:
                (kver,krel) = splt
            else: # Handle cases where a custom build kernel has an extra '-' in the release
                kver=splt[1]
                krel="-".join(splt[1:])
            if krel.split('.')[-1] == os.uname()[-1]:
                krel = ".".join(krel.split('.')[:-1])
        else:
            kver = runningkernel
            krel = ""

        #  This is roughly what we want, but when there are multiple packages
        # we want to keep N of each.
        # remove = kernels[count:]
        kern_name_map = {}
        for kern in kernels:
            if kern.name not in kern_name_map:
                kern_name_map[kern.name] = []
            kern_name_map[kern.name].append(kern)
        remove = []
        for kern in kern_name_map.values():
            remove.extend(kern[count:])
        
        toremove = []
        # Remove running kernel from remove list
        for kernel in remove:
            if kernel.version == kver and kernel.release == krel:
                print "Not removing kernel %s-%s because it is the running kernel" % (kver,krel)
            else:
                toremove.append(kernel)
        
            
        # Now extend the list with all kernel-devel packages that either
        # have no matching kernel installed or belong to a kernel that is to
        # be removed
        if not keepdevel: 
            toremove.extend(self._get_old_kernel_devel(kernels, toremove))

        for po in toremove:
            self.remove(po)


    def main(self):
        opts = self.doUtilConfigSetup()
        if not exactlyOne([opts.problems, opts.dupes, opts.leaves, opts.kernels,
                           opts.orphans, opts.cleandupes]):
            print self.optparser.format_help()
            sys.exit(1)

        if self.conf.uid != 0:
            self.setCacheDir()
        
        if opts.problems:
            issues = self.rpmdb.check_dependencies()
            for prob in issues:
                print 'Package %s' % prob

            if issues:
                sys.exit(1)
            else:
                print 'No Problems Found'
                sys.exit(0)

        if opts.dupes:
            dupes = self._find_installed_duplicates()
            for name, pkglists in dupes.items():
                for pkglist in pkglists:
                    for pkg in pkglist:
                        print '%s' % pkg.hdr.sprintf(opts.qf)
            sys.exit(0)
        
        if opts.kernels:
            if self.conf.uid != 0:
                print "Error: Cannot remove kernels as a user, must be root"
                sys.exit(1)
            if int(opts.kernelcount) < 1:
                print "Error should keep at least 1 kernel!"
                sys.exit(100)
                
            self._remove_old_kernels(opts.kernelcount, opts.keepdevel)
            self.run_with_package_names.add('yum-utils')
            if hasattr(self, 'doUtilBuildTransaction'):
                errc = self.doUtilBuildTransaction()
                if errc:
                    sys.exit(errc)
            else:
                try:
                    self.buildTransaction()
                except yum.Errors.YumBaseError, e:
                    self.logger.critical("Error building transaction: %s" % e)
                    sys.exit(1)

            if len(self.tsInfo) < 1:
                print 'No old kernels to remove'
                sys.exit(0)
            
            sys.exit(self.doUtilTransaction())
            
        
        if opts.leaves:
            leaves = self.rpmdb.returnLeafNodes()
            leaf_reg = re.compile(opts.leaf_regex, re.IGNORECASE)
            for po in sorted(leaves):
                if opts.all_nodes or \
                   self._should_show_leaf(po, leaf_reg, opts.exclude_devel,
                        opts.exclude_bin):
                    print po.hdr.sprintf(opts.qf)
            
            sys.exit(0)

        if opts.orphans:
            if not self.setCacheDir():
                self.logger.error("Error: Could not make cachedir, exiting")
                sys.exit(50)
            try:
                for po in sorted(self.doPackageLists(pkgnarrow='extras').extras):
                    print po.hdr.sprintf(opts.qf)
            except YumBaseError,e:
                self.logger.error("Error: %s" % str(e))
                sys.exit(1)                
            sys.exit(0)


        if opts.cleandupes:
            if os.geteuid() != 0:
                print "Error: Cannot remove packages as a user, must be root"
                sys.exit(1)
            if opts.noscripts:
                self.conf.tsflags.append('noscripts')
            excluded = self._remove_dupes(opts.removenewestdupes)
            for po, requiredby in excluded.iteritems():
                count = len(requiredby)
                print ('Not removing %s because it is required by %s '
                       'installed package%s' %
                       (po.hdr.sprintf(opts.qf), count,
                        's' if count > 1 else ''))
            self.run_with_package_names.add('yum-utils')

            if hasattr(self, 'doUtilBuildTransaction'):
                errc = self.doUtilBuildTransaction()
                if errc:
                    sys.exit(errc)
            else:
                try:
                    self.buildTransaction()
                except yum.Errors.YumBaseError, e:
                    self.logger.critical("Error building transaction: %s" % e)
                    sys.exit(1)
                                    

            if len(self.tsInfo) < 1:
                print 'No duplicates to remove'
                errc = 0
            else:
                errc = self.doUtilTransaction()

            if excluded:
                self.logger.warn(
                    'Warning: Some duplicates were not removed because they '
                    'are required by installed packages.\n'
                    'You can try --cleandupes with%s --removenewestdupes, '
                    'or review them with --dupes and remove manually.' %
                    ('out' if opts.removenewestdupes else '')
                )

            sys.exit(errc)

    
if __name__ == '__main__':
    setup_locale()
    util = PackageCleanup()

Rosenblum TV: Video training, virtual workshops, classes, tutorials
logologologologo
  • About
  • What We Do
  • Our Clients
  • Case Studies
    • The BBC
    • CBS News
    • New York Times Television
    • Spectrum News
    • The Newark Star-Ledger
    • The United Nations
    • McGraw/Hill
    • Oyster Yachts
    • Scottish Environmental Protection Agency
  • The Power of Storytelling
  • Why iPhones?
  • Michael on Media
  • Books
  • Contact
  • About
  • What We Do
  • Our Clients
  • Case Studies
    • The BBC
    • CBS News
    • New York Times Television
    • Spectrum News
    • The Newark Star-Ledger
    • The United Nations
    • McGraw/Hill
    • Oyster Yachts
    • Scottish Environmental Protection Agency
  • The Power of Storytelling
  • Why iPhones?
  • Michael on Media
  • Books
  • Contact

RE-INVENTING THE TELEVISION NEWS BUSINESS*

A revolution in video storytelling

Creating entirely new & cost-effective production methods

From the world leaders in video production training and the creators of Character Driven Storytelling™

*and every other business that uses video

WHAT WE DO

Over the past 35 years, we have designed, built or restructured some of the most powerful news and journalism companies in the world.

We replace the traditional TV news ‘crew’ with one highly trained journalist, working alone with nothing but an iPhone.

No more TV news ‘crews’, no editors and no field producers.

This is television news done the way newspaper journalism is done – one reporter with their electronic pad and pencil.

In doing this, we can cut the cost of production by as much as 75% while increasing ratings and audience engagement.

In the place of conventional TV news ‘packages’ – ie, reporter stand up, interview, b-roll, man on the street, we marry great journalism with Netflix and Hollywood storytelling.

It’s a combination that works.

We have taken most of our clients to #1 in their respective markets.

And it’s not just for news. Any company, any profit, any NGO and anyone else who is online needs to tell their story in compelling yet cost-effective video. We can teach you to do that. Either in person or virtually.

EXAMPLES OF WHAT WE CAN TEACH YOUR STAFF TO PRODUCE

ITAY HOD

Itay Hod, MMJ with KPIX/CBS in San Francisco, took the 5-Day Intensive Video Storytelling Bootcamp in 2018.

Because he works alone, with only an iPhone, he was able to embed himself with a homeless family.

Here’s the story he produced in a one-day turn.

KIET DO

Kiet Do, an MMJ with KPIX/CBS in San Francisco, took the 5-Day Intensive Video Storytelling Bootcamp in 2021.

Here is a story he produced, all on his own, with only an iPhone and in a one-day turn.

TAYLOR SCHAUB

Taylor Schaub, an MMJ with Spectrum News 1 in LA, took the 5-Day Intensive Video Storytelling Bootcamp in 2023.

Here is a story he turned in only one day, using only an iPhone. It was the first video story he ever did and it was nominated for an Emmy.

THE BOOTCAMP

How do we convert stations and whole networks to working in this way?

Since 1988, we have run intensive 5-Day Video Storytelling Bootcamps

We have done these all over the world.

These are hands-on bootcamps, and participants learn an entirely new way of creating TV news stories.

-We shoot at a 3:1 ratio or lower, so turnaround times are fast.

-We go directly from camera to timelilne and edit – no written scripts.  We work in the medium of pictures and sound.

-We are entirely character-driven.

-We are driven by pictures and real events.

-We are focused almost entirely on ’the viewer experience’.

Since 1988, more than 70,000 journalists around the world have taken our bootcamps, either in person on virtualy.

Case Studies

CBS Case Study Logos
CBS News

We have started to work with CBS News, bringing our ideas of character-driven storytelling to one of the most successful and biggest networks in the United States. Since beginning to work with them ratings have climbed and more importantly, audience engagement is through the ceiling.

Learn More
NYT Case Study Logos
New York Times Television

We started New York Times Television in 1990 and it was the first paper to be brought into the world of TV. It quickly became one of the most successful non-fiction production companies in the United States. The series and documentaries we produced won many awards including multiple Emmys.

Learn More
BBC Case Study Logos
The BBC

We have been working with the BBC since the year 2000 helping to convert their national news network to our visual storytelling technique. Most recently we have trained teams from their sports, documentaries, and comedy divisions to make character-driven stories using only smartphones.

Learn More
Spectrum Case Study Logos
Spectrum News

For the past five years we have worked with Spectrum News to introduce and train their journalists on visual, character driven storytelling using smartphones helping to create a different kind of local news for their network of 24-Hour News Stations across the United States.

Learn More
UN Case Study Logos
The United Nations

In 2006, we were approached by the United Nations. Rather than rely on news outlets, it would be much easier to train the field operatives to produce their own stories. We spent two years working with the UN, training more than 100 of their staff in bootcamps in Geneva and Nairobi.

Learn More
Star Ledger Case Study Logos
The Newark Star-Ledger

We trained 50 print reporters at the paper to shoot and tell their own stories, in conjunction with their print work. We built a TV newsroom in their existing print newsroom – you could not ask for a better set and they began to live stream their stories in conjunction with their print work.

Learn More
Mcgraw Hill Case Study Logos
Mcgraw Hill

We spent two years with McGraw Hill, training more than 150 of their staffers, making them completely video literate. McGraw/Hill media properties we transit included Business Week, Aviation Week, (what was the name of the architecture magazine), and JD Power and Associates.

Learn More
VOA Case Study Logos
Voice of America

In 1990, we were approached by The Voice of America, the official broadcasting agency for the United States Government. When we met with VOA, they were only a short wave radio broadcaster, but working with them, we took them into television, launching VOA-TV.

Learn More
Oyster Case Study Logos
Oyster Yachts

British based Oyster Yachts makes some of the finest yachts in the world. Like every other company, they had to find a way to feed the never-ending video demands of social media – sites like Instagram and TikTok. We trained the Oyster staff to tell their own stories, using only iPhones.

Learn More
SEPA Case Study Logos
Scottish Environmental Protection Agency

We were approached by SEPA, the Scottish Environmental Protection Agency because they had to continually find a way to ‘feed the media beast’. The result was that SEPA was able to tell their own stories, whenever they wanted, and at almost no additional cost.

Learn More
Image 11-11-22 at 6.25 PM

Michael on Media

Michael Rosenblum has been writing about the media since 1988. His work and ideas have appeared in The Guardian, The Huffington Post, Ilkeston Life and many other publications.

He has been blogging regularly for the past 35 years on this subject. Having taught media studies at Columbia University, NYU and now the University of Oxford, he is considered an expert on this subject.

Continue reading this post or look back at previous posts.

Read More

Do You Have Questions About Learning Video Skills?

If you would like to know more about our courses contact us and one of our training advisors will be happy to call you.

Contact Us

Copyright 2024. All rights reserved.