home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / share / pyshared / apt / progress.py < prev   
Encoding:
Python Source  |  2009-03-30  |  10.9 KB  |  357 lines

  1. # Progress.py - progress reporting classes
  2. #
  3. #  Copyright (c) 2005 Canonical
  4. #
  5. #  Author: Michael Vogt <michael.vogt@ubuntu.com>
  6. #
  7. #  This program is free software; you can redistribute it and/or
  8. #  modify it under the terms of the GNU General Public License as
  9. #  published by the Free Software Foundation; either version 2 of the
  10. #  License, or (at your option) any later version.
  11. #
  12. #  This program is distributed in the hope that it will be useful,
  13. #  but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  15. #  GNU General Public License for more details.
  16. #
  17. #  You should have received a copy of the GNU General Public License
  18. #  along with this program; if not, write to the Free Software
  19. #  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
  20. #  USA
  21. """progress reporting classes.
  22.  
  23. This module provides classes for progress reporting. They can be used with
  24. e.g., for reporting progress on the cache opening process, the cache update
  25. progress, or the package install progress.
  26. """
  27.  
  28. import errno
  29. import fcntl
  30. import os
  31. import re
  32. import select
  33. import sys
  34.  
  35. import apt_pkg
  36.  
  37.  
  38. __all__ = ('CdromProgress', 'DpkgInstallProgress', 'DumbInstallProgress',
  39.           'FetchProgress', 'InstallProgress', 'OpProgress', 'OpTextProgress',
  40.           'TextFetchProgress')
  41.  
  42.  
  43. class OpProgress(object):
  44.     """Abstract class to implement reporting on cache opening.
  45.  
  46.     Subclass this class to implement simple Operation progress reporting.
  47.     """
  48.  
  49.     def __init__(self):
  50.         self.op = None
  51.         self.subOp = None
  52.  
  53.     def update(self, percent):
  54.         """Called periodically to update the user interface."""
  55.  
  56.     def done(self):
  57.         """Called once an operation has been completed."""
  58.  
  59.  
  60. class OpTextProgress(OpProgress):
  61.     """A simple text based cache open reporting class."""
  62.  
  63.     def __init__(self):
  64.         OpProgress.__init__(self)
  65.  
  66.     def update(self, percent):
  67.         """Called periodically to update the user interface."""
  68.         sys.stdout.write("\r%s: %.2i  " % (self.subOp, percent))
  69.         sys.stdout.flush()
  70.  
  71.     def done(self):
  72.         """Called once an operation has been completed."""
  73.         sys.stdout.write("\r%s: Done\n" % self.op)
  74.  
  75.  
  76. class FetchProgress(object):
  77.     """Report the download/fetching progress.
  78.  
  79.     Subclass this class to implement fetch progress reporting
  80.     """
  81.  
  82.     # download status constants
  83.     dlDone = 0
  84.     dlQueued = 1
  85.     dlFailed = 2
  86.     dlHit = 3
  87.     dlIgnored = 4
  88.     dlStatusStr = {dlDone: "Done",
  89.                    dlQueued: "Queued",
  90.                    dlFailed: "Failed",
  91.                    dlHit: "Hit",
  92.                    dlIgnored: "Ignored"}
  93.  
  94.     def __init__(self):
  95.         self.eta = 0.0
  96.         self.percent = 0.0
  97.         # Make checking easier
  98.         self.currentBytes = 0
  99.         self.currentItems = 0
  100.         self.totalBytes = 0
  101.         self.totalItems = 0
  102.         self.currentCPS = 0
  103.  
  104.     def start(self):
  105.         """Called when the fetching starts."""
  106.  
  107.     def stop(self):
  108.         """Called when all files have been fetched."""
  109.  
  110.     def updateStatus(self, uri, descr, shortDescr, status):
  111.         """Called when the status of an item changes.
  112.  
  113.         This happens eg. when the downloads fails or is completed.
  114.         """
  115.  
  116.     def pulse(self):
  117.         """Called periodically to update the user interface.
  118.  
  119.         Return True to continue or False to cancel.
  120.         """
  121.         self.percent = (((self.currentBytes + self.currentItems) * 100.0) /
  122.                         float(self.totalBytes + self.totalItems))
  123.         if self.currentCPS > 0:
  124.             self.eta = ((self.totalBytes - self.currentBytes) /
  125.                         float(self.currentCPS))
  126.         return True
  127.  
  128.     def mediaChange(self, medium, drive):
  129.         """react to media change events."""
  130.  
  131.  
  132. class TextFetchProgress(FetchProgress):
  133.     """ Ready to use progress object for terminal windows """
  134.  
  135.     def __init__(self):
  136.         FetchProgress.__init__(self)
  137.         self.items = {}
  138.  
  139.     def updateStatus(self, uri, descr, shortDescr, status):
  140.         """Called when the status of an item changes.
  141.  
  142.         This happens eg. when the downloads fails or is completed.
  143.         """
  144.         if status != self.dlQueued:
  145.             print "\r%s %s" % (self.dlStatusStr[status], descr)
  146.         self.items[uri] = status
  147.  
  148.     def pulse(self):
  149.         """Called periodically to update the user interface.
  150.  
  151.         Return True to continue or False to cancel.
  152.         """
  153.         FetchProgress.pulse(self)
  154.         if self.currentCPS > 0:
  155.             s = "[%2.f%%] %sB/s %s" % (self.percent,
  156.                                        apt_pkg.SizeToStr(int(self.currentCPS)),
  157.                                        apt_pkg.TimeToStr(int(self.eta)))
  158.         else:
  159.             s = "%2.f%% [Working]" % (self.percent)
  160.         print "\r%s" % (s),
  161.         sys.stdout.flush()
  162.         return True
  163.  
  164.     def stop(self):
  165.         """Called when all files have been fetched."""
  166.         print "\rDone downloading            "
  167.  
  168.     def mediaChange(self, medium, drive):
  169.         """react to media change events."""
  170.         print ("Media change: please insert the disc labeled "
  171.                "'%s' in the drive '%s' and press enter") % (medium, drive)
  172.  
  173.         return raw_input() not in ('c', 'C')
  174.  
  175.  
  176. class DumbInstallProgress(object):
  177.     """Report the install progress.
  178.  
  179.     Subclass this class to implement install progress reporting.
  180.     """
  181.  
  182.     def startUpdate(self):
  183.         """Start update."""
  184.  
  185.     def run(self, pm):
  186.         """Start installation."""
  187.         return pm.DoInstall()
  188.  
  189.     def finishUpdate(self):
  190.         """Called when update has finished."""
  191.  
  192.     def updateInterface(self):
  193.         """Called periodically to update the user interface"""
  194.  
  195.  
  196. class InstallProgress(DumbInstallProgress):
  197.     """An InstallProgress that is pretty useful.
  198.  
  199.     It supports the attributes 'percent' 'status' and callbacks for the dpkg
  200.     errors and conffiles and status changes.
  201.     """
  202.  
  203.     def __init__(self):
  204.         DumbInstallProgress.__init__(self)
  205.         self.selectTimeout = 0.1
  206.         (read, write) = os.pipe()
  207.         self.writefd = write
  208.         self.statusfd = os.fdopen(read, "r")
  209.         fcntl.fcntl(self.statusfd.fileno(), fcntl.F_SETFL, os.O_NONBLOCK)
  210.         self.read = ""
  211.         self.percent = 0.0
  212.         self.status = ""
  213.  
  214.     def error(self, pkg, errormsg):
  215.         """Called when a error is detected during the install."""
  216.  
  217.     def conffile(self, current, new):
  218.         """Called when a conffile question from dpkg is detected."""
  219.  
  220.     def statusChange(self, pkg, percent, status):
  221.         """Called when the status changed."""
  222.  
  223.     def updateInterface(self):
  224.         """Called periodically to update the interface."""
  225.         if self.statusfd is None:
  226.             return
  227.         try:
  228.             while not self.read.endswith("\n"):
  229.                 self.read += os.read(self.statusfd.fileno(), 1)
  230.         except OSError, (errno_, errstr):
  231.             # resource temporarly unavailable is ignored
  232.             if errno_ != errno.EAGAIN and errno_ != errno.EWOULDBLOCK:
  233.                 print errstr
  234.         if not self.read.endswith("\n"):
  235.             return
  236.  
  237.         s = self.read
  238.         #print s
  239.         try:
  240.             (status, pkg, percent, status_str) = s.split(":", 3)
  241.         except ValueError:
  242.             # silently ignore lines that can't be parsed
  243.             self.read = ""
  244.             return
  245.         #print "percent: %s %s" % (pkg, float(percent)/100.0)
  246.         if status == "pmerror":
  247.             self.error(pkg, status_str)
  248.         elif status == "pmconffile":
  249.             # we get a string like this:
  250.             # 'current-conffile' 'new-conffile' useredited distedited
  251.             match = re.match("\s*\'(.*)\'\s*\'(.*)\'.*", status_str)
  252.             if match:
  253.                 self.conffile(match.group(1), match.group(2))
  254.         elif status == "pmstatus":
  255.             if float(percent) != self.percent or status_str != self.status:
  256.                 self.statusChange(pkg, float(percent),
  257.                                   status_str.strip())
  258.                 self.percent = float(percent)
  259.                 self.status = status_str.strip()
  260.         self.read = ""
  261.  
  262.     def fork(self):
  263.         """Fork."""
  264.         return os.fork()
  265.  
  266.     def waitChild(self):
  267.         """Wait for child progress to exit."""
  268.         while True:
  269.             select.select([self.statusfd], [], [], self.selectTimeout)
  270.             self.updateInterface()
  271.             (pid, res) = os.waitpid(self.child_pid, os.WNOHANG)
  272.             if pid == self.child_pid:
  273.                 break
  274.         return res
  275.  
  276.     def run(self, pm):
  277.         """Start installing."""
  278.         pid = self.fork()
  279.         if pid == 0:
  280.             # child
  281.             res = pm.DoInstall(self.writefd)
  282.             os._exit(res)
  283.         self.child_pid = pid
  284.         res = self.waitChild()
  285.         return os.WEXITSTATUS(res)
  286.  
  287.  
  288. class CdromProgress(object):
  289.     """Report the cdrom add progress.
  290.  
  291.     Subclass this class to implement cdrom add progress reporting.
  292.     """
  293.  
  294.     def __init__(self):
  295.         pass
  296.  
  297.     def update(self, text, step):
  298.         """Called periodically to update the user interface."""
  299.  
  300.     def askCdromName(self):
  301.         """Called to ask for the name of the cdrom."""
  302.  
  303.     def changeCdrom(self):
  304.         """Called to ask for the cdrom to be changed."""
  305.  
  306.  
  307. class DpkgInstallProgress(InstallProgress):
  308.     """Progress handler for a local Debian package installation."""
  309.  
  310.     def run(self, debfile):
  311.         """Start installing the given Debian package."""
  312.         self.debfile = debfile
  313.         self.debname = os.path.basename(debfile).split("_")[0]
  314.         pid = self.fork()
  315.         if pid == 0:
  316.             # child
  317.             res = os.system("/usr/bin/dpkg --status-fd %s -i %s" % \
  318.                             (self.writefd, self.debfile))
  319.             os._exit(os.WEXITSTATUS(res))
  320.         self.child_pid = pid
  321.         res = self.waitChild()
  322.         return res
  323.  
  324.     def updateInterface(self):
  325.         """Process status messages from dpkg."""
  326.         if self.statusfd is None:
  327.             return
  328.         while True:
  329.             try:
  330.                 self.read += os.read(self.statusfd.fileno(), 1)
  331.             except OSError, (errno_, errstr):
  332.                 # resource temporarly unavailable is ignored
  333.                 if errno_ != 11:
  334.                     print errstr
  335.                 break
  336.             if not self.read.endswith("\n"):
  337.                 continue
  338.  
  339.             statusl = self.read.split(":")
  340.             if len(statusl) < 3:
  341.                 print "got garbage from dpkg: '%s'" % self.read
  342.                 self.read = ""
  343.                 break
  344.             status = statusl[2].strip()
  345.             #print status
  346.             if status == "error":
  347.                 self.error(self.debname, status)
  348.             elif status == "conffile-prompt":
  349.                 # we get a string like this:
  350.                 # 'current-conffile' 'new-conffile' useredited distedited
  351.                 match = re.match("\s*\'(.*)\'\s*\'(.*)\'.*", statusl[3])
  352.                 if match:
  353.                     self.conffile(match.group(1), match.group(2))
  354.             else:
  355.                 self.status = status
  356.             self.read = ""
  357.