-
Notifications
You must be signed in to change notification settings - Fork 57
/
FinalizeStage.groovy
292 lines (254 loc) · 11.9 KB
/
FinalizeStage.groovy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
package org.ods.orchestration
import org.ods.orchestration.util.ProjectMessagesUtil
import org.ods.services.ServiceRegistry
import org.ods.orchestration.scheduler.LeVADocumentScheduler
import org.ods.orchestration.util.MROPipelineUtil
import org.ods.orchestration.util.Project
import org.ods.orchestration.util.PipelinePhaseLifecycleStage
import org.ods.orchestration.util.DeploymentDescriptor
import org.ods.services.BitbucketService
import org.ods.services.OpenShiftService
import org.ods.services.GitService
import org.ods.util.PipelineSteps
import org.ods.util.IPipelineSteps
import org.ods.util.Logger
import org.ods.util.ILogger
import groovy.json.JsonOutput
class FinalizeStage extends Stage {
public final String STAGE_NAME = 'Finalize'
private final String MASTER_BRANCH = "master"
FinalizeStage(def script, Project project, List<Set<Map>> repos) {
super(script, project, repos)
}
@SuppressWarnings(['ParameterName', 'AbcMetric', 'MethodSize'])
def run() {
def steps = ServiceRegistry.instance.get(PipelineSteps)
def levaDocScheduler = ServiceRegistry.instance.get(LeVADocumentScheduler)
def os = ServiceRegistry.instance.get(OpenShiftService)
def util = ServiceRegistry.instance.get(MROPipelineUtil)
def bitbucket = ServiceRegistry.instance.get(BitbucketService)
def git = ServiceRegistry.instance.get(GitService)
ILogger logger = ServiceRegistry.instance.get(Logger)
def phase = MROPipelineUtil.PipelinePhases.FINALIZE
def preExecuteRepo = { steps_, repo ->
levaDocScheduler.run(phase, PipelinePhaseLifecycleStage.PRE_EXECUTE_REPO, repo)
}
def postExecuteRepo = { steps_, repo ->
levaDocScheduler.run(phase, PipelinePhaseLifecycleStage.POST_EXECUTE_REPO, repo)
}
if (project.isAssembleMode) {
// Check if the target environment exists in OpenShift
def targetProject = project.targetProject
if (!os.envExists(targetProject)) {
throw new RuntimeException(
"Error: target environment '${targetProject}' does not exist in OpenShift."
)
}
}
def agentCondition = project.isAssembleMode && repos.size() > 0
runOnAgentPod(agentCondition) {
// Execute phase for each repository - here in parallel, all repos
Map repoFinalizeTasks = [ : ]
util.prepareExecutePhaseForReposNamedJob(
phase, repos, preExecuteRepo, postExecuteRepo).each { group ->
repoFinalizeTasks << group
}
repoFinalizeTasks.failFast = true
script.parallel(repoFinalizeTasks)
logger.debug("Integrate into main branch")
if (project.isAssembleMode && !project.isWorkInProgress) {
integrateIntoMainBranchRepos(steps, git)
}
logger.debug("Gathering commits")
gatherCreatedExecutionCommits(steps, git)
pushRepos(steps, git)
recordAndPushEnvStateForReleaseManager(steps, logger, git)
// add the tag commit that was created for traceability ..
logger.debug "Current release manager commit: ${project.gitData.commit}"
project.gitData.createdExecutionCommit = git.commitSha
}
if (project.isAssembleMode && !project.isWorkInProgress) {
logger.warn('!!! CAUTION: Any future changes that should affect version ' +
"'${project.buildParams.version}' " +
"need to be committed into branch '${project.gitReleaseBranch}'.")
}
if (project.hasWipJiraIssues()) {
util.warnBuild(ProjectMessagesUtil.generateWIPIssuesMessage(project))
}
// Dump a representation of the project
logger.debug("---- ODS Project (${project.key}) data ----\r${project}\r -----")
levaDocScheduler.run(phase, PipelinePhaseLifecycleStage.PRE_END)
logger.debug("Project has failing tests? ${project.hasFailingTests()}")
logger.debug("Project has unexecuted jira tests? ${project.hasUnexecutedJiraTests()}")
// Fail the build in case of failing tests.
if (project.hasFailingTests() || project.hasUnexecutedJiraTests()) {
def message = 'Error: '
if (project.hasFailingTests()) {
message += 'found failing tests'
}
if (project.hasFailingTests() && project.hasUnexecutedJiraTests()) {
message += ' and '
}
if (project.hasUnexecutedJiraTests()) {
message += 'found unexecuted Jira tests'
}
message += '.'
if (!project.isWorkInProgress) {
bitbucket.setBuildStatus (steps.env.BUILD_URL, project.gitData.commit,
'FAILED', "Release Manager for commit: ${project.gitData.commit}")
}
logger.debug(message)
util.failBuild(message)
throw new IllegalStateException(message)
} else {
logger.debug("Reporting pipeline status to Jira...")
project.reportPipelineStatus()
if (!project.isWorkInProgress) {
bitbucket.setBuildStatus (steps.env.BUILD_URL, project.gitData.commit,
"SUCCESSFUL", "Release Manager for commit: ${project.gitData.commit}")
}
}
}
private void pushRepos(IPipelineSteps steps, GitService git) {
def flattenedRepos = repos.flatten()
def repoPushTasks = [ : ]
def repoSize = flattenedRepos.size()
steps.echo "Finalize: Push flattened repos"
steps.echo "$flattenedRepos"
for (def i = 0; i < repoSize; i++) {
def repo = flattenedRepos[i]
if (repo.include) {
repoPushTasks << repoClosureMap(repo, steps, git)
}
}
repoPushTasks.failFast = true
script.parallel(repoPushTasks)
}
private Map<Object, Closure> repoClosureMap(repo, steps, git) {
return [(repo.id): {
steps.dir("${steps.env.WORKSPACE}/${MROPipelineUtil.REPOS_BASE_DIR}/${repo.id}") {
if (project.isWorkInProgress) {
String branchName = repo.data.git.branch ?: repo.branch
git.pushRef(branchName)
} else if (project.isAssembleMode) {
if (!git.remoteTagExists(project.targetTag)) {
git.createTag(project.targetTag)
}
git.pushBranchWithTags(project.gitReleaseBranch)
} else {
if (!git.remoteTagExists(project.targetTag)) {
git.createTag(project.targetTag)
}
git.pushRef(project.targetTag)
}
}
}
]
}
private void gatherCreatedExecutionCommits(IPipelineSteps steps, GitService git) {
def flattenedRepos = repos.flatten()
def gatherCommitTasks = [ : ]
def repoSize = flattenedRepos.size()
for (def i = 0; i < repoSize; i++) {
def repo = flattenedRepos[i]
if (repo.include) {
gatherCommitTasks << [(repo.id): {
steps.dir("${steps.env.WORKSPACE}/${MROPipelineUtil.REPOS_BASE_DIR}/${repo.id}") {
repo.data.git.createdExecutionCommit = git.commitSha
steps.echo "repo.id: ${repo.id}: ${repo.data.git.createdExecutionCommit}"
}
}
]
}
}
gatherCommitTasks.failFast = true
script.parallel(gatherCommitTasks)
}
private void integrateIntoMainBranchRepos(IPipelineSteps steps, GitService git) {
def flattenedRepos = repos.flatten()
def repoIntegrateTasks = [ : ]
def repoSize = flattenedRepos.size()
for (def i = 0; i < repoSize; i++) {
def repo = flattenedRepos[i]
if (repo.include) {
def repoType = repo.type?.toLowerCase()
if ((repoType != MROPipelineUtil.PipelineConfig.REPO_TYPE_ODS_TEST &&
repoType != MROPipelineUtil.PipelineConfig.REPO_TYPE_ODS_INFRA &&
repoType != MROPipelineUtil.PipelineConfig.REPO_TYPE_ODS_SAAS_SERVICE)) {
repoIntegrateTasks << [(repo.id): { doIntegrateIntoMainBranches(steps, repo, git) }]
}
}
}
repoIntegrateTasks.failFast = true
script.parallel(repoIntegrateTasks)
}
private List doIntegrateIntoMainBranches(IPipelineSteps steps, repo, git) {
steps.dir("${steps.env.WORKSPACE}/${MROPipelineUtil.REPOS_BASE_DIR}/${repo.id}") {
def files = steps.findFiles(glob: "**/${DeploymentDescriptor.FILE_NAME}")
if (!files || files.size() == 0) {
throw new RuntimeException("Error: Could not determine descriptor directory. " +
"Neither of [chart, openshift, openshift-exported] found.")
} else {
String deploymentDescDir = files[0].path.split('/')[0]
def filesToCheckout = ["${deploymentDescDir}/${DeploymentDescriptor.FILE_NAME}"]
if (steps.fileExists('openshift-exported/template.yml')) {
filesToCheckout << 'openshift-exported/template.yml'
}
git.mergeIntoMainBranch(project.gitReleaseBranch, repo.branch, filesToCheckout)
}
}
}
private void recordAndPushEnvStateForReleaseManager(IPipelineSteps steps, ILogger logger, GitService git) {
// record release manager repo state
logger.debug "Finalize: Recording HEAD commits from repos ..."
logger.debug "On release manager commit ${git.commitSha}"
def flattenedRepos = repos.flatten()
def gitHeads = [ : ]
def repoSize = flattenedRepos.size()
for (def i = 0; i < repoSize; i++) {
def repo = flattenedRepos[i]
logger.debug "HEAD of repo '${repo.id}': ${repo.data.git.createdExecutionCommit}"
gitHeads << [ (repo.id): (repo.data.git.createdExecutionCommit ?: '')]
}
def envState = [
version: project.buildParams.version,
changeId: project.buildParams.changeId,
repositories: gitHeads,
]
steps.writeFile(
file: project.envStateFileName,
text: JsonOutput.prettyPrint(JsonOutput.toJson(envState))
)
def filesToCommit = [project.envStateFileName]
def messageToCommit = "ODS: Record commits deployed into ${project.buildParams.targetEnvironmentToken}"
if (! project.isWorkInProgress) {
def projectDataFileNames = project.saveProjectData()
filesToCommit.addAll(projectDataFileNames)
messageToCommit = messageToCommit + " and data of version ${project.getVersionName()}"
}
git.commit(
filesToCommit,
messageToCommit
)
if (project.gitReleaseBranch == MASTER_BRANCH) {
git.pushRef(MASTER_BRANCH)
} else {
// We don't need to merge, we simply commit the env file.
// That avoids unnecessary merge conflicts.
git.switchToOriginTrackingBranch(MASTER_BRANCH)
git.checkoutAndCommitFiles(
project.gitReleaseBranch,
filesToCommit,
"ODS: Update ${project.buildParams.targetEnvironmentToken} env state"
)
git.pushRef(MASTER_BRANCH)
git.switchToExistingBranch(project.gitReleaseBranch)
if (!project.isWorkInProgress) {
git.createTag(project.targetTag)
}
// To overwrite the existing tag (if redeploy)
// FIXME: Review this functionality to avoid orphaned commits
git.pushForceBranchWithTags(project.gitReleaseBranch)
}
}
}