create_bwc_index.py 17 KB

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