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