/
EnvInjectListener.java
418 lines (337 loc) · 17.1 KB
/
EnvInjectListener.java
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
package org.jenkinsci.plugins.envinject;
import hudson.EnvVars;
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.matrix.MatrixBuild;
import hudson.matrix.MatrixRun;
import hudson.model.*;
import hudson.model.listeners.RunListener;
import hudson.remoting.Callable;
import hudson.slaves.EnvironmentVariablesNodeProperty;
import hudson.slaves.NodeProperty;
import hudson.tasks.BuildWrapper;
import hudson.tasks.BuildWrapperDescriptor;
import org.jenkinsci.lib.envinject.EnvInjectException;
import org.jenkinsci.lib.envinject.EnvInjectLogger;
import org.jenkinsci.plugins.envinject.model.EnvInjectJobPropertyContributor;
import org.jenkinsci.plugins.envinject.service.*;
import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* @author Gregory Boissinot
*/
@Extension
public class EnvInjectListener extends RunListener<Run> implements Serializable {
@Override
public Environment setUpEnvironment(AbstractBuild build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException {
if (isEligibleJobType(build)) {
EnvInjectLogger logger = new EnvInjectLogger(listener);
try {
//Process environment variables at node level
Node buildNode = build.getBuiltOn();
if (buildNode != null) {
loadEnvironmentVariablesNode(build, buildNode, logger);
}
//Load job envinject job property
if (isEnvInjectJobPropertyActive(build)) {
return setUpEnvironmentJobPropertyObject(build, launcher, listener, logger);
} else {
return setUpEnvironmentWithoutJobPropertyObject(build, launcher, listener);
}
} catch (Run.RunnerAbortedException rre) {
logger.info("Fail the build.");
throw new Run.RunnerAbortedException();
} catch (Throwable throwable) {
logger.error("SEVERE ERROR occurs: " + throwable.getMessage());
throw new Run.RunnerAbortedException();
}
}
return new Environment() {
};
}
private boolean isEligibleJobType(AbstractBuild build) {
if (build == null) {
throw new IllegalArgumentException("A build object must be set.");
}
Job job;
if (build instanceof MatrixRun) {
job = ((MatrixRun) build).getParentBuild().getParent();
} else {
job = build.getParent();
}
return job instanceof BuildableItemWithBuildWrappers;
}
private void loadEnvironmentVariablesNode(AbstractBuild build, Node buildNode, EnvInjectLogger logger) throws EnvInjectException {
logger.info("Loading node environment variables.");
if (buildNode == null) {
return;
}
FilePath nodePath = buildNode.getRootPath();
if (nodePath == null) {
return;
}
try {
//Default node envVars
Map<String, String> configNodeEnvVars = new HashMap<String, String>();
//Get env vars for the current node
Map<String, String> nodeEnvVars = nodePath.act(
new Callable<Map<String, String>, IOException>() {
public Map<String, String> call() throws IOException {
return EnvVars.masterEnvVars;
}
}
);
for (NodeProperty<?> nodeProperty : Hudson.getInstance().getGlobalNodeProperties()) {
if (nodeProperty instanceof EnvironmentVariablesNodeProperty) {
EnvironmentVariablesNodeProperty variablesNodeProperty = (EnvironmentVariablesNodeProperty) nodeProperty;
EnvVars envVars = variablesNodeProperty.getEnvVars();
EnvInjectEnvVars envInjectEnvVars = new EnvInjectEnvVars(logger);
configNodeEnvVars.putAll(envVars);
envInjectEnvVars.resolveVars(configNodeEnvVars, nodeEnvVars);
}
}
for (NodeProperty<?> nodeProperty : buildNode.getNodeProperties()) {
if (nodeProperty instanceof EnvironmentVariablesNodeProperty) {
EnvironmentVariablesNodeProperty variablesNodeProperty = (EnvironmentVariablesNodeProperty) nodeProperty;
EnvVars envVars = variablesNodeProperty.getEnvVars();
EnvInjectEnvVars envInjectEnvVars = new EnvInjectEnvVars(logger);
configNodeEnvVars.putAll(envVars);
envInjectEnvVars.resolveVars(configNodeEnvVars, nodeEnvVars);
}
}
EnvInjectActionSetter envInjectActionSetter = new EnvInjectActionSetter(nodePath);
envInjectActionSetter.addEnvVarsToEnvInjectBuildAction(build, configNodeEnvVars);
} catch (IOException ioe) {
throw new EnvInjectException(ioe);
} catch (InterruptedException ie) {
throw new EnvInjectException(ie);
}
}
private boolean isEnvInjectJobPropertyActive(AbstractBuild build) {
EnvInjectVariableGetter variableGetter = new EnvInjectVariableGetter();
EnvInjectJobProperty envInjectJobProperty = variableGetter.getEnvInjectJobProperty(build);
return envInjectJobProperty != null;
}
public static class JobSetupEnvironmentWrapper extends BuildWrapper {
@SuppressWarnings("unused")
@Extension
public static class JobSetupEnvironmentWrapperDescriptor extends BuildWrapperDescriptor {
public JobSetupEnvironmentWrapperDescriptor() {
}
public JobSetupEnvironmentWrapperDescriptor(Class<? extends BuildWrapper> clazz) {
super(JobSetupEnvironmentWrapper.class);
}
@Override
public boolean isApplicable(AbstractProject<?, ?> item) {
return false;
}
@Override
public String getDisplayName() {
return null;
}
}
@Override
public void preCheckout(AbstractBuild build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException {
EnvInjectLogger envInjectLogger = new EnvInjectLogger(listener);
EnvInjectVariableGetter variableGetter = new EnvInjectVariableGetter();
EnvInjectJobProperty envInjectJobProperty = variableGetter.getEnvInjectJobProperty(build);
assert envInjectJobProperty != null;
if (envInjectJobProperty.isKeepBuildVariables()) {
try {
//Get previous
Map<String, String> previousEnvVars = variableGetter.getEnvVarsPreviousSteps(build, envInjectLogger);
//Add workspace
FilePath ws = build.getWorkspace();
if (previousEnvVars.get("WORKSPACE") == null) {
previousEnvVars.put("WORKSPACE", ws.getRemote());
}
//Resolve variables each other and with WORKSPACE
EnvInjectEnvVars envInjectEnvVars = new EnvInjectEnvVars(envInjectLogger);
envInjectEnvVars.resolveVars(previousEnvVars, previousEnvVars);
//Remove unused variables
Map<String, String> cleanVariables = envInjectEnvVars.removeUnsetVars(previousEnvVars);
//Set new env vars
new EnvInjectActionSetter(build.getBuiltOn().getRootPath()).addEnvVarsToEnvInjectBuildAction(build, cleanVariables);
} catch (EnvInjectException e) {
throw new IOException(e.getMessage());
}
}
}
@Override
public Environment setUp(AbstractBuild build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException {
return new Environment() {
};
}
}
private Environment setUpEnvironmentJobPropertyObject(AbstractBuild build, Launcher launcher, BuildListener listener, EnvInjectLogger logger) throws IOException, InterruptedException, EnvInjectException {
logger.info("Preparing an environment for the build.");
EnvInjectVariableGetter variableGetter = new EnvInjectVariableGetter();
EnvInjectJobProperty envInjectJobProperty = variableGetter.getEnvInjectJobProperty(build);
assert envInjectJobProperty != null;
EnvInjectJobPropertyInfo info = envInjectJobProperty.getInfo();
assert envInjectJobProperty != null && envInjectJobProperty.isOn();
//Init infra env vars
Map<String, String> previousEnvVars = variableGetter.getEnvVarsPreviousSteps(build, logger);
Map<String, String> infraEnvVarsNode = new LinkedHashMap<String, String>(previousEnvVars);
Map<String, String> infraEnvVarsMaster = new LinkedHashMap<String, String>(previousEnvVars);
//Add Jenkins System variables
if (envInjectJobProperty.isKeepJenkinsSystemVariables()) {
logger.info("Keeping Jenkins system variables.");
infraEnvVarsMaster.putAll(variableGetter.getJenkinsSystemVariables(true));
infraEnvVarsNode.putAll(variableGetter.getJenkinsSystemVariables(false));
}
//Add build variables
if (envInjectJobProperty.isKeepBuildVariables()) {
logger.info("Keeping Jenkins build variables.");
Map<String, String> buildVariables = variableGetter.getBuildVariables(build, logger);
infraEnvVarsMaster.putAll(buildVariables);
infraEnvVarsNode.putAll(buildVariables);
}
//Add build parameters (or override)
logger.info("Adding build parameters as variables.");
Map<String, String> parametersVariables = variableGetter.overrideParametersVariablesWithSecret(build);
infraEnvVarsNode.putAll(parametersVariables);
final FilePath rootPath = getNodeRootPath();
if (rootPath != null) {
final EnvInjectEnvVars envInjectEnvVarsService = new EnvInjectEnvVars(logger);
//Execute script
int resultCode = envInjectEnvVarsService.executeScript(info.isLoadFilesFromMaster(),
info.getScriptContent(),
rootPath, info.getScriptFilePath(), infraEnvVarsMaster, infraEnvVarsNode, launcher, listener);
if (resultCode != 0) {
build.setResult(Result.FAILURE);
throw new Run.RunnerAbortedException();
}
//Evaluate Groovy script
Map<String, String> groovyMapEnvVars = envInjectEnvVarsService.executeAndGetMapGroovyScript(info.getGroovyScriptContent(), infraEnvVarsNode);
final Map<String, String> propertiesVariables = envInjectEnvVarsService.getEnvVarsPropertiesJobProperty(rootPath,
logger, info.isLoadFilesFromMaster(),
info.getPropertiesFilePath(), info.getPropertiesContentMap(previousEnvVars),
infraEnvVarsMaster, infraEnvVarsNode);
//Get variables get by contribution
Map<String, String> contributionVariables = getEnvVarsByContribution(build, envInjectJobProperty, logger, listener);
final Map<String, String> mergedVariables = envInjectEnvVarsService.getMergedVariables(
infraEnvVarsNode,
propertiesVariables,
groovyMapEnvVars,
contributionVariables);
//Add an action to share injected environment variables
new EnvInjectActionSetter(rootPath).addEnvVarsToEnvInjectBuildAction(build, mergedVariables);
//Add a wrapper to intercept the preCheckout event and add specific variables such as WORKSPACE variable
BuildWrapperService wrapperService = new BuildWrapperService();
wrapperService.addBuildWrapper(build, new JobSetupEnvironmentWrapper());
return new Environment() {
@Override
public void buildEnvVars(Map<String, String> env) {
envInjectEnvVarsService.resolveVars(mergedVariables, mergedVariables); //resolve variables each other
//however, here preCheckout of EnvBuildWrapper is not yet performed
env.putAll(mergedVariables);
}
};
}
return new Environment() {
};
}
private Environment setUpEnvironmentWithoutJobPropertyObject(AbstractBuild build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException, EnvInjectException {
final Map<String, String> resultVariables = new HashMap<String, String>();
EnvInjectVariableGetter variableGetter = new EnvInjectVariableGetter();
EnvInjectLogger logger = new EnvInjectLogger(listener);
Map<String, String> previousEnvVars = variableGetter.getEnvVarsPreviousSteps(build, logger);
resultVariables.putAll(previousEnvVars);
resultVariables.putAll(variableGetter.getJenkinsSystemVariables(false));
resultVariables.putAll(variableGetter.getBuildVariables(build, logger));
final FilePath rootPath = getNodeRootPath();
if (rootPath != null) {
new EnvInjectActionSetter(rootPath).addEnvVarsToEnvInjectBuildAction(build, resultVariables);
}
return new Environment() {
@Override
public void buildEnvVars(Map<String, String> env) {
env.putAll(resultVariables);
}
};
}
private Node getNode() {
Computer computer = Computer.currentComputer();
if (computer == null) {
return null;
}
return computer.getNode();
}
private FilePath getNodeRootPath() {
Node node = getNode();
if (node != null) {
return node.getRootPath();
}
return null;
}
private Map<String, String> getEnvVarsByContribution(AbstractBuild build, EnvInjectJobProperty envInjectJobProperty,
EnvInjectLogger logger, BuildListener listener) throws EnvInjectException {
assert envInjectJobProperty != null;
Map<String, String> contributionVariables = new HashMap<String, String>();
EnvInjectJobPropertyContributor[] contributors = envInjectJobProperty.getContributors();
if (contributors != null) {
logger.info("Injecting contributions.");
for (EnvInjectJobPropertyContributor contributor : contributors) {
contributionVariables.putAll(contributor.getEnvVars(build, listener));
}
}
return contributionVariables;
}
@Override
public void onCompleted(Run run, TaskListener listener) {
if (!(run instanceof AbstractBuild)) {
return;
}
AbstractBuild build = (AbstractBuild) run;
if (!isEligibleJobType(build)) {
return;
}
//Mask passwords
EnvVars envVars = new EnvVars();
EnvInjectLogger logger = new EnvInjectLogger(listener);
EnvInjectPasswordsMasker passwordsMasker = new EnvInjectPasswordsMasker();
passwordsMasker.maskPasswordsIfAny(build, logger, envVars);
if (!(build instanceof MatrixBuild)) {
EnvInjectPluginAction envInjectAction = run.getAction(EnvInjectPluginAction.class);
if (envInjectAction != null) {
//Remove technical wrappers
try {
BuildWrapperService wrapperService = new BuildWrapperService();
wrapperService.removeBuildWrappers(build, JobSetupEnvironmentWrapper.class);
} catch (EnvInjectException e) {
logger.error("SEVERE ERROR occurs: " + e.getMessage());
throw new Run.RunnerAbortedException();
}
} else {
try {
envVars.putAll(build.getEnvironment(listener));
} catch (IOException e) {
logger.error("SEVERE ERROR occurs: " + e.getMessage());
throw new Run.RunnerAbortedException();
} catch (InterruptedException e) {
logger.error("SEVERE ERROR occurs: " + e.getMessage());
throw new Run.RunnerAbortedException();
}
}
}
//Add or override EnvInject Action
EnvInjectActionSetter envInjectActionSetter = new EnvInjectActionSetter(getNodeRootPath());
try {
envInjectActionSetter.addEnvVarsToEnvInjectBuildAction((AbstractBuild<?, ?>) run, envVars);
} catch (EnvInjectException e) {
logger.error("SEVERE ERROR occurs: " + e.getMessage());
throw new Run.RunnerAbortedException();
} catch (IOException e) {
logger.error("SEVERE ERROR occurs: " + e.getMessage());
throw new Run.RunnerAbortedException();
} catch (InterruptedException e) {
logger.error("SEVERE ERROR occurs: " + e.getMessage());
throw new Run.RunnerAbortedException();
}
}
}