~straemer/ubuntu/quantal/update-manager/fix-for-1058070

« back to all changes in this revision

Viewing changes to UpdateManager/Core/utils.py

  • Committer: Package Import Robot
  • Author(s): Michael Terry
  • Date: 2012-06-29 10:59:30 UTC
  • mfrom: (389.1.2 precise-security)
  • Revision ID: package-import@ubuntu.com-20120629105930-0oaj9vdvykmvkjum
Tags: 1:0.165
* Implementation of "update on start" feature from spec
  https://wiki.ubuntu.com/SoftwareUpdates
* Use a single main window that changes instead of having modal dialogs
* Implement several special-purpose dialogs like "No updates" or
  "Dist upgrade needed" accordingn to the above spec
* Split out release upgrader code and DistUpgrade module into a separate
  source package
* Drop python-update-manager, as it is unused
* debian/tests:
  - Add dep8 tests

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# utils.py 
2
 
#  
 
1
# utils.py
 
2
# -*- Mode: Python; indent-tabs-mode: nil; tab-width: 4; coding: utf-8 -*-
 
3
#
3
4
#  Copyright (c) 2004-2008 Canonical
4
 
#  
 
5
#
5
6
#  Author: Michael Vogt <mvo@debian.org>
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 
 
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
9
10
#  published by the Free Software Foundation; either version 2 of the
10
11
#  License, or (at your option) any later version.
11
 
 
12
#
12
13
#  This program is distributed in the hope that it will be useful,
13
14
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
14
15
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
16
#  GNU General Public License for more details.
16
 
 
17
#
17
18
#  You should have received a copy of the GNU General Public License
18
19
#  along with this program; if not, write to the Free Software
19
20
#  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
44
45
        build_opener,
45
46
        install_opener,
46
47
        urlopen,
47
 
        )
 
48
    )
48
49
    from urllib.parse import urlsplit
49
50
except ImportError:
50
51
    from urllib2 import (
53
54
        build_opener,
54
55
        install_opener,
55
56
        urlopen,
56
 
        )
 
57
    )
57
58
    from urlparse import urlsplit
58
59
 
59
60
from copy import copy
68
69
    """
69
70
    def __init__(self, info=""):
70
71
        self.info = info
 
72
 
71
73
    def __enter__(self):
72
74
        self.now = time.time()
 
75
 
73
76
    def __exit__(self, type, value, stack):
74
77
        print("%s: %s" % (self.info, time.time() - self.now))
75
78
 
 
79
 
76
80
def get_string_with_no_auth_from_source_entry(entry):
77
81
    tmp = copy(entry)
78
82
    url_parts = urlsplit(tmp.uri)
82
86
        tmp.uri = tmp.uri.replace(url_parts.password, "hidden-p")
83
87
    return str(tmp)
84
88
 
 
89
 
85
90
def estimate_kernel_size_in_boot():
86
91
    """ estimate the amount of space that the current kernel takes in /boot """
87
92
    size = 0
90
95
        size += os.path.getsize(f)
91
96
    return size
92
97
 
 
98
 
93
99
def is_unity_running():
94
100
    """ return True if Unity is currently running """
95
101
    unity_running = False
101
107
        logging.exception("could not check for Unity dbus service")
102
108
    return unity_running
103
109
 
 
110
 
104
111
def is_child_of_process_name(processname, pid=None):
105
112
    if not pid:
106
113
        pid = os.getpid()
116
123
        pid = int(stat.partition(")")[2].split()[1])
117
124
    return False
118
125
 
 
126
 
119
127
def inside_chroot():
120
 
    """ returns True if we are inside a chroot 
 
128
    """ returns True if we are inside a chroot
121
129
    """
122
130
    # if there is no proc or no pid 1 we are very likely inside a chroot
123
131
    if not os.path.exists("/proc") or not os.path.exists("/proc/1"):
125
133
    # if the inode is differnt for pid 1 "/" and our "/"
126
134
    return os.stat("/") != os.stat("/proc/1/root")
127
135
 
 
136
 
128
137
def wrap(t, width=70, subsequent_indent=""):
129
138
    """ helpers inspired after textwrap - unfortunately
130
139
        we can not use textwrap directly because it break
132
141
    """
133
142
    out = ""
134
143
    for s in t.split():
135
 
        if (len(out)-out.rfind("\n")) + len(s) > width:
 
144
        if (len(out) - out.rfind("\n")) + len(s) > width:
136
145
            out += "\n" + subsequent_indent
137
146
        out += s + " "
138
147
    return out
139
 
    
 
148
 
 
149
 
140
150
def twrap(s, **kwargs):
141
151
    msg = ""
142
152
    paras = s.split("\n")
143
153
    for par in paras:
144
154
        s = wrap(par, **kwargs)
145
 
        msg += s+"\n"
 
155
        msg += s + "\n"
146
156
    return msg
147
157
 
 
158
 
148
159
def lsmod():
149
 
  " return list of loaded modules (or [] if lsmod is not found) "
150
 
  modules=[]
151
 
  # FIXME raise?
152
 
  if not os.path.exists("/sbin/lsmod"):
153
 
    return []
154
 
  p=subprocess.Popen(["/sbin/lsmod"], stdout=subprocess.PIPE,
155
 
                     universal_newlines=True)
156
 
  lines=p.communicate()[0].split("\n")
157
 
  # remove heading line: "Modules Size Used by"
158
 
  del lines[0]
159
 
  # add lines to list, skip empty lines
160
 
  for line in lines:
161
 
    if line:
162
 
      modules.append(line.split()[0])
163
 
  return modules
 
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
 
164
176
 
165
177
def check_and_fix_xbit(path):
166
 
  " check if a given binary has the executable bit and if not, add it"
167
 
  if not os.path.exists(path):
168
 
    return
169
 
  mode = S_IMODE(os.stat(path)[ST_MODE])
170
 
  if not ((mode & S_IXUSR) == S_IXUSR):
171
 
    os.chmod(path, mode | S_IXUSR)
 
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
 
172
185
 
173
186
def country_mirror():
174
 
  " helper to get the country mirror from the current locale "
175
 
  # special cases go here
176
 
  lang_mirror = { 'c'     : '',
177
 
                }
178
 
  # no lang, no mirror
179
 
  if not 'LANG' in os.environ:
 
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] + "."
180
205
    return ''
181
 
  lang = os.environ['LANG'].lower()
182
 
  # check if it is a special case
183
 
  if lang[:5] in lang_mirror:
184
 
    return lang_mirror[lang[:5]]
185
 
  # now check for the most comon form (en_US.UTF-8)
186
 
  if "_" in lang:
187
 
    country = lang.split(".")[0].split("_")[1]
188
 
    if "@" in country:
189
 
       country = country.split("@")[0]
190
 
    return country+"."
191
 
  else:
192
 
    return lang[:2]+"."
193
 
  return ''
 
206
 
194
207
 
195
208
def get_dist():
196
 
  " return the codename of the current runing distro "
197
 
  # support debug overwrite
198
 
  dist = os.environ.get("META_RELEASE_FAKE_CODENAME")
199
 
  if dist:
200
 
      logging.warn("using fake release name '%s' (because of META_RELEASE_FAKE_CODENAME environment) " % dist)
201
 
      return dist
202
 
  # then check the real one
203
 
  from subprocess import Popen, PIPE
204
 
  p = Popen(["lsb_release","-c","-s"], stdout=PIPE, universal_newlines=True)
205
 
  res = p.wait()
206
 
  if res != 0:
207
 
    sys.stderr.write("lsb_release returned exitcode: %i\n" % res)
208
 
    return "unknown distribution"
209
 
  dist = p.stdout.readline().strip()
210
 
  p.stdout.close()
211
 
  return dist
212
 
 
213
 
def get_dist_description():
214
 
  " return the description of the current runing distro "
215
 
  # support debug overwrite
216
 
  desc = os.environ.get("META_RELEASE_FAKE_DESCRIPTION")
217
 
  if desc:
218
 
      logging.warn("using fake release description '%s' (because of META_RELEASE_FAKE_DESCRIPTION environment) " % desc)
219
 
      return desc
220
 
  # then check the real one
221
 
  from subprocess import Popen, PIPE
222
 
  p = Popen(["lsb_release","-d","-s"], stdout=PIPE, universal_newlines=True)
223
 
  res = p.wait()
224
 
  if res != 0:
225
 
    sys.stderr.write("lsb_release returned exitcode: %i\n" % res)
226
 
    return "unknown distribution"
227
 
  desc = p.stdout.readline().strip()
228
 
  p.stdout.close()
229
 
  return desc
 
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
 
 
228
 
 
229
def get_dist_version():
 
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
 
230
249
 
231
250
class HeadRequest(Request):
232
251
    def get_method(self):
233
252
        return "HEAD"
234
253
 
 
254
 
235
255
def url_downloadable(uri, debug_func=None):
236
 
  """
237
 
  helper that checks if the given uri exists and is downloadable
238
 
  (supports optional debug_func function handler to support 
239
 
   e.g. logging)
240
 
 
241
 
  Supports http (via HEAD) and ftp (via size request)
242
 
  """
243
 
  if not debug_func:
244
 
      lambda x: True
245
 
  debug_func("url_downloadable: %s" % uri)
246
 
  (scheme, netloc, path, querry, fragment) = urlsplit(uri)
247
 
  debug_func("s='%s' n='%s' p='%s' q='%s' f='%s'" % (scheme, netloc, path, querry, fragment))
248
 
  if scheme == "http":
249
 
    try:
250
 
        http_file = urlopen(HeadRequest(uri))
251
 
        http_file.close()
252
 
        if http_file.code == 200:
253
 
            return True
254
 
        return False
255
 
    except Exception as e:
256
 
      debug_func("error from httplib: '%s'" % e)
257
 
      return False
258
 
  elif scheme == "ftp":
259
 
    import ftplib
260
 
    try:
261
 
      f = ftplib.FTP(netloc)
262
 
      f.login()
263
 
      f.cwd(os.path.dirname(path))
264
 
      size = f.size(os.path.basename(path))
265
 
      f.quit()
266
 
      if debug_func:
267
 
        debug_func("ftplib.size() returned: %s" % size)
268
 
      if size != 0:
269
 
        return True
270
 
    except Exception as e:
271
 
      if debug_func:
272
 
        debug_func("error from ftplib: '%s'" % e)
273
 
      return False
274
 
  return False
 
256
    """
 
257
    helper that checks if the given uri exists and is downloadable
 
258
    (supports optional debug_func function handler to support
 
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
 
275
297
 
276
298
def init_proxy(gsettings=None):
277
 
  """ init proxy settings 
278
 
 
279
 
  * first check for http_proxy environment (always wins),
280
 
  * then check the apt.conf http proxy, 
281
 
  * then look into synaptics conffile
282
 
  * then into gconf  (if gconfclient was supplied)
283
 
  """
284
 
  SYNAPTIC_CONF_FILE = "/root/.synaptic/synaptic.conf"
285
 
  proxy = None
286
 
  # generic apt config wins
287
 
  if apt_pkg.config.find("Acquire::http::Proxy") != '':
288
 
    proxy = apt_pkg.config.find("Acquire::http::Proxy")
289
 
  # then synaptic
290
 
  elif os.path.exists(SYNAPTIC_CONF_FILE):
291
 
    cnf = apt_pkg.Configuration()
292
 
    apt_pkg.read_config_file(cnf, SYNAPTIC_CONF_FILE)
293
 
    use_proxy = cnf.find_b("Synaptic::useProxy", False)
294
 
    if use_proxy:
295
 
      proxy_host = cnf.find("Synaptic::httpProxy")
296
 
      proxy_port = str(cnf.find_i("Synaptic::httpProxyPort"))
297
 
      if proxy_host and proxy_port:
298
 
        proxy = "http://%s:%s/" % (proxy_host, proxy_port)
299
 
  # gconf is no more
300
 
  # elif gconfclient:
301
 
  #   try: # see LP: #281248
302
 
  #     if gconfclient.get_bool("/system/http_proxy/use_http_proxy"):
303
 
  #       host = gconfclient.get_string("/system/http_proxy/host")
304
 
  #       port = gconfclient.get_int("/system/http_proxy/port")
305
 
  #       use_auth = gconfclient.get_bool("/system/http_proxy/use_authentication")
306
 
  #       if host and port:
307
 
  #         if use_auth:
308
 
  #           auth_user = gconfclient.get_string("/system/http_proxy/authentication_user")
309
 
  #           auth_pw = gconfclient.get_string("/system/http_proxy/authentication_password")
310
 
  #           proxy = "http://%s:%s@%s:%s/" % (auth_user,auth_pw,host, port)
311
 
  #         else:
312
 
  #           proxy = "http://%s:%s/" % (host, port)
313
 
  #   except Exception as e:
314
 
  #     print("error from gconf: %s" % e)
315
 
  # if we have a proxy, set it
316
 
  if proxy:
317
 
    # basic verification
318
 
    if not re.match("http://\w+", proxy):
319
 
      print("proxy '%s' looks invalid" % proxy, file=sys.stderr)
320
 
      return
321
 
    proxy_support = ProxyHandler({"http":proxy})
322
 
    opener = build_opener(proxy_support)
323
 
    install_opener(opener)
324
 
    os.putenv("http_proxy",proxy)
325
 
  return proxy
 
299
    """ init proxy settings
 
300
 
 
301
    * first check for http_proxy environment (always wins),
 
302
    * then check the apt.conf http proxy,
 
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
 
326
333
 
327
334
def on_battery():
328
 
  """
329
 
  Check via dbus if the system is running on battery.
330
 
  This function is using UPower per default, if UPower is not
331
 
  available it falls-back to DeviceKit.Power. 
332
 
  """
333
 
  try:
334
 
    import dbus
335
 
    bus = dbus.Bus(dbus.Bus.TYPE_SYSTEM)
 
335
    """
 
336
    Check via dbus if the system is running on battery.
 
337
    This function is using UPower per default, if UPower is not
 
338
    available it falls-back to DeviceKit.Power.
 
339
    """
336
340
    try:
337
 
        devobj = bus.get_object('org.freedesktop.UPower', 
338
 
                                '/org/freedesktop/UPower')
339
 
        dev = dbus.Interface(devobj, 'org.freedesktop.DBus.Properties')
340
 
        return dev.Get('org.freedesktop.UPower', 'OnBattery')
341
 
    except dbus.exceptions.DBusException as e:
342
 
        if e._dbus_error_name != 'org.freedesktop.DBus.Error.ServiceUnknown':
343
 
            raise
344
 
        devobj = bus.get_object('org.freedesktop.DeviceKit.Power', 
345
 
                                '/org/freedesktop/DeviceKit/Power')
346
 
        dev = dbus.Interface(devobj, "org.freedesktop.DBus.Properties")
347
 
        return dev.Get("org.freedesktop.DeviceKit.Power", "on_battery")
348
 
  except Exception as e:
349
 
    #import sys
350
 
    #print("on_battery returned error: ", e, file=sys.stderr)
351
 
    return False
 
341
        import dbus
 
342
        bus = dbus.Bus(dbus.Bus.TYPE_SYSTEM)
 
343
        try:
 
344
            devobj = bus.get_object('org.freedesktop.UPower',
 
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
 
352
            devobj = bus.get_object('org.freedesktop.DeviceKit.Power',
 
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
 
352
361
 
353
362
def inhibit_sleep():
354
 
  """
355
 
  Send a dbus signal to power-manager to not suspend
356
 
  the system, using the freedesktop common interface
357
 
  """
358
 
  try:
359
 
    import dbus
360
 
    bus = dbus.Bus(dbus.Bus.TYPE_SESSION)
361
 
    devobj = bus.get_object('org.freedesktop.PowerManagement', 
362
 
                          '/org/freedesktop/PowerManagement/Inhibit')
363
 
    dev = dbus.Interface(devobj, "org.freedesktop.PowerManagement.Inhibit")
364
 
    cookie = dev.Inhibit('UpdateManager', 'Updating system')
365
 
    return (dev, cookie)
366
 
  except Exception:
367
 
    #print("could not send the dbus Inhibit signal: %s" % e)
368
 
    return (False, False)
 
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)
 
370
        devobj = bus.get_object('org.freedesktop.PowerManagement',
 
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
 
369
379
 
370
380
def allow_sleep(dev, cookie):
371
 
  """Send a dbus signal to gnome-power-manager to allow a suspending
372
 
  the system"""
373
 
  try:
374
 
    dev.UnInhibit(cookie)
375
 
  except Exception as e:
376
 
    print("could not send the dbus UnInhibit signal: %s" % e)
 
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)
377
387
 
378
388
 
379
389
def str_to_bool(str):
380
 
  if str == "0" or str.upper() == "FALSE":
381
 
    return False
382
 
  return True
 
390
    if str == "0" or str.upper() == "FALSE":
 
391
        return False
 
392
    return True
 
393
 
383
394
 
384
395
def get_lang():
385
396
    import logging
386
397
    try:
387
398
        (locale_s, encoding) = locale.getdefaultlocale()
388
399
        return locale_s
389
 
    except Exception: 
 
400
    except Exception:
390
401
        logging.exception("gedefaultlocale() failed")
391
402
        return None
392
403
 
 
404
 
393
405
def get_ubuntu_flavor():
394
406
    """ try to guess the flavor based on the running desktop """
395
 
    # this will (of course) not work in a server environment, 
 
407
    # this will (of course) not work in a server environment,
396
408
    # but the main use case for this is to show the right
397
409
    # release notes
 
410
    # TODO: actually examine which meta packages are installed, like
 
411
    # DistUpgrade/DistUpgradeCache.py does and use that to choose a flavor.
398
412
    denv = os.environ.get("DESKTOP_SESSION", "")
399
413
    if "gnome" in denv:
400
414
        return "ubuntu"
407
421
    # default to ubuntu if nothing more specific is found
408
422
    return "ubuntu"
409
423
 
 
424
 
 
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
 
 
436
 
410
437
def error(parent, summary, message):
411
 
  from gi.repository import Gtk, Gdk
412
 
  d = Gtk.MessageDialog(parent=parent,
413
 
                        flags=Gtk.DialogFlags.MODAL,
414
 
                        type=Gtk.MessageType.ERROR,
415
 
                        buttons=Gtk.ButtonsType.CLOSE)
416
 
  d.set_markup("<big><b>%s</b></big>\n\n%s" % (summary, message))
417
 
  d.realize()
418
 
  d.window.set_functions(Gdk.FUNC_MOVE)
419
 
  d.set_title("")
420
 
  d.run()
421
 
  d.destroy()
422
 
  return False
 
438
    from gi.repository import Gtk, Gdk
 
439
    d = Gtk.MessageDialog(parent=parent,
 
440
                          flags=Gtk.DialogFlags.MODAL,
 
441
                          type=Gtk.MessageType.ERROR,
 
442
                          buttons=Gtk.ButtonsType.CLOSE)
 
443
    d.set_markup("<big><b>%s</b></big>\n\n%s" % (summary, message))
 
444
    d.realize()
 
445
    d.window.set_functions(Gdk.FUNC_MOVE)
 
446
    d.set_title("")
 
447
    d.run()
 
448
    d.destroy()
 
449
    return False
 
450
 
423
451
 
424
452
def humanize_size(bytes):
425
453
    """
427
455
    """
428
456
 
429
457
    if bytes < 1000 * 1000:
430
 
        # to have 0 for 0 bytes, 1 for 0-1000 bytes and for 1 and above round up
431
 
        size_in_kb = int(ceil(bytes/float(1000)));
 
458
        # to have 0 for 0 bytes, 1 for 0-1000 bytes and for 1 and above
 
459
        # round up
 
460
        size_in_kb = int(ceil(bytes / float(1000)))
432
461
        # TRANSLATORS: download size of small updates, e.g. "250 kB"
433
 
        return ngettext("%(size).0f kB", "%(size).0f kB", size_in_kb) % { "size" : size_in_kb }
 
462
        return ngettext("%(size).0f kB", "%(size).0f kB", size_in_kb) % {
 
463
            "size": size_in_kb}
434
464
    else:
435
465
        # TRANSLATORS: download size of updates, e.g. "2.3 MB"
436
466
        return locale.format_string(_("%.1f MB"), bytes / 1000.0 / 1000.0)
437
467
 
 
468
 
438
469
def get_arch():
439
470
    return apt_pkg.config.find("APT::Architecture")
440
471
 
454
485
            if not line:
455
486
                continue
456
487
            # split, values are:
457
 
            #   sl  local_address rem_address   st tx_queue rx_queue tr tm->when retrnsmt   uid  timeout inode                                                     
 
488
            #   sl  local_address rem_address   st tx_queue rx_queue tr
 
489
            #   tm->when retrnsmt   uid  timeout inode
458
490
            values = line.split()
459
491
            state = values[INDEX_STATE]
460
492
            if state != STATE_LISTENING:
469
501
def iptables_active():
470
502
    """ Return True if iptables is active """
471
503
    # FIXME: is there a better way?
472
 
    iptables_empty="""Chain INPUT (policy ACCEPT)
473
 
target     prot opt source               destination         
 
504
    iptables_empty = """Chain INPUT (policy ACCEPT)
 
505
target     prot opt source               destination
474
506
 
475
507
Chain FORWARD (policy ACCEPT)
476
 
target     prot opt source               destination         
 
508
target     prot opt source               destination
477
509
 
478
510
Chain OUTPUT (policy ACCEPT)
479
 
target     prot opt source               destination         
 
511
target     prot opt source               destination
480
512
"""
481
513
    if os.getuid() != 0:
482
514
        raise OSError("Need root to check the iptables state")
483
515
    if not os.path.exists("/sbin/iptables"):
484
516
        return False
485
 
    out = subprocess.Popen(["iptables", "-L"], 
 
517
    out = subprocess.Popen(["iptables", "-L"],
486
518
                           stdout=subprocess.PIPE,
487
519
                           universal_newlines=True).communicate()[0]
488
520
    if out == iptables_empty:
491
523
 
492
524
 
493
525
if __name__ == "__main__":
494
 
  #print(mirror_from_sources_list())
495
 
  #print(on_battery())
496
 
  #print(inside_chroot())
497
 
  print(iptables_active())
 
526
    #print(mirror_from_sources_list())
 
527
    #print(on_battery())
 
528
    #print(inside_chroot())
 
529
    print(iptables_active())