PageRenderTime 40ms CodeModel.GetById 9ms RepoModel.GetById 0ms app.codeStats 1ms

/dev-tools/scripts/smokeTestRelease.py

http://github.com/apache/lucene-solr
Python | 1490 lines | 1336 code | 96 blank | 58 comment | 176 complexity | f9ea87aa6d2997611b3bd5dbb8c057ef MD5 | raw file
Possible License(s): LGPL-2.1, CPL-1.0, MPL-2.0-no-copyleft-exception, JSON, Apache-2.0, AGPL-1.0, GPL-2.0, GPL-3.0, MIT, BSD-3-Clause

Large files files are truncated, but you can click here to view the full file

  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # Licensed to the Apache Software Foundation (ASF) under one or more
  4. # contributor license agreements. See the NOTICE file distributed with
  5. # this work for additional information regarding copyright ownership.
  6. # The ASF licenses this file to You under the Apache License, Version 2.0
  7. # (the "License"); you may not use this file except in compliance with
  8. # the License. You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. import argparse
  18. import codecs
  19. import datetime
  20. import filecmp
  21. import hashlib
  22. import http.client
  23. import os
  24. import platform
  25. import re
  26. import shutil
  27. import subprocess
  28. import sys
  29. import textwrap
  30. import traceback
  31. import urllib.error
  32. import urllib.parse
  33. import urllib.parse
  34. import urllib.request
  35. import xml.etree.ElementTree as ET
  36. import zipfile
  37. from collections import defaultdict
  38. from collections import namedtuple
  39. from scriptutil import download
  40. import checkJavaDocs
  41. import checkJavadocLinks
  42. # This tool expects to find /lucene and /solr off the base URL. You
  43. # must have a working gpg, tar, unzip in your path. This has been
  44. # tested on Linux and on Cygwin under Windows 7.
  45. cygwin = platform.system().lower().startswith('cygwin')
  46. cygwinWindowsRoot = os.popen('cygpath -w /').read().strip().replace('\\','/') if cygwin else ''
  47. def unshortenURL(url):
  48. parsed = urllib.parse.urlparse(url)
  49. if parsed[0] in ('http', 'https'):
  50. h = http.client.HTTPConnection(parsed.netloc)
  51. h.request('HEAD', parsed.path)
  52. response = h.getresponse()
  53. if int(response.status/100) == 3 and response.getheader('Location'):
  54. return response.getheader('Location')
  55. return url
  56. # TODO
  57. # + verify KEYS contains key that signed the release
  58. # + make sure changes HTML looks ok
  59. # - verify license/notice of all dep jars
  60. # - check maven
  61. # - check JAR manifest version
  62. # - check license/notice exist
  63. # - check no "extra" files
  64. # - make sure jars exist inside bin release
  65. # - run "ant test"
  66. # - make sure docs exist
  67. # - use java5 for lucene/modules
  68. reHREF = re.compile('<a href="(.*?)">(.*?)</a>')
  69. # Set to False to avoid re-downloading the packages...
  70. FORCE_CLEAN = True
  71. def getHREFs(urlString):
  72. # Deref any redirects
  73. while True:
  74. url = urllib.parse.urlparse(urlString)
  75. if url.scheme == "http":
  76. h = http.client.HTTPConnection(url.netloc)
  77. elif url.scheme == "https":
  78. h = http.client.HTTPSConnection(url.netloc)
  79. else:
  80. raise RuntimeError("Unknown protocol: %s" % url.scheme)
  81. h.request('HEAD', url.path)
  82. r = h.getresponse()
  83. newLoc = r.getheader('location')
  84. if newLoc is not None:
  85. urlString = newLoc
  86. else:
  87. break
  88. links = []
  89. try:
  90. html = load(urlString)
  91. except:
  92. print('\nFAILED to open url %s' % urlString)
  93. traceback.print_exc()
  94. raise
  95. for subUrl, text in reHREF.findall(html):
  96. fullURL = urllib.parse.urljoin(urlString, subUrl)
  97. links.append((text, fullURL))
  98. return links
  99. def load(urlString):
  100. try:
  101. content = urllib.request.urlopen(urlString).read().decode('utf-8')
  102. except Exception as e:
  103. print('Retrying download of url %s after exception: %s' % (urlString, e))
  104. content = urllib.request.urlopen(urlString).read().decode('utf-8')
  105. return content
  106. def noJavaPackageClasses(desc, file):
  107. with zipfile.ZipFile(file) as z2:
  108. for name2 in z2.namelist():
  109. if name2.endswith('.class') and (name2.startswith('java/') or name2.startswith('javax/')):
  110. raise RuntimeError('%s contains sheisty class "%s"' % (desc, name2))
  111. def decodeUTF8(bytes):
  112. return codecs.getdecoder('UTF-8')(bytes)[0]
  113. MANIFEST_FILE_NAME = 'META-INF/MANIFEST.MF'
  114. NOTICE_FILE_NAME = 'META-INF/NOTICE.txt'
  115. LICENSE_FILE_NAME = 'META-INF/LICENSE.txt'
  116. def checkJARMetaData(desc, jarFile, gitRevision, version):
  117. with zipfile.ZipFile(jarFile, 'r') as z:
  118. for name in (MANIFEST_FILE_NAME, NOTICE_FILE_NAME, LICENSE_FILE_NAME):
  119. try:
  120. # The Python docs state a KeyError is raised ... so this None
  121. # check is just defensive:
  122. if z.getinfo(name) is None:
  123. raise RuntimeError('%s is missing %s' % (desc, name))
  124. except KeyError:
  125. raise RuntimeError('%s is missing %s' % (desc, name))
  126. s = decodeUTF8(z.read(MANIFEST_FILE_NAME))
  127. for verify in (
  128. 'Specification-Vendor: The Apache Software Foundation',
  129. 'Implementation-Vendor: The Apache Software Foundation',
  130. # Make sure 1.8 compiler was used to build release bits:
  131. 'X-Compile-Source-JDK: 11',
  132. # Make sure 1.8, 1.9 or 1.10 ant was used to build release bits: (this will match 1.8.x, 1.9.x, 1.10.x)
  133. ('Ant-Version: Apache Ant 1.8', 'Ant-Version: Apache Ant 1.9', 'Ant-Version: Apache Ant 1.10'),
  134. # Make sure .class files are 1.8 format:
  135. 'X-Compile-Target-JDK: 11',
  136. 'Specification-Version: %s' % version,
  137. # Make sure the release was compiled with 1.8:
  138. 'Created-By: 11'):
  139. if type(verify) is not tuple:
  140. verify = (verify,)
  141. for x in verify:
  142. if s.find(x) != -1:
  143. break
  144. else:
  145. if len(verify) == 1:
  146. raise RuntimeError('%s is missing "%s" inside its META-INF/MANIFEST.MF' % (desc, verify[0]))
  147. else:
  148. raise RuntimeError('%s is missing one of "%s" inside its META-INF/MANIFEST.MF' % (desc, verify))
  149. if gitRevision != 'skip':
  150. # Make sure this matches the version and git revision we think we are releasing:
  151. # TODO: LUCENE-7023: is it OK that Implementation-Version's value now spans two lines?
  152. verifyRevision = 'Implementation-Version: %s %s' % (version, gitRevision)
  153. if s.find(verifyRevision) == -1:
  154. raise RuntimeError('%s is missing "%s" inside its META-INF/MANIFEST.MF (wrong git revision?)' % \
  155. (desc, verifyRevision))
  156. notice = decodeUTF8(z.read(NOTICE_FILE_NAME))
  157. license = decodeUTF8(z.read(LICENSE_FILE_NAME))
  158. justFileName = os.path.split(desc)[1]
  159. if justFileName.lower().find('solr') != -1:
  160. if SOLR_LICENSE is None:
  161. raise RuntimeError('BUG in smokeTestRelease!')
  162. if SOLR_NOTICE is None:
  163. raise RuntimeError('BUG in smokeTestRelease!')
  164. if notice != SOLR_NOTICE:
  165. raise RuntimeError('%s: %s contents doesn\'t match main NOTICE.txt' % \
  166. (desc, NOTICE_FILE_NAME))
  167. if license != SOLR_LICENSE:
  168. raise RuntimeError('%s: %s contents doesn\'t match main LICENSE.txt' % \
  169. (desc, LICENSE_FILE_NAME))
  170. else:
  171. if LUCENE_LICENSE is None:
  172. raise RuntimeError('BUG in smokeTestRelease!')
  173. if LUCENE_NOTICE is None:
  174. raise RuntimeError('BUG in smokeTestRelease!')
  175. if notice != LUCENE_NOTICE:
  176. raise RuntimeError('%s: %s contents doesn\'t match main NOTICE.txt' % \
  177. (desc, NOTICE_FILE_NAME))
  178. if license != LUCENE_LICENSE:
  179. raise RuntimeError('%s: %s contents doesn\'t match main LICENSE.txt' % \
  180. (desc, LICENSE_FILE_NAME))
  181. def normSlashes(path):
  182. return path.replace(os.sep, '/')
  183. def checkAllJARs(topDir, project, gitRevision, version, tmpDir, baseURL):
  184. print(' verify JAR metadata/identity/no javax.* or java.* classes...')
  185. if project == 'solr':
  186. luceneDistFilenames = dict()
  187. for file in getBinaryDistFiles('lucene', tmpDir, version, baseURL):
  188. luceneDistFilenames[os.path.basename(file)] = file
  189. for root, dirs, files in os.walk(topDir):
  190. normRoot = normSlashes(root)
  191. if project == 'solr' and normRoot.endswith('/server/lib'):
  192. # Solr's example intentionally ships servlet JAR:
  193. continue
  194. for file in files:
  195. if file.lower().endswith('.jar'):
  196. if project == 'solr':
  197. if ((normRoot.endswith('/contrib/dataimporthandler-extras/lib') and (file.startswith('javax.mail-') or file.startswith('activation-')))
  198. or (normRoot.endswith('/test-framework/lib') and file.startswith('jersey-'))
  199. or (normRoot.endswith('/contrib/extraction/lib') and file.startswith('xml-apis-'))):
  200. print(' **WARNING**: skipping check of %s/%s: it has javax.* classes' % (root, file))
  201. continue
  202. else:
  203. if normRoot.endswith('/replicator/lib') and file.startswith('javax.servlet'):
  204. continue
  205. fullPath = '%s/%s' % (root, file)
  206. noJavaPackageClasses('JAR file "%s"' % fullPath, fullPath)
  207. if file.lower().find('lucene') != -1 or file.lower().find('solr') != -1:
  208. checkJARMetaData('JAR file "%s"' % fullPath, fullPath, gitRevision, version)
  209. if project == 'solr' and file.lower().find('lucene') != -1:
  210. jarFilename = os.path.basename(file)
  211. if jarFilename not in luceneDistFilenames:
  212. raise RuntimeError('Artifact %s is not present in Lucene binary distribution' % fullPath)
  213. identical = filecmp.cmp(fullPath, luceneDistFilenames[jarFilename], shallow=False)
  214. if not identical:
  215. raise RuntimeError('Artifact %s is not identical to %s in Lucene binary distribution'
  216. % (fullPath, luceneDistFilenames[jarFilename]))
  217. def checkSigs(project, urlString, version, tmpDir, isSigned, keysFile):
  218. print(' test basics...')
  219. ents = getDirEntries(urlString)
  220. artifact = None
  221. changesURL = None
  222. mavenURL = None
  223. expectedSigs = []
  224. if isSigned:
  225. expectedSigs.append('asc')
  226. expectedSigs.extend(['sha512'])
  227. artifacts = []
  228. for text, subURL in ents:
  229. if text == 'KEYS':
  230. raise RuntimeError('%s: release dir should not contain a KEYS file - only toplevel /dist/lucene/KEYS is used' % project)
  231. elif text == 'maven/':
  232. mavenURL = subURL
  233. elif text.startswith('changes'):
  234. if text not in ('changes/', 'changes-%s/' % version):
  235. raise RuntimeError('%s: found %s vs expected changes-%s/' % (project, text, version))
  236. changesURL = subURL
  237. elif artifact == None:
  238. artifact = text
  239. artifactURL = subURL
  240. if project == 'solr':
  241. expected = 'solr-%s' % version
  242. else:
  243. expected = 'lucene-%s' % version
  244. if not artifact.startswith(expected):
  245. raise RuntimeError('%s: unknown artifact %s: expected prefix %s' % (project, text, expected))
  246. sigs = []
  247. elif text.startswith(artifact + '.'):
  248. sigs.append(text[len(artifact)+1:])
  249. else:
  250. if sigs != expectedSigs:
  251. raise RuntimeError('%s: artifact %s has wrong sigs: expected %s but got %s' % (project, artifact, expectedSigs, sigs))
  252. artifacts.append((artifact, artifactURL))
  253. artifact = text
  254. artifactURL = subURL
  255. sigs = []
  256. if sigs != []:
  257. artifacts.append((artifact, artifactURL))
  258. if sigs != expectedSigs:
  259. raise RuntimeError('%s: artifact %s has wrong sigs: expected %s but got %s' % (project, artifact, expectedSigs, sigs))
  260. if project == 'lucene':
  261. expected = ['lucene-%s-src.tgz' % version,
  262. 'lucene-%s.tgz' % version,
  263. 'lucene-%s.zip' % version]
  264. else:
  265. expected = ['solr-%s-src.tgz' % version,
  266. 'solr-%s.tgz' % version,
  267. 'solr-%s.zip' % version]
  268. actual = [x[0] for x in artifacts]
  269. if expected != actual:
  270. raise RuntimeError('%s: wrong artifacts: expected %s but got %s' % (project, expected, actual))
  271. # Set up clean gpg world; import keys file:
  272. gpgHomeDir = '%s/%s.gpg' % (tmpDir, project)
  273. if os.path.exists(gpgHomeDir):
  274. shutil.rmtree(gpgHomeDir)
  275. os.makedirs(gpgHomeDir, 0o700)
  276. run('gpg --homedir %s --import %s' % (gpgHomeDir, keysFile),
  277. '%s/%s.gpg.import.log' % (tmpDir, project))
  278. if mavenURL is None:
  279. raise RuntimeError('%s is missing maven' % project)
  280. if changesURL is None:
  281. raise RuntimeError('%s is missing changes-%s' % (project, version))
  282. testChanges(project, version, changesURL)
  283. for artifact, urlString in artifacts:
  284. print(' download %s...' % artifact)
  285. download(artifact, urlString, tmpDir, force_clean=FORCE_CLEAN)
  286. verifyDigests(artifact, urlString, tmpDir)
  287. if isSigned:
  288. print(' verify sig')
  289. # Test sig (this is done with a clean brand-new GPG world)
  290. download(artifact + '.asc', urlString + '.asc', tmpDir, force_clean=FORCE_CLEAN)
  291. sigFile = '%s/%s.asc' % (tmpDir, artifact)
  292. artifactFile = '%s/%s' % (tmpDir, artifact)
  293. logFile = '%s/%s.%s.gpg.verify.log' % (tmpDir, project, artifact)
  294. run('gpg --homedir %s --verify %s %s' % (gpgHomeDir, sigFile, artifactFile),
  295. logFile)
  296. # Forward any GPG warnings, except the expected one (since it's a clean world)
  297. f = open(logFile)
  298. for line in f.readlines():
  299. if line.lower().find('warning') != -1 \
  300. and line.find('WARNING: This key is not certified with a trusted signature') == -1:
  301. print(' GPG: %s' % line.strip())
  302. f.close()
  303. # Test trust (this is done with the real users config)
  304. run('gpg --import %s' % (keysFile),
  305. '%s/%s.gpg.trust.import.log' % (tmpDir, project))
  306. print(' verify trust')
  307. logFile = '%s/%s.%s.gpg.trust.log' % (tmpDir, project, artifact)
  308. run('gpg --verify %s %s' % (sigFile, artifactFile), logFile)
  309. # Forward any GPG warnings:
  310. f = open(logFile)
  311. for line in f.readlines():
  312. if line.lower().find('warning') != -1:
  313. print(' GPG: %s' % line.strip())
  314. f.close()
  315. def testChanges(project, version, changesURLString):
  316. print(' check changes HTML...')
  317. changesURL = None
  318. for text, subURL in getDirEntries(changesURLString):
  319. if text == 'Changes.html':
  320. changesURL = subURL
  321. if changesURL is None:
  322. raise RuntimeError('did not see Changes.html link from %s' % changesURLString)
  323. s = load(changesURL)
  324. checkChangesContent(s, version, changesURL, project, True)
  325. def testChangesText(dir, version, project):
  326. "Checks all CHANGES.txt under this dir."
  327. for root, dirs, files in os.walk(dir):
  328. # NOTE: O(N) but N should be smallish:
  329. if 'CHANGES.txt' in files:
  330. fullPath = '%s/CHANGES.txt' % root
  331. #print 'CHECK %s' % fullPath
  332. checkChangesContent(open(fullPath, encoding='UTF-8').read(), version, fullPath, project, False)
  333. reChangesSectionHREF = re.compile('<a id="(.*?)".*?>(.*?)</a>', re.IGNORECASE)
  334. reUnderbarNotDashHTML = re.compile(r'<li>(\s*(LUCENE|SOLR)_\d\d\d\d+)')
  335. reUnderbarNotDashTXT = re.compile(r'\s+((LUCENE|SOLR)_\d\d\d\d+)', re.MULTILINE)
  336. def checkChangesContent(s, version, name, project, isHTML):
  337. currentVersionTuple = versionToTuple(version, name)
  338. if isHTML and s.find('Release %s' % version) == -1:
  339. raise RuntimeError('did not see "Release %s" in %s' % (version, name))
  340. if isHTML:
  341. r = reUnderbarNotDashHTML
  342. else:
  343. r = reUnderbarNotDashTXT
  344. m = r.search(s)
  345. if m is not None:
  346. raise RuntimeError('incorrect issue (_ instead of -) in %s: %s' % (name, m.group(1)))
  347. if s.lower().find('not yet released') != -1:
  348. raise RuntimeError('saw "not yet released" in %s' % name)
  349. if not isHTML:
  350. if project == 'lucene':
  351. sub = 'Lucene %s' % version
  352. else:
  353. sub = version
  354. if s.find(sub) == -1:
  355. # benchmark never seems to include release info:
  356. if name.find('/benchmark/') == -1:
  357. raise RuntimeError('did not see "%s" in %s' % (sub, name))
  358. if isHTML:
  359. # Make sure that a section only appears once under each release,
  360. # and that each release is not greater than the current version
  361. seenIDs = set()
  362. seenText = set()
  363. release = None
  364. for id, text in reChangesSectionHREF.findall(s):
  365. if text.lower().startswith('release '):
  366. release = text[8:].strip()
  367. seenText.clear()
  368. releaseTuple = versionToTuple(release, name)
  369. if releaseTuple > currentVersionTuple:
  370. raise RuntimeError('Future release %s is greater than %s in %s' % (release, version, name))
  371. if id in seenIDs:
  372. raise RuntimeError('%s has duplicate section "%s" under release "%s"' % (name, text, release))
  373. seenIDs.add(id)
  374. if text in seenText:
  375. raise RuntimeError('%s has duplicate section "%s" under release "%s"' % (name, text, release))
  376. seenText.add(text)
  377. reVersion = re.compile(r'(\d+)\.(\d+)(?:\.(\d+))?\s*(-alpha|-beta|final|RC\d+)?\s*(?:\[.*\])?', re.IGNORECASE)
  378. def versionToTuple(version, name):
  379. versionMatch = reVersion.match(version)
  380. if versionMatch is None:
  381. raise RuntimeError('Version %s in %s cannot be parsed' % (version, name))
  382. versionTuple = versionMatch.groups()
  383. while versionTuple[-1] is None or versionTuple[-1] == '':
  384. versionTuple = versionTuple[:-1]
  385. if versionTuple[-1].lower() == '-alpha':
  386. versionTuple = versionTuple[:-1] + ('0',)
  387. elif versionTuple[-1].lower() == '-beta':
  388. versionTuple = versionTuple[:-1] + ('1',)
  389. elif versionTuple[-1].lower() == 'final':
  390. versionTuple = versionTuple[:-2] + ('100',)
  391. elif versionTuple[-1].lower()[:2] == 'rc':
  392. versionTuple = versionTuple[:-2] + (versionTuple[-1][2:],)
  393. return versionTuple
  394. reUnixPath = re.compile(r'\b[a-zA-Z_]+=(?:"(?:\\"|[^"])*"' + '|(?:\\\\.|[^"\'\\s])*' + r"|'(?:\\'|[^'])*')" \
  395. + r'|(/(?:\\.|[^"\'\s])*)' \
  396. + r'|("/(?:\\.|[^"])*")' \
  397. + r"|('/(?:\\.|[^'])*')")
  398. def unix2win(matchobj):
  399. if matchobj.group(1) is not None: return cygwinWindowsRoot + matchobj.group()
  400. if matchobj.group(2) is not None: return '"%s%s' % (cygwinWindowsRoot, matchobj.group().lstrip('"'))
  401. if matchobj.group(3) is not None: return "'%s%s" % (cygwinWindowsRoot, matchobj.group().lstrip("'"))
  402. return matchobj.group()
  403. def cygwinifyPaths(command):
  404. # The problem: Native Windows applications running under Cygwin
  405. # (e.g. Ant, which isn't available as a Cygwin package) can't
  406. # handle Cygwin's Unix-style paths. However, environment variable
  407. # values are automatically converted, so only paths outside of
  408. # environment variable values should be converted to Windows paths.
  409. # Assumption: all paths will be absolute.
  410. if '; ant ' in command: command = reUnixPath.sub(unix2win, command)
  411. return command
  412. def printFileContents(fileName):
  413. # Assume log file was written in system's default encoding, but
  414. # even if we are wrong, we replace errors ... the ASCII chars
  415. # (which is what we mostly care about eg for the test seed) should
  416. # still survive:
  417. txt = codecs.open(fileName, 'r', encoding=sys.getdefaultencoding(), errors='replace').read()
  418. # Encode to our output encoding (likely also system's default
  419. # encoding):
  420. bytes = txt.encode(sys.stdout.encoding, errors='replace')
  421. # Decode back to string and print... we should hit no exception here
  422. # since all errors have been replaced:
  423. print(codecs.getdecoder(sys.stdout.encoding)(bytes)[0])
  424. print()
  425. def run(command, logFile):
  426. if cygwin: command = cygwinifyPaths(command)
  427. if os.system('%s > %s 2>&1' % (command, logFile)):
  428. logPath = os.path.abspath(logFile)
  429. print('\ncommand "%s" failed:' % command)
  430. printFileContents(logFile)
  431. raise RuntimeError('command "%s" failed; see log file %s' % (command, logPath))
  432. def verifyDigests(artifact, urlString, tmpDir):
  433. print(' verify sha512 digest')
  434. sha512Expected, t = load(urlString + '.sha512').strip().split()
  435. if t != '*'+artifact:
  436. raise RuntimeError('SHA512 %s.sha512 lists artifact %s but expected *%s' % (urlString, t, artifact))
  437. s512 = hashlib.sha512()
  438. f = open('%s/%s' % (tmpDir, artifact), 'rb')
  439. while True:
  440. x = f.read(65536)
  441. if len(x) == 0:
  442. break
  443. s512.update(x)
  444. f.close()
  445. sha512Actual = s512.hexdigest()
  446. if sha512Actual != sha512Expected:
  447. raise RuntimeError('SHA512 digest mismatch for %s: expected %s but got %s' % (artifact, sha512Expected, sha512Actual))
  448. def getDirEntries(urlString):
  449. if urlString.startswith('file:/') and not urlString.startswith('file://'):
  450. # stupid bogus ant URI
  451. urlString = "file:///" + urlString[6:]
  452. if urlString.startswith('file://'):
  453. path = urlString[7:]
  454. if path.endswith('/'):
  455. path = path[:-1]
  456. if cygwin: # Convert Windows path to Cygwin path
  457. path = re.sub(r'^/([A-Za-z]):/', r'/cygdrive/\1/', path)
  458. l = []
  459. for ent in os.listdir(path):
  460. entPath = '%s/%s' % (path, ent)
  461. if os.path.isdir(entPath):
  462. entPath += '/'
  463. ent += '/'
  464. l.append((ent, 'file://%s' % entPath))
  465. l.sort()
  466. return l
  467. else:
  468. links = getHREFs(urlString)
  469. for i, (text, subURL) in enumerate(links):
  470. if text == 'Parent Directory' or text == '..':
  471. return links[(i+1):]
  472. def unpackAndVerify(java, project, tmpDir, artifact, gitRevision, version, testArgs, baseURL):
  473. destDir = '%s/unpack' % tmpDir
  474. if os.path.exists(destDir):
  475. shutil.rmtree(destDir)
  476. os.makedirs(destDir)
  477. os.chdir(destDir)
  478. print(' unpack %s...' % artifact)
  479. unpackLogFile = '%s/%s-unpack-%s.log' % (tmpDir, project, artifact)
  480. if artifact.endswith('.tar.gz') or artifact.endswith('.tgz'):
  481. run('tar xzf %s/%s' % (tmpDir, artifact), unpackLogFile)
  482. elif artifact.endswith('.zip'):
  483. run('unzip %s/%s' % (tmpDir, artifact), unpackLogFile)
  484. # make sure it unpacks to proper subdir
  485. l = os.listdir(destDir)
  486. expected = '%s-%s' % (project, version)
  487. if l != [expected]:
  488. raise RuntimeError('unpack produced entries %s; expected only %s' % (l, expected))
  489. unpackPath = '%s/%s' % (destDir, expected)
  490. verifyUnpacked(java, project, artifact, unpackPath, gitRevision, version, testArgs, tmpDir, baseURL)
  491. return unpackPath
  492. LUCENE_NOTICE = None
  493. LUCENE_LICENSE = None
  494. SOLR_NOTICE = None
  495. SOLR_LICENSE = None
  496. def verifyUnpacked(java, project, artifact, unpackPath, gitRevision, version, testArgs, tmpDir, baseURL):
  497. global LUCENE_NOTICE
  498. global LUCENE_LICENSE
  499. global SOLR_NOTICE
  500. global SOLR_LICENSE
  501. os.chdir(unpackPath)
  502. isSrc = artifact.find('-src') != -1
  503. l = os.listdir(unpackPath)
  504. textFiles = ['LICENSE', 'NOTICE', 'README']
  505. if project == 'lucene':
  506. textFiles.extend(('JRE_VERSION_MIGRATION', 'CHANGES', 'MIGRATE', 'SYSTEM_REQUIREMENTS'))
  507. if isSrc:
  508. textFiles.append('BUILD')
  509. for fileName in textFiles:
  510. fileNameTxt = fileName + '.txt'
  511. fileNameMd = fileName + '.md'
  512. if fileNameTxt in l:
  513. l.remove(fileNameTxt)
  514. elif fileNameMd in l:
  515. l.remove(fileNameMd)
  516. else:
  517. raise RuntimeError('file "%s".[txt|md] is missing from artifact %s' % (fileName, artifact))
  518. if project == 'lucene':
  519. if LUCENE_NOTICE is None:
  520. LUCENE_NOTICE = open('%s/NOTICE.txt' % unpackPath, encoding='UTF-8').read()
  521. if LUCENE_LICENSE is None:
  522. LUCENE_LICENSE = open('%s/LICENSE.txt' % unpackPath, encoding='UTF-8').read()
  523. else:
  524. if SOLR_NOTICE is None:
  525. SOLR_NOTICE = open('%s/NOTICE.txt' % unpackPath, encoding='UTF-8').read()
  526. if SOLR_LICENSE is None:
  527. SOLR_LICENSE = open('%s/LICENSE.txt' % unpackPath, encoding='UTF-8').read()
  528. if not isSrc:
  529. # TODO: we should add verifyModule/verifySubmodule (e.g. analysis) here and recurse through
  530. if project == 'lucene':
  531. expectedJARs = ()
  532. else:
  533. expectedJARs = ()
  534. for fileName in expectedJARs:
  535. fileName += '.jar'
  536. if fileName not in l:
  537. raise RuntimeError('%s: file "%s" is missing from artifact %s' % (project, fileName, artifact))
  538. l.remove(fileName)
  539. if project == 'lucene':
  540. # TODO: clean this up to not be a list of modules that we must maintain
  541. extras = ('analysis', 'backward-codecs', 'benchmark', 'classification', 'codecs', 'core', 'demo', 'docs', 'expressions', 'facet', 'grouping', 'highlighter', 'join', 'luke', 'memory', 'misc', 'monitor', 'queries', 'queryparser', 'replicator', 'sandbox', 'spatial-extras', 'spatial3d', 'suggest', 'test-framework', 'licenses')
  542. if isSrc:
  543. extras += ('build.gradle', 'build.xml', 'common-build.xml', 'module-build.xml', 'top-level-ivy-settings.xml', 'default-nested-ivy-settings.xml', 'ivy-versions.properties', 'ivy-ignore-conflicts.properties', 'version.properties', 'tools', 'site', 'dev-docs')
  544. else:
  545. extras = ()
  546. # TODO: if solr, verify lucene/licenses, solr/licenses are present
  547. for e in extras:
  548. if e not in l:
  549. raise RuntimeError('%s: %s missing from artifact %s' % (project, e, artifact))
  550. l.remove(e)
  551. if project == 'lucene':
  552. if len(l) > 0:
  553. raise RuntimeError('%s: unexpected files/dirs in artifact %s: %s' % (project, artifact, l))
  554. if isSrc:
  555. print(' make sure no JARs/WARs in src dist...')
  556. lines = os.popen('find . -name \\*.jar').readlines()
  557. if len(lines) != 0:
  558. print(' FAILED:')
  559. for line in lines:
  560. print(' %s' % line.strip())
  561. raise RuntimeError('source release has JARs...')
  562. lines = os.popen('find . -name \\*.war').readlines()
  563. if len(lines) != 0:
  564. print(' FAILED:')
  565. for line in lines:
  566. print(' %s' % line.strip())
  567. raise RuntimeError('source release has WARs...')
  568. # Can't run documentation-lint in lucene src, because dev-tools is missing
  569. validateCmd = 'ant validate' if project == 'lucene' else 'ant validate documentation-lint';
  570. print(' run "%s"' % validateCmd)
  571. java.run_java11(validateCmd, '%s/validate.log' % unpackPath)
  572. if project == 'lucene':
  573. print(" run tests w/ Java 11 and testArgs='%s'..." % testArgs)
  574. java.run_java11('ant clean test %s' % testArgs, '%s/test.log' % unpackPath)
  575. java.run_java11('ant jar', '%s/compile.log' % unpackPath)
  576. testDemo(java.run_java11, isSrc, version, '11')
  577. print(' generate javadocs w/ Java 11...')
  578. java.run_java11('ant javadocs', '%s/javadocs.log' % unpackPath)
  579. checkJavadocpathFull('%s/build/docs' % unpackPath)
  580. if java.run_java12:
  581. print(" run tests w/ Java 12 and testArgs='%s'..." % testArgs)
  582. java.run_java12('ant clean test %s' % testArgs, '%s/test.log' % unpackPath)
  583. java.run_java12('ant jar', '%s/compile.log' % unpackPath)
  584. testDemo(java.run_java12, isSrc, version, '12')
  585. #print(' generate javadocs w/ Java 12...')
  586. #java.run_java12('ant javadocs', '%s/javadocs.log' % unpackPath)
  587. #checkJavadocpathFull('%s/build/docs' % unpackPath)
  588. else:
  589. os.chdir('solr')
  590. print(" run tests w/ Java 11 and testArgs='%s'..." % testArgs)
  591. java.run_java11('ant clean test -Dtests.slow=false %s' % testArgs, '%s/test.log' % unpackPath)
  592. # test javadocs
  593. print(' generate javadocs w/ Java 11...')
  594. java.run_java11('ant clean javadocs', '%s/javadocs.log' % unpackPath)
  595. checkJavadocpathFull('%s/solr/build/docs' % unpackPath, False)
  596. print(' test solr example w/ Java 11...')
  597. java.run_java11('ant clean server', '%s/antexample.log' % unpackPath)
  598. testSolrExample(unpackPath, java.java11_home, True)
  599. if java.run_java12:
  600. print(" run tests w/ Java 12 and testArgs='%s'..." % testArgs)
  601. java.run_java12('ant clean test -Dtests.slow=false %s' % testArgs, '%s/test.log' % unpackPath)
  602. #print(' generate javadocs w/ Java 12...')
  603. #java.run_java12('ant clean javadocs', '%s/javadocs.log' % unpackPath)
  604. #checkJavadocpathFull('%s/solr/build/docs' % unpackPath, False)
  605. print(' test solr example w/ Java 12...')
  606. java.run_java12('ant clean server', '%s/antexample.log' % unpackPath)
  607. testSolrExample(unpackPath, java.java12_home, True)
  608. os.chdir('..')
  609. print(' check NOTICE')
  610. testNotice(unpackPath)
  611. else:
  612. checkAllJARs(os.getcwd(), project, gitRevision, version, tmpDir, baseURL)
  613. if project == 'lucene':
  614. testDemo(java.run_java11, isSrc, version, '11')
  615. if java.run_java12:
  616. testDemo(java.run_java12, isSrc, version, '12')
  617. print(' check Lucene\'s javadoc JAR')
  618. checkJavadocpath('%s/docs' % unpackPath)
  619. else:
  620. print(' copying unpacked distribution for Java 11 ...')
  621. java11UnpackPath = '%s-java11' % unpackPath
  622. if os.path.exists(java11UnpackPath):
  623. shutil.rmtree(java11UnpackPath)
  624. shutil.copytree(unpackPath, java11UnpackPath)
  625. os.chdir(java11UnpackPath)
  626. print(' test solr example w/ Java 11...')
  627. testSolrExample(java11UnpackPath, java.java11_home, False)
  628. if java.run_java12:
  629. print(' copying unpacked distribution for Java 12 ...')
  630. java12UnpackPath = '%s-java12' % unpackPath
  631. if os.path.exists(java12UnpackPath):
  632. shutil.rmtree(java12UnpackPath)
  633. shutil.copytree(unpackPath, java12UnpackPath)
  634. os.chdir(java12UnpackPath)
  635. print(' test solr example w/ Java 12...')
  636. testSolrExample(java12UnpackPath, java.java12_home, False)
  637. os.chdir(unpackPath)
  638. testChangesText('.', version, project)
  639. if project == 'lucene' and isSrc:
  640. print(' confirm all releases have coverage in TestBackwardsCompatibility')
  641. confirmAllReleasesAreTestedForBackCompat(version, unpackPath)
  642. def testNotice(unpackPath):
  643. solrNotice = open('%s/NOTICE.txt' % unpackPath, encoding='UTF-8').read()
  644. luceneNotice = open('%s/lucene/NOTICE.txt' % unpackPath, encoding='UTF-8').read()
  645. expected = """
  646. =========================================================================
  647. == Apache Lucene Notice ==
  648. =========================================================================
  649. """ + luceneNotice + """---
  650. """
  651. if solrNotice.find(expected) == -1:
  652. raise RuntimeError('Solr\'s NOTICE.txt does not have the verbatim copy, plus header/footer, of Lucene\'s NOTICE.txt')
  653. def readSolrOutput(p, startupEvent, failureEvent, logFile):
  654. f = open(logFile, 'wb')
  655. try:
  656. while True:
  657. line = p.stdout.readline()
  658. if len(line) == 0:
  659. p.poll()
  660. if not startupEvent.isSet():
  661. failureEvent.set()
  662. startupEvent.set()
  663. break
  664. f.write(line)
  665. f.flush()
  666. #print('SOLR: %s' % line.strip())
  667. if not startupEvent.isSet():
  668. if line.find(b'Started ServerConnector@') != -1 and line.find(b'{HTTP/1.1}{0.0.0.0:8983}') != -1:
  669. startupEvent.set()
  670. elif p.poll() is not None:
  671. failureEvent.set()
  672. startupEvent.set()
  673. break
  674. except:
  675. print()
  676. print('Exception reading Solr output:')
  677. traceback.print_exc()
  678. failureEvent.set()
  679. startupEvent.set()
  680. finally:
  681. f.close()
  682. def testSolrExample(unpackPath, javaPath, isSrc):
  683. # test solr using some examples it comes with
  684. logFile = '%s/solr-example.log' % unpackPath
  685. if isSrc:
  686. os.chdir(unpackPath+'/solr')
  687. subprocess.call(['chmod','+x',unpackPath+'/solr/bin/solr', unpackPath+'/solr/bin/solr.cmd', unpackPath+'/solr/bin/solr.in.cmd'])
  688. else:
  689. os.chdir(unpackPath)
  690. print(' start Solr instance (log=%s)...' % logFile)
  691. env = {}
  692. env.update(os.environ)
  693. env['JAVA_HOME'] = javaPath
  694. env['PATH'] = '%s/bin:%s' % (javaPath, env['PATH'])
  695. # Stop Solr running on port 8983 (in case a previous run didn't shutdown cleanly)
  696. try:
  697. if not cygwin:
  698. subprocess.call(['bin/solr','stop','-p','8983'])
  699. else:
  700. subprocess.call('env "PATH=`cygpath -S -w`:$PATH" bin/solr.cmd stop -p 8983', shell=True)
  701. except:
  702. print(' Stop failed due to: '+sys.exc_info()[0])
  703. print(' Running techproducts example on port 8983 from %s' % unpackPath)
  704. try:
  705. if not cygwin:
  706. runExampleStatus = subprocess.call(['bin/solr','-e','techproducts'])
  707. else:
  708. runExampleStatus = subprocess.call('env "PATH=`cygpath -S -w`:$PATH" bin/solr.cmd -e techproducts', shell=True)
  709. if runExampleStatus != 0:
  710. raise RuntimeError('Failed to run the techproducts example, check log for previous errors.')
  711. os.chdir('example')
  712. print(' test utf8...')
  713. run('sh ./exampledocs/test_utf8.sh http://localhost:8983/solr/techproducts', 'utf8.log')
  714. print(' run query...')
  715. s = load('http://localhost:8983/solr/techproducts/select/?q=video')
  716. if s.find('"numFound":3,"start":0') == -1:
  717. print('FAILED: response is:\n%s' % s)
  718. raise RuntimeError('query on solr example instance failed')
  719. s = load('http://localhost:8983/api/cores')
  720. if s.find('"status":0,') == -1:
  721. print('FAILED: response is:\n%s' % s)
  722. raise RuntimeError('query api v2 on solr example instance failed')
  723. finally:
  724. # Stop server:
  725. print(' stop server using: bin/solr stop -p 8983')
  726. if isSrc:
  727. os.chdir(unpackPath+'/solr')
  728. else:
  729. os.chdir(unpackPath)
  730. if not cygwin:
  731. subprocess.call(['bin/solr','stop','-p','8983'])
  732. else:
  733. subprocess.call('env "PATH=`cygpath -S -w`:$PATH" bin/solr.cmd stop -p 8983', shell=True)
  734. if isSrc:
  735. os.chdir(unpackPath+'/solr')
  736. else:
  737. os.chdir(unpackPath)
  738. # the weaker check: we can use this on java6 for some checks,
  739. # but its generated HTML is hopelessly broken so we cannot run
  740. # the link checking that checkJavadocpathFull does.
  741. def checkJavadocpath(path, failOnMissing=True):
  742. # check for level='package'
  743. # we fail here if its screwed up
  744. if failOnMissing and checkJavaDocs.checkPackageSummaries(path, 'package'):
  745. raise RuntimeError('missing javadocs package summaries!')
  746. # now check for level='class'
  747. if checkJavaDocs.checkPackageSummaries(path):
  748. # disabled: RM cannot fix all this, see LUCENE-3887
  749. # raise RuntimeError('javadoc problems')
  750. print('\n***WARNING***: javadocs want to fail!\n')
  751. # full checks
  752. def checkJavadocpathFull(path, failOnMissing=True):
  753. # check for missing, etc
  754. checkJavadocpath(path, failOnMissing)
  755. # also validate html/check for broken links
  756. if checkJavadocLinks.checkAll(path):
  757. raise RuntimeError('broken javadocs links found!')
  758. def testDemo(run_java, isSrc, version, jdk):
  759. if os.path.exists('index'):
  760. shutil.rmtree('index') # nuke any index from any previous iteration
  761. print(' test demo with %s...' % jdk)
  762. sep = ';' if cygwin else ':'
  763. if isSrc:
  764. cp = 'build/core/classes/java{0}build/demo/classes/java{0}build/analysis/common/classes/java{0}build/queryparser/classes/java'.format(sep)
  765. docsDir = 'core/src'
  766. else:
  767. cp = 'core/lucene-core-{0}.jar{1}demo/lucene-demo-{0}.jar{1}analysis/common/lucene-analyzers-common-{0}.jar{1}queryparser/lucene-queryparser-{0}.jar'.format(version, sep)
  768. docsDir = 'docs'
  769. run_java('java -cp "%s" org.apache.lucene.demo.IndexFiles -index index -docs %s' % (cp, docsDir), 'index.log')
  770. run_java('java -cp "%s" org.apache.lucene.demo.SearchFiles -index index -query lucene' % cp, 'search.log')
  771. reMatchingDocs = re.compile('(\d+) total matching documents')
  772. m = reMatchingDocs.search(open('search.log', encoding='UTF-8').read())
  773. if m is None:
  774. raise RuntimeError('lucene demo\'s SearchFiles found no results')
  775. else:
  776. numHits = int(m.group(1))
  777. if numHits < 100:
  778. raise RuntimeError('lucene demo\'s SearchFiles found too few results: %s' % numHits)
  779. print(' got %d hits for query "lucene"' % numHits)
  780. print(' checkindex with %s...' % jdk)
  781. run_java('java -ea -cp "%s" org.apache.lucene.index.CheckIndex index' % cp, 'checkindex.log')
  782. s = open('checkindex.log').read()
  783. m = re.search(r'^\s+version=(.*?)$', s, re.MULTILINE)
  784. if m is None:
  785. raise RuntimeError('unable to locate version=NNN output from CheckIndex; see checkindex.log')
  786. actualVersion = m.group(1)
  787. if removeTrailingZeros(actualVersion) != removeTrailingZeros(version):
  788. raise RuntimeError('wrong version from CheckIndex: got "%s" but expected "%s"' % (actualVersion, version))
  789. def removeTrailingZeros(version):
  790. return re.sub(r'(\.0)*$', '', version)
  791. def checkMaven(solrSrcUnpackPath, baseURL, tmpDir, gitRevision, version, isSigned, keysFile):
  792. POMtemplates = defaultdict()
  793. getPOMtemplates(solrSrcUnpackPath, POMtemplates, tmpDir)
  794. print(' download artifacts')
  795. artifacts = {'lucene': [], 'solr': []}
  796. for project in ('lucene', 'solr'):
  797. artifactsURL = '%s/%s/maven/org/apache/%s/' % (baseURL, project, project)
  798. targetDir = '%s/maven/org/apache/%s' % (tmpDir, project)
  799. if not os.path.exists(targetDir):
  800. os.makedirs(targetDir)
  801. crawl(artifacts[project], artifactsURL, targetDir)
  802. print()
  803. verifyPOMperBinaryArtifact(artifacts, version)
  804. verifyArtifactPerPOMtemplate(POMtemplates, artifacts, tmpDir, version)
  805. verifyMavenDigests(artifacts)
  806. checkJavadocAndSourceArtifacts(artifacts, version)
  807. verifyDeployedPOMsCoordinates(artifacts, version)
  808. if isSigned:
  809. verifyMavenSigs(baseURL, tmpDir, artifacts, keysFile)
  810. distFiles = getBinaryDistFilesForMavenChecks(tmpDir, version, baseURL)
  811. checkIdenticalMavenArtifacts(distFiles, artifacts, version)
  812. checkAllJARs('%s/maven/org/apache/lucene' % tmpDir, 'lucene', gitRevision, version, tmpDir, baseURL)
  813. checkAllJARs('%s/maven/org/apache/solr' % tmpDir, 'solr', gitRevision, version, tmpDir, baseURL)
  814. def getBinaryDistFilesForMavenChecks(tmpDir, version, baseURL):
  815. # TODO: refactor distribution unpacking so that it only happens once per distribution per smoker run
  816. distFiles = defaultdict()
  817. for project in ('lucene', 'solr'):
  818. distFiles[project] = getBinaryDistFiles(project, tmpDir, version, baseURL)
  819. return distFiles
  820. def getBinaryDistFiles(project, tmpDir, version, baseURL):
  821. distribution = '%s-%s.tgz' % (project, version)
  822. if not os.path.exists('%s/%s' % (tmpDir, distribution)):
  823. distURL = '%s/%s/%s' % (baseURL, project, distribution)
  824. print(' download %s...' % distribution, end=' ')
  825. download(distribution, distURL, tmpDir, force_clean=FORCE_CLEAN)
  826. destDir = '%s/unpack-%s-getBinaryDistFiles' % (tmpDir, project)
  827. if os.path.exists(destDir):
  828. shutil.rmtree(destDir)
  829. os.makedirs(destDir)
  830. os.chdir(destDir)
  831. print(' unpack %s...' % distribution)
  832. unpackLogFile = '%s/unpack-%s-getBinaryDistFiles.log' % (tmpDir, distribution)
  833. run('tar xzf %s/%s' % (tmpDir, distribution), unpackLogFile)
  834. distributionFiles = []
  835. for root, dirs, files in os.walk(destDir):
  836. distributionFiles.extend([os.path.join(root, file) for file in files])
  837. return distributionFiles
  838. def checkJavadocAndSourceArtifacts(artifacts, version):
  839. print(' check for javadoc and sources artifacts...')
  840. for project in ('lucene', 'solr'):
  841. for artifact in artifacts[project]:
  842. if artifact.endswith(version + '.jar'):
  843. javadocJar = artifact[:-4] + '-javadoc.jar'
  844. if javadocJar not in artifacts[project]:
  845. raise RuntimeError('missing: %s' % javadocJar)
  846. sourcesJar = artifact[:-4] + '-sources.jar'
  847. if sourcesJar not in artifacts[project]:
  848. raise RuntimeError('missing: %s' % sourcesJar)
  849. def getZipFileEntries(fileName):
  850. entries = []
  851. with zipfile.ZipFile(fileName) as zf:
  852. for zi in zf.infolist():
  853. entries.append(zi.filename)
  854. # Sort by name:
  855. entries.sort()
  856. return entries
  857. def checkIdenticalMavenArtifacts(distFiles, artifacts, version):
  858. print(' verify that Maven artifacts are same as in the binary distribution...')
  859. reJarWar = re.compile(r'%s\.[wj]ar$' % version) # exclude *-javadoc.jar and *-sources.jar
  860. for project in ('lucene', 'solr'):
  861. distFilenames = dict()
  862. for file in distFiles[project]:
  863. baseName = os.path.basename(file)
  864. distFilenames[baseName] = file
  865. for artifact in artifacts[project]:
  866. if reJarWar.search(artifact):
  867. artifactFilename = os.path.basename(artifact)
  868. if artifactFilename not in distFilenames:
  869. raise RuntimeError('Maven artifact %s is not present in %s binary distribution'
  870. % (artifact, project))
  871. else:
  872. identical = filecmp.cmp(artifact, distFilenames[artifactFilename], shallow=False)
  873. if not identical:
  874. raise RuntimeError('Maven artifact %s is not identical to %s in %s binary distribution'
  875. % (artifact, distFilenames[artifactFilename], project))
  876. def verifyMavenDigests(artifacts):
  877. print(" verify Maven artifacts' md5/sha1 digests...")
  878. reJarWarPom = re.compile(r'\.(?:[wj]ar|pom)$')
  879. for project in ('lucene', 'solr'):
  880. for artifactFile in [a for a in artifacts[project] if reJarWarPom.search(a)]:
  881. if artifactFile + '.md5' not in artifacts[project]:
  882. raise RuntimeError('missing: MD5 digest for %s' % artifactFile)
  883. if artifactFile + '.sha1' not in artifacts[project]:
  884. raise RuntimeError('missing: SHA1 digest for %s' % artifactFile)
  885. with open(artifactFile + '.md5', encoding='UTF-8') as md5File:
  886. md5Expected = md5File.read().strip()
  887. with open(artifactFile + '.sha1', encoding='UTF-8') as sha1File:
  888. sha1Expected = sha1File.read().strip()
  889. md5 = hashlib.md5()
  890. sha1 = hashlib.sha1()
  891. inputFile = open(artifactFile, 'rb')
  892. while True:
  893. bytes = inputFile.read(65536)
  894. if len(bytes) == 0:
  895. break
  896. md5.update(bytes)
  897. sha1.update(bytes)
  898. inputFile.close()
  899. md5Actual = md5.hexdigest()
  900. sha1Actual = sha1.hexdigest()
  901. if md5Actual != md5Expected:
  902. raise RuntimeError('MD5 digest mismatch for %s: expected %s but got %s'
  903. % (artifactFile, md5Expected, md5Actual))
  904. if sha1Actual != sha1Expected:
  905. raise RuntimeError('SHA1 digest mismatch for %s: expected %s but got %s'
  906. % (artifactFile, sha1Expected, sha1Actual))
  907. def getPOMcoordinate(treeRoot):
  908. namespace = '{http://maven.apache.org/POM/4.0.0}'
  909. groupId = treeRoot.find('%sgroupId' % namespace)
  910. if groupId is None:
  911. groupId = treeRoot.find('{0}parent/{0}groupId'.format(namespace))
  912. groupId = groupId.text.strip()
  913. artifactId = treeRoot.find('%sartifactId' % namespace).text.strip()
  914. version = treeRoot.find('%sversion' % namespace)
  915. if version is None:
  916. version = treeRoot.find('{0}parent/{0}version'.format(namespace))
  917. version = version.text.strip()
  918. packaging = treeRoot.find('%spackaging' % namespace)
  919. packaging = 'jar' if packaging is None else packaging.text.strip()
  920. return groupId, artifactId, packaging, version
  921. def verifyMavenSigs(baseURL, tmpDir, artifacts, keysFile):
  922. print(' verify maven artifact sigs', end=' ')
  923. for project in ('lucene', 'solr'):
  924. # Set up clean gpg world; import keys file:
  925. gpgHomeDir = '%s/%s.gpg' % (tmpDir, project)
  926. if os.path.exists(gpgHomeDir):
  927. shutil.rmtree(gpgHomeDir)
  928. os.makedirs(gpgHomeDir, 0o700)
  929. run('gpg --homedir %s --import %s' % (gpgHomeDir, keysFile),
  930. '%s/%s.gpg.import.log' % (tmpDir, project))
  931. reArtifacts = re.compile(r'\.(?:pom|[jw]ar)$')
  932. for artifactFile in [a for a in artifacts[project] if reArtifacts.search(a)]:
  933. artifact = os.path.basename(artifactFile)
  934. sigFile = '%s.asc' % artifactFile
  935. # Test sig (this is done with a clean brand-new GPG world)
  936. logFile = '%s/%s.%s.gpg.verify.log' % (tmpDir, project, artifact)
  937. run('gpg --homedir %s --verify %s %s' % (gpgHomeDir, sigFile, artifactFile),
  938. logFile)
  939. # Forward any GPG warnings, except the expected one (since it's a clean world)
  940. f = open(logFile)
  941. for line in f.readlines():
  942. if line.lower().find('warning') != -1 \
  943. and line.find('WARNING: This key is not certified with a trusted signature') == -1 \
  944. and line.find('WARNING: using insecure memory') == -1:
  945. print(' GPG: %s' % line.strip())
  946. f.close()
  947. # Test trust (this is done with the real users config)
  948. run('gpg --import %s' % keysFile,
  949. '%s/%s.gpg.trust.import.log' % (tmpDir, project))
  950. logFile = '%s/%s.%s.gpg.trust.log' % (tmpDir, project, artifact)
  951. run('gpg --verify %s %s' % (sigFile, artifactFile), logFile)
  952. # Forward any GPG warnings:
  953. f = open(logFile)
  954. for line in f.readlines():
  955. if line.lower().find('warning') != -1 \
  956. and line.find('WARNING: This key is not certified with a trusted signature') == -1 \
  957. and line.find('WARNING: using insecure memory') == -1:
  958. print(' GPG: %s' % line.strip())
  959. f.close()
  960. sys.stdout.write('.')
  961. print()
  962. def verifyPOMperBinaryArtifact(artifacts, version):
  963. print(' verify that each binary artifact has a deployed POM...')
  964. reBinaryJarWar = re.compile(r'%s\.[jw]ar$' % re.escape(version))
  965. for project in ('lucene', 'solr'):
  966. for artifact in [a for a in artifacts[project] if reBinaryJarWar.search(a)]:
  967. POM = artifact[:-4] + '.pom'
  968. if POM not in artifacts[project]:
  969. raise RuntimeError('missing: POM for %s' % artifact)
  970. def verifyDeployedPOMsCoordinates(artifacts, version):
  971. """
  972. verify that each POM's coordinate (drawn from its content) matches
  973. its filepath, and verify that the corresponding artifact exists.
  974. """
  975. print(" verify deployed POMs' coordinates...")
  976. for project in ('lucene', 'solr'):
  977. for POM in [a for a in artifacts[project] if a.endswith('.pom')]:
  978. treeRoot = ET.parse(POM).getroot()
  979. groupId, artifactId, packaging, POMversion = getPOMcoordinate(treeRoot)
  980. POMpath = '%s/%s/%s/%s-%s.pom' \
  981. % (groupId.replace('.', '/'), artifactId, version, artifactId, version)
  982. if not POM.endswith(POMpath):
  983. raise RuntimeError("Mismatch between POM coordinate %s:%s:%s and filepath: %s"
  984. % (groupId, artifactId, POMversion, POM))
  985. # Verify that the corresponding artifact exists
  986. artifact = POM[:-3] + packaging
  987. if artifact not in artifacts[project]:
  988. raise RuntimeError('Missing corresponding .%s artifact for POM %s' % (packaging, POM))
  989. def verifyArtifactPerPOMtemplate(POMtemplates, artifacts, tmpDir, version):
  990. print(' verify that there is an artifact for each POM template...')
  991. namespace = '{http://maven.apache.org/POM/4.0.0}'
  992. xpathPlugin = '{0}build/{0}plugins/{0}plugin'.format(namespace)
  993. xpathSkipConfiguration = '{0}configuration/{0}skip'.format(namespace)
  994. for project in ('lucene', 'solr'):
  995. for POMtemplate in POMtemplates[project]:
  996. treeRoot = ET.parse(POMtemplate).getroot()
  997. skipDeploy = False
  998. for plugin in treeRoot.findall(xpathPlugin):
  999. artifactId = plugin.find('%sartifactId' % namespace).text.strip()
  1000. if artifactId == 'maven-deploy-plugin':
  1001. skip = plugin.find(xpathSkipConfiguration)
  1002. if skip is not None: skipDeploy = (skip.text.strip().lower() == 'true')
  1003. if not skipDeploy:
  1004. groupId, artifactId, packaging, POMversion = getPOMcoordinate(treeRoot)
  1005. # Ignore POMversion, since its value will not have been interpolated
  1006. artifact = '%s/maven/%s/%s/%s/%s-%s.%s' \
  1007. % (tmpDir, groupId.replace('.', '/'), artifactId,
  1008. version, artifactId, version, packaging)
  1009. if artifact not in artifacts['lucene'] and artifact not in artifacts['solr']:
  1010. raise RuntimeError('Missing artifact %s' % artifact)
  1011. def getPOMtemplates(solrSrcUnpackPath, POMtemplates, tmpDir):
  1012. print(' find pom.xml.template files in the unpacked Solr source distribution')
  1013. allPOMtemplates = []
  1014. rePOMtemplate = re.compile(r'^pom\.xml\.template$')
  1015. for root, dirs, files in os.walk(solrSrcUnpackPath):
  1016. allPOMtemplates.extend([os.path.join(root, f) for f in files if rePOMtemplate.search(f)])
  1017. reLucenePOMtemplate = re.compile(r'.*/maven/lucene.*/pom\.xml\.template$')
  1018. POMtemplates['lucene'] = [p for p in allPOMtemplates if reLucenePOMtemplate.search(p)]
  1019. if POMtemplates['lucene'] is None:
  1020. raise RuntimeError('No Lucene POMs found at %s' % solrSrcUnpackPath)
  1021. reSolrPOMtemplate = re.compile(r'.*/maven/solr.*/pom\.xml\.template$')
  1022. POMtemplates['solr'] = [p for p in allPOMtemplates if reSolrPOMtemplate.search(p)]
  1023. if POMtemplates['solr'] is None:
  1024. raise RuntimeError('No Solr POMs found at %s' % solrSrcUnpackPath)
  1025. POMtemplates['grandfather'] = [p for p in allPOMtemplates if '/maven/pom.xml.template' in p]
  1026. if len(POMtemplates['grandfather']) == 0:
  1027. raise RuntimeError('No Lucene/Solr grandfather POM found at %s' % solrSrcUnpackPath)
  1028. def crawl(downloadedFiles, urlString, targetDir, exclusions=set()):
  1029. for text, subURL in getDirEntries(urlString):
  1030. if text not in exclusions:
  1031. path = os.path.join(targetDir, text)
  1032. if text.endswith('/'):
  1033. if not os.path.exists(path):
  1034. os.makedirs(path)
  1035. crawl(downloadedFiles, subURL, path, exclusions)
  1036. else:
  1037. if not os.path.exists(path) or FORCE_CLEAN:
  1038. download(text, subURL, targetDir, quiet=True, force_clean=FORCE_CLEAN)
  1039. downloadedFiles.append(path)
  1040. sys.stdout.write('.')
  1041. def make_java_config(parser, java12_home):
  1042. def _make_runner(java_home, version):
  1043. print('Java %s JAVA_HOME=%s' % (version, java_home))
  1044. if cygwin:
  1045. java_home = subprocess.check_output('cygpath -u "%s"' % java_home, shell=True).decode('utf-8').strip()
  1046. cmd_prefix = 'export JAVA_HOME="%s" PATH="%s/bin:$PATH" JAVACMD="%s/bin/java"' % \
  1047. (java_home, java_home, java_home)
  1048. s = subprocess.check_output('%s; java -version' % cmd_prefix,
  1049. shell=True, stderr=subprocess.STDOUT).decode('utf-8')
  1050. if s.find(' version "%s' % version) == -1:
  1051. parser.error('got wrong version for java %s:\n%s' % (version, s))
  1052. def run_java(cmd, logfile):
  1053. run('%s; %s' % (cmd_prefix, cmd), logfile)
  1054. return run_java
  1055. java11_home = os.environ.get('JAVA_HOME')
  1056. if java11_home is None:
  1057. parser.error('JAVA_HOME must be set')
  1058. run_java11 = _make_runner(java11_home, '11')
  1059. run_java12 = None
  1060. if java12_home is not None:
  1061. run_java12 = _make_runner(java12_home, '12')
  1062. jc = namedtuple('JavaConfig'

Large files files are truncated, but you can click here to view the full file