-
Notifications
You must be signed in to change notification settings - Fork 5.2k
/
IncProjectBuilder.java
1758 lines (1618 loc) · 74.6 KB
/
IncProjectBuilder.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
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
// Copyright 2000-2024 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.jps.incremental;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.tracing.Tracer;
import com.intellij.util.ReflectionUtil;
import com.intellij.util.SmartList;
import com.intellij.util.concurrency.AppExecutorUtil;
import com.intellij.util.containers.CollectionFactory;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.FileCollectionFactory;
import com.intellij.util.containers.MultiMap;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jps.ModuleChunk;
import org.jetbrains.jps.TimingLog;
import org.jetbrains.jps.api.BuildParametersKeys;
import org.jetbrains.jps.api.CanceledStatus;
import org.jetbrains.jps.api.GlobalOptions;
import org.jetbrains.jps.builders.*;
import org.jetbrains.jps.builders.impl.BuildOutputConsumerImpl;
import org.jetbrains.jps.builders.impl.BuildTargetChunk;
import org.jetbrains.jps.builders.impl.DirtyFilesHolderBase;
import org.jetbrains.jps.builders.java.JavaBuilderUtil;
import org.jetbrains.jps.builders.java.JavaModuleBuildTargetType;
import org.jetbrains.jps.builders.java.JavaSourceRootDescriptor;
import org.jetbrains.jps.builders.logging.ProjectBuilderLogger;
import org.jetbrains.jps.builders.storage.BuildDataCorruptedException;
import org.jetbrains.jps.builders.storage.SourceToOutputMapping;
import org.jetbrains.jps.cmdline.BuildRunner;
import org.jetbrains.jps.cmdline.ProjectDescriptor;
import org.jetbrains.jps.incremental.fs.BuildFSState;
import org.jetbrains.jps.incremental.fs.CompilationRound;
import org.jetbrains.jps.incremental.fs.FilesDelta;
import org.jetbrains.jps.incremental.messages.*;
import org.jetbrains.jps.incremental.storage.*;
import org.jetbrains.jps.indices.ModuleExcludeIndex;
import org.jetbrains.jps.javac.ExternalJavacManager;
import org.jetbrains.jps.javac.JavacMain;
import org.jetbrains.jps.model.java.JpsJavaExtensionService;
import org.jetbrains.jps.model.java.compiler.JpsJavaCompilerConfiguration;
import org.jetbrains.jps.model.module.JpsModule;
import org.jetbrains.jps.service.SharedThreadPool;
import org.jetbrains.jps.util.JpsPathUtil;
import java.io.File;
import java.io.IOException;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import static org.jetbrains.jps.builders.java.JavaBuilderUtil.isDepGraphEnabled;
@ApiStatus.Internal
public final class IncProjectBuilder {
private static final Logger LOG = Logger.getInstance(IncProjectBuilder.class);
private static final String CLASSPATH_INDEX_FILE_NAME = "classpath.index";
// CLASSPATH_INDEX_FILE_NAME cannot be used because IDEA on run creates CLASSPATH_INDEX_FILE_NAME only if some module class is loaded,
// so, not possible to distinguish case
// "classpath.index doesn't exist because deleted on module file change" vs "classpath.index doesn't exist because was not created"
private static final String UNMODIFIED_MARK_FILE_NAME = ".unmodified";
private static final int FLUSH_INVOCATIONS_TO_SKIP = 10;
//private static final boolean GENERATE_CLASSPATH_INDEX = Boolean.parseBoolean(System.getProperty(GlobalOptions.GENERATE_CLASSPATH_INDEX_OPTION, "false"));
private static final boolean SYNC_DELETE = Boolean.parseBoolean(System.getProperty("jps.sync.delete", "false"));
private static final GlobalContextKey<Set<BuildTarget<?>>> TARGET_WITH_CLEARED_OUTPUT = GlobalContextKey.create("_targets_with_cleared_output_");
public static final int MAX_BUILDER_THREADS;
static {
int maxThreads = Math.min(10, (75 * Runtime.getRuntime().availableProcessors()) / 100); // 75% of available logical cores, but not more than 10 threads
try {
maxThreads = Math.max(1, Integer.parseInt(System.getProperty(GlobalOptions.COMPILE_PARALLEL_MAX_THREADS_OPTION, Integer.toString(maxThreads))));
}
catch (NumberFormatException ignored) {
maxThreads = Math.max(1, maxThreads);
}
MAX_BUILDER_THREADS = maxThreads;
}
private final ProjectDescriptor myProjectDescriptor;
private final BuilderRegistry myBuilderRegistry;
private final Map<String, String> myBuilderParams;
private final CanceledStatus myCancelStatus;
private final List<MessageHandler> myMessageHandlers = new ArrayList<>();
private final MessageHandler myMessageDispatcher = new MessageHandler() {
@Override
public void processMessage(BuildMessage msg) {
for (MessageHandler h : myMessageHandlers) {
h.processMessage(msg);
}
}
};
private final boolean myIsTestMode;
private final int myTotalModuleLevelBuilderCount;
private final List<Future<?>> myAsyncTasks = Collections.synchronizedList(new ArrayList<>());
private final ConcurrentMap<Builder, AtomicLong> myElapsedTimeNanosByBuilder = new ConcurrentHashMap<>();
private final ConcurrentMap<Builder, AtomicInteger> myNumberOfSourcesProcessedByBuilder = new ConcurrentHashMap<>();
public IncProjectBuilder(@NotNull ProjectDescriptor pd, @NotNull BuilderRegistry builderRegistry,
@NotNull Map<String, String> builderParams, @NotNull CanceledStatus cs, final boolean isTestMode) {
myProjectDescriptor = pd;
myBuilderRegistry = builderRegistry;
myBuilderParams = builderParams;
myCancelStatus = cs;
myTotalModuleLevelBuilderCount = builderRegistry.getModuleLevelBuilderCount();
myIsTestMode = isTestMode;
}
public void addMessageHandler(MessageHandler handler) {
myMessageHandlers.add(handler);
}
public void checkUpToDate(@NotNull CompileScope scope) {
CompileContextImpl context = createContext(scope);
try {
final BuildFSState fsState = myProjectDescriptor.fsState;
ExecutorService executor = AppExecutorUtil.createBoundedApplicationPoolExecutor("IncProjectBuilder Check UpToDate Pool", SharedThreadPool.getInstance(), MAX_BUILDER_THREADS);
List<Future<?>> tasks = new ArrayList<>();
var notifier = new Object() {
private final AtomicBoolean hasWorkToDo = new AtomicBoolean(false);
boolean hasChanges() {
return hasWorkToDo.get();
}
void signalHasChanges() {
if (!hasWorkToDo.getAndSet(true)) {
// this will serve as a marker that compiler has work to do
myMessageDispatcher.processMessage(DoneSomethingNotification.INSTANCE);
}
}
};
for (BuildTarget<?> target : myProjectDescriptor.getBuildTargetIndex().getAllTargets()) {
if (notifier.hasChanges()) {
break;
}
if (scope.isAffected(target)) {
tasks.add(executor.submit(() -> {
try {
if (notifier.hasChanges()) {
return;
}
if (context.getCancelStatus().isCanceled()) {
notifier.signalHasChanges(); // unable to check all targets => assume has changes
return;
}
BuildOperations.ensureFSStateInitialized(context, target, true);
final FilesDelta delta = fsState.getEffectiveFilesDelta(context, target);
delta.lockData();
try {
for (Set<File> files : delta.getSourcesToRecompile().values()) {
for (File file : files) {
if (scope.isAffected(target, file)) {
notifier.signalHasChanges();
return;
}
}
}
}
finally {
delta.unlockData();
}
}
catch (Throwable e) {
LOG.info(e);
notifier.signalHasChanges(); // data can be corrupted => rebuild required => has changes
}
}));
}
}
for (Future<?> task : tasks) {
try {
task.get();
}
catch (Throwable e) {
LOG.info(e);
}
}
}
finally {
flushContext(context);
}
}
public void build(CompileScope scope, boolean forceCleanCaches) throws RebuildRequestedException {
Tracer.Span rebuildRequiredSpan = Tracer.start("IncProjectBuilder.checkRebuildRequired");
checkRebuildRequired(scope);
rebuildRequiredSpan.complete();
final LowMemoryWatcher memWatcher = LowMemoryWatcher.register(() -> {
JavacMain.clearCompilerZipFileCache();
myProjectDescriptor.dataManager.flush(false);
myProjectDescriptor.getProjectStamps().getStampStorage().force();
});
final CleanupTempDirectoryExtension cleaner = CleanupTempDirectoryExtension.getInstance();
final Future<Void> cleanupTask = cleaner != null && cleaner.getCleanupTask() != null? cleaner.getCleanupTask() : startTempDirectoryCleanupTask(myProjectDescriptor);
if (cleanupTask != null) {
myAsyncTasks.add(cleanupTask);
}
CompileContextImpl context = null;
BuildTargetSourcesState sourcesState = null;
try {
context = createContext(scope);
sourcesState = new BuildTargetSourcesState(context);
// Clear source state report if force clean or rebuild
if (forceCleanCaches || context.isProjectRebuild()) {
sourcesState.clearSourcesState();
}
Tracer.Span buildSpan = Tracer.start("IncProjectBuilder.runBuild");
runBuild(context, forceCleanCaches);
buildSpan.complete();
myProjectDescriptor.dataManager.saveVersion();
myProjectDescriptor.dataManager.reportUnhandledRelativizerPaths();
sourcesState.reportSourcesState();
reportRebuiltModules(context);
reportUnprocessedChanges(context);
}
catch (StopBuildException e) {
reportRebuiltModules(context);
reportUnprocessedChanges(context);
// If build was canceled for some reasons e.g., compilation error we should report built modules
sourcesState.reportSourcesState();
// some builder decided to stop the build
// report optional progress message if any
final String msg = e.getMessage();
if (!StringUtil.isEmptyOrSpaces(msg)) {
myMessageDispatcher.processMessage(new ProgressMessage(msg));
}
}
catch (BuildDataCorruptedException e) {
LOG.info(e);
requestRebuild(e, e);
}
catch (ProjectBuildException e) {
LOG.info(e);
final Throwable cause = e.getCause();
if (cause instanceof IOException ||
cause instanceof BuildDataCorruptedException ||
(cause instanceof RuntimeException && cause.getCause() instanceof IOException)) {
requestRebuild(e, cause);
}
else {
// should stop the build with error
final String errMessage = e.getMessage();
final CompilerMessage msg;
if (StringUtil.isEmptyOrSpaces(errMessage)) {
msg = new CompilerMessage("", cause != null ? cause : e);
}
else {
final String causeMessage = cause != null ? cause.getMessage() : "";
msg = new CompilerMessage("", BuildMessage.Kind.ERROR, StringUtil.isEmptyOrSpaces(causeMessage) || errMessage.trim().endsWith(causeMessage)
? errMessage
: errMessage + ": " + causeMessage);
}
myMessageDispatcher.processMessage(msg);
}
}
finally {
Tracer.Span finishingCompilationSpan = Tracer.start("finishing compilation");
memWatcher.stop();
flushContext(context);
// wait for async tasks
final CanceledStatus status = context == null ? CanceledStatus.NULL : context.getCancelStatus();
synchronized (myAsyncTasks) {
for (Future<?> task : myAsyncTasks) {
if (status.isCanceled()) {
break;
}
waitForTask(status, task);
}
}
finishingCompilationSpan.complete();
}
}
private void checkRebuildRequired(final CompileScope scope) throws RebuildRequestedException {
if (myIsTestMode || isAutoBuild()) {
// do not use the heuristic in tests in order to properly test all cases
// automatic builds should not cause start full project rebuilds to avoid situations when rebuild is not expected by user
if (LOG.isDebugEnabled()) {
LOG.debug("Rebuild heuristic: skipping the check; isTestMode = " + myIsTestMode + "; isAutoBuild = " + isAutoBuild());
}
return;
}
final BuildTargetsState targetsState = myProjectDescriptor.getTargetsState();
final long timeThreshold = targetsState.getLastSuccessfulRebuildDuration() * 95 / 100; // 95% of last registered clean rebuild time
if (timeThreshold <= 0) {
if (LOG.isDebugEnabled()) {
LOG.debug("Rebuild heuristic: no stats available");
}
return;
}
// check that this is a whole-project incremental build
// checking only JavaModuleBuildTargetType because these target types directly correspond to project modules
for (BuildTargetType<?> type : JavaModuleBuildTargetType.ALL_TYPES) {
if (!scope.isBuildIncrementally(type)) {
if (LOG.isDebugEnabled()) {
LOG.debug("Rebuild heuristic: skipping the check because rebuild is forced for targets of type " + type.getTypeId());
}
return;
}
if (!scope.isAllTargetsOfTypeAffected(type)) {
if (LOG.isDebugEnabled()) {
LOG.debug("Rebuild heuristic: skipping the check because some targets are excluded from compilation scope, e.g. targets of type " + type.getTypeId());
}
return;
}
}
// compute estimated times for dirty targets
final long estimatedWorkTime = calculateEstimatedBuildTime(myProjectDescriptor, new Predicate<>() {
private final Set<BuildTargetType<?>> allTargetsAffected = new HashSet<>(JavaModuleBuildTargetType.ALL_TYPES);
@Override
public boolean test(BuildTarget<?> target) {
// optimization, since we know here that all targets of types JavaModuleBuildTargetType are affected
return allTargetsAffected.contains(target.getTargetType()) || scope.isAffected(target);
}
});
if (LOG.isDebugEnabled()) {
LOG.debug("Rebuild heuristic: estimated build time / timeThreshold : " + estimatedWorkTime + " / " + timeThreshold);
}
if (estimatedWorkTime >= timeThreshold) {
final String message = JpsBuildBundle.message("build.message.too.many.modules.require.recompilation.forcing.full.project.rebuild");
LOG.info(message);
LOG.info("Estimated build duration (linear): " + StringUtil.formatDuration(estimatedWorkTime));
LOG.info("Last successful rebuild duration (linear): " + StringUtil.formatDuration(targetsState.getLastSuccessfulRebuildDuration()));
LOG.info("Rebuild heuristic time threshold: " + StringUtil.formatDuration(timeThreshold));
myMessageDispatcher.processMessage(new CompilerMessage("", BuildMessage.Kind.INFO, message));
throw new RebuildRequestedException(null);
}
}
public static long calculateEstimatedBuildTime(@NotNull ProjectDescriptor projectDescriptor, @NotNull Predicate<BuildTarget<?>> isAffected) {
final BuildTargetsState targetsState = projectDescriptor.getTargetsState();
// compute estimated times for dirty targets
long estimatedBuildTime = 0L;
final BuildTargetIndex targetIndex = projectDescriptor.getBuildTargetIndex();
int affectedTargets = 0;
for (BuildTarget<?> target : targetIndex.getAllTargets()) {
if (!targetIndex.isDummy(target)) {
final long avgTimeToBuild = targetsState.getAverageBuildTime(target.getTargetType());
if (avgTimeToBuild > 0) {
// 1. in general case this time should include dependency analysis and cache update times
// 2. need to check isAffected() since some targets (like artifacts) may be unaffected even for rebuild
if (targetsState.getTargetConfiguration(target).isTargetDirty(projectDescriptor) && isAffected.test(target)) {
estimatedBuildTime += avgTimeToBuild;
affectedTargets++;
}
}
}
}
LOG.info("Affected build targets count: " + affectedTargets);
return estimatedBuildTime;
}
private void requestRebuild(Exception e, Throwable cause) throws RebuildRequestedException {
myMessageDispatcher.processMessage(new CompilerMessage(
"", BuildMessage.Kind.INFO, JpsBuildBundle.message("build.message.internal.caches.are.corrupted", e.getMessage()))
);
throw new RebuildRequestedException(cause);
}
private static void waitForTask(@NotNull CanceledStatus status, Future<?> task) {
try {
while (true) {
try {
task.get(500L, TimeUnit.MILLISECONDS);
break;
}
catch (TimeoutException ignored) {
if (status.isCanceled()) {
break;
}
}
}
}
catch (Throwable th) {
LOG.info(th);
}
}
private static void reportRebuiltModules(CompileContextImpl context) {
final Set<JpsModule> modules = BuildTargetConfiguration.MODULES_WITH_TARGET_CONFIG_CHANGED_KEY.get(context);
if (modules == null || modules.isEmpty()) {
return;
}
int shown = modules.size() == 6 ? 6 : Math.min(5, modules.size());
String modulesText = modules.stream().limit(shown).map(m -> "'" + m.getName() + "'").collect(Collectors.joining(", "));
String text = JpsBuildBundle.message("build.messages.modules.were.fully.rebuilt", modulesText, modules.size(),
modules.size() - shown, ModuleBuildTarget.REBUILD_ON_DEPENDENCY_CHANGE ? 1 : 0);
context.processMessage(new CompilerMessage("", BuildMessage.Kind.INFO, text));
}
private static void reportUnprocessedChanges(CompileContextImpl context) {
final ProjectDescriptor pd = context.getProjectDescriptor();
final BuildFSState fsState = pd.fsState;
for (BuildTarget<?> target : pd.getBuildTargetIndex().getAllTargets()) {
if (fsState.hasUnprocessedChanges(context, target)) {
context.processMessage(new UnprocessedFSChangesNotification());
break;
}
}
}
private static void flushContext(CompileContext context) {
if (context != null) {
final ProjectDescriptor pd = context.getProjectDescriptor();
pd.getProjectStamps().getStampStorage().force();
pd.dataManager.flush(false);
}
final ExternalJavacManager server = ExternalJavacManager.KEY.get(context);
if (server != null) {
server.stop();
ExternalJavacManager.KEY.set(context, null);
}
}
private boolean isAutoBuild() {
return Boolean.parseBoolean(myBuilderParams.get(BuildParametersKeys.IS_AUTOMAKE));
}
private boolean isParallelBuild() {
return isAutoBuild() ? BuildRunner.isParallelBuildAutomakeEnabled() : BuildRunner.isParallelBuildEnabled();
}
private void runBuild(final CompileContextImpl context, boolean forceCleanCaches) throws ProjectBuildException {
context.setDone(0.0f);
LOG.info("Building project; isRebuild:" +
context.isProjectRebuild() +
"; isMake:" +
context.isMake() +
" parallel compilation:" +
isParallelBuild() +
"; dependency graph enabled:" +
isDepGraphEnabled());
context.addBuildListener(new ChainedTargetsBuildListener(context));
// deletes class loader classpath index files for changed output roots
context.addBuildListener(new BuildListener() {
@Override
public void filesGenerated(@NotNull FileGeneratedEvent event) {
Collection<Pair<String, String>> paths = event.getPaths();
FileSystem fs = FileSystems.getDefault();
if (paths.size() == 1) {
deleteFiles(paths.iterator().next().first, fs);
return;
}
Set<String> outputs = new HashSet<>();
for (Pair<String, String> pair : paths) {
String root = pair.getFirst();
if (outputs.add(root)) {
deleteFiles(root, fs);
}
}
}
private void deleteFiles(String rootPath, FileSystem fs) {
Path root = fs.getPath(rootPath);
try {
Files.deleteIfExists(root.resolve(CLASSPATH_INDEX_FILE_NAME));
Files.deleteIfExists(root.resolve(UNMODIFIED_MARK_FILE_NAME));
}
catch (IOException ignore) {
}
}
});
Tracer.Span allTargetBuilderBuildStartedSpan = Tracer.start("All TargetBuilder.buildStarted");
for (TargetBuilder<?, ?> builder : myBuilderRegistry.getTargetBuilders()) {
builder.buildStarted(context);
}
allTargetBuilderBuildStartedSpan.complete();
Tracer.Span allModuleLevelBuildersBuildStartedSpan = Tracer.start("All ModuleLevelBuilder.buildStarted");
for (ModuleLevelBuilder builder : myBuilderRegistry.getModuleLevelBuilders()) {
builder.buildStarted(context);
}
allModuleLevelBuildersBuildStartedSpan.complete();
BuildProgress buildProgress = null;
try {
buildProgress = new BuildProgress(myProjectDescriptor.dataManager, myProjectDescriptor.getBuildTargetIndex(),
myProjectDescriptor.getBuildTargetIndex().getSortedTargetChunks(context),
chunk -> isAffected(context.getScope(), chunk));
// clean roots for targets for which rebuild is forced
Tracer.Span cleanOutputSourcesSpan = Tracer.start("Clean output sources");
cleanOutputRoots(context, context.isProjectRebuild() || forceCleanCaches);
cleanOutputSourcesSpan.complete();
Tracer.Span beforeTasksSpan = Tracer.start("'before' tasks");
context.processMessage(new ProgressMessage(JpsBuildBundle.message("progress.message.running.before.tasks")));
runTasks(context, myBuilderRegistry.getBeforeTasks());
TimingLog.LOG.debug("'before' tasks finished");
beforeTasksSpan.complete();
Tracer.Span checkingSourcesSpan = Tracer.start("Building targets");
context.processMessage(new ProgressMessage(JpsBuildBundle.message("progress.message.checking.sources")));
buildChunks(context, buildProgress);
TimingLog.LOG.debug("Building targets finished");
checkingSourcesSpan.complete();
Tracer.Span afterTasksSpan = Tracer.start("'after' span");
context.processMessage(new ProgressMessage(JpsBuildBundle.message("progress.message.running.after.tasks")));
runTasks(context, myBuilderRegistry.getAfterTasks());
TimingLog.LOG.debug("'after' tasks finished");
sendElapsedTimeMessages(context);
afterTasksSpan.complete();
}
finally {
if (buildProgress != null) {
buildProgress.updateExpectedAverageTime();
if (context.isProjectRebuild() && !Utils.errorsDetected(context) && !context.getCancelStatus().isCanceled()) {
myProjectDescriptor.getTargetsState().setLastSuccessfulRebuildDuration(buildProgress.getAbsoluteBuildTime());
}
}
for (TargetBuilder<?, ?> builder : myBuilderRegistry.getTargetBuilders()) {
builder.buildFinished(context);
}
for (ModuleLevelBuilder builder : myBuilderRegistry.getModuleLevelBuilders()) {
builder.buildFinished(context);
}
context.processMessage(new ProgressMessage(JpsBuildBundle.message("progress.message.finished.saving.caches")));
}
}
private void sendElapsedTimeMessages(CompileContext context) {
myElapsedTimeNanosByBuilder.entrySet()
.stream()
.map(entry -> {
AtomicInteger processedSourcesRef = myNumberOfSourcesProcessedByBuilder.get(entry.getKey());
int processedSources = processedSourcesRef != null ? processedSourcesRef.get() : 0;
return new BuilderStatisticsMessage(entry.getKey().getPresentableName(), processedSources, entry.getValue().get()/1_000_000);
})
.sorted(Comparator.comparing(BuilderStatisticsMessage::getBuilderName))
.forEach(context::processMessage);
}
static @Nullable Future<Void> startTempDirectoryCleanupTask(final ProjectDescriptor pd) {
final String tempPath = System.getProperty("java.io.tmpdir", null);
if (StringUtil.isEmptyOrSpaces(tempPath)) {
return null;
}
final File tempDir = new File(tempPath);
final File dataRoot = pd.dataManager.getDataPaths().getDataStorageRoot();
if (!FileUtil.isAncestor(dataRoot, tempDir, true)) {
// cleanup only 'local' temp
return null;
}
final File[] files = tempDir.listFiles();
if (files == null) {
tempDir.mkdirs(); // ensure the directory exists
}
else if (files.length > 0) {
final RunnableFuture<Void> task = new FutureTask<>(() -> {
for (File tempFile : files) {
FileUtil.delete(tempFile);
}
}, null);
final Thread thread = new Thread(task, "Temp directory cleanup");
thread.setPriority(Thread.MIN_PRIORITY);
thread.setDaemon(true);
thread.start();
return task;
}
return null;
}
private CompileContextImpl createContext(@NotNull CompileScope scope) {
return new CompileContextImpl(scope, myProjectDescriptor, myMessageDispatcher, myBuilderParams, myCancelStatus);
}
private void cleanOutputRoots(CompileContext context, boolean cleanCaches) throws ProjectBuildException {
final ProjectDescriptor projectDescriptor = context.getProjectDescriptor();
ProjectBuildException ex = null;
final ExecutorService cleanupExecutor = AppExecutorUtil.createBoundedApplicationPoolExecutor("IncProjectBuilder Output Cleanup Pool", SharedThreadPool.getInstance(), MAX_BUILDER_THREADS);
final List<Future<?>> cleanupTasks = new ArrayList<>();
final long cleanStart = System.nanoTime();
try {
final JpsJavaCompilerConfiguration configuration = JpsJavaExtensionService.getInstance().getCompilerConfiguration(projectDescriptor.getProject());
if (configuration.isClearOutputDirectoryOnRebuild()) {
clearOutputs(context, cleanupExecutor, cleanupTasks);
}
else {
for (BuildTarget<?> target : projectDescriptor.getBuildTargetIndex().getAllTargets()) {
context.checkCanceled();
if (context.getScope().isBuildForced(target)) {
if (SYNC_DELETE) {
clearOutputFilesUninterruptibly(context, target);
}
else {
cleanupTasks.add(cleanupExecutor.submit(() -> clearOutputFilesUninterruptibly(context, target)));
}
}
}
}
for (BuildTargetType<?> type : TargetTypeRegistry.getInstance().getTargetTypes()) {
if (context.getScope().isAllTargetsOfTypeAffected(type)) {
cleanOutputOfStaleTargets(type, context);
}
}
}
catch (ProjectBuildException e) {
ex = e;
}
finally {
for (Future<?> task : cleanupTasks) {
try {
task.get();
}
catch (Throwable e) {
LOG.info(e);
}
}
LOG.info("Cleaned output directories in " + TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - cleanStart) + " ms");
if (cleanCaches) {
try {
projectDescriptor.getProjectStamps().getStampStorage().clean();
}
catch (IOException e) {
if (ex == null) {
ex = new ProjectBuildException(JpsBuildBundle.message("build.message.error.cleaning.timestamps.storage"), e);
}
else {
LOG.info("Error cleaning timestamps storage", e);
}
}
finally {
try {
projectDescriptor.dataManager.clean(myAsyncTasks::add);
}
catch (IOException e) {
if (ex == null) {
ex = new ProjectBuildException(JpsBuildBundle.message("build.message.error.cleaning.compiler.storages"), e);
}
else {
LOG.info("Error cleaning compiler storages", e);
}
}
finally {
projectDescriptor.fsState.clearAll();
if (ex != null) {
throw ex;
}
}
}
}
else {
final BuildTargetsState targetsState = projectDescriptor.getTargetsState();
for (BuildTarget<?> target : getTargetsWithClearedOutput(context)) {
// This will ensure the target will be fully rebuilt either in this or in the future build session.
// if this build fails or is cancelled, all such targets will still be marked as needing recompilation
targetsState.getTargetConfiguration(target).invalidate();
}
}
}
}
private void cleanOutputOfStaleTargets(BuildTargetType<?> type, CompileContext context) {
List<Pair<String, Integer>> targetIds = myProjectDescriptor.dataManager.getTargetsState().getStaleTargetIds(type);
if (targetIds.isEmpty()) return;
context.processMessage(new ProgressMessage(JpsBuildBundle.message("progress.message.cleaning.old.output.directories")));
for (Pair<String, Integer> ids : targetIds) {
String stringId = ids.first;
try {
SourceToOutputMappingImpl mapping = null;
try {
mapping = myProjectDescriptor.dataManager.createSourceToOutputMapForStaleTarget(type, stringId);
clearOutputFiles(context, mapping, type, ids.second);
}
finally {
if (mapping != null) {
mapping.close();
}
}
FileUtil.delete(myProjectDescriptor.dataManager.getDataPaths().getTargetDataRoot(type, stringId));
myProjectDescriptor.dataManager.getTargetsState().cleanStaleTarget(type, stringId);
}
catch (IOException e) {
LOG.warn(e);
myMessageDispatcher.processMessage(new CompilerMessage("", BuildMessage.Kind.WARNING,
JpsBuildBundle.message("build.message.failed.to.delete.output.files.from.obsolete.0.target.1",
stringId, e.toString())));
}
}
}
public static void clearOutputFiles(CompileContext context, BuildTarget<?> target) throws IOException {
final SourceToOutputMapping map = context.getProjectDescriptor().dataManager.getSourceToOutputMap(target);
BuildTargetType<?> targetType = target.getTargetType();
clearOutputFiles(context, map, targetType, context.getProjectDescriptor().dataManager.getTargetsState().getBuildTargetId(target));
registerTargetsWithClearedOutput(context, Collections.singletonList(target));
}
private static void clearOutputFiles(CompileContext context,
SourceToOutputMapping mapping,
BuildTargetType<?> targetType,
int targetId) throws IOException {
Set<File> dirsToDelete = targetType instanceof ModuleBasedBuildTargetType<?> ? FileCollectionFactory.createCanonicalFileSet() : null;
OutputToTargetRegistry outputToTargetRegistry = context.getProjectDescriptor().dataManager.getOutputToTargetRegistry();
for (String srcPath : mapping.getSources()) {
final Collection<String> outs = mapping.getOutputs(srcPath);
if (outs != null && !outs.isEmpty()) {
List<String> deletedPaths = new ArrayList<>();
for (String out : outs) {
BuildOperations.deleteRecursively(out, deletedPaths, dirsToDelete);
}
outputToTargetRegistry.removeMapping(outs, targetId);
if (!deletedPaths.isEmpty()) {
context.processMessage(new FileDeletedEvent(deletedPaths));
}
}
}
if (dirsToDelete != null) {
FSOperations.pruneEmptyDirs(context, dirsToDelete);
}
}
private static void registerTargetsWithClearedOutput(CompileContext context, Collection<? extends BuildTarget<?>> targets) {
synchronized (TARGET_WITH_CLEARED_OUTPUT) {
Set<BuildTarget<?>> data = context.getUserData(TARGET_WITH_CLEARED_OUTPUT);
if (data == null) {
data = new HashSet<>();
context.putUserData(TARGET_WITH_CLEARED_OUTPUT, data);
}
data.addAll(targets);
}
}
private static boolean isTargetOutputCleared(CompileContext context, BuildTarget<?> target) {
synchronized (TARGET_WITH_CLEARED_OUTPUT) {
Set<BuildTarget<?>> data = context.getUserData(TARGET_WITH_CLEARED_OUTPUT);
return data != null && data.contains(target);
}
}
private static Set<BuildTarget<?>> getTargetsWithClearedOutput(CompileContext context) {
synchronized (TARGET_WITH_CLEARED_OUTPUT) {
Set<BuildTarget<?>> data = context.getUserData(TARGET_WITH_CLEARED_OUTPUT);
return data != null ? Set.copyOf(data) : Collections.emptySet();
}
}
private enum Applicability {
NONE, PARTIAL, ALL;
static <T> Applicability calculate(Predicate<? super T> p, Collection<? extends T> collection) {
int count = 0;
int item = 0;
for (T elem : collection) {
item++;
if (p.test(elem)) {
count++;
if (item > count) {
return PARTIAL;
}
}
else {
if (count > 0) {
return PARTIAL;
}
}
}
return count == 0? NONE : ALL;
}
}
private void clearOutputs(CompileContext context, final ExecutorService cleanupExecutor, final List<Future<?>> cleanupTasks) throws ProjectBuildException {
final MultiMap<File, BuildTarget<?>> rootsToDelete = MultiMap.createSet();
final Set<File> allSourceRoots = FileCollectionFactory.createCanonicalFileSet();
final ProjectDescriptor projectDescriptor = context.getProjectDescriptor();
final List<? extends BuildTarget<?>> allTargets = projectDescriptor.getBuildTargetIndex().getAllTargets();
for (BuildTarget<?> target : allTargets) {
if (target instanceof ModuleBasedTarget) {
for (File file : target.getOutputRoots(context)) {
rootsToDelete.putValue(file, target);
}
}
else {
if (context.getScope().isBuildForced(target)) {
if (SYNC_DELETE) {
clearOutputFilesUninterruptibly(context, target);
}
else {
cleanupTasks.add(cleanupExecutor.submit(() -> clearOutputFilesUninterruptibly(context, target)));
}
}
}
}
final ModuleExcludeIndex moduleIndex = projectDescriptor.getModuleExcludeIndex();
for (BuildTarget<?> target : allTargets) {
for (BuildRootDescriptor descriptor : projectDescriptor.getBuildRootIndex().getTargetRoots(target, context)) {
// excluding from checks roots with generated sources; because it is safe to delete generated stuff
if (!descriptor.isGenerated()) {
File rootFile = descriptor.getRootFile();
//some roots aren't marked by as generated but in fact they are produced by some builder, and it's safe to remove them.
//However, if a root isn't excluded it means that its content will be shown in 'Project View' and a user can create new files under it,
//so it would be dangerous to clean such roots
if (moduleIndex.isInContent(rootFile)) {
allSourceRoots.add(rootFile);
}
}
}
}
// check that output and source roots are not overlapping
final CompileScope compileScope = context.getScope();
final List<File> filesToDelete = new ArrayList<>();
final Predicate<BuildTarget<?>> forcedBuild = input -> compileScope.isBuildForced(input);
for (Map.Entry<File, Collection<BuildTarget<?>>> entry : rootsToDelete.entrySet()) {
context.checkCanceled();
final File outputRoot = entry.getKey();
final Collection<BuildTarget<?>> rootTargets = entry.getValue();
final Applicability applicability = Applicability.calculate(forcedBuild, rootTargets);
if (applicability == Applicability.NONE) {
continue;
}
// It makes no sense to delete already empty root, but instead it makes sense to cleanup the target, because there may exist
// a directory that has been previously the output root for the target
boolean okToDelete = applicability == Applicability.ALL && !isEmpty(outputRoot);
if (okToDelete && !moduleIndex.isExcluded(outputRoot)) {
// if output root itself is directly or indirectly excluded,
// there cannot be any manageable sources under it, even if the output root is located under some source root
// so in this case it is safe to delete such root
if (JpsPathUtil.isUnder(allSourceRoots, outputRoot)) {
okToDelete = false;
}
else {
final Set<File> _outRoot = FileCollectionFactory.createCanonicalFileSet(Collections.singletonList(outputRoot));
for (File srcRoot : allSourceRoots) {
if (JpsPathUtil.isUnder(_outRoot, srcRoot)) {
okToDelete = false;
break;
}
}
}
if (!okToDelete) {
context.processMessage(new CompilerMessage(
"", BuildMessage.Kind.WARNING,
JpsBuildBundle.message("build.message.output.path.0.intersects.with.a.source.root", outputRoot.getPath()))
);
}
}
if (okToDelete) {
// do not delete output root itself to avoid lots of unnecessary "roots_changed" events in IDEA
final File[] children = outputRoot.listFiles();
if (children != null) {
for (File child : children) {
if (!child.delete()) {
filesToDelete.add(child);
}
}
}
else { // the output root must be file
if (!outputRoot.delete()) {
filesToDelete.add(outputRoot);
}
}
registerTargetsWithClearedOutput(context, rootTargets);
}
else {
context.processMessage(new ProgressMessage(JpsBuildBundle.message("progress.message.cleaning.output.directories")));
// clean only those files we are aware of
for (BuildTarget<?> target : rootTargets) {
if (compileScope.isBuildForced(target)) {
if (SYNC_DELETE) {
clearOutputFilesUninterruptibly(context, target);
}
else {
cleanupTasks.add(cleanupExecutor.submit(() -> clearOutputFilesUninterruptibly(context, target)));
}
}
}
}
}
if (!filesToDelete.isEmpty()) {
context.processMessage(new ProgressMessage(JpsBuildBundle.message("progress.message.cleaning.output.directories")));
if (SYNC_DELETE) {
for (File file : filesToDelete) {
context.checkCanceled();
FileUtil.delete(file);
}
}
else {
myAsyncTasks.add(FileUtil.asyncDelete(filesToDelete));
}
}
}
private static boolean isEmpty(File outputRoot) {
final String[] files = outputRoot.list();
return files == null || files.length == 0;
}
private static void clearOutputFilesUninterruptibly(CompileContext context, BuildTarget<?> target) {
try {
clearOutputFiles(context, target);
}
catch (Throwable e) {
LOG.info(e);
String reason = e.getMessage();
if (reason == null) {
reason = e.getClass().getName();
}
context.processMessage(new CompilerMessage("", BuildMessage.Kind.WARNING, JpsBuildBundle
.message("build.message.problems.clearing.output.files.for.target.0.1", target.getPresentableName(), reason)));
}
}
private static void runTasks(CompileContext context, final List<? extends BuildTask> tasks) throws ProjectBuildException {
for (BuildTask task : tasks) {
task.build(context);
}
}
private void buildChunks(final CompileContextImpl context, BuildProgress buildProgress) throws ProjectBuildException {
try {
boolean compileInParallel = isParallelBuild();
if (compileInParallel && MAX_BUILDER_THREADS <= 1) {
LOG.info("Switched off parallel compilation because maximum number of builder threads is less than 2. Set '"
+ GlobalOptions.COMPILE_PARALLEL_MAX_THREADS_OPTION + "' system property to a value greater than 1 to really enable parallel compilation.");
compileInParallel = false;
}
Tracer.Span buildSpan = Tracer.start(compileInParallel ? "Parallel build" : "Non-parallel build");
if (compileInParallel) {
new BuildParallelizer(context, buildProgress).buildInParallel();
}
else {
// non-parallel build
final ProjectDescriptor pd = context.getProjectDescriptor();
final Runnable flushCommand = Utils.asCountedRunnable(FLUSH_INVOCATIONS_TO_SKIP, () -> pd.dataManager.flush(true));
for (BuildTargetChunk chunk : pd.getBuildTargetIndex().getSortedTargetChunks(context)) {
try {
buildChunkIfAffected(context, context.getScope(), chunk, buildProgress);
}
finally {
pd.dataManager.closeSourceToOutputStorages(Collections.singleton(chunk));
flushCommand.run();
}
}
}
buildSpan.complete();
}
catch (IOException e) {
throw new ProjectBuildException(e);
}
}
private static final class BuildChunkTask {
private final BuildTargetChunk myChunk;
private final AtomicInteger myNotBuildDependenciesCount = new AtomicInteger(0);
private final Set<BuildChunkTask> myNotBuiltDependencies = new HashSet<>();
private final List<BuildChunkTask> myTasksDependsOnThis = new ArrayList<>();
private int mySelfScore = 0;
private int myDepsScore = 0;
private int myIndex = 0;
private BuildChunkTask(BuildTargetChunk chunk) {
myChunk = chunk;
}
private int getScore() {
return myDepsScore + mySelfScore;
}