home *** CD-ROM | disk | FTP | other *** search
/ PC Welt 2006 November (DVD) / PCWELT_11_2006.ISO / casper / filesystem.squashfs / usr / bin / unattended-upgrade < prev    next >
Encoding:
Text File  |  2006-07-27  |  8.9 KB  |  246 lines

  1. #!/usr/bin/python
  2. #
  3. # (c) 2005 Canonical
  4. # Author: Michael Vogt <michael.vogt@ubuntu.com>
  5. #
  6. # Released under the GPL
  7.  
  8. import apt_pkg, apt_inst
  9. import sys, os, string, datetime
  10. from optparse import OptionParser
  11. from subprocess import Popen, PIPE
  12.  
  13. import warnings
  14. warnings.filterwarnings("ignore", "apt API not stable yet", FutureWarning)
  15. import apt
  16. import logging
  17.  
  18. class MyCache(apt.Cache):
  19.     def __init__(self):
  20.         apt.Cache.__init__(self)
  21.     def clear(self):
  22.         self._depcache.Init()
  23.         assert self._depcache.InstCount == 0 and \
  24.                self._depcache.BrokenCount == 0 \
  25.                and self._depcache.DelCount == 0
  26.         
  27.  
  28. def is_allowed_origin(pkg, allowed_origins):
  29.     for origin in pkg.candidateOrigin:
  30.         for allowed in allowed_origins:
  31.             if origin.origin == allowed[0] and origin.archive == allowed[1]:
  32.                 return True
  33.     return False
  34.  
  35. def check_changes_for_sanity(cache, allowed_origins, blacklist):
  36.     if cache._depcache.BrokenCount != 0:
  37.         return False
  38.     for pkg in cache:
  39.         if pkg.markedDelete:
  40.             return False
  41.         if pkg.markedInstall or pkg.markedUpgrade:
  42.             if not is_allowed_origin(pkg, allowed_origins):
  43.                 return False
  44.             if pkg.name in blacklist:
  45.                 return False
  46.     return True
  47.  
  48. def pkgname_from_deb(debfile):
  49.     # FIXME: add error checking here
  50.     control = apt_inst.debExtractControl(open(debfile))
  51.     sections = apt_pkg.ParseSection(control)
  52.     return sections["Package"]
  53.  
  54. def conffile_prompt(destFile):
  55.     logging.debug("check_conffile_prompt('%s')" % destFile)
  56.     pkgname = pkgname_from_deb(destFile)
  57.     status_file = apt_pkg.Config.Find("Dir::State::status")
  58.     parse = apt_pkg.ParseTagFile(open(status_file,"r"))
  59.     while parse.Step() == 1:
  60.         if parse.Section.get("Package") == pkgname:
  61.             logging.debug("found pkg: %s" % pkgname)
  62.             if parse.Section.has_key("Conffiles"):
  63.                 conffiles = parse.Section.get("Conffiles")
  64.                 # Conffiles:
  65.                 # /etc/bash_completion.d/m-a c7780fab6b14d75ca54e11e992a6c11c
  66.                 for line in string.split(conffiles,"\n"):
  67.                     logging.debug("conffile line: %s", line)
  68.                     l = string.split(string.strip(line))
  69.                     file = l[0]
  70.                     md5 = l[1]
  71.                     if len(l) > 2:
  72.                         obs = l[2]
  73.                     else:
  74.                         obs = None
  75.                     if os.path.exists(file) and obs != "obsolete":
  76.                         current_md5 = apt_pkg.md5sum(open(file).read())
  77.                         if current_md5 != md5:
  78.                             return True
  79.     return False
  80.  
  81.  
  82. if __name__ == "__main__":
  83.  
  84.     # init the logging
  85.     logdir = apt_pkg.Config.FindDir("APT::UnattendedUpgrades::LogDir",
  86.                                     "/var/log/unattended-upgrades/")
  87.     logfile = logdir+apt_pkg.Config.Find("APT::UnattendedUpgrades::LogFile",
  88.                                          "unattended-upgrades.log")
  89.     logging.basicConfig(level=logging.INFO,
  90.                         format='%(asctime)s %(levelname)s %(message)s',
  91.                         filename=logfile)
  92.  
  93.     # init the options
  94.     parser = OptionParser()
  95.     parser.add_option("-d", "--debug",
  96.                       action="store_true", dest="debug", default=False,
  97.                       help="print debug messages")
  98.     (options, args) = parser.parse_args()
  99.     if options.debug:
  100.         logging.getLogger().setLevel(logging.DEBUG)
  101.         pass
  102.  
  103.     #dldir = "/tmp/pyapt-test"
  104.     #try:
  105.     #    os.mkdir(dldir)
  106.     #    os.mkdir(dldir+"/partial")
  107.     #except OSError:
  108.     #    pass
  109.     #apt_pkg.Config.Set("Dir::Cache::archives",dldir)
  110.  
  111.     # format (origin, archive), e.g. ("Ubuntu","dapper-security")
  112.     allowed_origins = map(string.split, apt_pkg.Config.ValueList("Unattended-Upgrade::Allowed-Origins"))
  113.  
  114.     # pkgs that are (for some reason) not save to install
  115.     blacklisted_pkgs = apt_pkg.Config.ValueList("Unattended-Upgrade::Package-Blacklist")
  116.     logging.info("Initial blacklisted packages: %s", "".join(blacklisted_pkgs))
  117.  
  118.     logging.info("Starting unattended upgrades script")
  119.  
  120.     # display available origin
  121.     logging.info("Allowed origins are: %s" % map(str,allowed_origins))
  122.     
  123.     # get a cache
  124.     cache = MyCache()
  125.  
  126.     # find out about the packages that are upgradable (in a allowed_origin)
  127.     pkgs_to_upgrade = []
  128.     for pkg in cache:
  129.         if options.debug and pkg.isUpgradable:
  130.             logging.debug("Checking: %s (%s)" % (pkg.name,map(str, pkg.candidateOrigin)))
  131.         if pkg.isUpgradable and \
  132.                is_allowed_origin(pkg,allowed_origins):
  133.             try:
  134.                 pkg.markUpgrade()
  135.                 if check_changes_for_sanity(cache, allowed_origins,
  136.                                             blacklisted_pkgs):
  137.                     pkgs_to_upgrade.append(pkg)
  138.             except SystemError:
  139.                 # can't upgrade
  140.                 pass
  141.             else:
  142.                 cache.clear()
  143.                 for pkg2 in pkgs_to_upgrade:
  144.                     pkg2.markUpgrade()
  145.  
  146.     pkgs = "\n".join([pkg.name for pkg in pkgs_to_upgrade])
  147.     logging.debug("pkgs that look like they should be upgraded: %s" % pkgs)
  148.            
  149.     # download what looks good
  150.     if options.debug:
  151.         fetcher = apt_pkg.GetAcquire(apt.progress.TextFetchProgress())
  152.     else:
  153.         fetcher = apt_pkg.GetAcquire()
  154.     list = apt_pkg.GetPkgSourceList()
  155.     list.ReadMainList()
  156.     recs = cache._records
  157.     pm = apt_pkg.GetPackageManager(cache._depcache)
  158.     pm.GetArchives(fetcher,list,recs)
  159.     res = fetcher.Run()
  160.  
  161.     # now check the downloaded debs for conffile conflicts and build
  162.     # a blacklist
  163.     for item in fetcher.Items:
  164.         logging.debug("%s" % item)
  165.         if item.Status == item.StatError:
  166.             print "A error ocured: '%s'" % item.ErrorText
  167.         if item.Complete == False:
  168.             print "The URI '%s' failed to download, aborting" % item.DescURI
  169.             sys.exit(1)
  170.         if item.IsTrusted == False:
  171.             blacklisted_pkgs.append(pkgname_from_deb(item.DestFile))
  172.         if conffile_prompt(item.DestFile):
  173.             # FIXME: skip package (means to re-run the whole marking again
  174.             # and making sure that the package will not be pulled in by
  175.             # some other package again!
  176.             logging.debug("pkg '%s' has conffile prompt" % pkgname_from_deb(item.DestFile))
  177.             blacklisted_pkgs.append(pkgname_from_deb(item.DestFile))
  178.  
  179.  
  180.     # redo the selection about the packages to upgrade based on the new
  181.     # blacklist
  182.     logging.debug("blacklist: %s" % blacklisted_pkgs)
  183.     # find out about the packages that are upgradable (in a allowed_origin)
  184.     if len(blacklisted_pkgs) > 0:
  185.         cache.clear()
  186.         old_pkgs_to_upgrade = pkgs_to_upgrade[:]
  187.         pkgs_to_upgrade = []
  188.         for pkg in old_pkgs_to_upgrade:
  189.             logging.debug("Checking (blacklist): %s" % (pkg.name))
  190.             pkg.markUpgrade()
  191.             if check_changes_for_sanity(cache, allowed_origins,
  192.                                         blacklisted_pkgs):
  193.                  pkgs_to_upgrade.append(pkg)
  194.             else:
  195.                 logging.info("package '%s' not upgraded" % pkg.name)
  196.                 cache.clear()
  197.                 for pkg2 in pkgs_to_upgrade:
  198.                     pkg2.markUpgrade()
  199.  
  200.     logging.debug("InstCount=%i DelCount=%i BrokenCout=%i" % (cache._depcache.InstCount, cache._depcache.DelCount, cache._depcache.BrokenCount))
  201.  
  202.     # check what we have
  203.     if len(pkgs_to_upgrade) == 0:
  204.         logging.info("No packages found that can be upgraded unattended")
  205.         sys.exit(0)    
  206.  
  207.     # do the install based on the new list of pkgs
  208.     pkgs = " ".join([pkg.name for pkg in pkgs_to_upgrade])
  209.     logging.info("Packages that are upgraded: %s" % pkgs)
  210.  
  211.     # set debconf to NON_INTERACTIVE, redirect output
  212.     os.putenv("DEBIAN_FRONTEND","noninteractive");
  213.     os.putenv("APT_LISTCHANGES_FRONTEND","none");
  214.     
  215.     # redirect to log
  216.     REDIRECT_INPUT = os.devnull
  217.     fd = os.open(REDIRECT_INPUT, os.O_RDWR)
  218.     os.dup2(fd,0)
  219.  
  220.     now = datetime.datetime.now()
  221.     logfile_dpkg = logdir+'unattended-upgrades-dpkg_%s.log' % now.isoformat('_')
  222.     logging.info("Writing dpkg log to '%s'" % logfile_dpkg)
  223.     fd = os.open(logfile_dpkg,os.O_RDWR|os.O_CREAT)
  224.     os.dup2(fd,1)
  225.     os.dup2(fd,2)
  226.  
  227.     # create a new package-manager. the blacklist may have changed
  228.     # the markings in the depcache
  229.     if options.debug:
  230.         apt_pkg.Config.Set("Debug::pkgDPkgPM","1")
  231.     #apt_pkg.Config.Set("Debug::pkgDPkgPM","1")    
  232.     pm = apt_pkg.GetPackageManager(cache._depcache)
  233.     pm.GetArchives(fetcher,list,recs)
  234.     try:
  235.         res = pm.DoInstall()
  236.     except SystemError,e:
  237.         logging.error("Installing the upgrades failed!")
  238.         logging.error("error message: '%s'" % e)
  239.         res = False
  240.                 
  241.     if res == pm.ResultFailed:
  242.         logging.error("dpkg returned a error! See '%s' for details" % logfile_dpkg)
  243.     else:
  244.         logging.info("All upgrades installed")
  245.  
  246.