~ubuntu-core-dev/update-manager/main

2511.1.15 by Michael Terry
auto-pep8'd more warnings
1
# utils.py
2511.1.10 by Michael Terry
pep8-ify Core/
2
# -*- Mode: Python; indent-tabs-mode: nil; tab-width: 4; coding: utf-8 -*-
2511.1.15 by Michael Terry
auto-pep8'd more warnings
3
#
1170 by Michael Vogt
* UpdateManager/Common/MyCache.py,
4
#  Copyright (c) 2004-2008 Canonical
2511.1.15 by Michael Terry
auto-pep8'd more warnings
5
#
1170 by Michael Vogt
* UpdateManager/Common/MyCache.py,
6
#  Author: Michael Vogt <mvo@debian.org>
2511.1.15 by Michael Terry
auto-pep8'd more warnings
7
#
8
#  This program is free software; you can redistribute it and/or
9
#  modify it under the terms of the GNU General Public License as
1170 by Michael Vogt
* UpdateManager/Common/MyCache.py,
10
#  published by the Free Software Foundation; either version 2 of the
11
#  License, or (at your option) any later version.
2511.1.15 by Michael Terry
auto-pep8'd more warnings
12
#
1170 by Michael Vogt
* UpdateManager/Common/MyCache.py,
13
#  This program is distributed in the hope that it will be useful,
14
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
15
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
#  GNU General Public License for more details.
2511.1.15 by Michael Terry
auto-pep8'd more warnings
17
#
1170 by Michael Vogt
* UpdateManager/Common/MyCache.py,
18
#  You should have received a copy of the GNU General Public License
19
#  along with this program; if not, write to the Free Software
20
#  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
21
#  USA
22
2394 by Colin Watson
Use Python 3-style print functions.
23
from __future__ import print_function
24
337.4.41 by Sebastian Heinlein
* Make some strings translatable - seems that gettext doesn't like being
25
from gettext import gettext as _
2318.1.1 by Robert Roth
Use ngettext to humanize size (LP: #351665)
26
from gettext import ngettext
2164 by Michael Vogt
make UpdateManager/, tests/ pyflakes clean
27
from stat import (S_IMODE, ST_MODE, S_IXUSR)
2318.1.1 by Robert Roth
Use ngettext to humanize size (LP: #351665)
28
from math import ceil
1595 by Michael Vogt
* UpdateManager/Core/utils.py:
29
30
import apt_pkg
1848 by Michael Vogt
* UpdateManager/Core/MetaRelease.py,
31
apt_pkg.init_config()
32
337.4.42 by Sebastian Heinlein
* Fixed a missing import
33
import locale
1751 by Michael Vogt
* check-new-release-gtk, UpdateManager/Core/MetaRelease.py:
34
import logging
1595 by Michael Vogt
* UpdateManager/Core/utils.py:
35
import re
668 by Michael Vogt
* UpdateManager/DistUpgradeFetcherCore.py:
36
import os
2141 by Michael Vogt
* DistUpgrade/DistUpgradeCache.py:
37
import glob
1595 by Michael Vogt
* UpdateManager/Core/utils.py:
38
import subprocess
39
import sys
1746 by Michael Vogt
add ExecutionTime helper, easy the UI hang problems a little bit
40
import time
2403 by Colin Watson
Use Python 3 renamings of urllib, urllib2, and urlparse if available.
41
try:
42
    from urllib.request import (
43
        ProxyHandler,
44
        Request,
45
        build_opener,
46
        install_opener,
47
        urlopen,
2511.1.10 by Michael Terry
pep8-ify Core/
48
    )
2403 by Colin Watson
Use Python 3 renamings of urllib, urllib2, and urlparse if available.
49
    from urllib.parse import urlsplit
50
except ImportError:
51
    from urllib2 import (
52
        ProxyHandler,
53
        Request,
54
        build_opener,
55
        install_opener,
56
        urlopen,
2511.1.10 by Michael Terry
pep8-ify Core/
57
    )
2403 by Colin Watson
Use Python 3 renamings of urllib, urllib2, and urlparse if available.
58
    from urlparse import urlsplit
1834 by Michael Vogt
fix url_downloadable and add tests, based on the patch from
59
2235 by Michael Vogt
* DistUpgrade/DistUpgradeController.py, UpdateManager/Core/utils.py:
60
from copy import copy
61
1372.1.6 by Michael Vogt
* DistUpgrade/DistUpgradeController.py:
62
1746 by Michael Vogt
add ExecutionTime helper, easy the UI hang problems a little bit
63
class ExecutionTime(object):
64
    """
65
    Helper that can be used in with statements to have a simple
2312 by Michael Vogt
* UpdateManager/Core/utils.py
66
    measure of the timing of a particular block of code, e.g.
67
    with ExecutionTime("db flush"):
1746 by Michael Vogt
add ExecutionTime helper, easy the UI hang problems a little bit
68
        db.flush()
69
    """
70
    def __init__(self, info=""):
71
        self.info = info
2511.1.10 by Michael Terry
pep8-ify Core/
72
1746 by Michael Vogt
add ExecutionTime helper, easy the UI hang problems a little bit
73
    def __enter__(self):
74
        self.now = time.time()
2511.1.10 by Michael Terry
pep8-ify Core/
75
1746 by Michael Vogt
add ExecutionTime helper, easy the UI hang problems a little bit
76
    def __exit__(self, type, value, stack):
2394 by Colin Watson
Use Python 3-style print functions.
77
        print("%s: %s" % (self.info, time.time() - self.now))
1746 by Michael Vogt
add ExecutionTime helper, easy the UI hang problems a little bit
78
2511.1.10 by Michael Terry
pep8-ify Core/
79
2235 by Michael Vogt
* DistUpgrade/DistUpgradeController.py, UpdateManager/Core/utils.py:
80
def get_string_with_no_auth_from_source_entry(entry):
81
    tmp = copy(entry)
82
    url_parts = urlsplit(tmp.uri)
83
    if url_parts.username:
84
        tmp.uri = tmp.uri.replace(url_parts.username, "hidden-u")
85
    if url_parts.password:
86
        tmp.uri = tmp.uri.replace(url_parts.password, "hidden-p")
87
    return str(tmp)
88
2511.1.10 by Michael Terry
pep8-ify Core/
89
2141 by Michael Vogt
* DistUpgrade/DistUpgradeCache.py:
90
def estimate_kernel_size_in_boot():
91
    """ estimate the amount of space that the current kernel takes in /boot """
92
    size = 0
93
    kver = os.uname()[2]
94
    for f in glob.glob("/boot/*%s*" % kver):
95
        size += os.path.getsize(f)
96
    return size
97
2511.1.10 by Michael Terry
pep8-ify Core/
98
2087 by Michael Vogt
merged lp:~evfool/update-manager/fix727069 (LP: #727069),
99
def is_unity_running():
100
    """ return True if Unity is currently running """
101
    unity_running = False
102
    try:
2088 by Michael Vogt
UpdateManager/Core/utils.py: use logging instead of LOG, import dbus
103
        import dbus
2087 by Michael Vogt
merged lp:~evfool/update-manager/fix727069 (LP: #727069),
104
        bus = dbus.SessionBus()
105
        unity_running = bus.name_has_owner("com.canonical.Unity")
106
    except:
2088 by Michael Vogt
UpdateManager/Core/utils.py: use logging instead of LOG, import dbus
107
        logging.exception("could not check for Unity dbus service")
2087 by Michael Vogt
merged lp:~evfool/update-manager/fix727069 (LP: #727069),
108
    return unity_running
109
2511.1.10 by Michael Terry
pep8-ify Core/
110
2095 by Michael Vogt
UpdateManager/Core/utils.py: add is_child_of_process_name() and add test
111
def is_child_of_process_name(processname, pid=None):
112
    if not pid:
113
        pid = os.getpid()
114
    while pid > 0:
115
        stat_file = "/proc/%s/stat" % pid
2419 by Colin Watson
Fix several ResourceWarnings with Python 3.
116
        with open(stat_file) as stat_f:
117
            stat = stat_f.read()
2095 by Michael Vogt
UpdateManager/Core/utils.py: add is_child_of_process_name() and add test
118
        # extract command (inside ())
119
        command = stat.partition("(")[2].partition(")")[0]
120
        if command == processname:
121
            return True
122
        # get parent (second to the right of command) and check that next
123
        pid = int(stat.partition(")")[2].split()[1])
124
    return False
125
2511.1.10 by Michael Terry
pep8-ify Core/
126
1973 by Michael Vogt
* DistUpgrade/DistUpgradeCache.py, UpdateManager/Core/utils.py:
127
def inside_chroot():
2511.1.15 by Michael Terry
auto-pep8'd more warnings
128
    """ returns True if we are inside a chroot
1973 by Michael Vogt
* DistUpgrade/DistUpgradeCache.py, UpdateManager/Core/utils.py:
129
    """
130
    # if there is no proc or no pid 1 we are very likely inside a chroot
131
    if not os.path.exists("/proc") or not os.path.exists("/proc/1"):
132
        return True
133
    # if the inode is differnt for pid 1 "/" and our "/"
134
    return os.stat("/") != os.stat("/proc/1/root")
135
2511.1.10 by Michael Terry
pep8-ify Core/
136
1653 by Michael Vogt
* update-manager-support-status:
137
def wrap(t, width=70, subsequent_indent=""):
1973 by Michael Vogt
* DistUpgrade/DistUpgradeCache.py, UpdateManager/Core/utils.py:
138
    """ helpers inspired after textwrap - unfortunately
139
        we can not use textwrap directly because it break
140
        packagenames with "-" in them into new lines
141
    """
1653 by Michael Vogt
* update-manager-support-status:
142
    out = ""
143
    for s in t.split():
2511.1.10 by Michael Terry
pep8-ify Core/
144
        if (len(out) - out.rfind("\n")) + len(s) > width:
1653 by Michael Vogt
* update-manager-support-status:
145
            out += "\n" + subsequent_indent
146
        out += s + " "
147
    return out
2511.1.10 by Michael Terry
pep8-ify Core/
148
149
1653 by Michael Vogt
* update-manager-support-status:
150
def twrap(s, **kwargs):
151
    msg = ""
152
    paras = s.split("\n")
153
    for par in paras:
154
        s = wrap(par, **kwargs)
2511.1.10 by Michael Terry
pep8-ify Core/
155
        msg += s + "\n"
1653 by Michael Vogt
* update-manager-support-status:
156
    return msg
157
2511.1.10 by Michael Terry
pep8-ify Core/
158
1406 by Michael Vogt
* DistUpgrade/DistUpgradeQuirks.py:
159
def lsmod():
2511.1.10 by Michael Terry
pep8-ify Core/
160
    " return list of loaded modules (or [] if lsmod is not found) "
161
    modules = []
162
    # FIXME raise?
163
    if not os.path.exists("/sbin/lsmod"):
164
        return []
165
    p = subprocess.Popen(["/sbin/lsmod"], stdout=subprocess.PIPE,
166
                         universal_newlines=True)
167
    lines = p.communicate()[0].split("\n")
168
    # remove heading line: "Modules Size Used by"
169
    del lines[0]
170
    # add lines to list, skip empty lines
171
    for line in lines:
172
        if line:
173
            modules.append(line.split()[0])
174
    return modules
175
1406 by Michael Vogt
* DistUpgrade/DistUpgradeQuirks.py:
176
1372.1.6 by Michael Vogt
* DistUpgrade/DistUpgradeController.py:
177
def check_and_fix_xbit(path):
2511.1.10 by Michael Terry
pep8-ify Core/
178
    " check if a given binary has the executable bit and if not, add it"
179
    if not os.path.exists(path):
180
        return
181
    mode = S_IMODE(os.stat(path)[ST_MODE])
182
    if not ((mode & S_IXUSR) == S_IXUSR):
183
        os.chmod(path, mode | S_IXUSR)
184
1009 by Michael Vogt
* do-release-upgrade:
185
1193 by Michael Vogt
* DistUpgrade/DistUpgradeController.py:
186
def country_mirror():
2511.1.10 by Michael Terry
pep8-ify Core/
187
    " helper to get the country mirror from the current locale "
188
    # special cases go here
189
    lang_mirror = {'c': ''}
190
    # no lang, no mirror
191
    if not 'LANG' in os.environ:
192
        return ''
193
    lang = os.environ['LANG'].lower()
194
    # check if it is a special case
195
    if lang[:5] in lang_mirror:
196
        return lang_mirror[lang[:5]]
197
    # now check for the most comon form (en_US.UTF-8)
198
    if "_" in lang:
199
        country = lang.split(".")[0].split("_")[1]
200
        if "@" in country:
201
            country = country.split("@")[0]
202
        return country + "."
203
    else:
204
        return lang[:2] + "."
1193 by Michael Vogt
* DistUpgrade/DistUpgradeController.py:
205
    return ''
2511.1.10 by Michael Terry
pep8-ify Core/
206
1193 by Michael Vogt
* DistUpgrade/DistUpgradeController.py:
207
1243 by Michael Vogt
improve logic that detects what mirror is in use by
208
def get_dist():
2511.1.10 by Michael Terry
pep8-ify Core/
209
    " return the codename of the current runing distro "
210
    # support debug overwrite
211
    dist = os.environ.get("META_RELEASE_FAKE_CODENAME")
212
    if dist:
213
        logging.warn("using fake release name '%s' (because of "
214
                     "META_RELEASE_FAKE_CODENAME environment) " % dist)
215
        return dist
216
    # then check the real one
217
    from subprocess import Popen, PIPE
218
    p = Popen(["lsb_release", "-c", "-s"], stdout=PIPE,
219
              universal_newlines=True)
220
    res = p.wait()
221
    if res != 0:
222
        sys.stderr.write("lsb_release returned exitcode: %i\n" % res)
223
        return "unknown distribution"
224
    dist = p.stdout.readline().strip()
225
    p.stdout.close()
226
    return dist
227
1243 by Michael Vogt
improve logic that detects what mirror is in use by
228
2428.4.5 by Michael Terry
move meta release checking into main UpdateManager class; use dialog panes for those interactions rather than popup dialogs
229
def get_dist_version():
2511.1.10 by Michael Terry
pep8-ify Core/
230
    " return the version of the current running distro "
231
    # support debug overwrite
232
    desc = os.environ.get("META_RELEASE_FAKE_VERSION")
233
    if desc:
234
        logging.warn("using fake release version '%s' (because of "
235
                     "META_RELEASE_FAKE_VERSION environment) " % desc)
236
        return desc
237
    # then check the real one
238
    from subprocess import Popen, PIPE
239
    p = Popen(["lsb_release", "-r", "-s"], stdout=PIPE,
240
              universal_newlines=True)
241
    res = p.wait()
242
    if res != 0:
243
        sys.stderr.write("lsb_release returned exitcode: %i\n" % res)
244
        return "unknown distribution"
245
    desc = p.stdout.readline().strip()
246
    p.stdout.close()
247
    return desc
248
2425.1.1 by Michael Terry
update several strings to match the software updater spec; most notably, rename from Update Manager to Software Updater
249
2403 by Colin Watson
Use Python 3 renamings of urllib, urllib2, and urlparse if available.
250
class HeadRequest(Request):
1834 by Michael Vogt
fix url_downloadable and add tests, based on the patch from
251
    def get_method(self):
252
        return "HEAD"
253
2511.1.10 by Michael Terry
pep8-ify Core/
254
1241 by Michael Vogt
when fetching from mirrors, add fallback if the mirror
255
def url_downloadable(uri, debug_func=None):
2511.1.10 by Michael Terry
pep8-ify Core/
256
    """
257
    helper that checks if the given uri exists and is downloadable
2511.1.15 by Michael Terry
auto-pep8'd more warnings
258
    (supports optional debug_func function handler to support
2511.1.10 by Michael Terry
pep8-ify Core/
259
     e.g. logging)
260
261
    Supports http (via HEAD) and ftp (via size request)
262
    """
263
    if not debug_func:
264
        lambda x: True
265
    debug_func("url_downloadable: %s" % uri)
266
    (scheme, netloc, path, querry, fragment) = urlsplit(uri)
267
    debug_func("s='%s' n='%s' p='%s' q='%s' f='%s'" % (scheme, netloc, path,
268
                                                       querry, fragment))
269
    if scheme == "http":
270
        try:
271
            http_file = urlopen(HeadRequest(uri))
272
            http_file.close()
273
            if http_file.code == 200:
274
                return True
275
            return False
276
        except Exception as e:
277
            debug_func("error from httplib: '%s'" % e)
278
            return False
279
    elif scheme == "ftp":
280
        import ftplib
281
        try:
282
            f = ftplib.FTP(netloc)
283
            f.login()
284
            f.cwd(os.path.dirname(path))
285
            size = f.size(os.path.basename(path))
286
            f.quit()
287
            if debug_func:
288
                debug_func("ftplib.size() returned: %s" % size)
289
            if size != 0:
290
                return True
291
        except Exception as e:
292
            if debug_func:
293
                debug_func("error from ftplib: '%s'" % e)
294
            return False
295
    return False
296
1193 by Michael Vogt
* DistUpgrade/DistUpgradeController.py:
297
2146.2.12 by Michael Vogt
get rid of gconfclient references
298
def init_proxy(gsettings=None):
2511.1.15 by Michael Terry
auto-pep8'd more warnings
299
    """ init proxy settings
2511.1.10 by Michael Terry
pep8-ify Core/
300
301
    * first check for http_proxy environment (always wins),
2511.1.15 by Michael Terry
auto-pep8'd more warnings
302
    * then check the apt.conf http proxy,
2511.1.10 by Michael Terry
pep8-ify Core/
303
    * then look into synaptics conffile
304
    * then into gconf  (if gconfclient was supplied)
305
    """
306
    SYNAPTIC_CONF_FILE = "/root/.synaptic/synaptic.conf"
307
    proxy = None
308
    # generic apt config wins
309
    if apt_pkg.config.find("Acquire::http::Proxy") != '':
310
        proxy = apt_pkg.config.find("Acquire::http::Proxy")
311
    # then synaptic
312
    elif os.path.exists(SYNAPTIC_CONF_FILE):
313
        cnf = apt_pkg.Configuration()
314
        apt_pkg.read_config_file(cnf, SYNAPTIC_CONF_FILE)
315
        use_proxy = cnf.find_b("Synaptic::useProxy", False)
316
        if use_proxy:
317
            proxy_host = cnf.find("Synaptic::httpProxy")
318
            proxy_port = str(cnf.find_i("Synaptic::httpProxyPort"))
319
            if proxy_host and proxy_port:
320
                proxy = "http://%s:%s/" % (proxy_host, proxy_port)
321
    # if we have a proxy, set it
322
    if proxy:
323
        # basic verification
324
        if not re.match("http://\w+", proxy):
325
            print("proxy '%s' looks invalid" % proxy, file=sys.stderr)
326
            return
327
        proxy_support = ProxyHandler({"http": proxy})
328
        opener = build_opener(proxy_support)
329
        install_opener(opener)
330
        os.putenv("http_proxy", proxy)
331
    return proxy
332
668 by Michael Vogt
* UpdateManager/DistUpgradeFetcherCore.py:
333
1455 by Michael Vogt
* UpdateManager/UpdateManager.py:
334
def on_battery():
2511.1.10 by Michael Terry
pep8-ify Core/
335
    """
336
    Check via dbus if the system is running on battery.
337
    This function is using UPower per default, if UPower is not
2511.1.15 by Michael Terry
auto-pep8'd more warnings
338
    available it falls-back to DeviceKit.Power.
2511.1.10 by Michael Terry
pep8-ify Core/
339
    """
1727 by Michael Vogt
* UpdateManager/Core/utils.py:
340
    try:
2511.1.10 by Michael Terry
pep8-ify Core/
341
        import dbus
342
        bus = dbus.Bus(dbus.Bus.TYPE_SYSTEM)
343
        try:
2511.1.15 by Michael Terry
auto-pep8'd more warnings
344
            devobj = bus.get_object('org.freedesktop.UPower',
2511.1.10 by Michael Terry
pep8-ify Core/
345
                                    '/org/freedesktop/UPower')
346
            dev = dbus.Interface(devobj, 'org.freedesktop.DBus.Properties')
347
            return dev.Get('org.freedesktop.UPower', 'OnBattery')
348
        except dbus.exceptions.DBusException as e:
349
            error_unknown = 'org.freedesktop.DBus.Error.ServiceUnknown'
350
            if e._dbus_error_name != error_unknown:
351
                raise
2511.1.15 by Michael Terry
auto-pep8'd more warnings
352
            devobj = bus.get_object('org.freedesktop.DeviceKit.Power',
2511.1.10 by Michael Terry
pep8-ify Core/
353
                                    '/org/freedesktop/DeviceKit/Power')
354
            dev = dbus.Interface(devobj, "org.freedesktop.DBus.Properties")
355
            return dev.Get("org.freedesktop.DeviceKit.Power", "on_battery")
356
    except Exception as e:
357
        #import sys
358
        #print("on_battery returned error: ", e, file=sys.stderr)
359
        return False
360
1455 by Michael Vogt
* UpdateManager/UpdateManager.py:
361
682 by Michael Vogt
* UpdateManager/UpdateManager.py, UpdateManager/Common/utils.py:
362
def inhibit_sleep():
2511.1.10 by Michael Terry
pep8-ify Core/
363
    """
364
    Send a dbus signal to power-manager to not suspend
365
    the system, using the freedesktop common interface
366
    """
367
    try:
368
        import dbus
369
        bus = dbus.Bus(dbus.Bus.TYPE_SESSION)
2511.1.15 by Michael Terry
auto-pep8'd more warnings
370
        devobj = bus.get_object('org.freedesktop.PowerManagement',
2511.1.10 by Michael Terry
pep8-ify Core/
371
                                '/org/freedesktop/PowerManagement/Inhibit')
372
        dev = dbus.Interface(devobj, "org.freedesktop.PowerManagement.Inhibit")
373
        cookie = dev.Inhibit('UpdateManager', 'Updating system')
374
        return (dev, cookie)
375
    except Exception:
376
        #print("could not send the dbus Inhibit signal: %s" % e)
377
        return (False, False)
378
682 by Michael Vogt
* UpdateManager/UpdateManager.py, UpdateManager/Common/utils.py:
379
380
def allow_sleep(dev, cookie):
2511.1.10 by Michael Terry
pep8-ify Core/
381
    """Send a dbus signal to gnome-power-manager to allow a suspending
382
    the system"""
383
    try:
384
        dev.UnInhibit(cookie)
385
    except Exception as e:
386
        print("could not send the dbus UnInhibit signal: %s" % e)
682 by Michael Vogt
* UpdateManager/UpdateManager.py, UpdateManager/Common/utils.py:
387
388
10 by Michael Vogt
* code cleanup, make it all more structured
389
def str_to_bool(str):
2511.1.10 by Michael Terry
pep8-ify Core/
390
    if str == "0" or str.upper() == "FALSE":
391
        return False
392
    return True
393
10 by Michael Vogt
* code cleanup, make it all more structured
394
1768 by Michael Vogt
when requesting the release announcement, append ?lang=current_lang
395
def get_lang():
396
    import logging
397
    try:
398
        (locale_s, encoding) = locale.getdefaultlocale()
399
        return locale_s
2511.1.15 by Michael Terry
auto-pep8'd more warnings
400
    except Exception:
1768 by Michael Vogt
when requesting the release announcement, append ?lang=current_lang
401
        logging.exception("gedefaultlocale() failed")
402
        return None
403
2511.1.10 by Michael Terry
pep8-ify Core/
404
2170 by Michael Vogt
when downloading the html release notes, ensure to send a
405
def get_ubuntu_flavor():
406
    """ try to guess the flavor based on the running desktop """
2511.1.15 by Michael Terry
auto-pep8'd more warnings
407
    # this will (of course) not work in a server environment,
2170 by Michael Vogt
when downloading the html release notes, ensure to send a
408
    # but the main use case for this is to show the right
409
    # release notes
2428.4.10 by Michael Terry
don't hardcore Ubuntu, use a flavor name if appropriate
410
    # TODO: actually examine which meta packages are installed, like
411
    # DistUpgrade/DistUpgradeCache.py does and use that to choose a flavor.
2170 by Michael Vogt
when downloading the html release notes, ensure to send a
412
    denv = os.environ.get("DESKTOP_SESSION", "")
413
    if "gnome" in denv:
414
        return "ubuntu"
415
    elif "kde" in denv:
416
        return "kubuntu"
417
    elif "xfce" in denv or "xubuntu" in denv:
418
        return "xubuntu"
2347.2.1 by Julien Lavergne
* DistUpgrade/DistUpgrade.cfg, DistUpgrade/removal_blacklist.cfg,
419
    elif "LXDE" in denv or "Lubuntu" in denv:
420
        return "lubuntu"
2170 by Michael Vogt
when downloading the html release notes, ensure to send a
421
    # default to ubuntu if nothing more specific is found
422
    return "ubuntu"
423
2511.1.10 by Michael Terry
pep8-ify Core/
424
2428.4.10 by Michael Terry
don't hardcore Ubuntu, use a flavor name if appropriate
425
def get_ubuntu_flavor_name():
426
    flavor = get_ubuntu_flavor()
427
    if flavor == "kubuntu":
428
        return "Kubuntu"
429
    elif flavor == "xubuntu":
430
        return "Xubuntu"
431
    elif flavor == "lubuntu":
432
        return "Lubuntu"
433
    else:
434
        return "Ubuntu"
435
2511.1.10 by Michael Terry
pep8-ify Core/
436
2569 by Michael Terry
remove last little unnecessary call to create a MessageDialog
437
# Unused by update-manager, but still used by ubuntu-release-upgrader
222 by Michael Vogt
* added better error reporting for the DistUpgradeFetcher
438
def error(parent, summary, message):
2511.1.10 by Michael Terry
pep8-ify Core/
439
    from gi.repository import Gtk, Gdk
440
    d = Gtk.MessageDialog(parent=parent,
441
                          flags=Gtk.DialogFlags.MODAL,
442
                          type=Gtk.MessageType.ERROR,
443
                          buttons=Gtk.ButtonsType.CLOSE)
444
    d.set_markup("<big><b>%s</b></big>\n\n%s" % (summary, message))
445
    d.realize()
2549 by Michael Vogt
fix crash in UpdateManager.Core.utils.error(), thanks to
446
    d.get_window().set_functions(Gdk.WMFunction.MOVE)
2511.1.10 by Michael Terry
pep8-ify Core/
447
    d.set_title("")
448
    d.run()
449
    d.destroy()
450
    return False
451
337.4.40 by Sebastian Heinlein
* move the humanize_size method to common.utils
452
337.4.41 by Sebastian Heinlein
* Make some strings translatable - seems that gettext doesn't like being
453
def humanize_size(bytes):
337.4.40 by Sebastian Heinlein
* move the humanize_size method to common.utils
454
    """
455
    Convert a given size in bytes to a nicer better readable unit
456
    """
2318.1.1 by Robert Roth
Use ngettext to humanize size (LP: #351665)
457
458
    if bytes < 1000 * 1000:
2511.1.10 by Michael Terry
pep8-ify Core/
459
        # to have 0 for 0 bytes, 1 for 0-1000 bytes and for 1 and above
460
        # round up
461
        size_in_kb = int(ceil(bytes / float(1000)))
2182.1.5 by Robert Roth
Updated translator comment to follow the Ubuntu Units policy
462
        # TRANSLATORS: download size of small updates, e.g. "250 kB"
2511.1.10 by Michael Terry
pep8-ify Core/
463
        return ngettext("%(size).0f kB", "%(size).0f kB", size_in_kb) % {
464
            "size": size_in_kb}
337.4.40 by Sebastian Heinlein
* move the humanize_size method to common.utils
465
    else:
466
        # TRANSLATORS: download size of updates, e.g. "2.3 MB"
2182.1.4 by Robert Roth
Display sizes according to the Ubuntu Units Policy (LP: #410310)
467
        return locale.format_string(_("%.1f MB"), bytes / 1000.0 / 1000.0)
1243 by Michael Vogt
improve logic that detects what mirror is in use by
468
2511.1.10 by Michael Terry
pep8-ify Core/
469
1959 by Michael Vogt
* UpdateManager/Core/utils.py:
470
def get_arch():
2418 by Colin Watson
Use python-apt 0.8 API spellings of apt_pkg.config methods.
471
    return apt_pkg.config.find("APT::Architecture")
1959 by Michael Vogt
* UpdateManager/Core/utils.py:
472
1977 by Michael Vogt
* DistUpgrade/DistUpgradeController.py:
473
2262 by Michael Vogt
* AutoUpgradeTester/UpgradeTestBackendQemu.py:
474
def is_port_already_listening(port):
475
    """ check if the current system is listening on the given tcp port """
476
    # index in the line
477
    INDEX_LOCAL_ADDR = 1
2303 by Michael Vogt
* pyflake fixes, remove some dead code
478
    #INDEX_REMOTE_ADDR = 2
2262 by Michael Vogt
* AutoUpgradeTester/UpgradeTestBackendQemu.py:
479
    INDEX_STATE = 3
480
    # state (st) that we care about
481
    STATE_LISTENING = '0A'
482
    # read the data
2419 by Colin Watson
Fix several ResourceWarnings with Python 3.
483
    with open("/proc/net/tcp") as net_tcp:
484
        for line in net_tcp:
485
            line = line.strip()
486
            if not line:
487
                continue
488
            # split, values are:
2511.1.10 by Michael Terry
pep8-ify Core/
489
            #   sl  local_address rem_address   st tx_queue rx_queue tr
490
            #   tm->when retrnsmt   uid  timeout inode
2419 by Colin Watson
Fix several ResourceWarnings with Python 3.
491
            values = line.split()
492
            state = values[INDEX_STATE]
493
            if state != STATE_LISTENING:
494
                continue
495
            local_port_str = values[INDEX_LOCAL_ADDR].split(":")[1]
496
            local_port = int(local_port_str, 16)
497
            if local_port == port:
498
                return True
2262 by Michael Vogt
* AutoUpgradeTester/UpgradeTestBackendQemu.py:
499
    return False
500
501
1977 by Michael Vogt
* DistUpgrade/DistUpgradeController.py:
502
def iptables_active():
503
    """ Return True if iptables is active """
504
    # FIXME: is there a better way?
2511.1.10 by Michael Terry
pep8-ify Core/
505
    iptables_empty = """Chain INPUT (policy ACCEPT)
2511.1.15 by Michael Terry
auto-pep8'd more warnings
506
target     prot opt source               destination
1977 by Michael Vogt
* DistUpgrade/DistUpgradeController.py:
507
508
Chain FORWARD (policy ACCEPT)
2511.1.15 by Michael Terry
auto-pep8'd more warnings
509
target     prot opt source               destination
1977 by Michael Vogt
* DistUpgrade/DistUpgradeController.py:
510
511
Chain OUTPUT (policy ACCEPT)
2511.1.15 by Michael Terry
auto-pep8'd more warnings
512
target     prot opt source               destination
1977 by Michael Vogt
* DistUpgrade/DistUpgradeController.py:
513
"""
514
    if os.getuid() != 0:
2401 by Colin Watson
Use "raise Exception(value)" syntax rather than the old-style "raise
515
        raise OSError("Need root to check the iptables state")
2246.1.5 by Michael Vogt
* UpdateManager/Core/utils.py:
516
    if not os.path.exists("/sbin/iptables"):
517
        return False
2511.1.15 by Michael Terry
auto-pep8'd more warnings
518
    out = subprocess.Popen(["iptables", "-L"],
2433 by Colin Watson
Open subprocesses with universal_newlines=True when expecting to read
519
                           stdout=subprocess.PIPE,
520
                           universal_newlines=True).communicate()[0]
1977 by Michael Vogt
* DistUpgrade/DistUpgradeController.py:
521
    if out == iptables_empty:
522
        return False
523
    return True
524
525
1243 by Michael Vogt
improve logic that detects what mirror is in use by
526
if __name__ == "__main__":
2511.1.10 by Michael Terry
pep8-ify Core/
527
    #print(mirror_from_sources_list())
528
    #print(on_battery())
529
    #print(inside_chroot())
2549 by Michael Vogt
fix crash in UpdateManager.Core.utils.error(), thanks to
530
    #print(iptables_active())
531
    error(None, "bar", "baz")