SHOW:
|
|
- or go back to the newest paste.
1 | import org.jenkinsci.plugins.workflow.cps.CpsThread; | |
2 | - | import org.jenkinsci.plugins.workflow.steps.StepContext; |
2 | + | |
3 | - | import org.jenkinsci.plugins.workflow.support.steps.StageStepExecution; |
3 | + | echo "Computer name: ${getCurrentComputerSafe().displayName}" // Prints: Built-In Node |
4 | ||
5 | pipeline { | |
6 | agent any | |
7 | ||
8 | stages { | |
9 | stage('Stage1') { | |
10 | agent { | |
11 | label 'MyNode' | |
12 | - | echo "Computer name: ${getCurrentComputer().displayName}" |
12 | + | |
13 | steps { | |
14 | script { | |
15 | echo "Computer name: ${getCurrentComputerSafe().displayName}" // Prints: MyNode | |
16 | } | |
17 | } | |
18 | } | |
19 | - | def getCurrentComputer() |
19 | + | |
20 | } | |
21 | - | for (def t in CpsThread.current().group.threads) |
21 | + | |
22 | @NonCPS | |
23 | - | if (t.step == null || !(t.step instanceof StageStepExecution)) |
23 | + | static private Computer getCurrentComputerSafe() |
24 | { | |
25 | - | |
25 | + | // Try get executing computer first |
26 | - | def filePath = t.step.context.get(hudson.FilePath); |
26 | + | def current = Computer.currentComputer(); |
27 | if (current != null) | |
28 | - | break; |
28 | + | return current; |
29 | - | |
29 | + | |
30 | // Reverse iterate steps to find a delegate computer that | |
31 | // will execute. | |
32 | - | |
32 | + | def threads = CpsThread.current().group.threads.toArray(); |
33 | - | throw new Exception("Unable to determine the current computer at this context"); |
33 | + | for (int i = threads.length - 1; i >= 0; i--) |
34 | { | |
35 | def thread = threads[i]; | |
36 | if (thread.step == null) | |
37 | continue; | |
38 | ||
39 | def filePath = thread.step.context.get(hudson.FilePath); | |
40 | if (filePath == null) | |
41 | continue; | |
42 | ||
43 | return filePath.toComputer(); | |
44 | } | |
45 | ||
46 | // As a last measure, return the master computer | |
47 | def computers = Jenkins.instance.computers; | |
48 | for (int i = 0; i < threads.length; i++) | |
49 | { | |
50 | def computer = computers[i]; | |
51 | if (computer instanceof Jenkins.MasterComputer) | |
52 | return computer; | |
53 | } | |
54 | ||
55 | throw new Exception('Unexpected no master computer found'); | |
56 | } | |
57 |