smoke_test_rc.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. # Licensed to Elasticsearch under one or more contributor
  2. # license agreements. See the NOTICE file distributed with
  3. # this work for additional information regarding copyright
  4. # ownership. Elasticsearch licenses this file to you under
  5. # the Apache License, Version 2.0 (the "License"); you may
  6. # not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing,
  12. # software distributed under the License is distributed on
  13. # an 'AS IS' BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
  14. # either express or implied. See the License for the specific
  15. # language governing permissions and limitations under the License.
  16. # Smoke-tests a release candidate
  17. #
  18. # 1. Downloads the tar.gz, deb, RPM and zip file from the staging URL
  19. # 2. Verifies it's sha1 hashes and GPG signatures against the release key
  20. # 3. Installs all official plugins
  21. # 4. Starts one node for tar.gz and zip packages and checks:
  22. # -- if it runs with Java 1.8
  23. # -- if the build hash given is the one that is returned by the status response
  24. # -- if the build is a release version and not a snapshot version
  25. # -- if all plugins are loaded
  26. # -- if the status response returns the correct version
  27. #
  28. # USAGE:
  29. #
  30. # python3 -B ./dev-tools/smoke_test_rc.py --version 2.0.0-beta1 --hash bfa3e47
  31. #
  32. # to also test other plugins try run
  33. #
  34. # python3 -B ./dev-tools/smoke_test_rc.py --version 2.0.0-beta1 --hash bfa3e47 --plugins license,shield,watcher
  35. #
  36. # Note: Ensure the script is run from the elasticsearch top level directory
  37. #
  38. # For testing a release from sonatype try this:
  39. #
  40. # python3 -B dev-tools/smoke_test_rc.py --version 2.0.0-beta1 --hash bfa3e47 --fetch_url https://oss.sonatype.org/content/repositories/releases/
  41. #
  42. import argparse
  43. import tempfile
  44. import os
  45. from os.path import basename, dirname, isdir, join
  46. import signal
  47. import shutil
  48. import urllib
  49. import urllib.request
  50. import hashlib
  51. import time
  52. import socket
  53. import json
  54. import base64
  55. from urllib.parse import urlparse
  56. from http.client import HTTPConnection
  57. def find_official_plugins():
  58. plugins_dir = join(dirname(dirname(__file__)), 'plugins')
  59. plugins = []
  60. for plugin in os.listdir(plugins_dir):
  61. if isdir(join(plugins_dir, plugin)):
  62. plugins.append(plugin)
  63. return plugins
  64. DEFAULT_PLUGINS = find_official_plugins()
  65. try:
  66. JAVA_HOME = os.environ['JAVA_HOME']
  67. except KeyError:
  68. raise RuntimeError("""
  69. Please set JAVA_HOME in the env before running release tool
  70. On OSX use: export JAVA_HOME=`/usr/libexec/java_home -v '1.8*'`""")
  71. # console colors
  72. COLOR_OK = '\033[92m'
  73. COLOR_END = '\033[0m'
  74. def run(command, env_vars=None):
  75. if env_vars:
  76. for key, value in env_vars.items():
  77. os.putenv(key, value)
  78. print('*** Running: %s%s%s' % (COLOR_OK, command, COLOR_END))
  79. if os.system(command):
  80. raise RuntimeError(' FAILED: %s' % (command))
  81. def java_exe():
  82. path = JAVA_HOME
  83. return 'export JAVA_HOME="%s" PATH="%s/bin:$PATH" JAVACMD="%s/bin/java"' % (path, path, path)
  84. def verify_java_version(version):
  85. s = os.popen('%s; java -version 2>&1' % java_exe()).read()
  86. if ' version "%s.' % version not in s:
  87. raise RuntimeError('got wrong version for java %s:\n%s' % (version, s))
  88. def sha1(file):
  89. with open(file, 'rb') as f:
  90. return hashlib.sha1(f.read()).hexdigest()
  91. def read_fully(file):
  92. with open(file, encoding='utf-8') as f:
  93. return f.read()
  94. def wait_for_node_startup(es_dir, timeout=60, header={}):
  95. print(' Waiting until node becomes available for at most %s seconds' % timeout)
  96. for _ in range(timeout):
  97. conn = None
  98. try:
  99. time.sleep(1)
  100. host = get_host_from_ports_file(es_dir)
  101. conn = HTTPConnection(host, timeout=1)
  102. conn.request('GET', '/', headers=header)
  103. res = conn.getresponse()
  104. if res.status == 200:
  105. return True
  106. except IOError as e:
  107. pass
  108. #that is ok it might not be there yet
  109. finally:
  110. if conn:
  111. conn.close()
  112. return False
  113. def download_and_verify(version, hash, files, base_url, plugins=DEFAULT_PLUGINS):
  114. print('Downloading and verifying release %s from %s' % (version, base_url))
  115. tmp_dir = tempfile.mkdtemp()
  116. try:
  117. downloaded_files = []
  118. print(' ' + '*' * 80)
  119. # here we create a temp gpg home where we download the release key as the only key into
  120. # when we verify the signature it will fail if the signed key is not in the keystore and that
  121. # way we keep the executing host unmodified since we don't have to import the key into the default keystore
  122. gpg_home_dir = os.path.join(tmp_dir, "gpg_home_dir")
  123. os.makedirs(gpg_home_dir, 0o700)
  124. run('gpg --homedir %s --keyserver pool.sks-keyservers.net --recv-key D88E42B4' % gpg_home_dir)
  125. for file in files:
  126. name = os.path.basename(file)
  127. print(' Smoketest file: %s' % name)
  128. url = '%s/%s' % (base_url, file)
  129. print(' Downloading %s' % (url))
  130. artifact_path = os.path.join(tmp_dir, file)
  131. downloaded_files.append(artifact_path)
  132. current_artifact_dir = os.path.dirname(artifact_path)
  133. urllib.request.urlretrieve(url, os.path.join(tmp_dir, file))
  134. sha1_url = ''.join([url, '.sha1'])
  135. checksum_file = artifact_path + ".sha1"
  136. print(' Downloading %s' % (sha1_url))
  137. urllib.request.urlretrieve(sha1_url, checksum_file)
  138. print(' Verifying checksum %s' % (checksum_file))
  139. expected = read_fully(checksum_file)
  140. actual = sha1(artifact_path)
  141. if expected != actual :
  142. raise RuntimeError('sha1 hash for %s doesn\'t match %s != %s' % (name, expected, actual))
  143. gpg_url = ''.join([url, '.asc'])
  144. gpg_file = artifact_path + ".asc"
  145. print(' Downloading %s' % (gpg_url))
  146. urllib.request.urlretrieve(gpg_url, gpg_file)
  147. print(' Verifying gpg signature %s' % (gpg_file))
  148. run('cd %s && gpg --homedir %s --verify %s' % (current_artifact_dir, gpg_home_dir, os.path.basename(gpg_file)))
  149. print(' ' + '*' * 80)
  150. print()
  151. smoke_test_release(version, downloaded_files, hash, plugins)
  152. print(' SUCCESS')
  153. finally:
  154. shutil.rmtree(tmp_dir)
  155. def get_host_from_ports_file(es_dir):
  156. return read_fully(os.path.join(es_dir, 'logs/http.ports')).splitlines()[0]
  157. def smoke_test_release(release, files, hash, plugins):
  158. for release_file in files:
  159. if not os.path.isfile(release_file):
  160. raise RuntimeError('Smoketest failed missing file %s' % (release_file))
  161. tmp_dir = tempfile.mkdtemp()
  162. if release_file.endswith('tar.gz'):
  163. run('tar -xzf %s -C %s' % (release_file, tmp_dir))
  164. elif release_file.endswith('zip'):
  165. run('unzip %s -d %s' % (release_file, tmp_dir))
  166. else:
  167. print(' Skip SmokeTest for [%s]' % release_file)
  168. continue # nothing to do here
  169. es_dir = os.path.join(tmp_dir, 'elasticsearch-%s' % (release))
  170. es_run_path = os.path.join(es_dir, 'bin/elasticsearch')
  171. print(' Smoke testing package [%s]' % release_file)
  172. es_plugin_path = os.path.join(es_dir, 'bin/elasticsearch-plugin')
  173. plugin_names = {}
  174. for plugin in plugins:
  175. print(' Install plugin [%s]' % (plugin))
  176. run('%s; export ES_JAVA_OPTS="-Des.plugins.staging=%s"; %s %s %s' % (java_exe(), hash, es_plugin_path, 'install -b', plugin))
  177. plugin_names[plugin] = True
  178. if 'x-pack' in plugin_names:
  179. headers = { 'Authorization' : 'Basic %s' % base64.b64encode(b"es_admin:foobar").decode("UTF-8") }
  180. es_shield_path = os.path.join(es_dir, 'bin/x-pack/users')
  181. print(" Install dummy shield user")
  182. run('%s; %s useradd es_admin -r superuser -p foobar' % (java_exe(), es_shield_path))
  183. else:
  184. headers = {}
  185. print(' Starting elasticsearch deamon from [%s]' % es_dir)
  186. try:
  187. run('%s; %s -Enode.name=smoke_tester -Ecluster.name=prepare_release -Erepositories.url.allowed_urls=http://snapshot.test* %s -Epidfile=%s -Enode.portsfile=true'
  188. % (java_exe(), es_run_path, '-d', os.path.join(es_dir, 'es-smoke.pid')))
  189. if not wait_for_node_startup(es_dir, header=headers):
  190. print("elasticsearch logs:")
  191. print('*' * 80)
  192. logs = read_fully(os.path.join(es_dir, 'logs/prepare_release.log'))
  193. print(logs)
  194. print('*' * 80)
  195. raise RuntimeError('server didn\'t start up')
  196. try: # we now get / and /_nodes to fetch basic infos like hashes etc and the installed plugins
  197. host = get_host_from_ports_file(es_dir)
  198. conn = HTTPConnection(host, timeout=20)
  199. conn.request('GET', '/', headers=headers)
  200. res = conn.getresponse()
  201. if res.status == 200:
  202. version = json.loads(res.read().decode("utf-8"))['version']
  203. if release != version['number']:
  204. raise RuntimeError('Expected version [%s] but was [%s]' % (release, version['number']))
  205. if version['build_snapshot']:
  206. raise RuntimeError('Expected non snapshot version')
  207. print(' Verify if plugins are listed in _nodes')
  208. conn.request('GET', '/_nodes/plugins?pretty=true', headers=headers)
  209. res = conn.getresponse()
  210. if res.status == 200:
  211. nodes = json.loads(res.read().decode("utf-8"))['nodes']
  212. for _, node in nodes.items():
  213. node_plugins = node['plugins']
  214. for node_plugin in node_plugins:
  215. if not plugin_names.get(node_plugin['name'].strip(), False):
  216. raise RuntimeError('Unexpected plugin %s' % node_plugin['name'])
  217. del plugin_names[node_plugin['name']]
  218. if plugin_names:
  219. raise RuntimeError('Plugins not loaded %s' % list(plugin_names.keys()))
  220. else:
  221. raise RuntimeError('Expected HTTP 200 but got %s' % res.status)
  222. else:
  223. raise RuntimeError('Expected HTTP 200 but got %s' % res.status)
  224. finally:
  225. conn.close()
  226. finally:
  227. pid_path = os.path.join(es_dir, 'es-smoke.pid')
  228. if os.path.exists(pid_path): # try reading the pid and kill the node
  229. pid = int(read_fully(pid_path))
  230. os.kill(pid, signal.SIGKILL)
  231. shutil.rmtree(tmp_dir)
  232. print(' ' + '*' * 80)
  233. print()
  234. def parse_list(string):
  235. return [x.strip() for x in string.split(',')]
  236. if __name__ == "__main__":
  237. parser = argparse.ArgumentParser(description='SmokeTests a Release Candidate from S3 staging repo')
  238. parser.add_argument('--version', '-v', dest='version', default=None,
  239. help='The Elasticsearch Version to smoke-tests', required=True)
  240. parser.add_argument('--hash', '-s', dest='hash', default=None, required=True,
  241. help='The hash of the unified release')
  242. parser.add_argument('--plugins', '-p', dest='plugins', default=[], required=False, type=parse_list,
  243. help='A list of additional plugins to smoketest')
  244. parser.add_argument('--fetch_url', '-u', dest='url', default=None,
  245. help='Fetched from the specified URL')
  246. parser.set_defaults(hash=None)
  247. parser.set_defaults(plugins=[])
  248. parser.set_defaults(version=None)
  249. parser.set_defaults(url=None)
  250. args = parser.parse_args()
  251. plugins = args.plugins
  252. version = args.version
  253. hash = args.hash
  254. url = args.url
  255. files = [ x % {'version': version} for x in [
  256. 'elasticsearch-%(version)s.tar.gz',
  257. 'elasticsearch-%(version)s.zip',
  258. 'elasticsearch-%(version)s.deb',
  259. 'elasticsearch-%(version)s.rpm'
  260. ]]
  261. verify_java_version('1.8')
  262. if url:
  263. download_url = url
  264. else:
  265. download_url = 'https://staging.elastic.co/%s-%s/downloads/elasticsearch' % (version, hash)
  266. download_and_verify(version, hash, files, download_url, plugins=DEFAULT_PLUGINS + plugins)