2 Decentralized storage grid.
4 community web site: U{http://tahoe-lafs.org/}
7 class PackagingError(EnvironmentError):
9 Raised when there is an error in packaging of Tahoe-LAFS or its
10 dependencies which makes it impossible to proceed safely.
14 __version__ = "unknown"
16 from allmydata._version import __version__
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.
23 __appname__ = "unknown"
25 from allmydata._appname import __appname__
27 # We're running in a tree that hasn't run "./setup.py". This shouldn't happen.
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__)
35 import os, platform, re, subprocess, sys
36 _distributor_id_cmdline_re = re.compile("(?:Distributor ID:)\s*(.*)", re.I)
37 _release_cmdline_re = re.compile("(?:Release:)\s*(.*)", re.I)
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)
42 global _distname,_version
46 def get_linux_distro():
47 """ Tries to determine the name of the Linux OS distribution name.
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.
53 If that doesn't work, then invoke platform.dist().
55 If that doesn't work, then try to execute "lsb_release", as standardized in
58 http://refspecs.freestandards.org/LSB_1.0.0/gLSB/lsbrelease.html
60 The current version of the standard is here:
62 http://refspecs.freestandards.org/LSB_3.2.0/LSB-Core-generic/LSB-Core-generic/lsbrelease.html
64 that lsb_release emitted, as strings.
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",
70 A version of this has been submitted to python as a patch for the standard
71 library module "platform":
73 http://bugs.python.org/issue3937
75 global _distname,_version
76 if _distname and _version:
77 return (_distname, _version)
80 etclsbrel = open("/etc/lsb-release", "rU")
81 for line in etclsbrel:
82 m = _distributor_id_file_re.search(line)
84 _distname = m.group(1).strip()
85 if _distname and _version:
86 return (_distname, _version)
87 m = _release_file_re.search(line)
89 _version = m.group(1).strip()
90 if _distname and _version:
91 return (_distname, _version)
92 except EnvironmentError:
95 (_distname, _version) = platform.dist()[:2]
96 if _distname and _version:
97 return (_distname, _version)
100 p = subprocess.Popen(["lsb_release", "--all"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
103 for line in p.stdout.readlines():
104 m = _distributor_id_cmdline_re.search(line)
106 _distname = m.group(1).strip()
107 if _distname and _version:
108 return (_distname, _version)
110 m = _release_cmdline_re.search(p.stdout.read())
112 _version = m.group(1).strip()
113 if _distname and _version:
114 return (_distname, _version)
115 except EnvironmentError:
118 if os.path.exists("/etc/arch-release"):
119 return ("Arch_Linux", "")
121 return (_distname,_version)
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])
132 return platform.platform()
135 from allmydata.util import verlib
136 def normalized_version(verstr, what=None):
138 return verlib.NormalizedVersion(verlib.suggest_normalized_version(verstr))
139 except (StandardError, verlib.IrrationalVersionError):
140 cls, value, traceback = sys.exc_info()
141 raise PackagingError, ("could not parse %s due to %s: %s"
142 % (what or repr(verstr), cls.__name__, value)), traceback
145 def get_package_versions_and_locations():
147 from _auto_deps import package_imports, deprecation_messages, deprecation_imports
149 def package_dir(srcfile):
150 return os.path.dirname(os.path.dirname(os.path.normcase(os.path.realpath(srcfile))))
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.
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",
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 .
167 for msg in deprecation_messages:
168 warnings.filterwarnings("ignore", category=DeprecationWarning, message=msg, append=True)
170 for modulename in deprecation_imports:
172 __import__(modulename)
176 for ign in deprecation_messages:
177 warnings.filters.pop()
181 def get_version(module, attr):
182 return str(getattr(module, attr, 'unknown'))
184 for pkgname, modulename in [(__appname__, 'allmydata')] + package_imports:
187 __import__(modulename)
188 module = sys.modules[modulename]
190 packages.append( (pkgname, (None, None, modulename)) )
192 if 'sqlite' in pkgname:
193 packages.append( (pkgname, (get_version(module, 'version'), package_dir(module.__file__),
194 'sqlite %s' % (get_version(module, 'sqlite_version'),))) )
197 if pkgname == 'setuptools' and hasattr(module, '_distribute'):
198 # distribute does not report its version in any module variables
199 comment = 'distribute'
200 packages.append( (pkgname, (get_version(module, '__version__'), package_dir(module.__file__), comment)) )
201 elif pkgname == 'python':
202 packages.append( (pkgname, (platform.python_version(), sys.executable, None)) )
203 elif pkgname == 'platform':
204 packages.append( (pkgname, (get_platform(), None, None)) )
209 def check_requirement(req, vers_and_locs):
210 # TODO: check [] options
211 # We support only disjunctions of >= and ==
213 reqlist = req.split(',')
214 name = reqlist[0].split('>=')[0].split('==')[0].strip(' ').split('[')[0]
215 if name not in vers_and_locs:
216 raise PackagingError("no version info for %s" % (name,))
217 if req.strip(' ') == name:
219 (actual, location, comment) = vers_and_locs[name]
221 # comment is the module name
222 raise ImportError("could not import %r for requirement %r" % (comment, req))
223 if actual == 'unknown':
225 actualver = normalized_version(actual, what="actual version %r of %s from %r" % (actual, name, location))
230 required = s[1].strip(' ')
231 if actualver >= normalized_version(required, what="required minimum version %r in %r" % (required, req)):
232 return # minimum requirement met
236 required = s[1].strip(' ')
237 if actualver == normalized_version(required, what="required exact version %r in %r" % (required, req)):
238 return # exact requirement met
240 raise PackagingError("no version info or could not understand requirement %r" % (req,))
242 msg = ("We require %s, but could only find version %s.\n" % (req, actual))
243 if location and location != 'unknown':
244 msg += "The version we found is from %r.\n" % (location,)
245 msg += ("To resolve this problem, uninstall that version, either using your\n"
246 "operating system's package manager or by moving aside the directory.")
247 raise PackagingError(msg)
250 _vers_and_locs_list = get_package_versions_and_locations()
253 def cross_check_pkg_resources_versus_import():
254 """This function returns a list of errors due to any failed cross-checks."""
257 from _auto_deps import install_requires
259 pkg_resources_vers_and_locs = dict([(p.project_name.lower(), (str(p.version), p.location))
260 for p in pkg_resources.require(install_requires)])
262 return cross_check(pkg_resources_vers_and_locs, _vers_and_locs_list)
265 def cross_check(pkg_resources_vers_and_locs, imported_vers_and_locs_list):
266 """This function returns a list of errors due to any failed cross-checks."""
269 not_pkg_resourceable = set(['sqlite3', 'python', 'platform', __appname__.lower()])
270 not_import_versionable = set(['zope.interface', 'mock', 'pyasn1'])
271 ignorable = set(['argparse', 'pyutil', 'zbase32', 'distribute'])
273 for name, (imp_ver, imp_loc, imp_comment) in imported_vers_and_locs_list:
275 if name not in not_pkg_resourceable:
276 if name not in pkg_resources_vers_and_locs:
277 if name == "setuptools" and "distribute" in pkg_resources_vers_and_locs:
278 pr_ver, pr_loc = pkg_resources_vers_and_locs["distribute"]
279 if not (os.path.normpath(os.path.realpath(pr_loc)) == os.path.normpath(os.path.realpath(imp_loc))
280 and imp_comment == "distribute"):
281 errors.append("Warning: dependency 'setuptools' found to be version %r of 'distribute' from %r "
282 "by pkg_resources, but 'import setuptools' gave version %r [%s] from %r. "
283 "A version mismatch is expected, but a location mismatch is not."
284 % (pr_ver, pr_loc, imp_ver, imp_comment or 'probably *not* distribute', imp_loc))
286 errors.append("Warning: dependency %r (version %r imported from %r) was not found by pkg_resources."
287 % (name, imp_ver, imp_loc))
290 pr_ver, pr_loc = pkg_resources_vers_and_locs[name]
292 pr_normver = normalized_version(pr_ver)
294 errors.append("Warning: version number %r found for dependency %r by pkg_resources could not be parsed. "
295 "The version found by import was %r from %r. "
296 "pkg_resources thought it should be found at %r. "
297 "The exception was %s: %s"
298 % (pr_ver, name, imp_ver, imp_loc, pr_loc, e.__class__.__name__, e))
300 if imp_ver == 'unknown':
301 if name not in not_import_versionable:
302 errors.append("Warning: unexpectedly could not find a version number for dependency %r imported from %r. "
303 "pkg_resources thought it should be version %r at %r."
304 % (name, imp_loc, pr_ver, pr_loc))
307 imp_normver = normalized_version(imp_ver)
309 errors.append("Warning: version number %r found for dependency %r (imported from %r) could not be parsed. "
310 "pkg_resources thought it should be version %r at %r. "
311 "The exception was %s: %s"
312 % (imp_ver, name, imp_loc, pr_ver, pr_loc, e.__class__.__name__, e))
314 if pr_ver == 'unknown' or (pr_normver != imp_normver):
315 if not os.path.normpath(os.path.realpath(pr_loc)) == os.path.normpath(os.path.realpath(imp_loc)):
316 errors.append("Warning: dependency %r found to have version number %r (normalized to %r, from %r) "
317 "by pkg_resources, but version %r (normalized to %r, from %r) by import."
318 % (name, pr_ver, str(pr_normver), pr_loc, imp_ver, str(imp_normver), imp_loc))
320 imported_packages = set([p.lower() for (p, _) in imported_vers_and_locs_list])
321 for pr_name, (pr_ver, pr_loc) in pkg_resources_vers_and_locs.iteritems():
322 if pr_name not in imported_packages and pr_name not in ignorable:
323 errors.append("Warning: dependency %r (version %r) found by pkg_resources not found by import."
329 def get_error_string(errors, debug=False):
330 from allmydata._auto_deps import install_requires
332 msg = "\n%s\n" % ("\n".join(errors),)
335 "For debugging purposes, the PYTHONPATH was\n"
337 "install_requires was\n"
339 "sys.path after importing pkg_resources was\n"
341 % (os.environ.get('PYTHONPATH'), install_requires, (os.pathsep+"\n ").join(sys.path)) )
344 def check_all_requirements():
345 """This function returns a list of errors due to any failed checks."""
347 from allmydata._auto_deps import install_requires
351 # we require 2.4.4 on non-UCS-2, non-Redhat builds to avoid <http://www.python.org/news/security/PSF-2006-001/>
352 # 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
353 # we require at least 2.4.2 in any case to avoid a bug in the base64 module: <http://bugs.python.org/issue1171487>
354 if sys.maxunicode == 65535:
355 if sys.version_info < (2, 4, 2) or sys.version_info[0] > 2:
356 errors.append("Tahoe-LAFS current requires Python v2.4.2 or greater "
357 "for a UCS-2 build (but less than v3), not %r" %
359 elif platform.platform().lower().find('redhat') >= 0:
360 if sys.version_info < (2, 4, 3) or sys.version_info[0] > 2:
361 errors.append("Tahoe-LAFS current requires Python v2.4.3 or greater "
362 "on Redhat-based distributions (but less than v3), not %r" %
365 if sys.version_info < (2, 4, 4) or sys.version_info[0] > 2:
366 errors.append("Tahoe-LAFS current requires Python v2.4.4 or greater "
367 "for a non-UCS-2 build (but less than v3), not %r" %
370 vers_and_locs = dict(_vers_and_locs_list)
371 for requirement in install_requires:
373 check_requirement(requirement, vers_and_locs)
375 errors.append("%s: %s" % (e.__class__.__name__, e))
378 raise PackagingError(get_error_string(errors, debug=True))
380 check_all_requirements()
383 def get_package_versions():
384 return dict([(k, v) for k, (v, l, c) in _vers_and_locs_list])
386 def get_package_locations():
387 return dict([(k, l) for k, (v, l, c) in _vers_and_locs_list])
389 def get_package_versions_string(show_paths=False, debug=False):
391 for p, (v, loc, comment) in _vers_and_locs_list:
392 info = str(p) + ": " + str(v)
394 info = info + " [%s]" % str(comment)
396 info = info + " (%s)" % str(loc)
399 output = ",\n".join(res) + "\n"
401 if not hasattr(sys, 'frozen'):
402 errors = cross_check_pkg_resources_versus_import()
404 output += get_error_string(errors, debug=debug)