-
Notifications
You must be signed in to change notification settings - Fork 119
/
CopyArtifact.java
560 lines (504 loc) · 24.7 KB
/
CopyArtifact.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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
/*
* The MIT License
*
* Copyright (c) 2004-2011, Sun Microsystems, Inc., Alan Harder
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.plugins.copyartifact;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import hudson.DescriptorExtensionList;
import hudson.EnvVars;
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.Util;
import hudson.console.HyperlinkNote;
import hudson.diagnosis.OldDataMonitor;
import hudson.init.InitMilestone;
import hudson.init.Initializer;
import hudson.matrix.MatrixBuild;
import hudson.matrix.MatrixProject;
import hudson.maven.MavenBuild;
import hudson.maven.MavenModuleSet;
import hudson.maven.MavenModuleSetBuild;
import hudson.model.*;
import hudson.model.listeners.ItemListener;
import hudson.model.listeners.RunListener;
import hudson.security.ACL;
import hudson.security.SecurityRealm;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.Builder;
import hudson.util.DescribableList;
import hudson.util.FormValidation;
import hudson.util.XStream2;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import jenkins.model.Jenkins;
import org.acegisecurity.Authentication;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import org.apache.commons.lang.StringUtils;
import org.kohsuke.stapler.AncestorInPath;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerRequest;
/**
* Build step to copy artifacts from another project.
* @author Alan Harder
*/
public class CopyArtifact extends Builder {
// specifies upgradeCopyArtifact is needed to work.
private static boolean upgradeNeeded = false;
private static Logger LOGGER = Logger.getLogger(CopyArtifact.class.getName());
@Deprecated private String projectName;
private String project;
private String parameters;
private final String filter, target;
private final String excludes;
private /*almost final*/ BuildSelector selector;
@Deprecated private transient Boolean stable;
private final Boolean flatten, optional;
private final boolean doNotFingerprintArtifacts;
@Deprecated
public CopyArtifact(String projectName, String parameters, BuildSelector selector, String filter, String target,
boolean flatten, boolean optional) {
this(projectName, parameters, selector, filter, target, flatten, optional, true);
}
@Deprecated
public CopyArtifact(String projectName, String parameters, BuildSelector selector, String filter, String target,
boolean flatten, boolean optional, boolean fingerprintArtifacts) {
this(projectName, parameters, selector, filter, null, target, flatten, optional, fingerprintArtifacts);
}
@DataBoundConstructor
public CopyArtifact(String projectName, String parameters, BuildSelector selector, String filter, String excludes, String target,
boolean flatten, boolean optional, boolean fingerprintArtifacts) {
// check the permissions only if we can
StaplerRequest req = Stapler.getCurrentRequest();
if (req!=null) {
AbstractProject<?,?> p = req.findAncestorObject(AbstractProject.class);
if (p != null) {
ItemGroup<?> context = p.getParent();
// Prevents both invalid values and access to artifacts of projects which this user cannot see.
// If value is parameterized, it will be checked when build runs.
if (projectName.indexOf('$') < 0 && Jenkins.getInstance().getItem(projectName, context, Job.class) == null)
projectName = ""; // Ignore/clear bad value to avoid ugly 500 page
}
}
this.project = projectName;
this.parameters = Util.fixEmptyAndTrim(parameters);
this.selector = selector;
this.filter = Util.fixNull(filter).trim();
this.excludes = Util.fixNull(excludes).trim();
this.target = Util.fixNull(target).trim();
this.flatten = flatten ? Boolean.TRUE : null;
this.optional = optional ? Boolean.TRUE : null;
this.doNotFingerprintArtifacts = !fingerprintArtifacts;
}
// Upgrade data from old format
public static class ConverterImpl extends XStream2.PassthruConverter<CopyArtifact> {
public ConverterImpl(XStream2 xstream) { super(xstream); }
@Override protected void callback(CopyArtifact obj, UnmarshallingContext context) {
if (obj.selector == null) {
obj.selector = new StatusBuildSelector(obj.stable != null && obj.stable);
OldDataMonitor.report(context, "1.355"); // Core version# when CopyArtifact 1.2 released
}
if (obj.isUpgradeNeeded()) {
// A Copy Artifact to be upgraded.
// For information of the containing project is needed,
// The upgrade will be performed by upgradeCopyArtifact.
setUpgradeNeeded();
}
}
}
private static synchronized void setUpgradeNeeded() {
if (!upgradeNeeded) {
LOGGER.info("Upgrade for Copy Artifact is scheduled.");
upgradeNeeded = true;
}
}
// get all CopyArtifacts configured to AbstractProject. This works both for Project and MatrixProject.
private static List<CopyArtifact> getCopyArtifactsInProject(AbstractProject<?,?> project) throws IOException {
DescribableList<Builder,Descriptor<Builder>> list =
project instanceof Project ? ((Project<?,?>)project).getBuildersList()
: (project instanceof MatrixProject ?
((MatrixProject)project).getBuildersList() : null);
if (list == null) return Collections.emptyList();
return list.getAll(CopyArtifact.class);
}
@Initializer(after=InitMilestone.JOB_LOADED)
public static void upgradeCopyArtifact() {
if (!upgradeNeeded) {
return;
}
upgradeNeeded = false;
boolean isUpgraded = false;
for (AbstractProject<?,?> project: Jenkins.getInstance().getAllItems(AbstractProject.class)) {
try {
for (CopyArtifact target: getCopyArtifactsInProject(project)) {
try {
if (target.upgradeIfNecessary(project)) {
isUpgraded = true;
}
} catch(IOException e) {
LOGGER.log(Level.SEVERE, String.format("Failed to upgrade CopyArtifact in %s", project.getFullName()), e);
}
}
} catch (IOException e) {
LOGGER.log(Level.SEVERE, String.format("Failed to upgrade CopyArtifact in %s", project.getFullName()), e);
}
}
if (!isUpgraded) {
// No CopyArtifact is upgraded.
LOGGER.warning("Update of CopyArtifact is scheduled, but no CopyArtifact to upgrade was found!");
}
}
public String getProjectName() {
return project;
}
public String getParameters() {
return parameters;
}
public BuildSelector getBuildSelector() {
return selector;
}
public String getFilter() {
return filter;
}
public String getExcludes() {
return excludes;
}
public String getTarget() {
return target;
}
public boolean isFlatten() {
return flatten != null && flatten;
}
public boolean isOptional() {
return optional != null && optional;
}
private boolean upgradeIfNecessary(AbstractProject<?,?> job) throws IOException {
if (isUpgradeNeeded()) {
int i = projectName.lastIndexOf('/');
if (i != -1 && projectName.indexOf('=', i) != -1 && /* not matrix */Jenkins.getInstance().getItem(projectName, job.getParent(), Job.class) == null) {
project = projectName.substring(0, i);
parameters = projectName.substring(i + 1);
} else {
project = projectName;
parameters = null;
}
LOGGER.log(Level.INFO, "Split {0} into {1} with parameters {2}", new Object[] {projectName, project, parameters});
projectName = null;
job.save();
return true;
} else {
return false;
}
}
private boolean isUpgradeNeeded() {
return (projectName != null);
}
public boolean isFingerprintArtifacts() {
return !doNotFingerprintArtifacts;
}
@Override
public boolean perform(AbstractBuild<?,?> build, Launcher launcher, BuildListener listener)
throws InterruptedException, IOException {
upgradeIfNecessary(build.getProject());
PrintStream console = listener.getLogger();
String expandedProject = project, expandedFilter = filter;
String expandedExcludes = getExcludes();
try {
EnvVars env = build.getEnvironment(listener);
env.overrideAll(build.getBuildVariables()); // Add in matrix axes..
expandedProject = env.expand(project);
Job<?, ?> job = Jenkins.getInstance().getItem(expandedProject, build.getProject().getRootProject().getParent(), Job.class);
if (job != null && !expandedProject.equals(project)
// If projectName is parameterized, need to do permission check on source project.
&& !canReadFrom(job, build)) {
job = null; // Disallow access
}
if (job == null) {
console.println(Messages.CopyArtifact_MissingProject(expandedProject));
return false;
}
Run src = selector.getBuild(job, env, parameters != null ? new ParametersBuildFilter(env.expand(parameters)) : new BuildFilter(), build);
if (src == null) {
console.println(Messages.CopyArtifact_MissingBuild(expandedProject));
return isOptional(); // Fail build unless copy is optional
}
FilePath targetDir = build.getWorkspace(), baseTargetDir = targetDir;
if (targetDir == null || !targetDir.exists()) {
console.println(Messages.CopyArtifact_MissingWorkspace()); // (see JENKINS-3330)
return isOptional(); // Fail build unless copy is optional
}
// Add info about the selected build into the environment
EnvAction envData = build.getAction(EnvAction.class);
if (envData == null) {
envData = new EnvAction();
build.addAction(envData);
}
envData.add(getItemGroup(build), expandedProject, src.getNumber());
if (target.length() > 0) targetDir = new FilePath(targetDir, env.expand(target));
expandedFilter = env.expand(filter);
if (expandedFilter.trim().length() == 0) expandedFilter = "**";
expandedExcludes = env.expand(expandedExcludes);
if (StringUtils.isBlank(expandedExcludes)) {
expandedExcludes = null;
}
Copier copier = Jenkins.getInstance().getExtensionList(Copier.class).get(0).clone();
if (Hudson.getInstance().getPlugin("maven-plugin") != null && (src instanceof MavenModuleSetBuild) ) {
// use classes in the "maven-plugin" plugin as might not be installed
// Copy artifacts from the build (ArchiveArtifacts build step)
boolean ok = perform(src, build, expandedFilter, expandedExcludes, targetDir, baseTargetDir, copier, console);
// Copy artifacts from all modules of this Maven build (automatic archiving)
for (Iterator<MavenBuild> it = ((MavenModuleSetBuild)src).getModuleLastBuilds().values().iterator(); it.hasNext(); ) {
// for(Run r: ....values()) causes upcasting and loading MavenBuild compiled with jdk 1.6.
// SEE https://wiki.jenkins-ci.org/display/JENKINS/Tips+for+optional+dependencies for details.
Run<?,?> r = it.next();
ok |= perform(r, build, expandedFilter, expandedExcludes, targetDir, baseTargetDir, copier, console);
}
return ok;
} else if (src instanceof MatrixBuild) {
boolean ok = false;
// Copy artifacts from all configurations of this matrix build
// Use MatrixBuild.getExactRuns if available
for (Run r : ((MatrixBuild) src).getExactRuns())
// Use subdir of targetDir with configuration name (like "jdk=java6u20")
ok |= perform(r, build, expandedFilter, expandedExcludes, targetDir.child(r.getParent().getName()),
baseTargetDir, copier, console);
return ok;
} else {
return perform(src, build, expandedFilter, expandedExcludes, targetDir, baseTargetDir, copier, console);
}
}
catch (IOException ex) {
Util.displayIOException(ex, listener);
ex.printStackTrace(listener.error(
Messages.CopyArtifact_FailedToCopy(expandedProject, expandedFilter)));
return false;
}
}
private boolean canReadFrom(Job<?, ?> job, AbstractBuild<?, ?> build) {
if ((job instanceof AbstractProject) && CopyArtifactPermissionProperty.canCopyArtifact(
build.getProject().getRootProject(),
((AbstractProject<?,?>)job).getRootProject()
)) {
return true;
}
Authentication a = Jenkins.getAuthentication();
if (!ACL.SYSTEM.equals(a)) {
// if the build does not run on SYSTEM authorization,
// Jenkins is configured to use QueueItemAuthenticator.
// In this case, builds are configured to run with a proper authorization
// (for example, builds run with the authorization of the user who triggered the build),
// and we should check access permission with that authorization.
// QueueItemAuthenticator is available from Jenkins 1.520.
// See also JENKINS-14999, JENKINS-16956, JENKINS-18285.
boolean b = job.getACL().hasPermission(Item.READ);
if (!b)
LOGGER.fine(String.format("Refusing to copy artifact from %s to %s because %s lacks Item.READ access",job,build, a));
return b;
}
// for the backward compatibility,
// test the permission as an anonymous authenticated user.
boolean b = job.getACL().hasPermission(
new UsernamePasswordAuthenticationToken("authenticated", "",
new GrantedAuthority[]{ SecurityRealm.AUTHENTICATED_AUTHORITY }),
Item.READ);
if (!b)
LOGGER.fine(String.format("Refusing to copy artifact from %s to %s because 'authenticated' lacks Item.READ access",job,build));
return b;
}
// retrieve the "folder" (jenkins root if no folder used) for this build
private ItemGroup getItemGroup(AbstractBuild<?, ?> build) {
ItemGroup group = build.getProject().getRootProject().getParent();
return group;
}
private boolean perform(Run src, AbstractBuild<?,?> dst, String expandedFilter, String expandedExcludes, FilePath targetDir,
FilePath baseTargetDir, Copier copier, PrintStream console)
throws IOException, InterruptedException {
FilePath srcDir = selector.getSourceDirectory(src, console);
if (srcDir == null) {
return isOptional(); // Fail build unless copy is optional
}
copier.init(src,dst,srcDir,baseTargetDir);
try {
int cnt;
if (!isFlatten())
cnt = copier.copyAll(srcDir, expandedFilter, expandedExcludes, targetDir, isFingerprintArtifacts());
else {
targetDir.mkdirs(); // Create target if needed
FilePath[] list = srcDir.list(expandedFilter, expandedExcludes, false);
for (FilePath file : list)
copier.copyOne(file, new FilePath(targetDir, file.getName()), isFingerprintArtifacts());
cnt = list.length;
}
console.println(Messages.CopyArtifact_Copied(cnt, HyperlinkNote.encodeTo('/'+ src.getParent().getUrl(), src.getParent().getFullDisplayName()),
HyperlinkNote.encodeTo('/'+src.getUrl(), Integer.toString(src.getNumber()))));
// Fail build if 0 files copied unless copy is optional
return cnt > 0 || isOptional();
} finally {
copier.end();
}
}
@Extension
public static final class DescriptorImpl extends BuildStepDescriptor<Builder> {
public FormValidation doCheckProjectName(
@AncestorInPath AbstractProject anc, @QueryParameter String value) {
// Require CONFIGURE permission on this project
if (!anc.hasPermission(Item.CONFIGURE)) return FormValidation.ok();
FormValidation result;
Item item = Jenkins.getInstance().getItem(value, anc.getParent());
if (item != null)
if (Hudson.getInstance().getPlugin("maven-plugin") != null && item instanceof MavenModuleSet) {
result = FormValidation.warning(Messages.CopyArtifact_MavenProject());
} else {
result = (item instanceof MatrixProject)
? FormValidation.warning(Messages.CopyArtifact_MatrixProject())
: FormValidation.ok();
}
else if (value.indexOf('$') >= 0)
result = FormValidation.warning(Messages.CopyArtifact_ParameterizedName());
else
result = FormValidation.error(
hudson.tasks.Messages.BuildTrigger_NoSuchProject(
value, AbstractProject.findNearest(value).getName()));
return result;
}
public boolean isApplicable(Class<? extends AbstractProject> clazz) {
return true;
}
public String getDisplayName() {
return Messages.CopyArtifact_DisplayName();
}
public DescriptorExtensionList<BuildSelector,Descriptor<BuildSelector>> getBuildSelectors() {
return Hudson.getInstance().<BuildSelector,Descriptor<BuildSelector>>getDescriptorList(BuildSelector.class);
}
}
// Listen for project renames and update property here if needed.
@Extension
public static final class ListenerImpl extends ItemListener {
@Override
public void onRenamed(Item item, String oldName, String newName) {
String oldFullName = Items.getCanonicalName(item.getParent(), oldName);
String newFullName = Items.getCanonicalName(item.getParent(), newName);
for (AbstractProject<?,?> project
: Hudson.getInstance().getAllItems(AbstractProject.class)) {
try {
for (CopyArtifact ca : getCopiers(project)) {
String projectName = ca.getProjectName();
String suffix = "";
// Support rename for "MatrixJobName/AxisName=value" type of name
int i = projectName.indexOf('=');
if (i > 0) {
int end = projectName.substring(0,i).lastIndexOf('/');
suffix = projectName.substring(end);
projectName = projectName.substring(0, end);
}
ItemGroup context = project.getParent();
String newProjectName = Items.computeRelativeNamesAfterRenaming(oldFullName, newFullName, projectName, context);
if (!projectName.equals(newProjectName)) {
ca.project = newProjectName + suffix;
project.save();
}
}
} catch (IOException ex) {
Logger.getLogger(ListenerImpl.class.getName()).log(Level.WARNING,
"Failed to resave project " + project.getName()
+ " for project rename in CopyArtifact build step ("
+ oldName + " =>" + newName + ")", ex);
}
}
}
private static List<CopyArtifact> getCopiers(AbstractProject<?,?> project) throws IOException {
List<CopyArtifact> copiers = getCopyArtifactsInProject(project);
for (CopyArtifact copier : copiers) {
copier.upgradeIfNecessary(project);
}
return copiers;
}
}
private static class EnvAction implements EnvironmentContributingAction {
// Decided not to record this data in build.xml, so marked transient:
private transient Map<String,String> data = new HashMap<String,String>();
private void add(ItemGroup ctx, String projectName, int buildNumber) {
if (data==null) return;
Item item = getProject(ctx, projectName);
// Use full name if configured with absolute path
// and relative otherwise
projectName = projectName.startsWith("/") ? item.getFullName() : item.getRelativeNameFrom(ctx);
if (projectName == null) {
// this is a case when the copying project doesn't belong to Jenkins item tree.
// (e.g. promotion for Promoted Builds plugin)
LOGGER.log(
Level.WARNING,
"Failed to calculate a relative path of {0} from {2}",
new Object[] {
item.getFullName(),
ctx.getFullName(),
}
);
return;
}
data.put("COPYARTIFACT_BUILD_NUMBER_"
+ projectName.toUpperCase().replaceAll("[^A-Z]+", "_"), // Only use letters and _
Integer.toString(buildNumber));
}
/**
* Retrieve root Job identified by this projectPath. For legacy reason, projectPath uses '/' as separator for
* job name and parameters or matrix axe, so can't just use {@link Jenkins#getItemByFullName(String)}.
* As a workaround, we split the path into parts and retrieve the item(group)s up to a Job.
*/
private Job getProject(ItemGroup ctx, String projectPath) {
String[] parts = projectPath.split("/");
if (projectPath.startsWith("/")) ctx = Jenkins.getInstance();
for (int i =0; i<parts.length; i++) {
String part = parts[i];
if (part.length() == 0) continue;
if (part.equals("..")) {
ctx = ((Item) ctx).getParent();
continue;
}
Item item = ctx.getItem(part);
if (item == null && i == 0) {
// not a relative job name, fall back to "classic" interpretation to consider absolute
item = Jenkins.getInstance().getItem(part);
}
if (item instanceof Job) return (Job) item;
ctx = (ItemGroup) item;
}
return null;
}
public void buildEnvVars(AbstractBuild<?,?> build, EnvVars env) {
if (data!=null) env.putAll(data);
}
public String getIconFileName() { return null; }
public String getDisplayName() { return null; }
public String getUrlName() { return null; }
}
}