]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/__init__.py
44f971f8634fd86b8f9bf53678acdb29875d3be4
[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     if os.path.isfile("/usr/bin/lsb_release") or os.path.isfile("/bin/lsb_release"):
110         try:
111             p = subprocess.Popen(["lsb_release", "--all"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
112             rc = p.wait()
113             if rc == 0:
114                 for line in p.stdout.readlines():
115                     m = _distributor_id_cmdline_re.search(line)
116                     if m:
117                         _distname = m.group(1).strip()
118                         if _distname and _version:
119                             return (_distname, _version)
120
121                     m = _release_cmdline_re.search(p.stdout.read())
122                     if m:
123                         _version = m.group(1).strip()
124                         if _distname and _version:
125                             return (_distname, _version)
126         except EnvironmentError:
127             pass
128
129     if os.path.exists("/etc/arch-release"):
130         return ("Arch_Linux", "")
131
132     return (_distname,_version)
133
134 def get_platform():
135     # Our version of platform.platform(), telling us both less and more than the
136     # Python Standard Library's version does.
137     # We omit details such as the Linux kernel version number, but we add a
138     # more detailed and correct rendition of the Linux distribution and
139     # distribution-version.
140     if "linux" in platform.system().lower():
141         return platform.system()+"-"+"_".join(get_linux_distro())+"-"+platform.machine()+"-"+"_".join([x for x in platform.architecture() if x])
142     else:
143         return platform.platform()
144
145
146 from allmydata.util import verlib
147 def normalized_version(verstr, what=None):
148     try:
149         return verlib.NormalizedVersion(verlib.suggest_normalized_version(verstr))
150     except (StandardError, verlib.IrrationalVersionError):
151         cls, value, trace = sys.exc_info()
152         raise PackagingError, ("could not parse %s due to %s: %s"
153                                % (what or repr(verstr), cls.__name__, value)), trace
154
155
156 def get_package_versions_and_locations():
157     import warnings
158     from _auto_deps import package_imports, global_deprecation_messages, deprecation_messages, \
159         runtime_warning_messages, warning_imports
160
161     def package_dir(srcfile):
162         return os.path.dirname(os.path.dirname(os.path.normcase(os.path.realpath(srcfile))))
163
164     # pkg_resources.require returns the distribution that pkg_resources attempted to put
165     # on sys.path, which can differ from the one that we actually import due to #1258,
166     # or any other bug that causes sys.path to be set up incorrectly. Therefore we
167     # must import the packages in order to check their versions and paths.
168
169     # This is to suppress all UserWarnings and various DeprecationWarnings and RuntimeWarnings
170     # (listed in _auto_deps.py).
171
172     warnings.filterwarnings("ignore", category=UserWarning, append=True)
173
174     for msg in global_deprecation_messages + deprecation_messages:
175         warnings.filterwarnings("ignore", category=DeprecationWarning, message=msg, append=True)
176     for msg in runtime_warning_messages:
177         warnings.filterwarnings("ignore", category=RuntimeWarning, message=msg, append=True)
178     try:
179         for modulename in warning_imports:
180             try:
181                 __import__(modulename)
182             except ImportError:
183                 pass
184     finally:
185         # Leave suppressions for UserWarnings and global_deprecation_messages active.
186         for ign in runtime_warning_messages + deprecation_messages:
187             warnings.filters.pop()
188
189     packages = []
190
191     def get_version(module):
192         if hasattr(module, '__version__'):
193             return str(getattr(module, '__version__'))
194         elif hasattr(module, 'version'):
195             ver = getattr(module, 'version')
196             if isinstance(ver, tuple):
197                 return '.'.join(map(str, ver))
198             else:
199                 return str(ver)
200         else:
201             return 'unknown'
202
203     for pkgname, modulename in [(__appname__, 'allmydata')] + package_imports:
204         if modulename:
205             try:
206                 __import__(modulename)
207                 module = sys.modules[modulename]
208             except ImportError:
209                 etype, emsg, etrace = sys.exc_info()
210                 trace_info = (etype, str(emsg), ([None] + traceback.extract_tb(etrace))[-1])
211                 packages.append( (pkgname, (None, None, trace_info)) )
212             else:
213                 comment = None
214                 if pkgname == __appname__:
215                     comment = "%s: %s" % (branch, full_version)
216                 elif pkgname == 'setuptools' and hasattr(module, '_distribute'):
217                     # distribute does not report its version in any module variables
218                     comment = 'distribute'
219                 packages.append( (pkgname, (get_version(module), package_dir(module.__file__), comment)) )
220         elif pkgname == 'python':
221             packages.append( (pkgname, (platform.python_version(), sys.executable, None)) )
222         elif pkgname == 'platform':
223             packages.append( (pkgname, (get_platform(), None, None)) )
224
225     return packages
226
227
228 def check_requirement(req, vers_and_locs):
229     # We support only conjunctions of <=, >=, and !=
230
231     reqlist = req.split(',')
232     name = reqlist[0].split('<=')[0].split('>=')[0].split('!=')[0].strip(' ').split('[')[0]
233     if name not in vers_and_locs:
234         raise PackagingError("no version info for %s" % (name,))
235     if req.strip(' ') == name:
236         return
237     (actual, location, comment) = vers_and_locs[name]
238     if actual is None:
239         # comment is (type, message, (filename, line number, function name, text)) for the original ImportError
240         raise ImportError("for requirement %r: %s" % (req, comment))
241     if actual == 'unknown':
242         return
243     actualver = normalized_version(actual, what="actual version %r of %s from %r" % (actual, name, location))
244
245     if not match_requirement(req, reqlist, actualver):
246         msg = ("We require %s, but could only find version %s.\n" % (req, actual))
247         if location and location != 'unknown':
248             msg += "The version we found is from %r.\n" % (location,)
249         msg += ("To resolve this problem, uninstall that version, either using your\n"
250                 "operating system's package manager or by moving aside the directory.")
251         raise PackagingError(msg)
252
253
254 def match_requirement(req, reqlist, actualver):
255     for r in reqlist:
256         s = r.split('<=')
257         if len(s) == 2:
258             required = s[1].strip(' ')
259             if not (actualver <= normalized_version(required, what="required maximum version %r in %r" % (required, req))):
260                 return False  # maximum requirement not met
261         else:
262             s = r.split('>=')
263             if len(s) == 2:
264                 required = s[1].strip(' ')
265                 if not (actualver >= normalized_version(required, what="required minimum version %r in %r" % (required, req))):
266                     return False  # minimum requirement not met
267             else:
268                 s = r.split('!=')
269                 if len(s) == 2:
270                     required = s[1].strip(' ')
271                     if not (actualver != normalized_version(required, what="excluded version %r in %r" % (required, req))):
272                         return False  # not-equal requirement not met
273                 else:
274                     raise PackagingError("no version info or could not understand requirement %r" % (req,))
275
276     return True
277
278
279 _vers_and_locs_list = get_package_versions_and_locations()
280
281
282 def cross_check_pkg_resources_versus_import():
283     """This function returns a list of errors due to any failed cross-checks."""
284
285     import pkg_resources
286     from _auto_deps import install_requires
287
288     pkg_resources_vers_and_locs = dict([(p.project_name.lower(), (str(p.version), p.location))
289                                         for p in pkg_resources.require(install_requires)])
290
291     return cross_check(pkg_resources_vers_and_locs, _vers_and_locs_list)
292
293
294 def cross_check(pkg_resources_vers_and_locs, imported_vers_and_locs_list):
295     """This function returns a list of errors due to any failed cross-checks."""
296
297     from _auto_deps import not_import_versionable, ignorable
298
299     errors = []
300     not_pkg_resourceable = ['python', 'platform', __appname__.lower()]
301
302     for name, (imp_ver, imp_loc, imp_comment) in imported_vers_and_locs_list:
303         name = name.lower()
304         if name not in not_pkg_resourceable:
305             if name not in pkg_resources_vers_and_locs:
306                 if name == "setuptools" and "distribute" in pkg_resources_vers_and_locs:
307                     pr_ver, pr_loc = pkg_resources_vers_and_locs["distribute"]
308                     if not (os.path.normpath(os.path.realpath(pr_loc)) == os.path.normpath(os.path.realpath(imp_loc))
309                             and imp_comment == "distribute"):
310                         errors.append("Warning: dependency 'setuptools' found to be version %r of 'distribute' from %r "
311                                       "by pkg_resources, but 'import setuptools' gave version %r [%s] from %r. "
312                                       "A version mismatch is expected, but a location mismatch is not."
313                                       % (pr_ver, pr_loc, imp_ver, imp_comment or 'probably *not* distribute', imp_loc))
314                 else:
315                     errors.append("Warning: dependency %r (version %r imported from %r) was not found by pkg_resources."
316                                   % (name, imp_ver, imp_loc))
317                 continue
318
319             pr_ver, pr_loc = pkg_resources_vers_and_locs[name]
320             if imp_ver is None and imp_loc is None:
321                 errors.append("Warning: dependency %r could not be imported. pkg_resources thought it should be possible "
322                               "to import version %r from %r.\nThe exception trace was %r."
323                               % (name, pr_ver, pr_loc, imp_comment))
324                 continue
325
326             try:
327                 pr_normver = normalized_version(pr_ver)
328             except Exception, e:
329                 errors.append("Warning: version number %r found for dependency %r by pkg_resources could not be parsed. "
330                               "The version found by import was %r from %r. "
331                               "pkg_resources thought it should be found at %r. "
332                               "The exception was %s: %s"
333                               % (pr_ver, name, imp_ver, imp_loc, pr_loc, e.__class__.__name__, e))
334             else:
335                 if imp_ver == 'unknown':
336                     if name not in not_import_versionable:
337                         errors.append("Warning: unexpectedly could not find a version number for dependency %r imported from %r. "
338                                       "pkg_resources thought it should be version %r at %r."
339                                       % (name, imp_loc, pr_ver, pr_loc))
340                 else:
341                     try:
342                         imp_normver = normalized_version(imp_ver)
343                     except Exception, e:
344                         errors.append("Warning: version number %r found for dependency %r (imported from %r) could not be parsed. "
345                                       "pkg_resources thought it should be version %r at %r. "
346                                       "The exception was %s: %s"
347                                       % (imp_ver, name, imp_loc, pr_ver, pr_loc, e.__class__.__name__, e))
348                     else:
349                         if pr_ver == 'unknown' or (pr_normver != imp_normver):
350                             if not os.path.normpath(os.path.realpath(pr_loc)) == os.path.normpath(os.path.realpath(imp_loc)):
351                                 errors.append("Warning: dependency %r found to have version number %r (normalized to %r, from %r) "
352                                               "by pkg_resources, but version %r (normalized to %r, from %r) by import."
353                                               % (name, pr_ver, str(pr_normver), pr_loc, imp_ver, str(imp_normver), imp_loc))
354
355     imported_packages = set([p.lower() for (p, _) in imported_vers_and_locs_list])
356     for pr_name, (pr_ver, pr_loc) in pkg_resources_vers_and_locs.iteritems():
357         if pr_name not in imported_packages and pr_name not in ignorable:
358             errors.append("Warning: dependency %r (version %r) found by pkg_resources not found by import."
359                           % (pr_name, pr_ver))
360
361     return errors
362
363
364 def get_error_string(errors, debug=False):
365     from allmydata._auto_deps import install_requires
366
367     msg = "\n%s\n" % ("\n".join(errors),)
368     if debug:
369         msg += ("\n"
370                 "For debugging purposes, the PYTHONPATH was\n"
371                 "  %r\n"
372                 "install_requires was\n"
373                 "  %r\n"
374                 "sys.path after importing pkg_resources was\n"
375                 "  %s\n"
376                 % (os.environ.get('PYTHONPATH'), install_requires, (os.pathsep+"\n  ").join(sys.path)) )
377     return msg
378
379 def check_all_requirements():
380     """This function returns a list of errors due to any failed checks."""
381
382     from allmydata._auto_deps import install_requires
383
384     errors = []
385
386     # We require at least 2.6 on all platforms.
387     # (On Python 3, we'll have failed long before this point.)
388     if sys.version_info < (2, 6):
389         try:
390             version_string = ".".join(map(str, sys.version_info))
391         except Exception:
392             version_string = repr(sys.version_info)
393         errors.append("Tahoe-LAFS currently requires Python v2.6 or greater (but less than v3), not %s"
394                       % (version_string,))
395
396     vers_and_locs = dict(_vers_and_locs_list)
397     for requirement in install_requires:
398         try:
399             check_requirement(requirement, vers_and_locs)
400         except (ImportError, PackagingError), e:
401             errors.append("%s: %s" % (e.__class__.__name__, e))
402
403     if errors:
404         raise PackagingError(get_error_string(errors, debug=True))
405
406 check_all_requirements()
407
408
409 def get_package_versions():
410     return dict([(k, v) for k, (v, l, c) in _vers_and_locs_list])
411
412 def get_package_locations():
413     return dict([(k, l) for k, (v, l, c) in _vers_and_locs_list])
414
415 def get_package_versions_string(show_paths=False, debug=False):
416     res = []
417     for p, (v, loc, comment) in _vers_and_locs_list:
418         info = str(p) + ": " + str(v)
419         if comment:
420             info = info + " [%s]" % str(comment)
421         if show_paths:
422             info = info + " (%s)" % str(loc)
423         res.append(info)
424
425     output = "\n".join(res) + "\n"
426
427     if not hasattr(sys, 'frozen'):
428         errors = cross_check_pkg_resources_versus_import()
429         if errors:
430             output += get_error_string(errors, debug=debug)
431
432     return output