smoke_test_rc.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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. import signal
  46. import shutil
  47. import urllib
  48. import urllib.request
  49. import hashlib
  50. import time
  51. import socket
  52. import json
  53. import base64
  54. from urllib.parse import urlparse
  55. from prepare_release_candidate import run
  56. from http.client import HTTPConnection
  57. DEFAULT_PLUGINS = ["analysis-icu",
  58. "analysis-kuromoji",
  59. "analysis-phonetic",
  60. "analysis-smartcn",
  61. "analysis-stempel",
  62. "discovery-azure-classic",
  63. "discovery-ec2",
  64. "discovery-gce",
  65. "ingest-attachment",
  66. "ingest-geoip",
  67. "lang-javascript",
  68. "lang-python",
  69. "mapper-attachments",
  70. "mapper-murmur3",
  71. "mapper-size",
  72. "repository-azure",
  73. "repository-gcs",
  74. "repository-hdfs",
  75. "repository-s3",
  76. "store-smb"]
  77. try:
  78. JAVA_HOME = os.environ['JAVA_HOME']
  79. except KeyError:
  80. raise RuntimeError("""
  81. Please set JAVA_HOME in the env before running release tool
  82. On OSX use: export JAVA_HOME=`/usr/libexec/java_home -v '1.8*'`""")
  83. def java_exe():
  84. path = JAVA_HOME
  85. return 'export JAVA_HOME="%s" PATH="%s/bin:$PATH" JAVACMD="%s/bin/java"' % (path, path, path)
  86. def verify_java_version(version):
  87. s = os.popen('%s; java -version 2>&1' % java_exe()).read()
  88. if ' version "%s.' % version not in s:
  89. raise RuntimeError('got wrong version for java %s:\n%s' % (version, s))
  90. def sha1(file):
  91. with open(file, 'rb') as f:
  92. return hashlib.sha1(f.read()).hexdigest()
  93. def read_fully(file):
  94. with open(file, encoding='utf-8') as f:
  95. return f.read()
  96. def wait_for_node_startup(es_dir, timeout=60, header={}):
  97. print(' Waiting until node becomes available for at most %s seconds' % timeout)
  98. for _ in range(timeout):
  99. conn = None
  100. try:
  101. time.sleep(1)
  102. host = get_host_from_ports_file(es_dir)
  103. conn = HTTPConnection(host, timeout=1)
  104. conn.request('GET', '/', headers=header)
  105. res = conn.getresponse()
  106. if res.status == 200:
  107. return True
  108. except IOError as e:
  109. pass
  110. #that is ok it might not be there yet
  111. finally:
  112. if conn:
  113. conn.close()
  114. return False
  115. def download_and_verify(version, hash, files, base_url, plugins=DEFAULT_PLUGINS):
  116. print('Downloading and verifying release %s from %s' % (version, base_url))
  117. tmp_dir = tempfile.mkdtemp()
  118. try:
  119. downloaded_files = []
  120. print(' ' + '*' * 80)
  121. for file in files:
  122. name = os.path.basename(file)
  123. print(' Smoketest file: %s' % name)
  124. url = '%s/%s' % (base_url, file)
  125. print(' Downloading %s' % (url))
  126. artifact_path = os.path.join(tmp_dir, file)
  127. downloaded_files.append(artifact_path)
  128. current_artifact_dir = os.path.dirname(artifact_path)
  129. os.makedirs(current_artifact_dir)
  130. urllib.request.urlretrieve(url, os.path.join(tmp_dir, file))
  131. sha1_url = ''.join([url, '.sha1'])
  132. checksum_file = artifact_path + ".sha1"
  133. print(' Downloading %s' % (sha1_url))
  134. urllib.request.urlretrieve(sha1_url, checksum_file)
  135. print(' Verifying checksum %s' % (checksum_file))
  136. expected = read_fully(checksum_file)
  137. actual = sha1(artifact_path)
  138. if expected != actual :
  139. raise RuntimeError('sha1 hash for %s doesn\'t match %s != %s' % (name, expected, actual))
  140. gpg_url = ''.join([url, '.asc'])
  141. gpg_file = artifact_path + ".asc"
  142. print(' Downloading %s' % (gpg_url))
  143. urllib.request.urlretrieve(gpg_url, gpg_file)
  144. print(' Verifying gpg signature %s' % (gpg_file))
  145. # here we create a temp gpg home where we download the release key as the only key into
  146. # when we verify the signature it will fail if the signed key is not in the keystore and that
  147. # way we keep the executing host unmodified since we don't have to import the key into the default keystore
  148. gpg_home_dir = os.path.join(current_artifact_dir, "gpg_home_dir")
  149. os.makedirs(gpg_home_dir, 0o700)
  150. run('gpg --homedir %s --keyserver pool.sks-keyservers.net --recv-key D88E42B4' % gpg_home_dir)
  151. run('cd %s && gpg --homedir %s --verify %s' % (current_artifact_dir, gpg_home_dir, os.path.basename(gpg_file)))
  152. print(' ' + '*' * 80)
  153. print()
  154. smoke_test_release(version, downloaded_files, hash, plugins)
  155. print(' SUCCESS')
  156. finally:
  157. shutil.rmtree(tmp_dir)
  158. def get_host_from_ports_file(es_dir):
  159. return read_fully(os.path.join(es_dir, 'logs/http.ports')).splitlines()[0]
  160. def smoke_test_release(release, files, expected_hash, plugins):
  161. for release_file in files:
  162. if not os.path.isfile(release_file):
  163. raise RuntimeError('Smoketest failed missing file %s' % (release_file))
  164. tmp_dir = tempfile.mkdtemp()
  165. if release_file.endswith('tar.gz'):
  166. run('tar -xzf %s -C %s' % (release_file, tmp_dir))
  167. elif release_file.endswith('zip'):
  168. run('unzip %s -d %s' % (release_file, tmp_dir))
  169. else:
  170. print(' Skip SmokeTest for [%s]' % release_file)
  171. continue # nothing to do here
  172. es_dir = os.path.join(tmp_dir, 'elasticsearch-%s' % (release))
  173. es_run_path = os.path.join(es_dir, 'bin/elasticsearch')
  174. print(' Smoke testing package [%s]' % release_file)
  175. es_plugin_path = os.path.join(es_dir, 'bin/elasticsearch-plugin')
  176. plugin_names = {}
  177. for plugin in plugins:
  178. print(' Install plugin [%s]' % (plugin))
  179. run('%s; export ES_JAVA_OPTS="-Des.plugins.staging=%s"; %s %s %s' % (java_exe(), expected_hash, es_plugin_path, 'install -b', plugin))
  180. plugin_names[plugin] = True
  181. if 'x-pack' in plugin_names:
  182. headers = { 'Authorization' : 'Basic %s' % base64.b64encode(b"es_admin:foobar").decode("UTF-8") }
  183. es_shield_path = os.path.join(es_dir, 'bin/x-pack/users')
  184. print(" Install dummy shield user")
  185. run('%s; %s useradd es_admin -r superuser -p foobar' % (java_exe(), es_shield_path))
  186. else:
  187. headers = {}
  188. print(' Starting elasticsearch deamon from [%s]' % es_dir)
  189. try:
  190. run('%s; %s -Enode.name=smoke_tester -Ecluster.name=prepare_release -Escript.inline=true -Escript.stored=true -Erepositories.url.allowed_urls=http://snapshot.test* %s -Epidfile=%s -Enode.portsfile=true'
  191. % (java_exe(), es_run_path, '-d', os.path.join(es_dir, 'es-smoke.pid')))
  192. if not wait_for_node_startup(es_dir, header=headers):
  193. print("elasticsearch logs:")
  194. print('*' * 80)
  195. logs = read_fully(os.path.join(es_dir, 'logs/prepare_release.log'))
  196. print(logs)
  197. print('*' * 80)
  198. raise RuntimeError('server didn\'t start up')
  199. try: # we now get / and /_nodes to fetch basic infos like hashes etc and the installed plugins
  200. host = get_host_from_ports_file(es_dir)
  201. conn = HTTPConnection(host, timeout=20)
  202. conn.request('GET', '/', headers=headers)
  203. res = conn.getresponse()
  204. if res.status == 200:
  205. version = json.loads(res.read().decode("utf-8"))['version']
  206. if release != version['number']:
  207. raise RuntimeError('Expected version [%s] but was [%s]' % (release, version['number']))
  208. if version['build_snapshot']:
  209. raise RuntimeError('Expected non snapshot version')
  210. if expected_hash != version['build_hash'].strip():
  211. raise RuntimeError('HEAD hash does not match expected [%s] but got [%s]' % (expected_hash, version['build_hash']))
  212. print(' Verify if plugins are listed in _nodes')
  213. conn.request('GET', '/_nodes?plugin=true&pretty=true', headers=headers)
  214. res = conn.getresponse()
  215. if res.status == 200:
  216. nodes = json.loads(res.read().decode("utf-8"))['nodes']
  217. for _, node in nodes.items():
  218. node_plugins = node['plugins']
  219. for node_plugin in node_plugins:
  220. if not plugin_names.get(node_plugin['name'].strip(), False):
  221. raise RuntimeError('Unexpected plugin %s' % node_plugin['name'])
  222. del plugin_names[node_plugin['name']]
  223. if plugin_names:
  224. raise RuntimeError('Plugins not loaded %s' % list(plugin_names.keys()))
  225. else:
  226. raise RuntimeError('Expected HTTP 200 but got %s' % res.status)
  227. else:
  228. raise RuntimeError('Expected HTTP 200 but got %s' % res.status)
  229. finally:
  230. conn.close()
  231. finally:
  232. pid_path = os.path.join(es_dir, 'es-smoke.pid')
  233. if os.path.exists(pid_path): # try reading the pid and kill the node
  234. pid = int(read_fully(pid_path))
  235. os.kill(pid, signal.SIGKILL)
  236. shutil.rmtree(tmp_dir)
  237. print(' ' + '*' * 80)
  238. print()
  239. def parse_list(string):
  240. return [x.strip() for x in string.split(',')]
  241. if __name__ == "__main__":
  242. parser = argparse.ArgumentParser(description='SmokeTests a Release Candidate from S3 staging repo')
  243. parser.add_argument('--version', '-v', dest='version', default=None,
  244. help='The Elasticsearch Version to smoke-tests', required=True)
  245. parser.add_argument('--hash', '-s', dest='hash', default=None, required=True,
  246. help='The sha1 short hash of the git commit to smoketest')
  247. parser.add_argument('--plugins', '-p', dest='plugins', default=[], required=False, type=parse_list,
  248. help='A list of additional plugins to smoketest')
  249. parser.add_argument('--fetch_url', '-u', dest='url', default=None,
  250. help='Fetched from the specified URL')
  251. parser.set_defaults(hash=None)
  252. parser.set_defaults(plugins=[])
  253. parser.set_defaults(version=None)
  254. parser.set_defaults(url=None)
  255. args = parser.parse_args()
  256. plugins = args.plugins
  257. version = args.version
  258. hash = args.hash
  259. url = args.url
  260. files = [ x % {'version': version} for x in [
  261. 'org/elasticsearch/distribution/tar/elasticsearch/%(version)s/elasticsearch-%(version)s.tar.gz',
  262. 'org/elasticsearch/distribution/zip/elasticsearch/%(version)s/elasticsearch-%(version)s.zip',
  263. 'org/elasticsearch/distribution/deb/elasticsearch/%(version)s/elasticsearch-%(version)s.deb',
  264. 'org/elasticsearch/distribution/rpm/elasticsearch/%(version)s/elasticsearch-%(version)s.rpm'
  265. ]]
  266. verify_java_version('1.8')
  267. if url:
  268. download_url = url
  269. else:
  270. download_url = '%s/%s-%s' % ('http://download.elasticsearch.org/elasticsearch/staging', version, hash)
  271. download_and_verify(version, hash, files, download_url, plugins=DEFAULT_PLUGINS + plugins)