Jenkinsfile 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930
  1. #!/usr/bin/env groovy
  2. /*
  3. * Copyright (c) Contributors to the Open 3D Engine Project.
  4. * For complete copyright and license terms please see the LICENSE at the root of this distribution.
  5. *
  6. * SPDX-License-Identifier: Apache-2.0 OR MIT
  7. *
  8. */
  9. import groovy.json.JsonOutput
  10. PIPELINE_CONFIG_FILE = 'scripts/build/Jenkins/lumberyard.json'
  11. INCREMENTAL_BUILD_SCRIPT_PATH = 'scripts/build/bootstrap/incremental_build_util.py'
  12. PIPELINE_RETRY_ATTEMPTS = 3
  13. EMPTY_JSON = readJSON text: '{}'
  14. PROJECT_REPOSITORY_NAME = 'loft-arch-vis-sample'
  15. PROJECT_ORGANIZATION_NAME = 'aws-lumberyard'
  16. PROJECT_PATH = "Project"
  17. ENGINE_REPOSITORY_NAME = 'o3de'
  18. ENGINE_ORGANIZATION_NAME = 'o3de'
  19. ENGINE_BRANCH_DEFAULT = "${env.BRANCH_DEFAULT}" ?: "${env.BRANCH_NAME}"
  20. // Branches with build snapshots
  21. BUILD_SNAPSHOTS = ['development', 'stabilization/2205']
  22. // Build snapshots with empty snapshot (for use with 'SNAPSHOT' pipeline parameter)
  23. BUILD_SNAPSHOTS_WITH_EMPTY = BUILD_SNAPSHOTS + ''
  24. // The default build snapshot to be selected in the 'SNAPSHOT' pipeline parameter
  25. DEFAULT_BUILD_SNAPSHOT = BUILD_SNAPSHOTS_WITH_EMPTY.get(0)
  26. // Branches with build snapshots as comma separated value string
  27. env.BUILD_SNAPSHOTS = BUILD_SNAPSHOTS.join(",")
  28. def pipelineProperties = []
  29. def pipelineParameters = [
  30. // Build/clean Parameters
  31. // The CLEAN_OUTPUT_DIRECTORY is used by ci_build scripts. Creating the parameter here passes it as an environment variable to jobs and is consumed that way
  32. booleanParam(defaultValue: false, description: 'Deletes the contents of the output directory before building. This will cause a \"clean\" build. NOTE: does not imply CLEAN_ASSETS', name: 'CLEAN_OUTPUT_DIRECTORY'),
  33. booleanParam(defaultValue: false, description: 'Deletes the contents of the output directories of the AssetProcessor before building.', name: 'CLEAN_ASSETS'),
  34. booleanParam(defaultValue: false, description: 'Deletes the contents of the workspace and forces a complete pull.', name: 'CLEAN_WORKSPACE'),
  35. booleanParam(defaultValue: false, description: 'Recreates the volume used for the workspace. The volume will be created out of a snapshot taken from main.', name: 'RECREATE_VOLUME'),
  36. stringParam(defaultValue: "${ENGINE_BRANCH_DEFAULT}", description: 'Sets a different branch from o3de engine repo to use or use commit id. Default is branchname', trim: true, name: 'ENGINE_BRANCH')
  37. ]
  38. def palSh(cmd, lbl = '', winSlashReplacement = true, winCharReplacement = true) {
  39. if (env.IS_UNIX) {
  40. sh label: lbl,
  41. script: cmd
  42. } else {
  43. if (winSlashReplacement) {
  44. cmd = cmd.replace('/','\\')
  45. }
  46. if (winCharReplacement) {
  47. cmd = cmd.replace('%', '%%')
  48. }
  49. bat label: lbl,
  50. script: cmd
  51. }
  52. }
  53. def palMkdir(path) {
  54. if (env.IS_UNIX) {
  55. sh label: "Making directories ${path}",
  56. script: "mkdir -p ${path}"
  57. } else {
  58. def win_path = path.replace('/','\\')
  59. bat label: "Making directories ${win_path}",
  60. script: "mkdir ${win_path}."
  61. }
  62. }
  63. def palRm(path) {
  64. if (env.IS_UNIX) {
  65. sh label: "Removing ${path}",
  66. script: "rm ${path}"
  67. } else {
  68. def win_path = path.replace('/','\\')
  69. bat label: "Removing ${win_path}",
  70. script: "del /Q ${win_path}"
  71. }
  72. }
  73. def palRmDir(path) {
  74. if (env.IS_UNIX) {
  75. sh label: "Removing ${path}",
  76. script: "if [ -d ${path} ]; then rm -rf ${path}; fi"
  77. } else {
  78. def win_path = path.replace('/','\\')
  79. bat label: "Removing ${win_path}",
  80. script: "IF exist ${win_path} rd /s /q ${win_path}"
  81. }
  82. }
  83. def IsPullRequest(branchName) {
  84. // temporarily using the name to detect if we are in a PR
  85. // In the future we will check with github
  86. return branchName.startsWith('PR-')
  87. }
  88. def IsJobEnabled(branchName, buildTypeMap, pipelineName, platformName) {
  89. if (IsPullRequest(branchName)) {
  90. return buildTypeMap.value.TAGS && buildTypeMap.value.TAGS.contains(pipelineName)
  91. }
  92. def job_list_override = params.JOB_LIST_OVERRIDE ? params.JOB_LIST_OVERRIDE.tokenize(',') : ''
  93. if (!job_list_override.isEmpty()) {
  94. return params[platformName] && job_list_override.contains(buildTypeMap.key);
  95. } else {
  96. return params[platformName] && buildTypeMap.value.TAGS && buildTypeMap.value.TAGS.contains(pipelineName)
  97. }
  98. }
  99. def IsAPLogUpload(branchName, jobName) {
  100. return !IsPullRequest(branchName) && jobName.toLowerCase().contains('asset') && env.AP_LOGS_S3_BUCKET
  101. }
  102. def GetRunningPipelineName(JENKINS_JOB_NAME) {
  103. // If the job name has an underscore
  104. def job_parts = JENKINS_JOB_NAME.tokenize('/')[0].tokenize('_')
  105. if (job_parts.size() > 1) {
  106. return [job_parts.take(job_parts.size() - 1).join('_'), job_parts[job_parts.size()-1]]
  107. }
  108. return [job_parts[0], 'default']
  109. }
  110. @NonCPS
  111. def RegexMatcher(str, regex) {
  112. def matcher = (str =~ regex)
  113. return matcher ? matcher.group(1) : null
  114. }
  115. def LoadPipelineConfig(String pipelineName, String branchName) {
  116. echo 'Loading pipeline config'
  117. def pipelineConfig = {}
  118. pipelineConfig = readJSON file: PIPELINE_CONFIG_FILE
  119. palRm(PIPELINE_CONFIG_FILE)
  120. pipelineConfig.platforms = EMPTY_JSON
  121. // Load the pipeline configs per platform
  122. pipelineConfig.PIPELINE_CONFIGS.each { pipeline_config ->
  123. def platform_regex = pipeline_config.replace('.','\\.').replace('*', '(.*)')
  124. if (!env.IS_UNIX) {
  125. platform_regex = platform_regex.replace('/','\\\\')
  126. }
  127. echo "Searching platform pipeline configs in ${pipeline_config} using ${platform_regex}"
  128. for (pipeline_config_path in findFiles(glob: pipeline_config)) {
  129. echo "\tFound platform pipeline config ${pipeline_config_path}"
  130. def platform = RegexMatcher(pipeline_config_path, platform_regex)
  131. if (platform) {
  132. pipelineConfig.platforms[platform] = EMPTY_JSON
  133. pipelineConfig.platforms[platform].PIPELINE_ENV = readJSON file: pipeline_config_path.toString()
  134. }
  135. palRm(pipeline_config_path.toString())
  136. }
  137. }
  138. // Load the build configs
  139. pipelineConfig.BUILD_CONFIGS.each { build_config ->
  140. def platform_regex = build_config.replace('.','\\.').replace('*', '(.*)')
  141. if (!env.IS_UNIX) {
  142. platform_regex = platform_regex.replace('/','\\\\')
  143. }
  144. echo "Searching configs in ${build_config} using ${platform_regex}"
  145. for (build_config_path in findFiles(glob: build_config)) {
  146. echo "\tFound config ${build_config_path}"
  147. def platform = RegexMatcher(build_config_path, platform_regex)
  148. if (platform) {
  149. pipelineConfig.platforms[platform].build_types = readJSON file: build_config_path.toString()
  150. }
  151. }
  152. }
  153. return pipelineConfig
  154. }
  155. def GetBuildEnvVars(Map platformEnv, Map buildTypeEnv, String pipelineName) {
  156. def envVarMap = [:]
  157. platformPipelineEnv = platformEnv['ENV'] ?: [:]
  158. platformPipelineEnv.each { var ->
  159. envVarMap[var.key] = var.value
  160. }
  161. platformEnvOverride = platformEnv['PIPELINE_ENV_OVERRIDE'] ?: [:]
  162. platformPipelineEnvOverride = platformEnvOverride[pipelineName] ?: [:]
  163. platformPipelineEnvOverride.each { var ->
  164. envVarMap[var.key] = var.value
  165. }
  166. buildTypeEnv.each { var ->
  167. // This may override the above one if there is an entry defined by the job
  168. envVarMap[var.key] = var.value
  169. }
  170. // Environment that only applies to to Jenkins tweaks.
  171. // For 3rdParty downloads, we store them in the EBS volume so we can reuse them across node
  172. // instances. This allow us to scale up and down without having to re-download 3rdParty
  173. envVarMap['LY_PACKAGE_DOWNLOAD_CACHE_LOCATION'] = "${envVarMap['WORKSPACE']}/3rdParty/downloaded_packages"
  174. envVarMap['LY_PACKAGE_UNPACK_LOCATION'] = "${envVarMap['WORKSPACE']}/3rdParty/packages"
  175. return envVarMap
  176. }
  177. def GetEnvStringList(Map envVarMap) {
  178. def strList = []
  179. envVarMap.each { var ->
  180. strList.add("${var.key}=${var.value}")
  181. }
  182. return strList
  183. }
  184. def GetEngineRemoteConfig(remoteConfigs) {
  185. def engineRemoteConfigs = [name: "${ENGINE_REPOSITORY_NAME}",
  186. url: remoteConfigs.url[0]
  187. .replace("${PROJECT_REPOSITORY_NAME}", "${ENGINE_REPOSITORY_NAME}")
  188. .replace("/${PROJECT_ORGANIZATION_NAME}/", "/${ENGINE_ORGANIZATION_NAME}/"),
  189. credentialsId: remoteConfigs.credentialsId[0]
  190. ]
  191. return engineRemoteConfigs
  192. }
  193. def CheckoutBootstrapScripts(String branchName) {
  194. checkout([$class: 'GitSCM',
  195. branches: [[name: "*/${branchName}"]],
  196. doGenerateSubmoduleConfigurations: false,
  197. extensions: [
  198. [$class: 'PruneStaleBranch'],
  199. [$class: 'AuthorInChangelog'],
  200. [$class: 'SparseCheckoutPaths', sparseCheckoutPaths: [
  201. [ $class: 'SparseCheckoutPath', path: 'scripts/build/Jenkins/' ],
  202. [ $class: 'SparseCheckoutPath', path: 'scripts/build/bootstrap/' ],
  203. [ $class: 'SparseCheckoutPath', path: 'scripts/build/Platform' ]
  204. ]],
  205. // Shallow checkouts break changelog computation. Do not enable.
  206. [$class: 'CloneOption', noTags: false, reference: '', shallow: false]
  207. ],
  208. submoduleCfg: [],
  209. userRemoteConfigs: [GetEngineRemoteConfig(scm.userRemoteConfigs)]
  210. ])
  211. }
  212. def CheckoutRepo(boolean disableSubmodules = false) {
  213. def projectsAndUrl = [
  214. "${ENGINE_REPOSITORY_NAME}": GetEngineRemoteConfig(scm.userRemoteConfigs),
  215. "${PROJECT_REPOSITORY_NAME}": scm.userRemoteConfigs[0]
  216. ]
  217. projectsAndUrl.each { projectAndUrl ->
  218. if (!fileExists(projectAndUrl.key)) {
  219. palMkdir(projectAndUrl.key)
  220. }
  221. dir(projectAndUrl.key) {
  222. palSh('git lfs uninstall', 'Git LFS Uninstall') // Prevent git from pulling lfs objects during checkout
  223. if (fileExists('.git')) {
  224. // If the repository after checkout is locked, likely we took a snapshot while git was running,
  225. // to leave the repo in a usable state, garbage collect.
  226. def indexLockFile = '.git/index.lock'
  227. if (fileExists(indexLockFile)) {
  228. palSh('git gc', 'Git GarbageCollect')
  229. }
  230. if (fileExists(indexLockFile)) { // if it is still there, remove it
  231. palRm(indexLockFile)
  232. }
  233. }
  234. }
  235. }
  236. def random = new Random()
  237. def retryAttempt = 0
  238. retry(5) {
  239. if (retryAttempt > 0) {
  240. sleep random.nextInt(60 * retryAttempt) // Stagger checkouts to prevent HTTP 429 (Too Many Requests) response from Github
  241. }
  242. retryAttempt = retryAttempt + 1
  243. projectsAndUrl.each { projectAndUrl ->
  244. dir(projectAndUrl.key) {
  245. def branchName = scm.branches
  246. if (projectAndUrl.key == "${ENGINE_REPOSITORY_NAME}") {
  247. branchName = [[name: params.ENGINE_BRANCH]]
  248. }
  249. checkout scm: [
  250. $class: 'GitSCM',
  251. branches: branchName,
  252. extensions: [
  253. [$class: 'PruneStaleBranch'],
  254. [$class: 'AuthorInChangelog'],
  255. [$class: 'SubmoduleOption', disableSubmodules: disableSubmodules, recursiveSubmodules: true],
  256. [$class: 'CheckoutOption', timeout: 60]
  257. ],
  258. userRemoteConfigs: [projectAndUrl.value]
  259. ]
  260. }
  261. }
  262. }
  263. // CHANGE_ID is used by some scripts to identify uniquely the current change (usually metric jobs)
  264. dir(PROJECT_REPOSITORY_NAME) {
  265. palSh('git rev-parse HEAD > commitid', 'Getting commit id')
  266. env.CHANGE_ID = readFile file: 'commitid'
  267. env.CHANGE_ID = env.CHANGE_ID.trim()
  268. palRm('commitid')
  269. // CHANGE_DATE is used by the installer to provide some ability to sort tagged builds in addition to BRANCH_NAME and CHANGE_ID
  270. commitDateFmt = '%%cI'
  271. if (env.IS_UNIX) commitDateFmt = '%cI'
  272. palSh("git show -s --format=${commitDateFmt} ${env.CHANGE_ID} > commitdate", 'Getting commit date')
  273. env.CHANGE_DATE = readFile file: 'commitdate'
  274. env.CHANGE_DATE = env.CHANGE_DATE.trim()
  275. palRm('commitdate')
  276. }
  277. }
  278. def HandleDriveMount(String snapshot, String repositoryName, String projectName, String pipeline, String branchName, String platform, String buildType, String workspace, boolean recreateVolume = false) {
  279. unstash name: 'incremental_build_script'
  280. def pythonCmd = ''
  281. if (env.IS_UNIX) pythonCmd = 'sudo -E python3 -u '
  282. else pythonCmd = 'python3 -u '
  283. if(recreateVolume) {
  284. palSh("${pythonCmd} ${INCREMENTAL_BUILD_SCRIPT_PATH} --action delete --repository_name ${repositoryName} --project ${projectName} --pipeline ${pipeline} --branch ${branchName} --platform ${platform} --build_type ${buildType}", 'Deleting volume', winSlashReplacement=false)
  285. }
  286. palSh("${pythonCmd} ${INCREMENTAL_BUILD_SCRIPT_PATH} --action mount --snapshot ${snapshot} --repository_name ${repositoryName} --project ${projectName} --pipeline ${pipeline} --branch ${branchName} --platform ${platform} --build_type ${buildType}", 'Mounting volume', winSlashReplacement=false)
  287. if (env.IS_UNIX) {
  288. sh label: 'Setting volume\'s ownership',
  289. script: """
  290. if sudo test ! -d "${workspace}"; then
  291. sudo mkdir -p ${workspace}
  292. cd ${workspace}/..
  293. sudo chown -R lybuilder:root .
  294. fi
  295. """
  296. }
  297. }
  298. def PreBuildCommonSteps(Map pipelineConfig, String snapshot, String repositoryName, String projectName, String pipeline, String branchName, String platform, String buildType, String workspace, boolean mount = true, boolean disableSubmodules = false) {
  299. echo 'Starting pre-build common steps...'
  300. if (mount) {
  301. if(env.RECREATE_VOLUME?.toBoolean()){
  302. echo 'Starting to recreating drive...'
  303. HandleDriveMount(snapshot, repositoryName, projectName, pipeline, branchName, platform, buildType, workspace, true)
  304. } else {
  305. echo 'Starting to mounting drive...'
  306. HandleDriveMount(snapshot, repositoryName, projectName, pipeline, branchName, platform, buildType, workspace, false)
  307. }
  308. }
  309. // Cleanup previous repo location, we are currently at the root of the workspace, if we have a .git folder
  310. // we need to cleanup. Once all branches take this relocation, we can remove this
  311. if (env.CLEAN_WORKSPACE?.toBoolean() || fileExists("${workspace}/.git")) {
  312. if (fileExists(workspace)) {
  313. palRmDir(workspace)
  314. }
  315. }
  316. dir(workspace) {
  317. // Add folder where we will store the 3rdParty downloads and packages
  318. if (!fileExists('3rdParty')) {
  319. palMkdir('3rdParty')
  320. }
  321. CheckoutRepo(disableSubmodules)
  322. }
  323. dir("${workspace}/${ENGINE_REPOSITORY_NAME}") {
  324. // Get python
  325. if (env.IS_UNIX) {
  326. sh label: 'Getting python',
  327. script: 'python/get_python.sh'
  328. } else {
  329. bat label: 'Getting python',
  330. script: 'python/get_python.bat'
  331. }
  332. // Always run the clean step, the scripts detect what variables were set, but it also cleans if
  333. // the NODE_LABEL has changed
  334. def command = "${pipelineConfig.PYTHON_DIR}/python"
  335. if (env.IS_UNIX) command += '.sh'
  336. else command += '.cmd'
  337. command += " -u ${pipelineConfig.BUILD_ENTRY_POINT} --platform ${platform} --type clean"
  338. palSh(command, "Running ${platform} clean")
  339. // Run lfs in a separate step. Jenkins is unable to load the credentials for the custom LFS endpoint
  340. withCredentials([usernamePassword(credentialsId: "${env.GITHUB_USER}", passwordVariable: 'accesstoken', usernameVariable: 'username')]) {
  341. palSh("git config -f .lfsconfig lfs.url https://${username}:${accesstoken}@${env.LFS_URL}", 'Set credentials', false)
  342. }
  343. if(fileExists('.lfsconfig')) {
  344. palSh("git lfs install", "LFS config exists. Installing LFS hooks to local repo")
  345. palSh("git lfs pull", "Pulling new LFS objects")
  346. }
  347. }
  348. }
  349. def Build(Map pipelineConfig, String platform, String type, String workspace) {
  350. // If EXECUTE_FROM_PROJECT is defined, we execute the script from the project instead of from the engine
  351. // In both cases, the scripts are in the engine, is just what the current dir is and how we get to the scripts
  352. def currentDir = "${workspace}/${ENGINE_REPOSITORY_NAME}"
  353. def pathToEngine = ""
  354. timeout(time: env.TIMEOUT, unit: 'MINUTES', activity: true) {
  355. def command = "${pipelineConfig.PYTHON_DIR}/python"
  356. def ext = ''
  357. if (env.IS_UNIX) {
  358. command += '.sh'
  359. ext = '.sh'
  360. }
  361. else command += '.cmd'
  362. // Setup environment for project execution, otherwise, register the project
  363. if (env.EXECUTE_FROM_PROJECT?.toBoolean()) {
  364. currentDir = "${workspace}/${PROJECT_REPOSITORY_NAME}"
  365. pathToEngine = "../${ENGINE_REPOSITORY_NAME}/"
  366. } else {
  367. dir("${workspace}/${ENGINE_REPOSITORY_NAME}") {
  368. palSh("scripts/o3de${ext} register --project-path ${workspace}/${PROJECT_REPOSITORY_NAME}/${PROJECT_PATH}", "Registering project ${PROJECT_REPOSITORY_NAME}")
  369. }
  370. }
  371. command += " -u ${pipelineConfig.BUILD_ENTRY_POINT} --platform ${platform} --type ${type}"
  372. dir("${workspace}/${ENGINE_REPOSITORY_NAME}") {
  373. palSh(command, "Running ${platform} ${type}")
  374. }
  375. }
  376. }
  377. def TestMetrics(Map pipelineConfig, String workspace, String branchName, String repoName, String buildJobName, String outputDirectory, String configuration) {
  378. catchError(buildResult: null, stageResult: null) {
  379. def cmakeBuildDir = [workspace, ENGINE_REPOSITORY_NAME, outputDirectory].join('/')
  380. dir("${workspace}/${ENGINE_REPOSITORY_NAME}") {
  381. checkout scm: [
  382. $class: 'GitSCM',
  383. branches: [[name: '*/main']],
  384. extensions: [
  385. [$class: 'AuthorInChangelog'],
  386. [$class: 'RelativeTargetDirectory', relativeTargetDir: 'mars']
  387. ],
  388. userRemoteConfigs: [[url: "${env.MARS_REPO}", name: 'mars', credentialsId: "${env.GITHUB_USER}"]]
  389. ]
  390. withCredentials([usernamePassword(credentialsId: "${env.SERVICE_USER}", passwordVariable: 'apitoken', usernameVariable: 'username')]) {
  391. def command = "${pipelineConfig.PYTHON_DIR}/python.cmd -u mars/scripts/python/ctest_test_metric_scraper.py " +
  392. '-e jenkins.creds.user %username% -e jenkins.creds.pass %apitoken% ' +
  393. "-e jenkins.base_url ${env.JENKINS_URL} " +
  394. "${cmakeBuildDir} ${branchName} %BUILD_NUMBER% AR ${configuration} ${repoName} --url ${env.BUILD_URL.replace('%','%%')}"
  395. bat label: "Publishing ${buildJobName} Test Metrics",
  396. script: command
  397. }
  398. }
  399. }
  400. }
  401. def BenchmarkMetrics(Map pipelineConfig, String workspace, String branchName, String outputDirectory) {
  402. catchError(buildResult: null, stageResult: null) {
  403. def cmakeBuildDir = [workspace, ENGINE_REPOSITORY_NAME, outputDirectory].join('/')
  404. dir("${workspace}/${ENGINE_REPOSITORY_NAME}") {
  405. checkout scm: [
  406. $class: 'GitSCM',
  407. branches: [[name: '*/main']],
  408. extensions: [
  409. [$class: 'AuthorInChangelog'],
  410. [$class: 'RelativeTargetDirectory', relativeTargetDir: 'mars']
  411. ],
  412. userRemoteConfigs: [[url: "${env.MARS_REPO}", name: 'mars', credentialsId: "${env.GITHUB_USER}"]]
  413. ]
  414. def command = "${pipelineConfig.PYTHON_DIR}/python.cmd -u mars/scripts/python/benchmark_scraper.py ${cmakeBuildDir} ${branchName}"
  415. palSh(command, "Publishing Benchmark Metrics")
  416. }
  417. }
  418. }
  419. def ExportTestResults(Map options, String platform, String type, String workspace, Map params) {
  420. catchError(message: "Error exporting tests results (this won't fail the build)", buildResult: 'SUCCESS', stageResult: 'FAILURE') {
  421. def o3deroot = "${workspace}/${ENGINE_REPOSITORY_NAME}"
  422. dir("${o3deroot}/${params.OUTPUT_DIRECTORY}") {
  423. junit testResults: "Testing/**/*.xml", skipPublishingChecks: true
  424. palRmDir("Testing")
  425. // Recreate test runner xml directories that need to be pre generated
  426. palMkdir("Testing/Pytest")
  427. palMkdir("Testing/Gtest")
  428. }
  429. }
  430. }
  431. def ExportTestScreenshots(Map options, String branchName, String platformName, String jobName, String workspace, Map params) {
  432. catchError(message: "Error exporting test screenshots (this won't fail the build)", buildResult: 'SUCCESS', stageResult: 'FAILURE') {
  433. dir("${workspace}/${ENGINE_REPOSITORY_NAME}") {
  434. def screenshotsFolder = "${workspace}/${PROJECT_REPOSITORY_NAME}/user/Scripts/Screenshots"
  435. def s3Uploader = "scripts/build/tools/upload_to_s3.py"
  436. def command = "${options.PYTHON_DIR}/python.cmd -u ${s3Uploader} --base_dir ${screenshotsFolder} " +
  437. '--file_regex \\"(.*\$)\\" ' +
  438. "--bucket ${env.TEST_SCREENSHOT_BUCKET} " +
  439. "--search_subdirectories True --key_prefix ${PROJECT_REPOSITORY_NAME}/${branchName}/${env.BUILD_NUMBER}/${jobName} " +
  440. '--extra_args {\\"ACL\\":\\"bucket-owner-full-control\\"}'
  441. palSh(command, "Uploading test screenshots for ${jobName}")
  442. }
  443. }
  444. }
  445. def UploadAPLogs(Map options, String branchName, String platformName, String jobName, String workspace, Map params) {
  446. catchError(message: "Error exporting logs (this won't fail the build)", buildResult: 'SUCCESS', stageResult: 'FAILURE') {
  447. dir("${workspace}/${ENGINE_REPOSITORY_NAME}") {
  448. def apLogsPath = "${workspace}/${PROJECT_REPOSITORY_NAME}/user/log"
  449. def s3UploadScriptPath = "scripts/build/tools/upload_to_s3.py"
  450. if(env.IS_UNIX) {
  451. pythonPath = "${options.PYTHON_DIR}/python.sh"
  452. }
  453. else {
  454. pythonPath = "${options.PYTHON_DIR}/python.cmd"
  455. }
  456. def command = "${pythonPath} -u ${s3UploadScriptPath} --base_dir ${apLogsPath} " +
  457. "--file_regex \".*\" --bucket ${env.AP_LOGS_S3_BUCKET} " +
  458. "--search_subdirectories True --key_prefix ${PROJECT_REPOSITORY_NAME}/${branchName}/${env.BUILD_NUMBER}/${platformName}/${jobName} " +
  459. '--extra_args {\\"ACL\\":\\"bucket-owner-full-control\\"}'
  460. palSh(command, "Uploading AP logs for job ${jobName} for branch ${branchName}", false)
  461. }
  462. }
  463. }
  464. def PostBuildCommonSteps(String workspace, boolean mount = true) {
  465. echo 'Starting post-build common steps...'
  466. if (mount) {
  467. def pythonCmd = ''
  468. if (env.IS_UNIX) pythonCmd = 'sudo -E python3 -u '
  469. else pythonCmd = 'python3 -u '
  470. try {
  471. timeout(5) {
  472. palSh("${pythonCmd} ${INCREMENTAL_BUILD_SCRIPT_PATH} --action unmount", 'Unmounting volume')
  473. }
  474. } catch (Exception e) {
  475. echo "Unmount script error ${e}"
  476. }
  477. }
  478. }
  479. def CreateSetupStage(Map pipelineConfig, String snapshot, String repositoryName, String projectName, String pipelineName, String branchName, String platformName, String jobName, Map environmentVars, boolean onlyMountEBSVolume = false) {
  480. return {
  481. stage('Setup') {
  482. if(onlyMountEBSVolume) {
  483. HandleDriveMount(snapshot, repositoryName, projectName, pipelineName, branchName, platformName, jobName, environmentVars['WORKSPACE'], false)
  484. } else {
  485. PreBuildCommonSteps(pipelineConfig, snapshot, repositoryName, projectName, pipelineName, branchName, platformName, jobName, environmentVars['WORKSPACE'], environmentVars['MOUNT_VOLUME'])
  486. }
  487. }
  488. }
  489. }
  490. def CreateBuildStage(Map pipelineConfig, String platformName, String jobName, Map environmentVars) {
  491. return {
  492. stage("${jobName}") {
  493. Build(pipelineConfig, platformName, jobName, environmentVars['WORKSPACE'])
  494. }
  495. }
  496. }
  497. def CreateTestMetricsStage(Map pipelineConfig, String branchName, Map environmentVars, String buildJobName, String outputDirectory, String configuration) {
  498. return {
  499. stage("${buildJobName}_metrics") {
  500. TestMetrics(pipelineConfig, environmentVars['WORKSPACE'], branchName, env.DEFAULT_REPOSITORY_NAME, buildJobName, outputDirectory, configuration)
  501. BenchmarkMetrics(pipelineConfig, environmentVars['WORKSPACE'], branchName, outputDirectory)
  502. }
  503. }
  504. }
  505. def CreateExportTestResultsStage(Map pipelineConfig, String platformName, String jobName, Map environmentVars, Map params) {
  506. return {
  507. stage("${jobName}_results") {
  508. ExportTestResults(pipelineConfig, platformName, jobName, environmentVars['WORKSPACE'], params)
  509. }
  510. }
  511. }
  512. def CreateExportTestScreenshotsStage(Map pipelineConfig, String branchName, String platformName, String jobName, Map environmentVars, Map params) {
  513. return {
  514. stage("${jobName}_screenshots") {
  515. ExportTestScreenshots(pipelineConfig, branchName, platformName, jobName, environmentVars['WORKSPACE'], params)
  516. }
  517. }
  518. }
  519. def CreateUploadAPLogsStage(Map pipelineConfig, String branchName, String platformName, String jobName, String workspace, Map params) {
  520. return {
  521. stage("${jobName}_upload_ap_logs") {
  522. UploadAPLogs(pipelineConfig, branchName, platformName, jobName, workspace, params)
  523. }
  524. }
  525. }
  526. def CreateTeardownStage(Map environmentVars) {
  527. return {
  528. stage('Teardown') {
  529. PostBuildCommonSteps(environmentVars['WORKSPACE'], environmentVars['MOUNT_VOLUME'])
  530. }
  531. }
  532. }
  533. def CreateSingleNode(Map pipelineConfig, def platform, def build_job, Map envVars, String branchName, String pipelineName, String repositoryName, String projectName, boolean onlyMountEBSVolume = false) {
  534. def nodeLabel = envVars['NODE_LABEL']
  535. return {
  536. def currentResult = ''
  537. def currentException = ''
  538. retry(PIPELINE_RETRY_ATTEMPTS) {
  539. node("${nodeLabel}") {
  540. if(isUnix()) { // Has to happen inside a node
  541. envVars['IS_UNIX'] = 1
  542. }
  543. withEnv(GetEnvStringList(envVars)) {
  544. def build_job_name = build_job.key
  545. try {
  546. CreateSetupStage(pipelineConfig, snapshot, repositoryName, projectName, pipelineName, branchName, platform.key, build_job.key, envVars, onlyMountEBSVolume).call()
  547. if(build_job.value.steps) { //this is a pipe with many steps so create all the build stages
  548. pipelineEnvVars = GetBuildEnvVars(platform.value.PIPELINE_ENV ?: EMPTY_JSON, build_job.value.PIPELINE_ENV ?: EMPTY_JSON, pipelineName)
  549. build_job.value.steps.each { build_step ->
  550. build_job_name = build_step
  551. // This addition of maps makes it that the right operand will override entries if they overlap with the left operand
  552. envVars = pipelineEnvVars + GetBuildEnvVars(platform.value.PIPELINE_ENV ?: EMPTY_JSON, platform.value.build_types[build_step].PIPELINE_ENV ?: EMPTY_JSON, pipelineName)
  553. try {
  554. CreateBuildStage(pipelineConfig, platform.key, build_step, envVars).call()
  555. }
  556. catch (Exception e) {
  557. if (envVars['NONBLOCKING_STEP']?.toBoolean()) {
  558. unstable(message: "Build step ${build_step} failed but it's a non-blocking step in build job ${build_job.key}")
  559. } else {
  560. throw e
  561. }
  562. }
  563. }
  564. } else {
  565. CreateBuildStage(pipelineConfig, platform.key, build_job.key, envVars).call()
  566. }
  567. }
  568. catch(Exception e) {
  569. if (e instanceof org.jenkinsci.plugins.workflow.steps.FlowInterruptedException) {
  570. def causes = e.getCauses().toString()
  571. if (causes.contains('RemovedNodeCause')) {
  572. error "Node disconnected during build: ${e}" // Error raised to retry stage on a new node
  573. }
  574. }
  575. if (IsAPLogUpload(branchName, build_job_name)) {
  576. CreateUploadAPLogsStage(pipelineConfig, branchName, platform.key, build_job_name, envVars['WORKSPACE'], platform.value.build_types[build_job_name].PARAMETERS).call()
  577. }
  578. // All other errors will be raised outside the retry block
  579. currentResult = envVars['ON_FAILURE_MARK'] ?: 'FAILURE'
  580. currentException = e.toString()
  581. }
  582. finally {
  583. def params = platform.value.build_types[build_job_name].PARAMETERS
  584. if (env.MARS_REPO && params && params.containsKey('TEST_METRICS') && params.TEST_METRICS == 'True') {
  585. def output_directory = params.OUTPUT_DIRECTORY
  586. def configuration = params.CONFIGURATION
  587. CreateTestMetricsStage(pipelineConfig, branchName, envVars, build_job_name, output_directory, configuration).call()
  588. }
  589. if (params && params.containsKey('TEST_RESULTS') && params.TEST_RESULTS == 'True') {
  590. CreateExportTestResultsStage(pipelineConfig, platform.key, build_job_name, envVars, params).call()
  591. }
  592. if (params && params.containsKey('TEST_SCREENSHOTS') && params.TEST_SCREENSHOTS == 'True' && currentResult == 'FAILURE') {
  593. CreateExportTestScreenshotsStage(pipelineConfig, branchName, platform.key, build_job_name, envVars, params).call()
  594. }
  595. CreateTeardownStage(envVars).call()
  596. }
  597. }
  598. }
  599. }
  600. // https://github.com/jenkinsci/jenkins/blob/master/core/src/main/java/hudson/model/Result.java
  601. // {SUCCESS,UNSTABLE,FAILURE,NOT_BUILT,ABORTED}
  602. if (currentResult == 'FAILURE') {
  603. currentBuild.result = 'FAILURE'
  604. error "FAILURE: ${currentException}"
  605. } else if (currentResult == 'UNSTABLE') {
  606. currentBuild.result = 'UNSTABLE'
  607. unstable(message: "UNSTABLE: ${currentException}")
  608. }
  609. }
  610. }
  611. // Used in CreateBuildJobs() to preprocess the build_job steps to programically create
  612. // Node sections with a set of steps that can run on that node.
  613. class PipeStepJobData {
  614. String m_nodeLabel = ""
  615. def m_steps = []
  616. PipeStepJobData(String label) {
  617. this.m_nodeLabel = label
  618. }
  619. def addStep(def step) {
  620. this.m_steps.add(step)
  621. }
  622. }
  623. def CreateBuildJobs(Map pipelineConfig, def platform, def build_job, Map envVars, String branchName, String pipelineName, String repositoryName, String projectName) {
  624. // if this is a pipeline, split jobs based on the NODE_LABEL
  625. if(build_job.value.steps) {
  626. def defaultLabel = envVars['NODE_LABEL']
  627. def lastNodeLable = ""
  628. def jobList = []
  629. def currentIdx = -1;
  630. // iterate the steps to build the order of node label + steps sets.
  631. // Order matters, as it is executed from first to last.
  632. // example layout.
  633. // node A
  634. // step 1
  635. // step 2
  636. // node B
  637. // step 3
  638. // node C
  639. // step 4
  640. build_job.value.steps.each { build_step ->
  641. //if node label defined
  642. if(platform.value.build_types[build_step] && platform.value.build_types[build_step].PIPELINE_ENV &&
  643. platform.value.build_types[build_step].PIPELINE_ENV['NODE_LABEL']) {
  644. //if the last node label doen't match the new one, append it.
  645. if(platform.value.build_types[build_step].PIPELINE_ENV['NODE_LABEL'] != lastNodeLable) {
  646. lastNodeLable = platform.value.build_types[build_step].PIPELINE_ENV['NODE_LABEL']
  647. jobList.add(new PipeStepJobData(lastNodeLable))
  648. currentIdx++
  649. }
  650. }
  651. //no label define, so it needs to run on the default node label
  652. else if(lastNodeLable != defaultLabel) { //if the last node is not the default, append default
  653. lastNodeLable = defaultLabel
  654. jobList.add(new PipeStepJobData(lastNodeLable))
  655. currentIdx++
  656. }
  657. //add the build_step to the current node
  658. jobList[currentIdx].addStep(build_step)
  659. }
  660. return {
  661. jobList.eachWithIndex{ element, idx ->
  662. //update the node label + steps to the discovered data
  663. envVars['NODE_LABEL'] = element.m_nodeLabel
  664. build_job.value.steps = element.m_steps
  665. //no any additional nodes just mount the drive, do not handle clean parameters as that will be done by the first node.
  666. boolean onlyMountEBSVolume = idx != 0;
  667. //add this node
  668. CreateSingleNode(pipelineConfig, platform, build_job, envVars, branchName, pipelineName, repositoryName, projectName, onlyMountEBSVolume).call()
  669. }
  670. }
  671. } else {
  672. return CreateSingleNode(pipelineConfig, platform, build_job, envVars, branchName, pipelineName, repositoryName, projectName)
  673. }
  674. }
  675. def projectName = ''
  676. def pipelineName = ''
  677. def branchName = ''
  678. def pipelineConfig = {}
  679. // Start Pipeline
  680. try {
  681. stage('Setup Pipeline') {
  682. node('controller') {
  683. def envVarList = []
  684. if (isUnix()) {
  685. envVarList.add('IS_UNIX=1')
  686. }
  687. withEnv(envVarList) {
  688. timestamps {
  689. repositoryUrl = scm.getUserRemoteConfigs()[0].getUrl()
  690. // repositoryName is the full repository name
  691. repositoryName = (repositoryUrl =~ /https:\/\/github.com\/(.*)\.git/)[0][1]
  692. env.REPOSITORY_NAME = repositoryName
  693. (projectName, pipelineName) = GetRunningPipelineName(env.JOB_NAME) // env.JOB_NAME is the name of the job given by Jenkins
  694. env.PIPELINE_NAME = pipelineName
  695. if(env.BRANCH_NAME) {
  696. branchName = env.BRANCH_NAME
  697. } else {
  698. branchName = scm.branches[0].name // for non-multibranch pipelines
  699. env.BRANCH_NAME = branchName // so scripts that read this environment have it (e.g. incremental_build_util.py)
  700. }
  701. if(env.CHANGE_TARGET) {
  702. // PR builds
  703. if(BUILD_SNAPSHOTS.contains(env.CHANGE_TARGET)) {
  704. snapshot = env.CHANGE_TARGET
  705. echo "Snapshot for destination branch \"${env.CHANGE_TARGET}\" found."
  706. } else {
  707. snapshot = DEFAULT_BUILD_SNAPSHOT
  708. echo "Snapshot for destination branch \"${env.CHANGE_TARGET}\" does not exist, defaulting to snapshot \"${snapshot}\""
  709. }
  710. } else {
  711. // Non-PR builds
  712. pipelineParameters.add(choice(defaultValue: DEFAULT_BUILD_SNAPSHOT, name: 'SNAPSHOT', choices: BUILD_SNAPSHOTS_WITH_EMPTY, description: 'Selects the build snapshot to use. A more diverted snapshot will cause longer build times, but will not cause build failures.'))
  713. snapshot = env.SNAPSHOT
  714. echo "Snapshot \"${snapshot}\" selected."
  715. }
  716. pipelineProperties.add(disableConcurrentBuilds())
  717. def engineBranch = params.ENGINE_BRANCH ?: "${ENGINE_BRANCH_DEFAULT}" // This allows the first run to work with parameters having null value, but use the engine branch parameter afterwards
  718. echo "Running repository: \"${repositoryName}\", pipeline: \"${pipelineName}\", branch: \"${branchName}\" on engine branch \"${engineBranch}\"..."
  719. CheckoutBootstrapScripts(engineBranch)
  720. // Load configs
  721. pipelineConfig = LoadPipelineConfig(pipelineName, branchName)
  722. // Add each platform as a parameter that the user can disable if needed
  723. if (!IsPullRequest(branchName)) {
  724. pipelineParameters.add(stringParam(defaultValue: '', description: 'Filters and overrides the list of jobs to run for each of the below platforms (comma-separated). Can\'t be used during a pull request.', name: 'JOB_LIST_OVERRIDE'))
  725. pipelineConfig.platforms.each { platform ->
  726. pipelineParameters.add(booleanParam(defaultValue: true, description: '', name: platform.key))
  727. }
  728. }
  729. // Add additional Jenkins parameters
  730. pipelineConfig.platforms.each { platform ->
  731. platformEnv = platform.value.PIPELINE_ENV
  732. pipelineJenkinsParameters = platformEnv['PIPELINE_JENKINS_PARAMETERS'] ?: [:]
  733. jenkinsParametersToAdd = pipelineJenkinsParameters[pipelineName] ?: [:]
  734. jenkinsParametersToAdd.each{ jenkinsParameter ->
  735. defaultValue = jenkinsParameter['default_value']
  736. // Use last run's value as default value so we can save values in different Jenkins environment
  737. if (jenkinsParameter['use_last_run_value']?.toBoolean()) {
  738. defaultValue = params."${jenkinsParameter['parameter_name']}" ?: jenkinsParameter['default_value']
  739. }
  740. switch (jenkinsParameter['parameter_type']) {
  741. case 'string':
  742. pipelineParameters.add(stringParam(defaultValue: defaultValue,
  743. description: jenkinsParameter['description'],
  744. name: jenkinsParameter['parameter_name']
  745. ))
  746. break
  747. case 'boolean':
  748. pipelineParameters.add(booleanParam(defaultValue: defaultValue,
  749. description: jenkinsParameter['description'],
  750. name: jenkinsParameter['parameter_name']
  751. ))
  752. break
  753. case 'password':
  754. pipelineParameters.add(password(defaultValue: defaultValue,
  755. description: jenkinsParameter['description'],
  756. name: jenkinsParameter['parameter_name']
  757. ))
  758. break
  759. }
  760. }
  761. }
  762. pipelineProperties.add(parameters(pipelineParameters))
  763. properties(pipelineProperties)
  764. // Stash the INCREMENTAL_BUILD_SCRIPT_PATH since all nodes will use it
  765. stash name: 'incremental_build_script',
  766. includes: INCREMENTAL_BUILD_SCRIPT_PATH
  767. }
  768. }
  769. }
  770. }
  771. if (env.BUILD_NUMBER == '1' && !IsPullRequest(branchName)) {
  772. // Exit pipeline early on the intial build. This allows Jenkins to load the pipeline for the branch and enables users
  773. // to select build parameters on their first actual build. See https://issues.jenkins.io/browse/JENKINS-41929
  774. currentBuild.result = 'SUCCESS'
  775. return
  776. }
  777. def someBuildHappened = false
  778. // Build and Post-Build Testing Stage
  779. def buildConfigs = [:]
  780. // Platform Builds run on EC2
  781. pipelineConfig.platforms.each { platform ->
  782. platform.value.build_types.each { build_job ->
  783. if (IsJobEnabled(branchName, build_job, pipelineName, platform.key)) { // User can filter jobs, jobs are tagged by pipeline
  784. def envVars = GetBuildEnvVars(platform.value.PIPELINE_ENV ?: EMPTY_JSON, build_job.value.PIPELINE_ENV ?: EMPTY_JSON, pipelineName)
  785. envVars['JOB_NAME'] = "${branchName}_${platform.key}_${build_job.key}" // backwards compatibility, some scripts rely on this
  786. envVars['CMAKE_LY_PROJECTS'] = "../${PROJECT_REPOSITORY_NAME}/${PROJECT_PATH}"
  787. def nodeLabel = envVars['NODE_LABEL']
  788. someBuildHappened = true
  789. buildConfigs["${platform.key} [${build_job.key}]"] = CreateBuildJobs(pipelineConfig, platform, build_job, envVars, branchName, pipelineName, repositoryName, projectName)
  790. }
  791. }
  792. }
  793. timestamps {
  794. stage('Build') {
  795. parallel buildConfigs // Run parallel builds
  796. }
  797. echo 'All builds successful'
  798. }
  799. if (!someBuildHappened) {
  800. currentBuild.result = 'NOT_BUILT'
  801. }
  802. }
  803. catch(Exception e) {
  804. error "Exception: ${e}"
  805. }
  806. finally {
  807. try {
  808. node('controller') {
  809. if("${currentBuild.currentResult}" == "SUCCESS") {
  810. buildFailure = ""
  811. emailBody = "${BUILD_URL}\nSuccess!"
  812. } else {
  813. buildFailure = tm('${BUILD_FAILURE_ANALYZER}')
  814. emailBody = "${BUILD_URL}\n${buildFailure}!"
  815. }
  816. if(env.POST_AR_BUILD_SNS_TOPIC) {
  817. message_json = [
  818. "build_url": env.BUILD_URL,
  819. "build_number": env.BUILD_NUMBER,
  820. "repository_name": env.REPOSITORY_NAME,
  821. "branch_name": env.BRANCH_NAME,
  822. "build_result": "${currentBuild.currentResult}",
  823. "build_failure": buildFailure,
  824. "recreate_volume": env.RECREATE_VOLUME,
  825. "clean_output_directory": env.CLEAN_OUTPUT_DIRECTORY,
  826. "clean_assets": env.CLEAN_ASSETS
  827. ]
  828. snsPublish(
  829. topicArn: env.POST_AR_BUILD_SNS_TOPIC,
  830. subject:'Build Result',
  831. message:JsonOutput.toJson(message_json)
  832. )
  833. }
  834. emailext (
  835. body: "${emailBody}",
  836. subject: "${currentBuild.currentResult}: ${JOB_NAME} - Build # ${BUILD_NUMBER}",
  837. recipientProviders: [
  838. [$class: 'RequesterRecipientProvider']
  839. ]
  840. )
  841. }
  842. } catch(Exception e) {
  843. }
  844. }