-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathCacheControllerImpl.java
More file actions
1487 lines (1345 loc) · 68.3 KB
/
CacheControllerImpl.java
File metadata and controls
1487 lines (1345 loc) · 68.3 KB
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
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.maven.buildcache;
import javax.annotation.Nonnull;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Provider;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.TreeSet;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.UnaryOperator;
import java.util.regex.Pattern;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Strings;
import org.apache.commons.lang3.mutable.MutableBoolean;
import org.apache.maven.SessionScoped;
import org.apache.maven.artifact.handler.ArtifactHandler;
import org.apache.maven.artifact.handler.manager.ArtifactHandlerManager;
import org.apache.maven.buildcache.artifact.ArtifactRestorationReport;
import org.apache.maven.buildcache.artifact.OutputType;
import org.apache.maven.buildcache.artifact.RestoredArtifact;
import org.apache.maven.buildcache.checksum.MavenProjectInput;
import org.apache.maven.buildcache.hash.HashAlgorithm;
import org.apache.maven.buildcache.hash.HashFactory;
import org.apache.maven.buildcache.xml.Build;
import org.apache.maven.buildcache.xml.CacheConfig;
import org.apache.maven.buildcache.xml.CacheSource;
import org.apache.maven.buildcache.xml.DtoUtils;
import org.apache.maven.buildcache.xml.XmlService;
import org.apache.maven.buildcache.xml.build.Artifact;
import org.apache.maven.buildcache.xml.build.CompletedExecution;
import org.apache.maven.buildcache.xml.build.DigestItem;
import org.apache.maven.buildcache.xml.build.ProjectsInputInfo;
import org.apache.maven.buildcache.xml.build.Scm;
import org.apache.maven.buildcache.xml.config.DirName;
import org.apache.maven.buildcache.xml.config.PropertyName;
import org.apache.maven.buildcache.xml.config.TrackedProperty;
import org.apache.maven.buildcache.xml.diff.Diff;
import org.apache.maven.buildcache.xml.report.CacheReport;
import org.apache.maven.buildcache.xml.report.ProjectReport;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.execution.MojoExecutionEvent;
import org.apache.maven.plugin.MojoExecution;
import org.apache.maven.plugin.descriptor.Parameter;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectHelper;
import org.codehaus.plexus.util.ReflectionUtils;
import org.eclipse.aether.RepositorySystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static java.nio.file.StandardOpenOption.CREATE;
import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
import static org.apache.commons.lang3.StringUtils.split;
import static org.apache.maven.buildcache.CacheResult.empty;
import static org.apache.maven.buildcache.CacheResult.failure;
import static org.apache.maven.buildcache.CacheResult.partialSuccess;
import static org.apache.maven.buildcache.CacheResult.success;
import static org.apache.maven.buildcache.RemoteCacheRepository.BUILDINFO_XML;
import static org.apache.maven.buildcache.checksum.KeyUtils.getVersionlessProjectKey;
import static org.apache.maven.buildcache.checksum.MavenProjectInput.CACHE_IMPLEMENTATION_VERSION;
/**
* CacheControllerImpl
*/
@SessionScoped
@Named
@SuppressWarnings("unused")
public class CacheControllerImpl implements CacheController {
private static final Logger LOGGER = LoggerFactory.getLogger(CacheControllerImpl.class);
private static final String DEFAULT_FILE_GLOB = "*";
public static final String ERROR_MSG_RESTORATION_OUTSIDE_PROJECT =
"Blocked an attempt to restore files outside of a project directory: ";
private final MavenProjectHelper projectHelper;
private final ArtifactHandlerManager artifactHandlerManager;
private final XmlService xmlService;
private final CacheConfig cacheConfig;
private final LocalCacheRepository localCache;
private final RemoteCacheRepository remoteCache;
private final ConcurrentMap<String, CacheResult> cacheResults = new ConcurrentHashMap<>();
private final Provider<LifecyclePhasesHelper> providerLifecyclePhasesHelper;
private volatile Map<String, MavenProject> projectIndex;
private final ProjectInputCalculator projectInputCalculator;
private final RestoredArtifactHandler restoreArtifactHandler;
private volatile Scm scm;
/**
* Per-project cache state to ensure thread safety in multi-threaded builds.
* Each project gets isolated state for resource tracking, counters, and restored output tracking.
*/
private static class ProjectCacheState {
final Map<String, Path> attachedResourcesPathsById = new HashMap<>();
int attachedResourceCounter = 0;
final Set<String> restoredOutputClassifiers = new HashSet<>();
/**
* Tracks the staging directory path where pre-existing artifacts are moved.
* Artifacts are moved here before mojos run and restored after save() completes.
*/
Path stagingDirectory;
}
private final ConcurrentMap<String, ProjectCacheState> projectStates = new ConcurrentHashMap<>();
/**
* Get or create cache state for the given project (thread-safe).
*/
private ProjectCacheState getProjectState(MavenProject project) {
String key = getVersionlessProjectKey(project);
return projectStates.computeIfAbsent(key, k -> new ProjectCacheState());
}
// CHECKSTYLE_OFF: ParameterNumber
@Inject
public CacheControllerImpl(
MavenProjectHelper projectHelper,
RepositorySystem repoSystem,
ArtifactHandlerManager artifactHandlerManager,
XmlService xmlService,
LocalCacheRepository localCache,
RemoteCacheRepository remoteCache,
CacheConfig cacheConfig,
ProjectInputCalculator projectInputCalculator,
RestoredArtifactHandler restoreArtifactHandler,
Provider<LifecyclePhasesHelper> providerLifecyclePhasesHelper) {
// CHECKSTYLE_OFF: ParameterNumber
this.projectHelper = projectHelper;
this.localCache = localCache;
this.remoteCache = remoteCache;
this.cacheConfig = cacheConfig;
this.artifactHandlerManager = artifactHandlerManager;
this.xmlService = xmlService;
this.providerLifecyclePhasesHelper = providerLifecyclePhasesHelper;
this.projectInputCalculator = projectInputCalculator;
this.restoreArtifactHandler = restoreArtifactHandler;
}
@Override
@Nonnull
public CacheResult findCachedBuild(
MavenSession session, MavenProject project, List<MojoExecution> mojoExecutions, boolean skipCache) {
final LifecyclePhasesHelper lifecyclePhasesHelper = providerLifecyclePhasesHelper.get();
final String highestPhase = lifecyclePhasesHelper.resolveHighestLifecyclePhase(project, mojoExecutions);
if (!lifecyclePhasesHelper.isLaterPhaseThanClean(highestPhase)) {
return empty();
}
String projectName = getVersionlessProjectKey(project);
ProjectsInputInfo inputInfo = projectInputCalculator.calculateInput(project);
final CacheContext context = new CacheContext(project, inputInfo, session);
CacheResult result = empty(context);
if (!skipCache) {
LOGGER.info("Attempting to restore project {} from build cache", projectName);
// remote build first
if (cacheConfig.isRemoteCacheEnabled()) {
result = findCachedBuild(mojoExecutions, context);
if (!result.isSuccess() && result.getContext() != null) {
LOGGER.info("Remote cache is incomplete or missing, trying local build for {}", projectName);
}
}
if (!result.isSuccess() && result.getContext() != null) {
CacheResult localBuild = findLocalBuild(mojoExecutions, context);
if (localBuild.isSuccess() || (localBuild.isPartialSuccess() && !result.isPartialSuccess())) {
result = localBuild;
} else {
LOGGER.info(
"Local build was not found by checksum {} for {}", inputInfo.getChecksum(), projectName);
}
}
} else {
LOGGER.info(
"Project {} is marked as requiring force rebuild, will skip lookup in build cache", projectName);
}
cacheResults.put(getVersionlessProjectKey(project), result);
return result;
}
private CacheResult findCachedBuild(List<MojoExecution> mojoExecutions, CacheContext context) {
Optional<Build> cachedBuild = Optional.empty();
try {
cachedBuild = localCache.findBuild(context);
if (cachedBuild.isPresent()) {
return analyzeResult(context, mojoExecutions, cachedBuild.get());
}
} catch (Exception e) {
LOGGER.error("Cannot read cached remote build", e);
}
return cachedBuild.map(build -> failure(build, context)).orElseGet(() -> empty(context));
}
private CacheResult findLocalBuild(List<MojoExecution> mojoExecutions, CacheContext context) {
Optional<Build> localBuild = Optional.empty();
try {
localBuild = localCache.findLocalBuild(context);
if (localBuild.isPresent()) {
return analyzeResult(context, mojoExecutions, localBuild.get());
}
} catch (Exception e) {
LOGGER.error("Cannot read local build", e);
}
return localBuild.map(build -> failure(build, context)).orElseGet(() -> empty(context));
}
private CacheResult analyzeResult(CacheContext context, List<MojoExecution> mojoExecutions, Build build) {
try {
final ProjectsInputInfo inputInfo = context.getInputInfo();
String projectName = getVersionlessProjectKey(context.getProject());
LOGGER.info(
"Found cached build, restoring {} from cache by checksum {}", projectName, inputInfo.getChecksum());
LOGGER.debug("Cached build details: {}", build);
final String cacheImplementationVersion = build.getCacheImplementationVersion();
if (!CACHE_IMPLEMENTATION_VERSION.equals(cacheImplementationVersion)) {
LOGGER.warn(
"Maven and cached build implementations mismatch, caching might not work correctly. "
+ "Implementation version: " + CACHE_IMPLEMENTATION_VERSION + ", cached build: {}",
build.getCacheImplementationVersion());
}
final LifecyclePhasesHelper lifecyclePhasesHelper = providerLifecyclePhasesHelper.get();
List<MojoExecution> cachedSegment =
lifecyclePhasesHelper.getCachedSegment(context.getProject(), mojoExecutions, build);
List<MojoExecution> missingMojos = build.getMissingExecutions(cachedSegment);
if (!missingMojos.isEmpty()) {
LOGGER.warn(
"Cached build doesn't contains all requested plugin executions "
+ "(missing: {}), cannot restore",
missingMojos);
return failure(build, context);
}
if (!isCachedSegmentPropertiesPresent(context.getProject(), build, cachedSegment)) {
LOGGER.info("Cached build violates cache rules, cannot restore");
return failure(build, context);
}
final String highestRequestPhase =
lifecyclePhasesHelper.resolveHighestLifecyclePhase(context.getProject(), mojoExecutions);
if (lifecyclePhasesHelper.isLaterPhaseThanBuild(highestRequestPhase, build)
&& !canIgnoreMissingSegment(context.getProject(), build, mojoExecutions)) {
LOGGER.info(
"Project {} restored partially. Highest cached goal: {}, requested: {}",
projectName,
build.getHighestCompletedGoal(),
highestRequestPhase);
return partialSuccess(build, context);
}
return success(build, context);
} catch (Exception e) {
LOGGER.error("Failed to restore project", e);
localCache.clearCache(context);
return failure(build, context);
}
}
private boolean canIgnoreMissingSegment(MavenProject project, Build info, List<MojoExecution> mojoExecutions) {
final LifecyclePhasesHelper lifecyclePhasesHelper = providerLifecyclePhasesHelper.get();
final List<MojoExecution> postCachedSegment =
lifecyclePhasesHelper.getPostCachedSegment(project, mojoExecutions, info);
for (MojoExecution mojoExecution : postCachedSegment) {
if (!cacheConfig.canIgnore(mojoExecution)) {
return false;
}
}
return true;
}
private UnaryOperator<File> createRestorationToDiskConsumer(final MavenProject project, final Artifact artifact) {
if (cacheConfig.isRestoreOnDiskArtifacts() && MavenProjectInput.isRestoreOnDiskArtifacts(project)) {
Path restorationPath = project.getBasedir().toPath().resolve(artifact.getFilePath());
final AtomicBoolean restored = new AtomicBoolean(false);
return file -> {
// Set to restored even if it fails later, we don't want multiple try
if (restored.compareAndSet(false, true)) {
verifyRestorationInsideProject(project, restorationPath);
try {
restoreArtifactToDisk(file, artifact, restorationPath);
} catch (IOException e) {
LOGGER.error("Cannot restore file " + artifact.getFileName(), e);
throw new RuntimeException(e);
}
}
return restorationPath.toFile();
};
}
// Return a consumer doing nothing
return file -> file;
}
/**
* Restores an artifact from cache to disk, handling both regular files and directory artifacts.
* Directory artifacts (cached as zips) are unzipped back to their original directory structure.
*/
private void restoreArtifactToDisk(File cachedFile, Artifact artifact, Path restorationPath) throws IOException {
// Check the explicit isDirectory flag set during save.
// Directory artifacts (e.g., target/classes) are saved as zips and need to be unzipped on restore.
if (artifact.isIsDirectory()) {
restoreDirectoryArtifact(cachedFile, artifact, restorationPath);
} else {
restoreRegularFileArtifact(cachedFile, artifact, restorationPath);
}
}
/**
* Restores a directory artifact by unzipping the cached zip file.
*/
private void restoreDirectoryArtifact(File cachedZip, Artifact artifact, Path restorationPath) throws IOException {
if (!Files.exists(restorationPath)) {
Files.createDirectories(restorationPath);
}
CacheUtils.unzip(
cachedZip.toPath(),
restorationPath,
cacheConfig.isPreservePermissions(),
cacheConfig.isPreserveTimestamps());
LOGGER.debug("Restored directory artifact by unzipping: {} -> {}", artifact.getFileName(), restorationPath);
}
/**
* Restores a regular file artifact by copying it from cache.
*/
private void restoreRegularFileArtifact(File cachedFile, Artifact artifact, Path restorationPath)
throws IOException {
Files.createDirectories(restorationPath.getParent());
Files.copy(cachedFile.toPath(), restorationPath, StandardCopyOption.REPLACE_EXISTING);
LOGGER.debug("Restored file on disk ({} to {})", artifact.getFileName(), restorationPath);
}
private boolean isPathInsideProject(final MavenProject project, Path path) {
Path restorationPath = path.toAbsolutePath().normalize();
return restorationPath.startsWith(project.getBasedir().toPath());
}
private void verifyRestorationInsideProject(final MavenProject project, Path path) {
if (!isPathInsideProject(project, path)) {
Path normalized = path.toAbsolutePath().normalize();
LOGGER.error(ERROR_MSG_RESTORATION_OUTSIDE_PROJECT + normalized);
throw new RuntimeException(ERROR_MSG_RESTORATION_OUTSIDE_PROJECT + normalized);
}
}
@Override
public ArtifactRestorationReport restoreProjectArtifacts(CacheResult cacheResult) {
LOGGER.debug("Restore project artifacts");
final Build build = cacheResult.getBuildInfo();
final CacheContext context = cacheResult.getContext();
final MavenProject project = context.getProject();
final ProjectCacheState state = getProjectState(project);
ArtifactRestorationReport restorationReport = new ArtifactRestorationReport();
try {
RestoredArtifact restoredProjectArtifact = null;
List<RestoredArtifact> restoredAttachedArtifacts = new ArrayList<>();
if (build.getArtifact() != null && isNotBlank(build.getArtifact().getFileName())) {
final Artifact artifactInfo = build.getArtifact();
String originalVersion = artifactInfo.getVersion();
artifactInfo.setVersion(project.getVersion());
// TODO if remote is forced, probably need to refresh or reconcile all files
final Future<File> downloadTask =
createDownloadTask(cacheResult, context, project, artifactInfo, originalVersion);
restoredProjectArtifact = restoredArtifact(
project.getArtifact(),
artifactInfo.getType(),
artifactInfo.getClassifier(),
downloadTask,
createRestorationToDiskConsumer(project, artifactInfo));
if (!cacheConfig.isLazyRestore()) {
restoredProjectArtifact.getFile();
}
}
for (Artifact attachedArtifactInfo : build.getAttachedArtifacts()) {
String originalVersion = attachedArtifactInfo.getVersion();
attachedArtifactInfo.setVersion(project.getVersion());
if (isNotBlank(attachedArtifactInfo.getFileName())) {
OutputType outputType = OutputType.fromClassifier(attachedArtifactInfo.getClassifier());
if (OutputType.ARTIFACT != outputType) {
// restoring generated sources / extra output might be unnecessary in CI, could be disabled for
// performance reasons
// it may also be disabled on a per-project level (defaults to true - enable)
if (cacheConfig.isRestoreGeneratedSources()
&& MavenProjectInput.isRestoreGeneratedSources(project)) {
// Set this value before trying the restoration, to keep a trace of the attempt if it fails
restorationReport.setRestoredFilesInProjectDirectory(true);
// generated sources artifact
final Path attachedArtifactFile =
localCache.getArtifactFile(context, cacheResult.getSource(), attachedArtifactInfo);
restoreGeneratedSources(attachedArtifactInfo, attachedArtifactFile, project);
// Track this classifier as restored so save() includes it even with old timestamp
state.restoredOutputClassifiers.add(attachedArtifactInfo.getClassifier());
}
} else {
Future<File> downloadTask = createDownloadTask(
cacheResult, context, project, attachedArtifactInfo, originalVersion);
final RestoredArtifact restoredAttachedArtifact = restoredArtifact(
restoredProjectArtifact == null ? project.getArtifact() : restoredProjectArtifact,
attachedArtifactInfo.getType(),
attachedArtifactInfo.getClassifier(),
downloadTask,
createRestorationToDiskConsumer(project, attachedArtifactInfo));
if (!cacheConfig.isLazyRestore()) {
restoredAttachedArtifact.getFile();
}
restoredAttachedArtifacts.add(restoredAttachedArtifact);
}
}
}
// Actually modify project at the end in case something went wrong during restoration,
// in which case, the project is unmodified and we continue with normal build.
if (restoredProjectArtifact != null) {
project.setArtifact(restoredProjectArtifact);
// need to include package lifecycle to save build info for incremental builds
if (!project.hasLifecyclePhase("package")) {
project.addLifecyclePhase("package");
}
}
restoredAttachedArtifacts.forEach(project::addAttachedArtifact);
restorationReport.setSuccess(true);
} catch (Exception e) {
LOGGER.debug("Cannot restore cache, continuing with normal build.", e);
}
return restorationReport;
}
/**
* Helper method similar to {@link org.apache.maven.project.MavenProjectHelper#attachArtifact} to work specifically
* with restored from cache artifacts
*/
private RestoredArtifact restoredArtifact(
org.apache.maven.artifact.Artifact parent,
String artifactType,
String artifactClassifier,
Future<File> artifactFile,
UnaryOperator<File> restoreToDiskConsumer) {
ArtifactHandler handler = null;
if (artifactType != null) {
handler = artifactHandlerManager.getArtifactHandler(artifactType);
}
if (handler == null) {
handler = artifactHandlerManager.getArtifactHandler("jar");
}
// todo: probably need update download url to cache
RestoredArtifact artifact = new RestoredArtifact(
parent, artifactFile, artifactType, artifactClassifier, handler, restoreToDiskConsumer);
artifact.setResolved(true);
return artifact;
}
private Future<File> createDownloadTask(
CacheResult cacheResult,
CacheContext context,
MavenProject project,
Artifact artifact,
String originalVersion) {
final FutureTask<File> downloadTask = new FutureTask<>(() -> {
LOGGER.debug("Downloading artifact {}", artifact.getArtifactId());
final Path artifactFile = localCache.getArtifactFile(context, cacheResult.getSource(), artifact);
if (!Files.exists(artifactFile)) {
throw new FileNotFoundException("Missing file for cached build, cannot restore. File: " + artifactFile);
}
LOGGER.debug("Downloaded artifact {} to: {}", artifact.getArtifactId(), artifactFile);
return restoreArtifactHandler
.adjustArchiveArtifactVersion(project, originalVersion, artifactFile)
.toFile();
});
if (!cacheConfig.isLazyRestore()) {
downloadTask.run();
}
return downloadTask;
}
@Override
public void save(
CacheResult cacheResult,
List<MojoExecution> mojoExecutions,
Map<String, MojoExecutionEvent> executionEvents) {
CacheContext context = cacheResult.getContext();
if (context == null || context.getInputInfo() == null) {
LOGGER.info("Cannot save project in cache, skipping");
return;
}
final MavenProject project = context.getProject();
final MavenSession session = context.getSession();
final ProjectCacheState state = getProjectState(project);
try {
state.attachedResourcesPathsById.clear();
state.attachedResourceCounter = 0;
// Get build start time to filter out stale artifacts from previous builds
final long buildStartTime = session.getRequest().getStartTime().getTime();
final HashFactory hashFactory = cacheConfig.getHashFactory();
final HashAlgorithm algorithm = hashFactory.createAlgorithm();
final org.apache.maven.artifact.Artifact projectArtifact = project.getArtifact();
// Cache compile outputs (classes, test-classes, generated sources) if enabled
// This allows compile-only builds to create restorable cache entries
// Can be disabled with -Dmaven.build.cache.cacheCompile=false to reduce IO overhead
final boolean cacheCompile = cacheConfig.isCacheCompile();
if (cacheCompile) {
attachGeneratedSources(project, state, buildStartTime);
attachOutputs(project, state, buildStartTime);
}
final List<org.apache.maven.artifact.Artifact> attachedArtifacts =
project.getAttachedArtifacts() != null ? project.getAttachedArtifacts() : Collections.emptyList();
final List<Artifact> attachedArtifactDtos = artifactDtos(attachedArtifacts, algorithm, project, state);
// Always create artifact DTO - if package phase hasn't run, the file will be null
// and restoration will safely skip it. This ensures all builds have an artifact DTO.
final Artifact projectArtifactDto = artifactDto(project.getArtifact(), algorithm, project, state);
List<CompletedExecution> completedExecution = buildExecutionInfo(mojoExecutions, executionEvents);
// CRITICAL: Don't create incomplete cache entries!
// Only save cache entry if we have SOMETHING useful to restore.
// Exclude consumer POMs (Maven metadata) from the "useful artifacts" check.
// This prevents the bug where:
// 1. mvn compile (cacheCompile=false) creates cache entry with only metadata
// 2. mvn compile (cacheCompile=true) tries to restore incomplete cache and fails
//
// Save cache entry if ANY of these conditions are met:
// 1. Project artifact file exists:
// a) Regular file (JAR/WAR/etc from package phase)
// b) Directory (target/classes from compile-only builds) - only if cacheCompile=true
// 2. Has attached artifacts (classes/test-classes from cacheCompile=true)
// 3. POM project with plugin executions (worth caching to skip plugin execution on cache hit)
//
// NOTE: No timestamp checking needed - stagePreExistingArtifacts() ensures only fresh files
// are visible (stale files are moved to staging directory).
// Check if project artifact is valid (exists and is correct type)
boolean hasArtifactFile = projectArtifact.getFile() != null
&& projectArtifact.getFile().exists()
&& (projectArtifact.getFile().isFile()
|| (cacheCompile && projectArtifact.getFile().isDirectory()));
boolean hasAttachedArtifacts = !attachedArtifactDtos.isEmpty()
&& attachedArtifactDtos.stream()
.anyMatch(a -> !"consumer".equals(a.getClassifier()) || !"pom".equals(a.getType()));
// Only save POM projects if they executed plugins (not just aggregator POMs with no work)
boolean isPomProjectWithWork = "pom".equals(project.getPackaging()) && !completedExecution.isEmpty();
if (!hasArtifactFile && !hasAttachedArtifacts && !isPomProjectWithWork) {
LOGGER.info(
"Skipping cache save: no artifacts to save ({}only metadata present)",
cacheCompile ? "" : "cacheCompile=false, ");
return;
}
final Build build = new Build(
session.getGoals(),
projectArtifactDto,
attachedArtifactDtos,
context.getInputInfo(),
completedExecution,
hashFactory.getAlgorithm());
populateGitInfo(build, session);
build.getDto().set_final(cacheConfig.isSaveToRemoteFinal());
cacheResults.put(getVersionlessProjectKey(project), CacheResult.rebuilt(cacheResult, build));
localCache.beforeSave(context);
// Save project artifact file if it exists (created by package or compile phase)
if (projectArtifact.getFile() != null) {
saveProjectArtifact(cacheResult, projectArtifact, project);
}
for (org.apache.maven.artifact.Artifact attachedArtifact : attachedArtifacts) {
if (attachedArtifact.getFile() != null) {
boolean storeArtifact =
isOutputArtifact(attachedArtifact.getFile().getName());
if (storeArtifact) {
localCache.saveArtifactFile(cacheResult, attachedArtifact);
} else {
LOGGER.debug(
"Skipping attached project artifact '{}' = "
+ " it is marked for exclusion from caching",
attachedArtifact.getFile().getName());
}
}
}
localCache.saveBuildInfo(cacheResult, build);
if (cacheConfig.isBaselineDiffEnabled()) {
produceDiffReport(cacheResult, build);
}
} catch (Exception e) {
LOGGER.error("Failed to save project, cleaning cache. Project: {}", project, e);
try {
localCache.clearCache(context);
} catch (Exception ex) {
LOGGER.error("Failed to clean cache due to unexpected error:", ex);
}
} finally {
// Cleanup project state to free memory, but preserve stagingDirectory for restore
// Note: stagingDirectory must persist until restoreStagedArtifacts() is called
state.attachedResourcesPathsById.clear();
state.attachedResourceCounter = 0;
state.restoredOutputClassifiers.clear();
// stagingDirectory is NOT cleared here - it's cleared in restoreStagedArtifacts()
}
}
/**
* Saves a project artifact to cache, handling both regular files and directory artifacts.
* Directory artifacts (e.g., target/classes from compile-only builds) are zipped before saving
* since Files.copy() cannot handle directories.
*/
private void saveProjectArtifact(
CacheResult cacheResult, org.apache.maven.artifact.Artifact projectArtifact, MavenProject project)
throws IOException {
File originalFile = projectArtifact.getFile();
try {
if (originalFile.isDirectory()) {
saveDirectoryArtifact(cacheResult, projectArtifact, project, originalFile);
} else {
// Regular file (JAR/WAR) - save directly
localCache.saveArtifactFile(cacheResult, projectArtifact);
}
} finally {
// Restore original file reference in case it was temporarily changed
projectArtifact.setFile(originalFile);
}
}
/**
* Saves a directory artifact by zipping it first, then saving the zip to cache.
*/
private void saveDirectoryArtifact(
CacheResult cacheResult,
org.apache.maven.artifact.Artifact projectArtifact,
MavenProject project,
File originalFile)
throws IOException {
Path tempZip = Files.createTempFile("maven-cache-", "-" + project.getArtifactId() + ".zip");
boolean hasFiles = CacheUtils.zip(
originalFile.toPath(),
tempZip,
"*",
cacheConfig.isPreservePermissions(),
cacheConfig.isPreserveTimestamps());
if (hasFiles) {
// Temporarily replace artifact file with zip for saving
projectArtifact.setFile(tempZip.toFile());
localCache.saveArtifactFile(cacheResult, projectArtifact);
LOGGER.debug("Saved directory artifact as zip: {} -> {}", originalFile, tempZip);
// Clean up temp file after it's been saved to cache
Files.deleteIfExists(tempZip);
} else {
LOGGER.info("Skipping empty directory artifact: {}", originalFile);
}
}
public void produceDiffReport(CacheResult cacheResult, Build build) {
MavenProject project = cacheResult.getContext().getProject();
Optional<Build> baselineHolder = remoteCache.findBaselineBuild(project);
if (baselineHolder.isPresent()) {
Build baseline = baselineHolder.get();
String outputDirectory = project.getBuild().getDirectory();
Path reportOutputDir = Paths.get(outputDirectory, "incremental-maven");
LOGGER.info("Saving cache builds diff to: {}", reportOutputDir);
Diff diff = new CacheDiff(build.getDto(), baseline.getDto(), cacheConfig).compare();
try {
Files.createDirectories(reportOutputDir);
final ProjectsInputInfo baselineInputs = baseline.getDto().getProjectsInputInfo();
final String checksum = baselineInputs.getChecksum();
Files.write(
reportOutputDir.resolve("buildinfo-baseline-" + checksum + ".xml"),
xmlService.toBytes(baseline.getDto()),
TRUNCATE_EXISTING,
CREATE);
Files.write(
reportOutputDir.resolve("buildinfo-" + checksum + ".xml"),
xmlService.toBytes(build.getDto()),
TRUNCATE_EXISTING,
CREATE);
Files.write(
reportOutputDir.resolve("buildsdiff-" + checksum + ".xml"),
xmlService.toBytes(diff),
TRUNCATE_EXISTING,
CREATE);
final Optional<DigestItem> pom =
CacheDiff.findPom(build.getDto().getProjectsInputInfo());
if (pom.isPresent()) {
Files.write(
reportOutputDir.resolve("effective-pom-" + checksum + ".xml"),
pom.get().getValue().getBytes(StandardCharsets.UTF_8),
TRUNCATE_EXISTING,
CREATE);
}
final Optional<DigestItem> baselinePom = CacheDiff.findPom(baselineInputs);
if (baselinePom.isPresent()) {
Files.write(
reportOutputDir.resolve("effective-pom-baseline-" + baselineInputs.getChecksum() + ".xml"),
baselinePom.get().getValue().getBytes(StandardCharsets.UTF_8),
TRUNCATE_EXISTING,
CREATE);
}
} catch (IOException e) {
LOGGER.error("Cannot produce build diff for project", e);
}
} else {
LOGGER.info("Cannot find project in baseline build, skipping diff");
}
}
private List<Artifact> artifactDtos(
List<org.apache.maven.artifact.Artifact> attachedArtifacts,
HashAlgorithm digest,
MavenProject project,
ProjectCacheState state)
throws IOException {
List<Artifact> result = new ArrayList<>();
for (org.apache.maven.artifact.Artifact attachedArtifact : attachedArtifacts) {
if (attachedArtifact.getFile() != null
&& isOutputArtifact(attachedArtifact.getFile().getName())) {
result.add(artifactDto(attachedArtifact, digest, project, state));
}
}
return result;
}
private Artifact artifactDto(
org.apache.maven.artifact.Artifact projectArtifact,
HashAlgorithm algorithm,
MavenProject project,
ProjectCacheState state)
throws IOException {
final Artifact dto = DtoUtils.createDto(projectArtifact);
if (projectArtifact.getFile() != null) {
final Path file = projectArtifact.getFile().toPath();
// Only set hash and size for regular files (not directories like target/classes for JPMS projects)
if (Files.isRegularFile(file)) {
dto.setFileHash(algorithm.hash(file));
dto.setFileSize(Files.size(file));
} else if (Files.isDirectory(file)) {
// Mark directory artifacts explicitly so we can unzip them on restore
dto.setIsDirectory(true);
}
// Always set filePath (needed for artifact restoration)
// Get the relative path of any extra zip directory added to the cache
Path relativePath = state.attachedResourcesPathsById.get(projectArtifact.getClassifier());
if (relativePath == null) {
// If the path was not a member of this map, we are in presence of an original artifact.
// we get its location on the disk
relativePath = project.getBasedir().toPath().relativize(file.toAbsolutePath());
}
dto.setFilePath(FilenameUtils.separatorsToUnix(relativePath.toString()));
}
return dto;
}
private List<CompletedExecution> buildExecutionInfo(
List<MojoExecution> mojoExecutions, Map<String, MojoExecutionEvent> executionEvents) {
List<CompletedExecution> list = new ArrayList<>();
for (MojoExecution mojoExecution : mojoExecutions) {
final String executionKey = CacheUtils.mojoExecutionKey(mojoExecution);
final MojoExecutionEvent executionEvent =
executionEvents != null ? executionEvents.get(executionKey) : null;
CompletedExecution executionInfo = new CompletedExecution();
executionInfo.setExecutionKey(executionKey);
executionInfo.setMojoClassName(mojoExecution.getMojoDescriptor().getImplementation());
if (executionEvent != null) {
recordMojoProperties(executionInfo, executionEvent);
}
list.add(executionInfo);
}
return list;
}
private void recordMojoProperties(CompletedExecution execution, MojoExecutionEvent executionEvent) {
final MojoExecution mojoExecution = executionEvent.getExecution();
final boolean logAll = cacheConfig.isLogAllProperties(mojoExecution);
List<TrackedProperty> trackedProperties = cacheConfig.getTrackedProperties(mojoExecution);
List<PropertyName> noLogProperties = cacheConfig.getNologProperties(mojoExecution);
List<PropertyName> forceLogProperties = cacheConfig.getLoggedProperties(mojoExecution);
final Object mojo = executionEvent.getMojo();
final File baseDir = executionEvent.getProject().getBasedir();
final String baseDirPath = FilenameUtils.normalizeNoEndSeparator(baseDir.getAbsolutePath()) + File.separator;
final List<Parameter> parameters = mojoExecution.getMojoDescriptor().getParameters();
for (Parameter parameter : parameters) {
// editable parameters could be configured by user
if (!parameter.isEditable()) {
continue;
}
final String propertyName = parameter.getName();
final boolean tracked = isTracked(propertyName, trackedProperties);
if (!tracked && isExcluded(propertyName, logAll, noLogProperties, forceLogProperties)) {
continue;
}
try {
Field field = ReflectionUtils.getFieldByNameIncludingSuperclasses(propertyName, mojo.getClass());
if (field != null) {
final Object value = ReflectionUtils.getValueIncludingSuperclasses(propertyName, mojo);
DtoUtils.addProperty(execution, propertyName, value, baseDirPath, tracked);
continue;
}
// no field but maybe there is a getter with standard naming and no args
Method getter = getGetter(propertyName, mojo.getClass());
if (getter != null) {
Object value = getter.invoke(mojo);
DtoUtils.addProperty(execution, propertyName, value, baseDirPath, tracked);
continue;
}
if (LOGGER.isWarnEnabled()) {
LOGGER.warn(
"Cannot find a Mojo parameter '{}' to read for Mojo {}. This parameter should be ignored.",
propertyName,
mojoExecution);
}
} catch (IllegalAccessException | InvocationTargetException e) {
LOGGER.info("Cannot get property {} value from {}: {}", propertyName, mojo, e.getMessage());
if (tracked) {
throw new IllegalArgumentException("Property configured in cache introspection config " + "for "
+ mojo + " is not accessible: " + propertyName);
}
}
}
}
private static Method getGetter(String fieldName, Class<?> clazz) {
String getterMethodName = "get" + org.codehaus.plexus.util.StringUtils.capitalizeFirstLetter(fieldName);
Method[] methods = clazz.getMethods();
for (Method method : methods) {
if (method.getName().equals(getterMethodName)
&& !method.getReturnType().equals(Void.TYPE)
&& method.getParameterCount() == 0) {
return method;
}
}
return null;
}
private boolean isExcluded(
String propertyName,
boolean logAll,
List<PropertyName> excludedProperties,
List<PropertyName> forceLogProperties) {
if (!forceLogProperties.isEmpty()) {
for (PropertyName logProperty : forceLogProperties) {
if (Strings.CS.equals(propertyName, logProperty.getPropertyName())) {
return false;
}
}
return true;
}
if (!excludedProperties.isEmpty()) {
for (PropertyName excludedProperty : excludedProperties) {
if (Strings.CS.equals(propertyName, excludedProperty.getPropertyName())) {
return true;
}
}
return false;
}
return !logAll;
}
private boolean isTracked(String propertyName, List<TrackedProperty> trackedProperties) {
for (TrackedProperty trackedProperty : trackedProperties) {
if (Strings.CS.equals(propertyName, trackedProperty.getPropertyName())) {
return true;
}
}
return false;
}
private boolean isCachedSegmentPropertiesPresent(
MavenProject project, Build build, List<MojoExecution> mojoExecutions) {
for (MojoExecution mojoExecution : mojoExecutions) {
// completion of all mojos checked above, so we expect tp have execution info here
final List<TrackedProperty> trackedProperties = cacheConfig.getTrackedProperties(mojoExecution);
final CompletedExecution cachedExecution = build.findMojoExecutionInfo(mojoExecution);
if (cachedExecution == null) {
LOGGER.info(
"Execution is not cached. Plugin: {}, goal {}, executionId: {}",
mojoExecution.getPlugin(),
mojoExecution.getGoal(),
mojoExecution.getExecutionId());
return false;
}
if (!DtoUtils.containsAllProperties(cachedExecution, trackedProperties)) {
LOGGER.warn(
"Cached build record doesn't contain all tracked properties. Plugin: {}, goal: {},"
+ " executionId: {}",
mojoExecution.getPlugin(),
mojoExecution.getGoal(),
mojoExecution.getExecutionId());
return false;
}
}
return true;
}
@Override
public boolean isForcedExecution(MavenProject project, MojoExecution execution) {
if (cacheConfig.isForcedExecution(execution)) {
return true;
}
if (StringUtils.isNotBlank(cacheConfig.getAlwaysRunPlugins())) {
String[] alwaysRunPluginsList = split(cacheConfig.getAlwaysRunPlugins(), ",");
for (String pluginAndGoal : alwaysRunPluginsList) {
String[] tokens = pluginAndGoal.split(":");
String alwaysRunPlugin = tokens[0];
String alwaysRunGoal = tokens.length == 1 ? "*" : tokens[1];
if (Objects.equals(execution.getPlugin().getArtifactId(), alwaysRunPlugin)
&& ("*".equals(alwaysRunGoal) || Objects.equals(execution.getGoal(), alwaysRunGoal))) {
return true;
}
}
}
return false;
}