Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.

bootstrap.py 8.1 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. #!/usr/bin/env python
  2. # Copyright 2014 The Chromium Authors. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. # Modified from go/bootstrap.py in Chromium infrastructure's repository to patch
  6. # out everything but the core toolchain.
  7. #
  8. # https://chromium.googlesource.com/infra/infra/
  9. """Prepares a local hermetic Go installation.
  10. - Downloads and unpacks the Go toolset in ../golang.
  11. """
  12. import contextlib
  13. import logging
  14. import os
  15. import platform
  16. import shutil
  17. import stat
  18. import subprocess
  19. import sys
  20. import tarfile
  21. import tempfile
  22. import urllib
  23. import zipfile
  24. # TODO(vadimsh): Migrate to new golang.org/x/ paths once Golang moves to
  25. # git completely.
  26. LOGGER = logging.getLogger(__name__)
  27. # /path/to/util/bot
  28. ROOT = os.path.dirname(os.path.abspath(__file__))
  29. # Where to install Go toolset to. GOROOT would be <TOOLSET_ROOT>/go.
  30. TOOLSET_ROOT = os.path.join(os.path.dirname(ROOT), 'golang')
  31. # Default workspace with infra go code.
  32. WORKSPACE = os.path.join(ROOT, 'go')
  33. # Platform depended suffix for executable files.
  34. EXE_SFX = '.exe' if sys.platform == 'win32' else ''
  35. # Pinned version of Go toolset to download.
  36. TOOLSET_VERSION = 'go1.4'
  37. # Platform dependent portion of a download URL. See http://golang.org/dl/.
  38. TOOLSET_VARIANTS = {
  39. ('darwin', 'x86-32'): 'darwin-386-osx10.8.tar.gz',
  40. ('darwin', 'x86-64'): 'darwin-amd64-osx10.8.tar.gz',
  41. ('linux2', 'x86-32'): 'linux-386.tar.gz',
  42. ('linux2', 'x86-64'): 'linux-amd64.tar.gz',
  43. ('win32', 'x86-32'): 'windows-386.zip',
  44. ('win32', 'x86-64'): 'windows-amd64.zip',
  45. }
  46. # Download URL root.
  47. DOWNLOAD_URL_PREFIX = 'https://storage.googleapis.com/golang'
  48. class Failure(Exception):
  49. """Bootstrap failed."""
  50. def get_toolset_url():
  51. """URL of a platform specific Go toolset archive."""
  52. # TODO(vadimsh): Support toolset for cross-compilation.
  53. arch = {
  54. 'amd64': 'x86-64',
  55. 'x86_64': 'x86-64',
  56. 'i386': 'x86-32',
  57. 'x86': 'x86-32',
  58. }.get(platform.machine().lower())
  59. variant = TOOLSET_VARIANTS.get((sys.platform, arch))
  60. if not variant:
  61. # TODO(vadimsh): Compile go lang from source.
  62. raise Failure('Unrecognized platform')
  63. return '%s/%s.%s' % (DOWNLOAD_URL_PREFIX, TOOLSET_VERSION, variant)
  64. def read_file(path):
  65. """Returns contents of a given file or None if not readable."""
  66. assert isinstance(path, (list, tuple))
  67. try:
  68. with open(os.path.join(*path), 'r') as f:
  69. return f.read()
  70. except IOError:
  71. return None
  72. def write_file(path, data):
  73. """Writes |data| to a file."""
  74. assert isinstance(path, (list, tuple))
  75. with open(os.path.join(*path), 'w') as f:
  76. f.write(data)
  77. def remove_directory(path):
  78. """Recursively removes a directory."""
  79. assert isinstance(path, (list, tuple))
  80. p = os.path.join(*path)
  81. if not os.path.exists(p):
  82. return
  83. LOGGER.info('Removing %s', p)
  84. # Crutch to remove read-only file (.git/* in particular) on Windows.
  85. def onerror(func, path, _exc_info):
  86. if not os.access(path, os.W_OK):
  87. os.chmod(path, stat.S_IWUSR)
  88. func(path)
  89. else:
  90. raise
  91. shutil.rmtree(p, onerror=onerror if sys.platform == 'win32' else None)
  92. def install_toolset(toolset_root, url):
  93. """Downloads and installs Go toolset.
  94. GOROOT would be <toolset_root>/go/.
  95. """
  96. if not os.path.exists(toolset_root):
  97. os.makedirs(toolset_root)
  98. pkg_path = os.path.join(toolset_root, url[url.rfind('/')+1:])
  99. LOGGER.info('Downloading %s...', url)
  100. download_file(url, pkg_path)
  101. LOGGER.info('Extracting...')
  102. if pkg_path.endswith('.zip'):
  103. with zipfile.ZipFile(pkg_path, 'r') as f:
  104. f.extractall(toolset_root)
  105. elif pkg_path.endswith('.tar.gz'):
  106. with tarfile.open(pkg_path, 'r:gz') as f:
  107. f.extractall(toolset_root)
  108. else:
  109. raise Failure('Unrecognized archive format')
  110. LOGGER.info('Validating...')
  111. if not check_hello_world(toolset_root):
  112. raise Failure('Something is not right, test program doesn\'t work')
  113. def download_file(url, path):
  114. """Fetches |url| to |path|."""
  115. last_progress = [0]
  116. def report(a, b, c):
  117. progress = int(a * b * 100.0 / c)
  118. if progress != last_progress[0]:
  119. print >> sys.stderr, 'Downloading... %d%%' % progress
  120. last_progress[0] = progress
  121. # TODO(vadimsh): Use something less crippled, something that validates SSL.
  122. urllib.urlretrieve(url, path, reporthook=report)
  123. @contextlib.contextmanager
  124. def temp_dir(path):
  125. """Creates a temporary directory, then deletes it."""
  126. tmp = tempfile.mkdtemp(dir=path)
  127. try:
  128. yield tmp
  129. finally:
  130. remove_directory([tmp])
  131. def check_hello_world(toolset_root):
  132. """Compiles and runs 'hello world' program to verify that toolset works."""
  133. with temp_dir(toolset_root) as tmp:
  134. path = os.path.join(tmp, 'hello.go')
  135. write_file([path], r"""
  136. package main
  137. func main() { println("hello, world\n") }
  138. """)
  139. out = subprocess.check_output(
  140. [get_go_exe(toolset_root), 'run', path],
  141. env=get_go_environ(toolset_root, tmp),
  142. stderr=subprocess.STDOUT)
  143. if out.strip() != 'hello, world':
  144. LOGGER.error('Failed to run sample program:\n%s', out)
  145. return False
  146. return True
  147. def ensure_toolset_installed(toolset_root):
  148. """Installs or updates Go toolset if necessary.
  149. Returns True if new toolset was installed.
  150. """
  151. installed = read_file([toolset_root, 'INSTALLED_TOOLSET'])
  152. available = get_toolset_url()
  153. if installed == available:
  154. LOGGER.debug('Go toolset is up-to-date: %s', TOOLSET_VERSION)
  155. return False
  156. LOGGER.info('Installing Go toolset.')
  157. LOGGER.info(' Old toolset is %s', installed)
  158. LOGGER.info(' New toolset is %s', available)
  159. remove_directory([toolset_root])
  160. install_toolset(toolset_root, available)
  161. LOGGER.info('Go toolset installed: %s', TOOLSET_VERSION)
  162. write_file([toolset_root, 'INSTALLED_TOOLSET'], available)
  163. return True
  164. def get_go_environ(
  165. toolset_root,
  166. workspace=None):
  167. """Returns a copy of os.environ with added GO* environment variables.
  168. Overrides GOROOT, GOPATH and GOBIN. Keeps everything else. Idempotent.
  169. Args:
  170. toolset_root: GOROOT would be <toolset_root>/go.
  171. workspace: main workspace directory or None if compiling in GOROOT.
  172. """
  173. env = os.environ.copy()
  174. env['GOROOT'] = os.path.join(toolset_root, 'go')
  175. if workspace:
  176. env['GOBIN'] = os.path.join(workspace, 'bin')
  177. else:
  178. env.pop('GOBIN', None)
  179. all_go_paths = []
  180. if workspace:
  181. all_go_paths.append(workspace)
  182. env['GOPATH'] = os.pathsep.join(all_go_paths)
  183. # New PATH entries.
  184. paths_to_add = [
  185. os.path.join(env['GOROOT'], 'bin'),
  186. env.get('GOBIN'),
  187. ]
  188. # Make sure not to add duplicates entries to PATH over and over again when
  189. # get_go_environ is invoked multiple times.
  190. path = env['PATH'].split(os.pathsep)
  191. paths_to_add = [p for p in paths_to_add if p and p not in path]
  192. env['PATH'] = os.pathsep.join(paths_to_add + path)
  193. return env
  194. def get_go_exe(toolset_root):
  195. """Returns path to go executable."""
  196. return os.path.join(toolset_root, 'go', 'bin', 'go' + EXE_SFX)
  197. def bootstrap(logging_level):
  198. """Installs all dependencies in default locations.
  199. Supposed to be called at the beginning of some script (it modifies logger).
  200. Args:
  201. logging_level: logging level of bootstrap process.
  202. """
  203. logging.basicConfig()
  204. LOGGER.setLevel(logging_level)
  205. ensure_toolset_installed(TOOLSET_ROOT)
  206. def prepare_go_environ():
  207. """Returns dict with environment variables to set to use Go toolset.
  208. Installs or updates the toolset if necessary.
  209. """
  210. bootstrap(logging.INFO)
  211. return get_go_environ(TOOLSET_ROOT, WORKSPACE)
  212. def find_executable(name, workspaces):
  213. """Returns full path to an executable in some bin/ (in GOROOT or GOBIN)."""
  214. basename = name
  215. if EXE_SFX and basename.endswith(EXE_SFX):
  216. basename = basename[:-len(EXE_SFX)]
  217. roots = [os.path.join(TOOLSET_ROOT, 'go', 'bin')]
  218. for path in workspaces:
  219. roots.extend([
  220. os.path.join(path, 'bin'),
  221. ])
  222. for root in roots:
  223. full_path = os.path.join(root, basename + EXE_SFX)
  224. if os.path.exists(full_path):
  225. return full_path
  226. return name
  227. def main(args):
  228. if args:
  229. print >> sys.stderr, sys.modules[__name__].__doc__,
  230. return 2
  231. bootstrap(logging.DEBUG)
  232. return 0
  233. if __name__ == '__main__':
  234. sys.exit(main(sys.argv[1:]))