]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/__init__.py
Suppress all UserWarnings, not just ones with known messages. refs #2248
[tahoe-lafs/tahoe-lafs.git] / src / allmydata / __init__.py
1 """
2 Decentralized storage grid.
3
4 community web site: U{https://tahoe-lafs.org/}
5 """
6
7 class PackagingError(EnvironmentError):
8     """
9     Raised when there is an error in packaging of Tahoe-LAFS or its
10     dependencies which makes it impossible to proceed safely.
11     """
12     pass
13
14 __version__ = "unknown"
15 try:
16     from allmydata._version import __version__
17 except ImportError:
18     # We're running in a tree that hasn't run update_version, and didn't
19     # come with a _version.py, so we don't know what our version is.
20     # This should not happen very often.
21     pass
22
23 full_version = "unknown"
24 branch = "unknown"
25 try:
26     from allmydata._version import full_version, branch
27 except ImportError:
28     # We're running in a tree that hasn't run update_version, and didn't
29     # come with a _version.py, so we don't know what our full version or
30     # branch is. This should not happen very often.
31     pass
32
33 __appname__ = "unknown"
34 try:
35     from allmydata._appname import __appname__
36 except ImportError:
37     # We're running in a tree that hasn't run "./setup.py".  This shouldn't happen.
38     pass
39
40 # __full_version__ is the one that you ought to use when identifying yourself in the
41 # "application" part of the Tahoe versioning scheme:
42 # https://tahoe-lafs.org/trac/tahoe-lafs/wiki/Versioning
43 __full_version__ = __appname__ + '/' + str(__version__)
44
45 import os, platform, re, subprocess, sys, traceback
46 _distributor_id_cmdline_re = re.compile("(?:Distributor ID:)\s*(.*)", re.I)
47 _release_cmdline_re = re.compile("(?:Release:)\s*(.*)", re.I)
48
49 _distributor_id_file_re = re.compile("(?:DISTRIB_ID\s*=)\s*(.*)", re.I)
50 _release_file_re = re.compile("(?:DISTRIB_RELEASE\s*=)\s*(.*)", re.I)
51
52 global _distname,_version
53 _distname = None
54 _version = None
55
56 def get_linux_distro():
57     """ Tries to determine the name of the Linux OS distribution name.
58
59     First, try to parse a file named "/etc/lsb-release".  If it exists, and
60     contains the "DISTRIB_ID=" line and the "DISTRIB_RELEASE=" line, then return
61     the strings parsed from that file.
62
63     If that doesn't work, then invoke platform.dist().
64
65     If that doesn't work, then try to execute "lsb_release", as standardized in
66     2001:
67
68     http://refspecs.freestandards.org/LSB_1.0.0/gLSB/lsbrelease.html
69
70     The current version of the standard is here:
71
72     http://refspecs.freestandards.org/LSB_3.2.0/LSB-Core-generic/LSB-Core-generic/lsbrelease.html
73
74     that lsb_release emitted, as strings.
75
76     Returns a tuple (distname,version). Distname is what LSB calls a
77     "distributor id", e.g. "Ubuntu".  Version is what LSB calls a "release",
78     e.g. "8.04".
79
80     A version of this has been submitted to python as a patch for the standard
81     library module "platform":
82
83     http://bugs.python.org/issue3937
84     """
85     global _distname,_version
86     if _distname and _version:
87         return (_distname, _version)
88
89     try:
90         etclsbrel = open("/etc/lsb-release", "rU")
91         for line in etclsbrel:
92             m = _distributor_id_file_re.search(line)
93             if m:
94                 _distname = m.group(1).strip()
95                 if _distname and _version:
96                     return (_distname, _version)
97             m = _release_file_re.search(line)
98             if m:
99                 _version = m.group(1).strip()
100                 if _distname and _version:
101                     return (_distname, _version)
102     except EnvironmentError:
103         pass
104
105     (_distname, _version) = platform.dist()[:2]
106     if _distname and _version:
107         return (_distname, _version)
108
109     try:
110         p = subprocess.Popen(["lsb_release", "--all"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
111         rc = p.wait()
112         if rc == 0:
113             for line in p.stdout.readlines():
114                 m = _distributor_id_cmdline_re.search(line)
115                 if m:
116                     _distname = m.group(1).strip()
117                     if _distname and _version:
118                         return (_distname, _version)
119
120                 m = _release_cmdline_re.search(p.stdout.read())
121                 if m:
122                     _version = m.group(1).strip()
123                     if _distname and _version:
124                         return (_distname, _version)
125     except EnvironmentError:
126         pass
127
128     if os.path.exists("/etc/arch-release"):
129         return ("Arch_Linux", "")
130
131     return (_distname,_version)
132
133 def get_platform():
134     # Our version of platform.platform(), telling us both less and more than the
135     # Python Standard Library's version does.
136     # We omit details such as the Linux kernel version number, but we add a
137     # more detailed and correct rendition of the Linux distribution and
138     # distribution-version.
139     if "linux" in platform.system().lower():
140         return platform.system()+"-"+"_".join(get_linux_distro())+"-"+platform.machine()+"-"+"_".join([x for x in platform.architecture() if x])
141     else:
142         return platform.platform()
143
144
145 from allmydata.util import verlib
146 def normalized_version(verstr, what=None):
147     try:
148         return verlib.NormalizedVersion(verlib.suggest_normalized_version(verstr))
149     except (StandardError, verlib.IrrationalVersionError):
150         cls, value, trace = sys.exc_info()
151         raise PackagingError, ("could not parse %s due to %s: %s"
152                                % (what or repr(verstr), cls.__name__, value)), trace
153
154
155 def get_package_versions_and_locations():
156     import warnings
157     from _auto_deps import package_imports, global_deprecation_messages, deprecation_messages, \
158         runtime_warning_messages, warning_imports
159
160     def package_dir(srcfile):
161         return os.path.dirname(os.path.dirname(os.path.normcase(os.path.realpath(srcfile))))
162
163     # pkg_resources.require returns the distribution that pkg_resources attempted to put
164     # on sys.path, which can differ from the one that we actually import due to #1258,
165     # or any other bug that causes sys.path to be set up incorrectly. Therefore we
166     # must import the packages in order to check their versions and paths.
167
168     # This is to suppress all UserWarnings and various DeprecationWarnings and RuntimeWarnings
169     # (listed in _auto_deps.py).
170
171     warnings.filterwarnings("ignore", category=UserWarning, append=True)
172
173     for msg in global_deprecation_messages + deprecation_messages:
174         warnings.filterwarnings("ignore", category=DeprecationWarning, message=msg, append=True)
175     for msg in runtime_warning_messages:
176         warnings.filterwarnings("ignore", category=RuntimeWarning, message=msg, append=True)
177     try:
178         for modulename in warning_imports:
179             try:
180                 __import__(modulename)
181             except ImportError:
182                 pass
183     finally:
184         # Leave suppressions for UserWarnings and global_deprecation_messages active.
185         for ign in runtime_warning_messages + deprecation_messages:
186             warnings.filters.pop()
187
188     packages = []
189
190     def get_version(module, attr):
191         return str(getattr(module, attr, 'unknown'))
192
193     for pkgname, modulename in [(__appname__, 'allmydata')] + package_imports:
194         if modulename:
195             try:
196                 __import__(modulename)
197                 module = sys.modules[modulename]
198             except ImportError:
199                 etype, emsg, etrace = sys.exc_info()
200                 trace_info = (etype, str(emsg), ([None] + traceback.extract_tb(etrace))[-1])
201                 packages.append( (pkgname, (None, None, trace_info)) )
202             else:
203                 comment = None
204                 if pkgname == __appname__:
205                     comment = "%s: %s" % (branch, full_version)
206                 elif pkgname == 'setuptools' and hasattr(module, '_distribute'):
207                     # distribute does not report its version in any module variables
208                     comment = 'distribute'
209                 packages.append( (pkgname, (get_version(module, '__version__'), package_dir(module.__file__), comment)) )
210         elif pkgname == 'python':
211             packages.append( (pkgname, (platform.python_version(), sys.executable, None)) )
212         elif pkgname == 'platform':
213             packages.append( (pkgname, (get_platform(), None, None)) )
214
215     return packages
216
217
218 def check_requirement(req, vers_and_locs):
219     # TODO: check [] options
220     # We support only disjunctions of <=, >=, and ==
221
222     reqlist = req.split(',')
223     name = reqlist[0].split('<=')[0].split('>=')[0].split('==')[0].strip(' ').split('[')[0]
224     if name not in vers_and_locs:
225         raise PackagingError("no version info for %s" % (name,))
226     if req.strip(' ') == name:
227         return
228     (actual, location, comment) = vers_and_locs[name]
229     if actual is None:
230         # comment is (type, message, (filename, line number, function name, text)) for the original ImportError
231         raise ImportError("for requirement %r: %s" % (req, comment))
232     if actual == 'unknown':
233         return
234     actualver = normalized_version(actual, what="actual version %r of %s from %r" % (actual, name, location))
235
236     for r in reqlist:
237         s = r.split('<=')
238         if len(s) == 2:
239             required = s[1].strip(' ')
240             if actualver <= normalized_version(required, what="required maximum version %r in %r" % (required, req)):
241                 return  # maximum requirement met
242         else:
243             s = r.split('>=')
244             if len(s) == 2:
245                 required = s[1].strip(' ')
246                 if actualver >= normalized_version(required, what="required minimum version %r in %r" % (required, req)):
247                     return  # minimum requirement met
248             else:
249                 s = r.split('==')
250                 if len(s) == 2:
251                     required = s[1].strip(' ')
252                     if actualver == normalized_version(required, what="required exact version %r in %r" % (required, req)):
253                         return  # exact requirement met
254                 else:
255                     raise PackagingError("no version info or could not understand requirement %r" % (req,))
256
257     msg = ("We require %s, but could only find version %s.\n" % (req, actual))
258     if location and location != 'unknown':
259         msg += "The version we found is from %r.\n" % (location,)
260     msg += ("To resolve this problem, uninstall that version, either using your\n"
261             "operating system's package manager or by moving aside the directory.")
262     raise PackagingError(msg)
263
264
265 _vers_and_locs_list = get_package_versions_and_locations()
266
267
268 def cross_check_pkg_resources_versus_import():
269     """This function returns a list of errors due to any failed cross-checks."""
270
271     import pkg_resources
272     from _auto_deps import install_requires
273
274     pkg_resources_vers_and_locs = dict([(p.project_name.lower(), (str(p.version), p.location))
275                                         for p in pkg_resources.require(install_requires)])
276
277     return cross_check(pkg_resources_vers_and_locs, _vers_and_locs_list)
278
279
280 def cross_check(pkg_resources_vers_and_locs, imported_vers_and_locs_list):
281     """This function returns a list of errors due to any failed cross-checks."""
282
283     errors = []
284     not_pkg_resourceable = set(['python', 'platform', __appname__.lower()])
285     not_import_versionable = set(['zope.interface', 'mock', 'pyasn1'])
286     ignorable = set(['argparse', 'pyutil', 'zbase32', 'distribute', 'twisted-web', 'twisted-core', 'twisted-conch'])
287
288     for name, (imp_ver, imp_loc, imp_comment) in imported_vers_and_locs_list:
289         name = name.lower()
290         if name not in not_pkg_resourceable:
291             if name not in pkg_resources_vers_and_locs:
292                 if name == "setuptools" and "distribute" in pkg_resources_vers_and_locs:
293                     pr_ver, pr_loc = pkg_resources_vers_and_locs["distribute"]
294                     if not (os.path.normpath(os.path.realpath(pr_loc)) == os.path.normpath(os.path.realpath(imp_loc))
295                             and imp_comment == "distribute"):
296                         errors.append("Warning: dependency 'setuptools' found to be version %r of 'distribute' from %r "
297                                       "by pkg_resources, but 'import setuptools' gave version %r [%s] from %r. "
298                                       "A version mismatch is expected, but a location mismatch is not."
299                                       % (pr_ver, pr_loc, imp_ver, imp_comment or 'probably *not* distribute', imp_loc))
300                 else:
301                     errors.append("Warning: dependency %r (version %r imported from %r) was not found by pkg_resources."
302                                   % (name, imp_ver, imp_loc))
303                 continue
304
305             pr_ver, pr_loc = pkg_resources_vers_and_locs[name]
306             if imp_ver is None and imp_loc is None:
307                 errors.append("Warning: dependency %r could not be imported. pkg_resources thought it should be possible "
308                               "to import version %r from %r.\nThe exception trace was %r."
309                               % (name, pr_ver, pr_loc, imp_comment))
310                 continue
311
312             try:
313                 pr_normver = normalized_version(pr_ver)
314             except Exception, e:
315                 errors.append("Warning: version number %r found for dependency %r by pkg_resources could not be parsed. "
316                               "The version found by import was %r from %r. "
317                               "pkg_resources thought it should be found at %r. "
318                               "The exception was %s: %s"
319                               % (pr_ver, name, imp_ver, imp_loc, pr_loc, e.__class__.__name__, e))
320             else:
321                 if imp_ver == 'unknown':
322                     if name not in not_import_versionable:
323                         errors.append("Warning: unexpectedly could not find a version number for dependency %r imported from %r. "
324                                       "pkg_resources thought it should be version %r at %r."
325                                       % (name, imp_loc, pr_ver, pr_loc))
326                 else:
327                     try:
328                         imp_normver = normalized_version(imp_ver)
329                     except Exception, e:
330                         errors.append("Warning: version number %r found for dependency %r (imported from %r) could not be parsed. "
331                                       "pkg_resources thought it should be version %r at %r. "
332                                       "The exception was %s: %s"
333                                       % (imp_ver, name, imp_loc, pr_ver, pr_loc, e.__class__.__name__, e))
334                     else:
335                         if pr_ver == 'unknown' or (pr_normver != imp_normver):
336                             if not os.path.normpath(os.path.realpath(pr_loc)) == os.path.normpath(os.path.realpath(imp_loc)):
337                                 errors.append("Warning: dependency %r found to have version number %r (normalized to %r, from %r) "
338                                               "by pkg_resources, but version %r (normalized to %r, from %r) by import."
339                                               % (name, pr_ver, str(pr_normver), pr_loc, imp_ver, str(imp_normver), imp_loc))
340
341     imported_packages = set([p.lower() for (p, _) in imported_vers_and_locs_list])
342     for pr_name, (pr_ver, pr_loc) in pkg_resources_vers_and_locs.iteritems():
343         if pr_name not in imported_packages and pr_name not in ignorable:
344             errors.append("Warning: dependency %r (version %r) found by pkg_resources not found by import."
345                           % (pr_name, pr_ver))
346
347     return errors
348
349
350 def get_error_string(errors, debug=False):
351     from allmydata._auto_deps import install_requires
352
353     msg = "\n%s\n" % ("\n".join(errors),)
354     if debug:
355         msg += ("\n"
356                 "For debugging purposes, the PYTHONPATH was\n"
357                 "  %r\n"
358                 "install_requires was\n"
359                 "  %r\n"
360                 "sys.path after importing pkg_resources was\n"
361                 "  %s\n"
362                 % (os.environ.get('PYTHONPATH'), install_requires, (os.pathsep+"\n  ").join(sys.path)) )
363     return msg
364
365 def check_all_requirements():
366     """This function returns a list of errors due to any failed checks."""
367
368     from allmydata._auto_deps import install_requires
369
370     errors = []
371
372     # We require at least 2.6 on all platforms.
373     # (On Python 3, we'll have failed long before this point.)
374     if sys.version_info < (2, 6):
375         try:
376             version_string = ".".join(map(str, sys.version_info))
377         except Exception:
378             version_string = repr(sys.version_info)
379         errors.append("Tahoe-LAFS currently requires Python v2.6 or greater (but less than v3), not %s"
380                       % (version_string,))
381
382     vers_and_locs = dict(_vers_and_locs_list)
383     for requirement in install_requires:
384         try:
385             check_requirement(requirement, vers_and_locs)
386         except (ImportError, PackagingError), e:
387             errors.append("%s: %s" % (e.__class__.__name__, e))
388
389     if errors:
390         raise PackagingError(get_error_string(errors, debug=True))
391
392 check_all_requirements()
393
394
395 def get_package_versions():
396     return dict([(k, v) for k, (v, l, c) in _vers_and_locs_list])
397
398 def get_package_locations():
399     return dict([(k, l) for k, (v, l, c) in _vers_and_locs_list])
400
401 def get_package_versions_string(show_paths=False, debug=False):
402     res = []
403     for p, (v, loc, comment) in _vers_and_locs_list:
404         info = str(p) + ": " + str(v)
405         if comment:
406             info = info + " [%s]" % str(comment)
407         if show_paths:
408             info = info + " (%s)" % str(loc)
409         res.append(info)
410
411     output = "\n".join(res) + "\n"
412
413     if not hasattr(sys, 'frozen'):
414         errors = cross_check_pkg_resources_versus_import()
415         if errors:
416             output += get_error_string(errors, debug=debug)
417
418     return output