pipeline中任务分段日志获取

脚本式pipeline

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
import hudson.model.Action
import org.jenkinsci.plugins.workflow.cps.nodes.StepStartNode
import org.jenkinsci.plugins.workflow.graph.FlowNode
import org.jenkinsci.plugins.workflow.actions.LabelAction

def hasLabelAction(FlowNode flowNode) {
def actions = flowNode.getActions()
for (Action action : actions) {
if (action instanceof LabelAction) {
return true
}
}
return false
}

def getStepStartNode(List<FlowNode> flowNodes, String stepNodeName, def depth) {
if (depth < 0) {
return null
}
for(FlowNode flowNode : flowNodes) {
def labelActionFlag = false
if (flowNode instanceof StepStartNode) {
labelActionFlag = hasLabelAction(flowNode)
}
if (labelActionFlag && flowNode.getDisplayName().equals(stepNodeName)) {
return flowNode
}

// 递归查询
def node = getStepStartNode(flowNode.getParents(), stepNodeName, depth)
if(node) {
return node
}
}
return null
}

def getBlueOceanLogUrlByName(String stepNodeName) {
// currentBuild: class org.jenkinsci.plugins.workflow.support.steps.build.RunWrapper
// build: class org.jenkinsci.plugins.workflow.job.WorkflowRun
def build = currentBuild.getRawBuild()
// execution: class org.jenkinsci.plugins.workflow.cps.CpsFlowExecution
def execution = build.getExecution()
// executionHeads: class java.util.ArrayList
def executionHeads = execution.getCurrentHeads()
def flowNode = getStepStartNode(executionHeads, stepNodeName, 10)
if (flowNode) {
return Jenkins.instance.getRootUrl() + "blue/rest/organizations/jenkins/pipelines/${JOB_NAME}/runs/${BUILD_NUMBER}/nodes/" + flowNode.getId() + "/log"
}
return ""
}

def generateTask(def taskName) {
def taskBody = {
println getBlueOceanLogUrlByName("Branch: ${taskName}")
node {
println("====> ${taskName} start")
sleep 3
println("====> ${taskName} end")
}
}
taskBody
}

def createParallelTasks(def jobs) {
def pipelineConfig = [:]
jobs.each { def job ->
def taskBody = generateTask(job)
pipelineConfig.put(job, taskBody)
}
pipelineConfig
}


script {
def jobs = ["job_a", "job_b", "job_c"]
def pipelineConfig = createParallelTasks(jobs)
stage('test') {
println getBlueOceanLogUrlByName("test")
parallel pipelineConfig
}
}