create_bwc_index.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  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. import argparse
  17. import glob
  18. import logging
  19. import os
  20. import random
  21. import shutil
  22. import subprocess
  23. import sys
  24. import tempfile
  25. import time
  26. DEFAULT_TRANSPORT_TCP_PORT = 9300
  27. DEFAULT_HTTP_TCP_PORT = 9200
  28. if sys.version_info[0] < 3:
  29. print('%s must use python 3.x (for the ES python client)' % sys.argv[0])
  30. from datetime import datetime
  31. try:
  32. from elasticsearch import Elasticsearch
  33. from elasticsearch.exceptions import ConnectionError
  34. from elasticsearch.exceptions import TransportError
  35. except ImportError as e:
  36. print('Can\'t import elasticsearch please install `sudo pip3 install elasticsearch`')
  37. sys.exit(1)
  38. # sometimes returns True
  39. def rarely():
  40. return random.randint(0, 10) == 0
  41. # usually returns True
  42. def frequently():
  43. return not rarely()
  44. # asserts the correctness of the given hits given they are sorted asc
  45. def assert_sort(hits):
  46. values = [hit['sort'] for hit in hits['hits']['hits']]
  47. assert len(values) > 0, 'expected non emtpy result'
  48. val = min(values)
  49. for x in values:
  50. assert x >= val, '%s >= %s' % (x, val)
  51. val = x
  52. # Indexes the given number of document into the given index
  53. # and randomly runs refresh, optimize and flush commands
  54. def index_documents(es, index_name, type, num_docs):
  55. logging.info('Indexing %s docs' % num_docs)
  56. for id in range(0, num_docs):
  57. es.index(index=index_name, doc_type=type, id=id, body={'string': str(random.randint(0, 100)),
  58. 'long_sort': random.randint(0, 100),
  59. 'double_sort' : float(random.randint(0, 100)),
  60. 'bool' : random.choice([True, False])})
  61. if rarely():
  62. es.indices.refresh(index=index_name)
  63. if rarely():
  64. es.indices.flush(index=index_name, force=frequently())
  65. logging.info('Flushing index')
  66. es.indices.flush(index=index_name)
  67. def delete_by_query(es, version, index_name, doc_type):
  68. logging.info('Deleting long_sort:[10..20] docs')
  69. query = {'query':
  70. {'range':
  71. {'long_sort':
  72. {'gte': 10,
  73. 'lte': 20}}}}
  74. if version.startswith('0.') or version in ('1.0.0.Beta1', '1.0.0.Beta2'):
  75. # TODO #10262: we can't write DBQ into the translog for these old versions until we fix this back-compat bug:
  76. # #4074: these versions don't expect to see the top-level 'query' to count/delete_by_query:
  77. query = query['query']
  78. return
  79. deleted_count = es.count(index=index_name, doc_type=doc_type, body=query)['count']
  80. result = es.delete_by_query(index=index_name,
  81. doc_type=doc_type,
  82. body=query)
  83. # make sure no shards failed:
  84. assert result['_indices'][index_name]['_shards']['failed'] == 0, 'delete by query failed: %s' % result
  85. logging.info('Deleted %d docs' % deleted_count)
  86. def run_basic_asserts(es, index_name, type, num_docs):
  87. count = es.count(index=index_name)['count']
  88. assert count == num_docs, 'Expected %r but got %r documents' % (num_docs, count)
  89. for _ in range(0, num_docs):
  90. random_doc_id = random.randint(0, num_docs-1)
  91. doc = es.get(index=index_name, doc_type=type, id=random_doc_id)
  92. assert doc, 'Expected document for id %s but got %s' % (random_doc_id, doc)
  93. assert_sort(es.search(index=index_name,
  94. body={
  95. 'sort': [
  96. {'double_sort': {'order': 'asc'}}
  97. ]
  98. }))
  99. assert_sort(es.search(index=index_name,
  100. body={
  101. 'sort': [
  102. {'long_sort': {'order': 'asc'}}
  103. ]
  104. }))
  105. def build_version(version_tuple):
  106. return '.'.join([str(x) for x in version_tuple])
  107. def build_tuple(version_string):
  108. return [int(x) for x in version_string.split('.')]
  109. def start_node(version, release_dir, data_dir, repo_dir, tcp_port=DEFAULT_TRANSPORT_TCP_PORT, http_port=DEFAULT_HTTP_TCP_PORT, cluster_name=None):
  110. logging.info('Starting node from %s on port %s/%s, data_dir %s' % (release_dir, tcp_port, http_port, data_dir))
  111. if cluster_name is None:
  112. cluster_name = 'bwc_index_' + version
  113. cmd = [
  114. os.path.join(release_dir, 'bin/elasticsearch'),
  115. '-Des.path.data=%s' % data_dir,
  116. '-Des.path.logs=logs',
  117. '-Des.cluster.name=%s' % cluster_name,
  118. '-Des.network.host=localhost',
  119. '-Des.discovery.zen.ping.multicast.enabled=false',
  120. '-Des.transport.tcp.port=%s' % tcp_port,
  121. '-Des.http.port=%s' % http_port,
  122. '-Des.path.repo=%s' % repo_dir
  123. ]
  124. if version.startswith('0.') or version.startswith('1.0.0.Beta') :
  125. cmd.append('-f') # version before 1.0 start in background automatically
  126. return subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  127. def create_client(http_port=DEFAULT_HTTP_TCP_PORT, timeout=30):
  128. logging.info('Waiting for node to startup')
  129. for _ in range(0, timeout):
  130. # TODO: ask Honza if there is a better way to do this?
  131. try:
  132. client = Elasticsearch([{'host': '127.0.0.1', 'port': http_port}])
  133. client.cluster.health(wait_for_nodes=1)
  134. client.count() # can we actually search or do we get a 503? -- anyway retry
  135. return client
  136. except (ConnectionError, TransportError):
  137. pass
  138. time.sleep(1)
  139. assert False, 'Timed out waiting for node for %s seconds' % timeout
  140. def generate_index(client, version, index_name):
  141. client.indices.delete(index=index_name, ignore=404)
  142. logging.info('Create single shard test index')
  143. mappings = {}
  144. if not version.startswith('2.'):
  145. # TODO: we need better "before/onOr/after" logic in python
  146. # backcompat test for legacy type level analyzer settings, see #8874
  147. mappings['analyzer_type1'] = {
  148. 'analyzer': 'standard',
  149. 'properties': {
  150. 'string_with_index_analyzer': {
  151. 'type': 'string',
  152. 'index_analyzer': 'standard'
  153. },
  154. }
  155. }
  156. # completion type was added in 0.90.3
  157. if not version.startswith('0.20') and version not in ['0.90.0.Beta1', '0.90.0.RC1', '0.90.0.RC2', '0.90.0', '0.90.1', '0.90.2']:
  158. mappings['analyzer_type1']['properties']['completion_with_index_analyzer'] = {
  159. 'type': 'completion',
  160. 'index_analyzer': 'standard'
  161. }
  162. mappings['analyzer_type2'] = {
  163. 'index_analyzer': 'standard',
  164. 'search_analyzer': 'keyword',
  165. 'search_quote_analyzer': 'english',
  166. }
  167. mappings['index_name_and_path'] = {
  168. 'properties': {
  169. 'parent_multi_field': {
  170. 'type': 'string',
  171. 'path': 'just_name',
  172. 'fields': {
  173. 'raw': {'type': 'string', 'index': 'not_analyzed', 'index_name': 'raw_multi_field'}
  174. }
  175. },
  176. 'field_with_index_name': {
  177. 'type': 'string',
  178. 'index_name': 'custom_index_name_for_field'
  179. }
  180. }
  181. }
  182. mappings['meta_fields'] = {
  183. '_id': {
  184. 'path': 'myid'
  185. },
  186. '_routing': {
  187. 'path': 'myrouting'
  188. },
  189. '_boost': {
  190. 'null_value': 2.0
  191. }
  192. }
  193. mappings['custom_formats'] = {
  194. 'properties': {
  195. 'string_with_custom_postings': {
  196. 'type': 'string',
  197. 'postings_format': 'Lucene41'
  198. },
  199. 'long_with_custom_doc_values': {
  200. 'type': 'long',
  201. 'doc_values_format': 'Lucene42'
  202. }
  203. }
  204. }
  205. mappings['auto_boost'] = {
  206. '_all': {
  207. 'auto_boost': True
  208. }
  209. }
  210. client.indices.create(index=index_name, body={
  211. 'settings': {
  212. 'number_of_shards': 1,
  213. 'number_of_replicas': 0,
  214. # Same as ES default (60 seconds), but missing the units to make sure they are inserted on upgrade:
  215. "gc_deletes": '60000',
  216. # Same as ES default (5 GB), but missing the units to make sure they are inserted on upgrade:
  217. "merge.policy.max_merged_segment": '5368709120'
  218. },
  219. 'mappings': mappings
  220. })
  221. health = client.cluster.health(wait_for_status='green', wait_for_relocating_shards=0)
  222. assert health['timed_out'] == False, 'cluster health timed out %s' % health
  223. num_docs = random.randint(2000, 3000)
  224. if version == "1.1.0":
  225. # 1.1.0 is buggy and creates lots and lots of segments, so we create a
  226. # lighter index for it to keep bw tests reasonable
  227. # see https://github.com/elastic/elasticsearch/issues/5817
  228. num_docs = int(num_docs / 10)
  229. index_documents(client, index_name, 'doc', num_docs)
  230. logging.info('Running basic asserts on the data added')
  231. run_basic_asserts(client, index_name, 'doc', num_docs)
  232. def snapshot_index(client, version, repo_dir):
  233. # Add bogus persistent settings to make sure they can be restored
  234. client.cluster.put_settings(body={
  235. 'persistent': {
  236. 'cluster.routing.allocation.exclude.version_attr': version,
  237. # Same as ES default (30 seconds), but missing the units to make sure they are inserted on upgrade:
  238. 'discovery.zen.publish_timeout': '30000',
  239. # Same as ES default (512 KB), but missing the units to make sure they are inserted on upgrade:
  240. 'indices.recovery.file_chunk_size': '524288',
  241. }
  242. })
  243. client.indices.put_template(name='template_' + version.lower(), order=0, body={
  244. "template": "te*",
  245. "settings": {
  246. "number_of_shards" : 1
  247. },
  248. "mappings": {
  249. "type1": {
  250. "_source": { "enabled" : False }
  251. }
  252. },
  253. "aliases": {
  254. "alias1": {},
  255. "alias2": {
  256. "filter": {
  257. "term": {"version" : version }
  258. },
  259. "routing": "kimchy"
  260. },
  261. "{index}-alias": {}
  262. }
  263. })
  264. client.snapshot.create_repository(repository='test_repo', body={
  265. 'type': 'fs',
  266. 'settings': {
  267. 'location': repo_dir
  268. }
  269. })
  270. client.snapshot.create(repository='test_repo', snapshot='test_1', wait_for_completion=True)
  271. client.snapshot.delete_repository(repository='test_repo')
  272. def compress_index(version, tmp_dir, output_dir):
  273. compress(tmp_dir, output_dir, 'index-%s.zip' % version, 'data')
  274. def compress_repo(version, tmp_dir, output_dir):
  275. compress(tmp_dir, output_dir, 'repo-%s.zip' % version, 'repo')
  276. def compress(tmp_dir, output_dir, zipfile, directory):
  277. abs_output_dir = os.path.abspath(output_dir)
  278. zipfile = os.path.join(abs_output_dir, zipfile)
  279. if os.path.exists(zipfile):
  280. os.remove(zipfile)
  281. logging.info('Compressing index into %s, tmpDir %s', zipfile, tmp_dir)
  282. olddir = os.getcwd()
  283. os.chdir(tmp_dir)
  284. subprocess.check_call('zip -r %s %s' % (zipfile, directory), shell=True)
  285. os.chdir(olddir)
  286. def parse_config():
  287. parser = argparse.ArgumentParser(description='Builds an elasticsearch index for backwards compatibility tests')
  288. required = parser.add_mutually_exclusive_group(required=True)
  289. required.add_argument('versions', metavar='X.Y.Z', nargs='*', default=[],
  290. help='The elasticsearch version to build an index for')
  291. required.add_argument('--all', action='store_true', default=False,
  292. help='Recreate all existing backwards compatibility indexes')
  293. parser.add_argument('--releases-dir', '-d', default='backwards', metavar='DIR',
  294. help='The directory containing elasticsearch releases')
  295. parser.add_argument('--output-dir', '-o', default='core/src/test/resources/org/elasticsearch/bwcompat',
  296. help='The directory to write the zipped index into')
  297. parser.add_argument('--tcp-port', default=DEFAULT_TRANSPORT_TCP_PORT, type=int,
  298. help='The port to use as the minimum port for TCP communication')
  299. parser.add_argument('--http-port', default=DEFAULT_HTTP_TCP_PORT, type=int,
  300. help='The port to use as the minimum port for HTTP communication')
  301. cfg = parser.parse_args()
  302. if not os.path.exists(cfg.output_dir):
  303. parser.error('Output directory does not exist: %s' % cfg.output_dir)
  304. if not cfg.versions:
  305. # --all
  306. for bwc_index in glob.glob(os.path.join(cfg.output_dir, 'index-*.zip')):
  307. version = os.path.basename(bwc_index)[len('index-'):-len('.zip')]
  308. cfg.versions.append(version)
  309. return cfg
  310. def create_bwc_index(cfg, version):
  311. logging.info('--> Creating bwc index for %s' % version)
  312. release_dir = os.path.join(cfg.releases_dir, 'elasticsearch-%s' % version)
  313. if not os.path.exists(release_dir):
  314. raise RuntimeError('ES version %s does not exist in %s' % (version, cfg.releases_dir))
  315. snapshot_supported = not (version.startswith('0.') or version == '1.0.0.Beta1')
  316. tmp_dir = tempfile.mkdtemp()
  317. data_dir = os.path.join(tmp_dir, 'data')
  318. repo_dir = os.path.join(tmp_dir, 'repo')
  319. logging.info('Temp data dir: %s' % data_dir)
  320. logging.info('Temp repo dir: %s' % repo_dir)
  321. node = None
  322. try:
  323. node = start_node(version, release_dir, data_dir, repo_dir, cfg.tcp_port, cfg.http_port)
  324. client = create_client(cfg.http_port)
  325. index_name = 'index-%s' % version.lower()
  326. generate_index(client, version, index_name)
  327. if snapshot_supported:
  328. snapshot_index(client, version, repo_dir)
  329. # 10067: get a delete-by-query into the translog on upgrade. We must do
  330. # this after the snapshot, because it calls flush. Otherwise the index
  331. # will already have the deletions applied on upgrade.
  332. delete_by_query(client, version, index_name, 'doc')
  333. shutdown_node(node)
  334. node = None
  335. compress_index(version, tmp_dir, cfg.output_dir)
  336. if snapshot_supported:
  337. compress_repo(version, tmp_dir, cfg.output_dir)
  338. finally:
  339. if node is not None:
  340. # This only happens if we've hit an exception:
  341. shutdown_node(node)
  342. shutil.rmtree(tmp_dir)
  343. def shutdown_node(node):
  344. logging.info('Shutting down node with pid %d', node.pid)
  345. node.terminate()
  346. node.wait()
  347. def main():
  348. logging.basicConfig(format='[%(levelname)s] [%(asctime)s] %(message)s', level=logging.INFO,
  349. datefmt='%Y-%m-%d %I:%M:%S %p')
  350. logging.getLogger('elasticsearch').setLevel(logging.ERROR)
  351. logging.getLogger('urllib3').setLevel(logging.WARN)
  352. cfg = parse_config()
  353. for version in cfg.versions:
  354. create_bwc_index(cfg, version)
  355. if __name__ == '__main__':
  356. try:
  357. main()
  358. except KeyboardInterrupt:
  359. print('Caught keyboard interrupt, exiting...')