create-bwc-index.py 13 KB

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