1
0

build_release.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803
  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 re
  17. import tempfile
  18. import shutil
  19. import os
  20. import datetime
  21. import json
  22. import time
  23. import sys
  24. import argparse
  25. import hmac
  26. import urllib
  27. import fnmatch
  28. import socket
  29. import urllib.request
  30. import subprocess
  31. from functools import partial
  32. from http.client import HTTPConnection
  33. from http.client import HTTPSConnection
  34. """
  35. This tool builds a release from the a given elasticsearch branch.
  36. In order to execute it go in the top level directory and run:
  37. $ python3 dev_tools/build_release.py --branch 0.90 --publish --remote origin
  38. By default this script runs in 'dry' mode which essentially simulates a release. If the
  39. '--publish' option is set the actual release is done. The script takes over almost all
  40. steps necessary for a release from a high level point of view it does the following things:
  41. - run prerequisit checks ie. check for Java 1.7 being presend or S3 credentials available as env variables
  42. - detect the version to release from the specified branch (--branch) or the current branch
  43. - creates a release branch & updates pom.xml and Version.java to point to a release version rather than a snapshot
  44. - builds the artifacts and runs smoke-tests on the build zip & tar.gz files
  45. - commits the new version and merges the release branch into the source branch
  46. - creates a tag and pushes the commit to the specified origin (--remote)
  47. - publishes the releases to Sonatype and S3
  48. Once it's done it will print all the remaining steps.
  49. Prerequisites:
  50. - Python 3k for script execution
  51. - Boto for S3 Upload ($ apt-get install python-boto)
  52. - RPM for RPM building ($ apt-get install rpm)
  53. - S3 keys exported via ENV variables (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)
  54. - GPG data exported via ENV variables (GPG_KEY_ID, GPG_PASSPHRASE, optionally GPG_KEYRING)
  55. - S3 target repository via ENV variables (S3_BUCKET_SYNC_TO, optionally S3_BUCKET_SYNC_FROM)
  56. """
  57. env = os.environ
  58. PLUGINS = [('license', 'elasticsearch/license/latest'),
  59. ('bigdesk', 'lukas-vlcek/bigdesk'),
  60. ('paramedic', 'karmi/elasticsearch-paramedic'),
  61. ('segmentspy', 'polyfractal/elasticsearch-segmentspy'),
  62. ('inquisitor', 'polyfractal/elasticsearch-inquisitor'),
  63. ('head', 'mobz/elasticsearch-head')]
  64. LOG = env.get('ES_RELEASE_LOG', '/tmp/elasticsearch_release.log')
  65. # console colors
  66. COLOR_OK = '\033[92m'
  67. COLOR_END = '\033[0m'
  68. COLOR_FAIL = '\033[91m'
  69. def log(msg):
  70. log_plain('\n%s' % msg)
  71. def log_plain(msg):
  72. f = open(LOG, mode='ab')
  73. f.write(msg.encode('utf-8'))
  74. f.close()
  75. def run(command, quiet=False):
  76. log('%s: RUN: %s\n' % (datetime.datetime.now(), command))
  77. if os.system('%s >> %s 2>&1' % (command, LOG)):
  78. msg = ' FAILED: %s [see log %s]' % (command, LOG)
  79. if not quiet:
  80. print(msg)
  81. raise RuntimeError(msg)
  82. try:
  83. JAVA_HOME = env['JAVA_HOME']
  84. except KeyError:
  85. raise RuntimeError("""
  86. Please set JAVA_HOME in the env before running release tool
  87. On OSX use: export JAVA_HOME=`/usr/libexec/java_home -v '1.7*'`""")
  88. try:
  89. JAVA_HOME = env['JAVA7_HOME']
  90. except KeyError:
  91. pass #no JAVA7_HOME - we rely on JAVA_HOME
  92. try:
  93. # make sure mvn3 is used if mvn3 is available
  94. # some systems use maven 2 as default
  95. subprocess.check_output('mvn3 --version', shell=True, stderr=subprocess.STDOUT)
  96. MVN = 'mvn3'
  97. except subprocess.CalledProcessError:
  98. MVN = 'mvn'
  99. def java_exe():
  100. path = JAVA_HOME
  101. return 'export JAVA_HOME="%s" PATH="%s/bin:$PATH" JAVACMD="%s/bin/java"' % (path, path, path)
  102. def verify_java_version(version):
  103. s = os.popen('%s; java -version 2>&1' % java_exe()).read()
  104. if ' version "%s.' % version not in s:
  105. raise RuntimeError('got wrong version for java %s:\n%s' % (version, s))
  106. # Verifies the java version. We guarantee that we run with Java 1.7
  107. # If 1.7 is not available fail the build!
  108. def verify_mvn_java_version(version, mvn):
  109. s = os.popen('%s; %s --version 2>&1' % (java_exe(), mvn)).read()
  110. if 'Java version: %s' % version not in s:
  111. raise RuntimeError('got wrong java version for %s %s:\n%s' % (mvn, version, s))
  112. # Returns the hash of the current git HEAD revision
  113. def get_head_hash():
  114. return os.popen(' git rev-parse --verify HEAD 2>&1').read().strip()
  115. # Returns the hash of the given tag revision
  116. def get_tag_hash(tag):
  117. return os.popen('git show-ref --tags %s --hash 2>&1' % (tag)).read().strip()
  118. # Returns the name of the current branch
  119. def get_current_branch():
  120. return os.popen('git rev-parse --abbrev-ref HEAD 2>&1').read().strip()
  121. # Utility that returns the name of the release branch for a given version
  122. def release_branch(version):
  123. return 'release_branch_%s' % version
  124. # runs get fetch on the given remote
  125. def fetch(remote):
  126. run('git fetch %s' % remote)
  127. # Creates a new release branch from the given source branch
  128. # and rebases the source branch from the remote before creating
  129. # the release branch. Note: This fails if the source branch
  130. # doesn't exist on the provided remote.
  131. def create_release_branch(remote, src_branch, release):
  132. run('git checkout %s' % src_branch)
  133. run('git pull --rebase %s %s' % (remote, src_branch))
  134. run('git checkout -b %s' % (release_branch(release)))
  135. # Reads the given file and applies the
  136. # callback to it. If the callback changed
  137. # a line the given file is replaced with
  138. # the modified input.
  139. def process_file(file_path, line_callback):
  140. fh, abs_path = tempfile.mkstemp()
  141. modified = False
  142. with open(abs_path,'w', encoding='utf-8') as new_file:
  143. with open(file_path, encoding='utf-8') as old_file:
  144. for line in old_file:
  145. new_line = line_callback(line)
  146. modified = modified or (new_line != line)
  147. new_file.write(new_line)
  148. os.close(fh)
  149. if modified:
  150. #Remove original file
  151. os.remove(file_path)
  152. #Move new file
  153. shutil.move(abs_path, file_path)
  154. return True
  155. else:
  156. # nothing to do - just remove the tmp file
  157. os.remove(abs_path)
  158. return False
  159. # Walks the given directory path (defaults to 'docs')
  160. # and replaces all 'coming[$version]' tags with
  161. # 'added[$version]'. This method only accesses asciidoc files.
  162. def update_reference_docs(release_version, path='docs'):
  163. pattern = 'coming[%s' % (release_version)
  164. replacement = 'added[%s' % (release_version)
  165. pending_files = []
  166. def callback(line):
  167. return line.replace(pattern, replacement)
  168. for root, _, file_names in os.walk(path):
  169. for file_name in fnmatch.filter(file_names, '*.asciidoc'):
  170. full_path = os.path.join(root, file_name)
  171. if process_file(full_path, callback):
  172. pending_files.append(os.path.join(root, file_name))
  173. return pending_files
  174. # Moves the pom.xml file from a snapshot to a release
  175. def remove_maven_snapshot(pom, release):
  176. pattern = '<version>%s-SNAPSHOT</version>' % (release)
  177. replacement = '<version>%s</version>' % (release)
  178. def callback(line):
  179. return line.replace(pattern, replacement)
  180. process_file(pom, callback)
  181. # Moves the Version.java file from a snapshot to a release
  182. def remove_version_snapshot(version_file, release):
  183. # 1.0.0.Beta1 -> 1_0_0_Beta1
  184. release = release.replace('.', '_')
  185. pattern = 'new Version(V_%s_ID, true' % (release)
  186. replacement = 'new Version(V_%s_ID, false' % (release)
  187. def callback(line):
  188. return line.replace(pattern, replacement)
  189. process_file(version_file, callback)
  190. # Stages the given files for the next git commit
  191. def add_pending_files(*files):
  192. for file in files:
  193. run('git add %s' % (file))
  194. # Executes a git commit with 'release [version]' as the commit message
  195. def commit_release(release):
  196. run('git commit -m "release [%s]"' % release)
  197. def commit_feature_flags(release):
  198. run('git commit -m "Update Documentation Feature Flags [%s]"' % release)
  199. def tag_release(release):
  200. run('git tag -a v%s -m "Tag release version %s"' % (release, release))
  201. def run_mvn(*cmd):
  202. for c in cmd:
  203. run('%s; %s %s' % (java_exe(), MVN, c))
  204. def build_release(run_tests=False, dry_run=True, cpus=1, bwc_version=None):
  205. target = 'deploy'
  206. if dry_run:
  207. target = 'package'
  208. if run_tests:
  209. run_mvn('clean',
  210. 'test -Dtests.jvms=%s -Des.node.mode=local' % (cpus),
  211. 'test -Dtests.jvms=%s -Des.node.mode=network' % (cpus))
  212. if bwc_version:
  213. print('Running Backwards compatibility tests against version [%s]' % (bwc_version))
  214. run_mvn('clean', 'test -Dtests.filter=@backwards -Dtests.bwc.version=%s -Dtests.bwc=true -Dtests.jvms=1' % bwc_version)
  215. run_mvn('clean test-compile -Dforbidden.test.signatures="org.apache.lucene.util.LuceneTestCase\$AwaitsFix @ Please fix all bugs before release"')
  216. gpg_args = '-Dgpg.key="%s" -Dgpg.passphrase="%s" -Ddeb.sign=true' % (env.get('GPG_KEY_ID'), env.get('GPG_PASSPHRASE'))
  217. if env.get('GPG_KEYRING'):
  218. gpg_args += ' -Dgpg.keyring="%s"' % env.get('GPG_KEYRING')
  219. run_mvn('clean %s -DskipTests %s' % (target, gpg_args))
  220. success = False
  221. try:
  222. run_mvn('-DskipTests rpm:rpm %s' % (gpg_args))
  223. success = True
  224. finally:
  225. if not success:
  226. print("""
  227. RPM Bulding failed make sure "rpm" tools are installed.
  228. Use on of the following commands to install:
  229. $ brew install rpm # on OSX
  230. $ apt-get install rpm # on Ubuntu et.al
  231. """)
  232. # Uses the github API to fetch open tickets for the given release version
  233. # if it finds any tickets open for that version it will throw an exception
  234. def ensure_no_open_tickets(version):
  235. version = "v%s" % version
  236. conn = HTTPSConnection('api.github.com')
  237. try:
  238. log('Checking for open tickets on Github for version %s' % version)
  239. log('Check if node is available')
  240. conn.request('GET', '/repos/elastic/elasticsearch/issues?state=open&labels=%s' % version, headers= {'User-Agent' : 'Elasticsearch version checker'})
  241. res = conn.getresponse()
  242. if res.status == 200:
  243. issues = json.loads(res.read().decode("utf-8"))
  244. if issues:
  245. urls = []
  246. for issue in issues:
  247. urls.append(issue['html_url'])
  248. raise RuntimeError('Found open issues for release version %s:\n%s' % (version, '\n'.join(urls)))
  249. else:
  250. log("No open issues found for version %s" % version)
  251. else:
  252. raise RuntimeError('Failed to fetch issue list from Github for release version %s' % version)
  253. except socket.error as e:
  254. log("Failed to fetch issue list from Github for release version %s' % version - Exception: [%s]" % (version, e))
  255. #that is ok it might not be there yet
  256. finally:
  257. conn.close()
  258. def wait_for_node_startup(host='127.0.0.1', port=9200,timeout=15):
  259. for _ in range(timeout):
  260. conn = HTTPConnection(host, port, timeout)
  261. try:
  262. log('Waiting until node becomes available for 1 second')
  263. time.sleep(1)
  264. log('Check if node is available')
  265. conn.request('GET', '')
  266. res = conn.getresponse()
  267. if res.status == 200:
  268. return True
  269. except socket.error as e:
  270. log("Failed while waiting for node - Exception: [%s]" % e)
  271. #that is ok it might not be there yet
  272. finally:
  273. conn.close()
  274. return False
  275. # Ensures we are using a true Lucene release, not a snapshot build:
  276. def verify_lucene_version():
  277. s = open('pom.xml', encoding='utf-8').read()
  278. if 'download.elastic.co/lucenesnapshots' in s:
  279. raise RuntimeError('pom.xml contains download.elastic.co/lucenesnapshots repository: remove that before releasing')
  280. m = re.search(r'<lucene.version>(.*?)</lucene.version>', s)
  281. if m is None:
  282. raise RuntimeError('unable to locate lucene.version in pom.xml')
  283. lucene_version = m.group(1)
  284. m = re.search(r'<lucene.maven.version>(.*?)</lucene.maven.version>', s)
  285. if m is None:
  286. raise RuntimeError('unable to locate lucene.maven.version in pom.xml')
  287. lucene_maven_version = m.group(1)
  288. if lucene_version != lucene_maven_version:
  289. raise RuntimeError('pom.xml is still using a snapshot release of lucene (%s): cutover to a real lucene release before releasing' % lucene_maven_version)
  290. # Checks the pom.xml for the release version.
  291. # This method fails if the pom file has no SNAPSHOT version set ie.
  292. # if the version is already on a release version we fail.
  293. # Returns the next version string ie. 0.90.7
  294. def find_release_version(src_branch):
  295. run('git checkout %s' % src_branch)
  296. with open('pom.xml', encoding='utf-8') as file:
  297. for line in file:
  298. match = re.search(r'<version>(.+)-SNAPSHOT</version>', line)
  299. if match:
  300. return match.group(1)
  301. raise RuntimeError('Could not find release version in branch %s' % src_branch)
  302. def artifact_names(release, path = ''):
  303. return [os.path.join(path, 'elasticsearch-%s.%s' % (release, t)) for t in ['deb', 'tar.gz', 'zip']]
  304. def get_artifacts(release):
  305. common_artifacts = artifact_names(release, 'target/releases/')
  306. for f in common_artifacts:
  307. if not os.path.isfile(f):
  308. raise RuntimeError('Could not find required artifact at %s' % f)
  309. rpm = os.path.join('target/rpm/elasticsearch/RPMS/noarch/', 'elasticsearch-%s-1.noarch.rpm' % release)
  310. if os.path.isfile(rpm):
  311. log('RPM [%s] contains: ' % rpm)
  312. run('rpm -pqli %s' % rpm)
  313. # this is an oddness of RPM that is attches -1 so we have to rename it
  314. renamed_rpm = os.path.join('target/rpm/elasticsearch/RPMS/noarch/', 'elasticsearch-%s.noarch.rpm' % release)
  315. shutil.move(rpm, renamed_rpm)
  316. common_artifacts.append(renamed_rpm)
  317. else:
  318. raise RuntimeError('Could not find required artifact at %s' % rpm)
  319. return common_artifacts
  320. # Checks the jar files in each package
  321. # Barfs if any of the package jar files differ
  322. def check_artifacts_for_same_jars(artifacts):
  323. jars = []
  324. for file in artifacts:
  325. if file.endswith('.zip'):
  326. jars.append(subprocess.check_output("unzip -l %s | grep '\.jar$' | awk -F '/' '{ print $NF }' | sort" % file, shell=True))
  327. if file.endswith('.tar.gz'):
  328. jars.append(subprocess.check_output("tar tzvf %s | grep '\.jar$' | awk -F '/' '{ print $NF }' | sort" % file, shell=True))
  329. if file.endswith('.rpm'):
  330. jars.append(subprocess.check_output("rpm -pqli %s | grep '\.jar$' | awk -F '/' '{ print $NF }' | sort" % file, shell=True))
  331. if file.endswith('.deb'):
  332. jars.append(subprocess.check_output("dpkg -c %s | grep '\.jar$' | awk -F '/' '{ print $NF }' | sort" % file, shell=True))
  333. if len(set(jars)) != 1:
  334. raise RuntimeError('JAR contents of packages are not the same, please check the package contents. Use [unzip -l], [tar tzvf], [dpkg -c], [rpm -pqli] to inspect')
  335. # Generates sha1 checsums for all files
  336. # and returns the checksum files as well
  337. # as the given files in a list
  338. def generate_checksums(files):
  339. res = []
  340. for release_file in files:
  341. directory = os.path.dirname(release_file)
  342. file = os.path.basename(release_file)
  343. checksum_file = '%s.sha1.txt' % file
  344. if os.system('cd %s; shasum %s > %s' % (directory, file, checksum_file)):
  345. raise RuntimeError('Failed to generate checksum for file %s' % release_file)
  346. res = res + [os.path.join(directory, checksum_file), release_file]
  347. return res
  348. def download_and_verify(release, files, plugins=None, base_url='https://download.elastic.co/elasticsearch/elasticsearch'):
  349. print('Downloading and verifying release %s from %s' % (release, base_url))
  350. tmp_dir = tempfile.mkdtemp()
  351. try:
  352. downloaded_files = []
  353. for file in files:
  354. name = os.path.basename(file)
  355. url = '%s/%s' % (base_url, name)
  356. abs_file_path = os.path.join(tmp_dir, name)
  357. print(' Downloading %s' % (url))
  358. downloaded_files.append(abs_file_path)
  359. urllib.request.urlretrieve(url, abs_file_path)
  360. url = ''.join([url, '.sha1.txt'])
  361. checksum_file = os.path.join(tmp_dir, ''.join([abs_file_path, '.sha1.txt']))
  362. urllib.request.urlretrieve(url, checksum_file)
  363. print(' Verifying checksum %s' % (checksum_file))
  364. run('cd %s && sha1sum -c %s' % (tmp_dir, os.path.basename(checksum_file)))
  365. smoke_test_release(release, downloaded_files, get_tag_hash('v%s' % release), plugins)
  366. print(' SUCCESS')
  367. finally:
  368. shutil.rmtree(tmp_dir)
  369. def smoke_test_release(release, files, expected_hash, plugins):
  370. for release_file in files:
  371. if not os.path.isfile(release_file):
  372. raise RuntimeError('Smoketest failed missing file %s' % (release_file))
  373. tmp_dir = tempfile.mkdtemp()
  374. if release_file.endswith('tar.gz'):
  375. run('tar -xzf %s -C %s' % (release_file, tmp_dir))
  376. elif release_file.endswith('zip'):
  377. run('unzip %s -d %s' % (release_file, tmp_dir))
  378. else:
  379. log('Skip SmokeTest for [%s]' % release_file)
  380. continue # nothing to do here
  381. es_run_path = os.path.join(tmp_dir, 'elasticsearch-%s' % (release), 'bin/elasticsearch')
  382. print(' Smoke testing package [%s]' % release_file)
  383. es_plugin_path = os.path.join(tmp_dir, 'elasticsearch-%s' % (release),'bin/plugin')
  384. plugin_names = {}
  385. for name, plugin in plugins:
  386. print(' Install plugin [%s] from [%s]' % (name, plugin))
  387. run('%s; %s %s %s' % (java_exe(), es_plugin_path, '-install', plugin))
  388. plugin_names[name] = True
  389. if release.startswith("0.90."):
  390. background = '' # 0.90.x starts in background automatically
  391. else:
  392. background = '-d'
  393. print(' Starting elasticsearch deamon from [%s]' % os.path.join(tmp_dir, 'elasticsearch-%s' % release))
  394. run('%s; %s -Des.node.name=smoke_tester -Des.cluster.name=prepare_release -Des.discovery.zen.ping.multicast.enabled=false -Des.script.inline=on -Des.script.indexed=on %s'
  395. % (java_exe(), es_run_path, background))
  396. conn = HTTPConnection('127.0.0.1', 9200, 20);
  397. wait_for_node_startup()
  398. try:
  399. try:
  400. conn.request('GET', '')
  401. res = conn.getresponse()
  402. if res.status == 200:
  403. version = json.loads(res.read().decode("utf-8"))['version']
  404. if release != version['number']:
  405. raise RuntimeError('Expected version [%s] but was [%s]' % (release, version['number']))
  406. if version['build_snapshot']:
  407. raise RuntimeError('Expected non snapshot version')
  408. if version['build_hash'].strip() != expected_hash:
  409. raise RuntimeError('HEAD hash does not match expected [%s] but got [%s]' % (expected_hash, version['build_hash']))
  410. print(' Running REST Spec tests against package [%s]' % release_file)
  411. run_mvn('test -Dtests.cluster=%s -Dtests.class=*.*RestTests' % ("127.0.0.1:9300"))
  412. print(' Verify if plugins are listed in _nodes')
  413. conn.request('GET', '/_nodes?plugin=true&pretty=true')
  414. res = conn.getresponse()
  415. if res.status == 200:
  416. nodes = json.loads(res.read().decode("utf-8"))['nodes']
  417. for _, node in nodes.items():
  418. node_plugins = node['plugins']
  419. for node_plugin in node_plugins:
  420. if not plugin_names.get(node_plugin['name'], False):
  421. raise RuntimeError('Unexpeced plugin %s' % node_plugin['name'])
  422. del plugin_names[node_plugin['name']]
  423. if plugin_names:
  424. raise RuntimeError('Plugins not loaded %s' % list(plugin_names.keys()))
  425. else:
  426. raise RuntimeError('Expected HTTP 200 but got %s' % res.status)
  427. else:
  428. raise RuntimeError('Expected HTTP 200 but got %s' % res.status)
  429. finally:
  430. conn.request('POST', '/_cluster/nodes/_local/_shutdown')
  431. time.sleep(1) # give the node some time to shut down
  432. if conn.getresponse().status != 200:
  433. raise RuntimeError('Expected HTTP 200 but got %s on node shutdown' % res.status)
  434. finally:
  435. conn.close()
  436. shutil.rmtree(tmp_dir)
  437. def merge_tag_push(remote, src_branch, release_version, dry_run):
  438. run('git checkout %s' % src_branch)
  439. run('git merge %s' % release_branch(release_version))
  440. run('git tag v%s' % release_version)
  441. if not dry_run:
  442. run('git push %s %s' % (remote, src_branch)) # push the commit
  443. run('git push %s v%s' % (remote, release_version)) # push the tag
  444. else:
  445. print(' dryrun [True] -- skipping push to remote %s' % remote)
  446. def publish_artifacts(artifacts, base='elasticsearch/elasticsearch', dry_run=True):
  447. location = os.path.dirname(os.path.realpath(__file__))
  448. for artifact in artifacts:
  449. if dry_run:
  450. print('Skip Uploading %s to Amazon S3' % artifact)
  451. else:
  452. print('Uploading %s to Amazon S3' % artifact)
  453. # requires boto to be installed but it is not available on python3k yet so we use a dedicated tool
  454. run('python %s/upload-s3.py --file %s ' % (location, os.path.abspath(artifact)))
  455. def publish_repositories(version, dry_run=True):
  456. if dry_run:
  457. print('Skipping package repository update')
  458. else:
  459. print('Triggering repository update - calling dev-tools/build_repositories.sh %s' % version)
  460. # src_branch is a version like 1.5/1.6/2.0/etc.. so we can use this
  461. run('dev-tools/build_repositories.sh %s' % src_branch)
  462. def print_sonatype_notice():
  463. settings = os.path.join(os.path.expanduser('~'), '.m2/settings.xml')
  464. if os.path.isfile(settings):
  465. with open(settings, encoding='utf-8') as settings_file:
  466. for line in settings_file:
  467. if line.strip() == '<id>sonatype-nexus-snapshots</id>':
  468. # moving out - we found the indicator no need to print the warning
  469. return
  470. print("""
  471. NOTE: No sonatype settings detected, make sure you have configured
  472. your sonatype credentials in '~/.m2/settings.xml':
  473. <settings>
  474. ...
  475. <servers>
  476. <server>
  477. <id>sonatype-nexus-snapshots</id>
  478. <username>your-jira-id</username>
  479. <password>your-jira-pwd</password>
  480. </server>
  481. <server>
  482. <id>sonatype-nexus-staging</id>
  483. <username>your-jira-id</username>
  484. <password>your-jira-pwd</password>
  485. </server>
  486. </servers>
  487. ...
  488. </settings>
  489. """)
  490. def check_command_exists(name, cmd):
  491. try:
  492. subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT)
  493. except subprocess.CalledProcessError:
  494. raise RuntimeError('Could not run command %s - please make sure it is installed' % (name))
  495. VERSION_FILE = 'src/main/java/org/elasticsearch/Version.java'
  496. POM_FILE = 'pom.xml'
  497. # finds the highest available bwc version to test against
  498. def find_bwc_version(release_version, bwc_dir='backwards'):
  499. log(' Lookup bwc version in directory [%s]' % bwc_dir)
  500. bwc_version = None
  501. if os.path.exists(bwc_dir) and os.path.isdir(bwc_dir):
  502. max_version = [int(x) for x in release_version.split('.')]
  503. for dir in os.listdir(bwc_dir):
  504. if os.path.isdir(os.path.join(bwc_dir, dir)) and dir.startswith('elasticsearch-'):
  505. version = [int(x) for x in dir[len('elasticsearch-'):].split('.')]
  506. if version < max_version: # bwc tests only against smaller versions
  507. if (not bwc_version) or version > [int(x) for x in bwc_version.split('.')]:
  508. bwc_version = dir[len('elasticsearch-'):]
  509. log(' Using bwc version [%s]' % bwc_version)
  510. else:
  511. log(' bwc directory [%s] does not exists or is not a directory - skipping' % bwc_dir)
  512. return bwc_version
  513. def ensure_checkout_is_clean(branchName):
  514. # Make sure no local mods:
  515. s = subprocess.check_output('git diff --shortstat', shell=True)
  516. if len(s) > 0:
  517. raise RuntimeError('git diff --shortstat is non-empty: got:\n%s' % s)
  518. # Make sure no untracked files:
  519. s = subprocess.check_output('git status', shell=True).decode('utf-8', errors='replace')
  520. if 'Untracked files:' in s:
  521. raise RuntimeError('git status shows untracked files: got:\n%s' % s)
  522. # Make sure we are on the right branch (NOTE: a bit weak, since we default to current branch):
  523. if 'On branch %s' % branchName not in s:
  524. raise RuntimeError('git status does not show branch %s: got:\n%s' % (branchName, s))
  525. # Make sure we have all changes from origin:
  526. if 'is behind' in s:
  527. raise RuntimeError('git status shows not all changes pulled from origin; try running "git pull origin %s": got:\n%s' % (branchName, s))
  528. # Make sure we no local unpushed changes (this is supposed to be a clean area):
  529. if 'is ahead' in s:
  530. raise RuntimeError('git status shows local commits; try running "git fetch origin", "git checkout %s", "git reset --hard origin/%s": got:\n%s' % (branchName, branchName, s))
  531. # Checks all source files for //NORELEASE comments
  532. def check_norelease(path='src'):
  533. pattern = re.compile(r'\bnorelease\b', re.IGNORECASE)
  534. for root, _, file_names in os.walk(path):
  535. for file_name in fnmatch.filter(file_names, '*.java'):
  536. full_path = os.path.join(root, file_name)
  537. line_number = 0
  538. with open(full_path, 'r', encoding='utf-8') as current_file:
  539. for line in current_file:
  540. line_number = line_number + 1
  541. if pattern.search(line):
  542. raise RuntimeError('Found //norelease comment in %s line %s' % (full_path, line_number))
  543. def run_and_print(text, run_function):
  544. try:
  545. print(text, end='')
  546. run_function()
  547. print(COLOR_OK + 'OK' + COLOR_END)
  548. return True
  549. except RuntimeError:
  550. print(COLOR_FAIL + 'NOT OK' + COLOR_END)
  551. return False
  552. def check_env_var(text, env_var):
  553. try:
  554. print(text, end='')
  555. env[env_var]
  556. print(COLOR_OK + 'OK' + COLOR_END)
  557. return True
  558. except KeyError:
  559. print(COLOR_FAIL + 'NOT OK' + COLOR_END)
  560. return False
  561. def check_environment_and_commandline_tools(check_only):
  562. checks = list()
  563. checks.append(check_env_var('Checking for AWS env configuration AWS_SECRET_ACCESS_KEY_ID... ', 'AWS_SECRET_ACCESS_KEY'))
  564. checks.append(check_env_var('Checking for AWS env configuration AWS_ACCESS_KEY_ID... ', 'AWS_ACCESS_KEY_ID'))
  565. checks.append(check_env_var('Checking for SONATYPE env configuration SONATYPE_USERNAME... ', 'SONATYPE_USERNAME'))
  566. checks.append(check_env_var('Checking for SONATYPE env configuration SONATYPE_PASSWORD... ', 'SONATYPE_PASSWORD'))
  567. checks.append(check_env_var('Checking for GPG env configuration GPG_KEY_ID... ', 'GPG_KEY_ID'))
  568. checks.append(check_env_var('Checking for GPG env configuration GPG_PASSPHRASE... ', 'GPG_PASSPHRASE'))
  569. checks.append(check_env_var('Checking for S3 repo upload env configuration S3_BUCKET_SYNC_TO... ', 'S3_BUCKET_SYNC_TO'))
  570. checks.append(check_env_var('Checking for git env configuration GIT_AUTHOR_NAME... ', 'GIT_AUTHOR_NAME'))
  571. checks.append(check_env_var('Checking for git env configuration GIT_AUTHOR_EMAIL... ', 'GIT_AUTHOR_EMAIL'))
  572. checks.append(run_and_print('Checking command: rpm... ', partial(check_command_exists, 'rpm', 'rpm --version')))
  573. checks.append(run_and_print('Checking command: dpkg... ', partial(check_command_exists, 'dpkg', 'dpkg --version')))
  574. checks.append(run_and_print('Checking command: gpg... ', partial(check_command_exists, 'gpg', 'gpg --version')))
  575. checks.append(run_and_print('Checking command: expect... ', partial(check_command_exists, 'expect', 'expect -v')))
  576. checks.append(run_and_print('Checking command: createrepo... ', partial(check_command_exists, 'createrepo', 'createrepo --version')))
  577. checks.append(run_and_print('Checking command: s3cmd... ', partial(check_command_exists, 's3cmd', 's3cmd --version')))
  578. checks.append(run_and_print('Checking command: apt-ftparchive... ', partial(check_command_exists, 'apt-ftparchive', 'apt-ftparchive --version')))
  579. # boto, check error code being returned
  580. location = os.path.dirname(os.path.realpath(__file__))
  581. command = 'python %s/upload-s3.py -h' % (location)
  582. checks.append(run_and_print('Testing boto python dependency... ', partial(check_command_exists, 'python-boto', command)))
  583. checks.append(run_and_print('Checking java version... ', partial(verify_java_version, '1.7')))
  584. checks.append(run_and_print('Checking java mvn version... ', partial(verify_mvn_java_version, '1.7', MVN)))
  585. if check_only:
  586. sys.exit(0)
  587. if False in checks:
  588. print("Exiting due to failing checks")
  589. sys.exit(0)
  590. if __name__ == '__main__':
  591. parser = argparse.ArgumentParser(description='Builds and publishes a Elasticsearch Release')
  592. parser.add_argument('--branch', '-b', metavar='RELEASE_BRANCH', default=get_current_branch(),
  593. help='The branch to release from. Defaults to the current branch.')
  594. parser.add_argument('--cpus', '-c', metavar='1', default=1,
  595. help='The number of cpus to use for running the test. Default is [1]')
  596. parser.add_argument('--skiptests', '-t', dest='tests', action='store_false',
  597. help='Skips tests before release. Tests are run by default.')
  598. parser.set_defaults(tests=True)
  599. parser.add_argument('--remote', '-r', metavar='origin', default='origin',
  600. help='The remote to push the release commit and tag to. Default is [origin]')
  601. parser.add_argument('--publish', '-d', dest='dryrun', action='store_false',
  602. help='Publishes the release. Disable by default.')
  603. parser.add_argument('--smoke', '-s', dest='smoke', default='',
  604. help='Smoke tests the given release')
  605. parser.add_argument('--bwc', '-w', dest='bwc', metavar='backwards', default='backwards',
  606. help='Backwards compatibility version path to use to run compatibility tests against')
  607. parser.add_argument('--check-only', dest='check_only', action='store_true',
  608. help='Checks and reports for all requirements and then exits')
  609. parser.set_defaults(dryrun=True)
  610. parser.set_defaults(smoke=None)
  611. parser.set_defaults(check_only=False)
  612. args = parser.parse_args()
  613. bwc_path = args.bwc
  614. src_branch = args.branch
  615. remote = args.remote
  616. run_tests = args.tests
  617. dry_run = args.dryrun
  618. cpus = args.cpus
  619. build = not args.smoke
  620. smoke_test_version = args.smoke
  621. check_environment_and_commandline_tools(args.check_only)
  622. # we print a notice if we can not find the relevant infos in the ~/.m2/settings.xml
  623. print_sonatype_notice()
  624. # we require to build with 1.7
  625. verify_java_version('1.7')
  626. verify_mvn_java_version('1.7', MVN)
  627. if os.path.exists(LOG):
  628. raise RuntimeError('please remove old release log %s first' % LOG)
  629. if not dry_run:
  630. print('WARNING: dryrun is set to "false" - this will push and publish the release')
  631. input('Press Enter to continue...')
  632. print(''.join(['-' for _ in range(80)]))
  633. print('Preparing Release from branch [%s] running tests: [%s] dryrun: [%s]' % (src_branch, run_tests, dry_run))
  634. print(' JAVA_HOME is [%s]' % JAVA_HOME)
  635. print(' Running with maven command: [%s] ' % (MVN))
  636. if build:
  637. check_norelease(path='src')
  638. ensure_checkout_is_clean(src_branch)
  639. verify_lucene_version()
  640. release_version = find_release_version(src_branch)
  641. ensure_no_open_tickets(release_version)
  642. if not dry_run:
  643. smoke_test_version = release_version
  644. head_hash = get_head_hash()
  645. run_mvn('clean') # clean the env!
  646. print(' Release version: [%s]' % release_version)
  647. create_release_branch(remote, src_branch, release_version)
  648. print(' Created release branch [%s]' % (release_branch(release_version)))
  649. success = False
  650. try:
  651. pending_files = [POM_FILE, VERSION_FILE]
  652. remove_maven_snapshot(POM_FILE, release_version)
  653. remove_version_snapshot(VERSION_FILE, release_version)
  654. print(' Done removing snapshot version')
  655. add_pending_files(*pending_files) # expects var args use * to expand
  656. commit_release(release_version)
  657. pending_files = update_reference_docs(release_version)
  658. version_head_hash = None
  659. # split commits for docs and version to enable easy cherry-picking
  660. if pending_files:
  661. add_pending_files(*pending_files) # expects var args use * to expand
  662. commit_feature_flags(release_version)
  663. version_head_hash = get_head_hash()
  664. print(' Committed release version [%s]' % release_version)
  665. print(''.join(['-' for _ in range(80)]))
  666. print('Building Release candidate')
  667. input('Press Enter to continue...')
  668. if not dry_run:
  669. print(' Running maven builds now and publish to Sonatype - run-tests [%s]' % run_tests)
  670. else:
  671. print(' Running maven builds now run-tests [%s]' % run_tests)
  672. build_release(run_tests=run_tests, dry_run=dry_run, cpus=cpus, bwc_version=find_bwc_version(release_version, bwc_path))
  673. artifacts = get_artifacts(release_version)
  674. print('Checking if all artifacts contain the same jars')
  675. check_artifacts_for_same_jars(artifacts)
  676. artifacts_and_checksum = generate_checksums(artifacts)
  677. smoke_test_release(release_version, artifacts, get_head_hash(), PLUGINS)
  678. print(''.join(['-' for _ in range(80)]))
  679. print('Finish Release -- dry_run: %s' % dry_run)
  680. input('Press Enter to continue...')
  681. print(' merge release branch, tag and push to %s %s -- dry_run: %s' % (remote, src_branch, dry_run))
  682. merge_tag_push(remote, src_branch, release_version, dry_run)
  683. print(' publish artifacts to S3 -- dry_run: %s' % dry_run)
  684. publish_artifacts(artifacts_and_checksum, dry_run=dry_run)
  685. print(' Updating package repositories -- dry_run: %s' % dry_run)
  686. publish_repositories(src_branch, dry_run=dry_run)
  687. cherry_pick_command = '.'
  688. if version_head_hash:
  689. cherry_pick_command = ' and cherry-pick the documentation changes: \'git cherry-pick %s\' to the development branch' % (version_head_hash)
  690. pending_msg = """
  691. Release successful pending steps:
  692. * create a new vX.Y.Z label on github for the next release, with label color #dddddd (https://github.com/elastic/elasticsearch/labels)
  693. * publish the maven artifacts on Sonatype: https://oss.sonatype.org/index.html
  694. - here is a guide: http://central.sonatype.org/pages/releasing-the-deployment.html
  695. * check if the release is there https://oss.sonatype.org/content/repositories/releases/org/elasticsearch/elasticsearch/%(version)s
  696. * announce the release on the website / blog post
  697. * tweet about the release
  698. * announce the release in the google group/mailinglist
  699. * Move to a Snapshot version to the current branch for the next point release%(cherry_pick)s
  700. """
  701. print(pending_msg % { 'version' : release_version, 'cherry_pick' : cherry_pick_command} )
  702. success = True
  703. finally:
  704. if not success:
  705. run('git reset --hard HEAD')
  706. run('git checkout %s' % src_branch)
  707. elif dry_run:
  708. run('git reset --hard %s' % head_hash)
  709. run('git tag -d v%s' % release_version)
  710. # we delete this one anyways
  711. run('git branch -D %s' % (release_branch(release_version)))
  712. else:
  713. print("Skipping build - smoketest only against version %s" % smoke_test_version)
  714. run_mvn('clean') # clean the env!
  715. if smoke_test_version:
  716. fetch(remote)
  717. download_and_verify(smoke_test_version, artifact_names(smoke_test_version), plugins=PLUGINS)