summaryrefslogtreecommitdiff
path: root/apt/progress.py
blob: 51eb2426821055a999f3a856114952b74ddb146d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
# Progress.py - progress reporting classes
#
#  Copyright (c) 2005 Canonical
#
#  Author: Michael Vogt <michael.vogt@ubuntu.com>
#
#  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., 59 Temple Place, Suite 330, Boston, MA 02111-1307
#  USA
"""progress reporting classes.

This module provides classes for progress reporting. They can be used with
e.g., for reporting progress on the cache opening process, the cache update
progress, or the package install progress.
"""

import errno
import fcntl
import os
import re
import select
import sys

import apt_pkg


__all__ = ('CdromProgress', 'DpkgInstallProgress', 'DumbInstallProgress',
          'FetchProgress', 'InstallProgress', 'OpProgress', 'OpTextProgress',
          'TextFetchProgress')


class OpProgress(object):
    """Abstract class to implement reporting on cache opening.

    Subclass this class to implement simple Operation progress reporting.
    """

    def __init__(self):
        self.op = None
        self.subOp = None

    def update(self, percent):
        """Called periodically to update the user interface."""

    def done(self):
        """Called once an operation has been completed."""


class OpTextProgress(OpProgress):
    """A simple text based cache open reporting class."""

    def __init__(self):
        OpProgress.__init__(self)

    def update(self, percent):
        """Called periodically to update the user interface."""
        sys.stdout.write("\r%s: %.2i  " % (self.subOp, percent))
        sys.stdout.flush()

    def done(self):
        """Called once an operation has been completed."""
        sys.stdout.write("\r%s: Done\n" % self.op)


class FetchProgress(object):
    """Report the download/fetching progress.

    Subclass this class to implement fetch progress reporting
    """

    # download status constants
    dlDone = 0
    dlQueued = 1
    dlFailed = 2
    dlHit = 3
    dlIgnored = 4
    dlStatusStr = {dlDone: "Done",
                   dlQueued: "Queued",
                   dlFailed: "Failed",
                   dlHit: "Hit",
                   dlIgnored: "Ignored"}

    def __init__(self):
        self.eta = 0.0
        self.percent = 0.0
        # Make checking easier
        self.currentBytes = 0
        self.currentItems = 0
        self.totalBytes = 0
        self.totalItems = 0
        self.currentCPS = 0

    def start(self):
        """Called when the fetching starts."""

    def stop(self):
        """Called when all files have been fetched."""

    def updateStatus(self, uri, descr, shortDescr, status):
        """Called when the status of an item changes.

        This happens eg. when the downloads fails or is completed.
        """

    def pulse(self):
        """Called periodically to update the user interface.

        Return True to continue or False to cancel.
        """
        self.percent = (((self.currentBytes + self.currentItems) * 100.0) /
                        float(self.totalBytes + self.totalItems))
        if self.currentCPS > 0:
            self.eta = ((self.totalBytes - self.currentBytes) /
                        float(self.currentCPS))
        return True

    def mediaChange(self, medium, drive):
        """react to media change events."""


class TextFetchProgress(FetchProgress):
    """ Ready to use progress object for terminal windows """

    def __init__(self):
        FetchProgress.__init__(self)
        self.items = {}

    def updateStatus(self, uri, descr, shortDescr, status):
        """Called when the status of an item changes.

        This happens eg. when the downloads fails or is completed.
        """
        if status != self.dlQueued:
            print "\r%s %s" % (self.dlStatusStr[status], descr)
        self.items[uri] = status

    def pulse(self):
        """Called periodically to update the user interface.

        Return True to continue or False to cancel.
        """
        FetchProgress.pulse(self)
        if self.currentCPS > 0:
            s = "[%2.f%%] %sB/s %s" % (self.percent,
                                       apt_pkg.SizeToStr(int(self.currentCPS)),
                                       apt_pkg.TimeToStr(int(self.eta)))
        else:
            s = "%2.f%% [Working]" % (self.percent)
        print "\r%s" % (s),
        sys.stdout.flush()
        return True

    def stop(self):
        """Called when all files have been fetched."""
        print "\rDone downloading            "

    def mediaChange(self, medium, drive):
        """react to media change events."""
        print ("Media change: please insert the disc labeled "
               "'%s' in the drive '%s' and press enter") % (medium, drive)

        return raw_input() not in ('c', 'C')


class DumbInstallProgress(object):
    """Report the install progress.

    Subclass this class to implement install progress reporting.
    """

    def startUpdate(self):
        """Start update."""

    def run(self, pm):
        """Start installation."""
        return pm.DoInstall()

    def finishUpdate(self):
        """Called when update has finished."""

    def updateInterface(self):
        """Called periodically to update the user interface"""


class InstallProgress(DumbInstallProgress):
    """An InstallProgress that is pretty useful.

    It supports the attributes 'percent' 'status' and callbacks for the dpkg
    errors and conffiles and status changes.
    """

    def __init__(self):
        DumbInstallProgress.__init__(self)
        self.selectTimeout = 0.1
        (read, write) = os.pipe()
        self.writefd = write
        self.statusfd = os.fdopen(read, "r")
        fcntl.fcntl(self.statusfd.fileno(), fcntl.F_SETFL, os.O_NONBLOCK)
        self.read = ""
        self.percent = 0.0
        self.status = ""

    def error(self, pkg, errormsg):
        """Called when a error is detected during the install."""

    def conffile(self, current, new):
        """Called when a conffile question from dpkg is detected."""

    def statusChange(self, pkg, percent, status):
        """Called when the status changed."""

    def updateInterface(self):
        """Called periodically to update the interface."""
        if self.statusfd is None:
            return
        try:
            while not self.read.endswith("\n"):
                self.read += os.read(self.statusfd.fileno(), 1)
        except OSError, (errno_, errstr):
            # resource temporarly unavailable is ignored
            if errno_ != errno.EAGAIN and errno_ != errno.EWOULDBLOCK:
                print errstr
        if not self.read.endswith("\n"):
            return

        s = self.read
        #print s
        try:
            (status, pkg, percent, status_str) = s.split(":", 3)
        except ValueError:
            # silently ignore lines that can't be parsed
            self.read = ""
            return
        #print "percent: %s %s" % (pkg, float(percent)/100.0)
        if status == "pmerror":
            self.error(pkg, status_str)
        elif status == "pmconffile":
            # we get a string like this:
            # 'current-conffile' 'new-conffile' useredited distedited
            match = re.match("\s*\'(.*)\'\s*\'(.*)\'.*", status_str)
            if match:
                self.conffile(match.group(1), match.group(2))
        elif status == "pmstatus":
            if float(percent) != self.percent or status_str != self.status:
                self.statusChange(pkg, float(percent),
                                  status_str.strip())
                self.percent = float(percent)
                self.status = status_str.strip()
        self.read = ""

    def fork(self):
        """Fork."""
        return os.fork()

    def waitChild(self):
        """Wait for child progress to exit."""
        while True:
            select.select([self.statusfd], [], [], self.selectTimeout)
            self.updateInterface()
            (pid, res) = os.waitpid(self.child_pid, os.WNOHANG)
            if pid == self.child_pid:
                break
        return res

    def run(self, pm):
        """Start installing."""
        pid = self.fork()
        if pid == 0:
            # child
            res = pm.DoInstall(self.writefd)
            os._exit(res)
        self.child_pid = pid
        res = self.waitChild()
        return os.WEXITSTATUS(res)


class CdromProgress(object):
    """Report the cdrom add progress.

    Subclass this class to implement cdrom add progress reporting.
    """

    def __init__(self):
        pass

    def update(self, text, step):
        """Called periodically to update the user interface."""

    def askCdromName(self):
        """Called to ask for the name of the cdrom."""

    def changeCdrom(self):
        """Called to ask for the cdrom to be changed."""


class DpkgInstallProgress(InstallProgress):
    """Progress handler for a local Debian package installation."""

    def run(self, debfile):
        """Start installing the given Debian package."""
        self.debfile = debfile
        self.debname = os.path.basename(debfile).split("_")[0]
        pid = self.fork()
        if pid == 0:
            # child
            res = os.system("/usr/bin/dpkg --status-fd %s -i %s" % \
                            (self.writefd, self.debfile))
            os._exit(os.WEXITSTATUS(res))
        self.child_pid = pid
        res = self.waitChild()
        return res

    def updateInterface(self):
        """Process status messages from dpkg."""
        if self.statusfd is None:
            return
        while True:
            try:
                self.read += os.read(self.statusfd.fileno(), 1)
            except OSError, (errno_, errstr):
                # resource temporarly unavailable is ignored
                if errno_ != 11:
                    print errstr
                break
            if not self.read.endswith("\n"):
                continue

            statusl = self.read.split(":")
            if len(statusl) < 3:
                print "got garbage from dpkg: '%s'" % self.read
                self.read = ""
                break
            status = statusl[2].strip()
            #print status
            if status == "error":
                self.error(self.debname, status)
            elif status == "conffile-prompt":
                # we get a string like this:
                # 'current-conffile' 'new-conffile' useredited distedited
                match = re.match("\s*\'(.*)\'\s*\'(.*)\'.*", statusl[3])
                if match:
                    self.conffile(match.group(1), match.group(2))
            else:
                self.status = status
            self.read = ""