-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
ExtensionDescriptorMojo.java
1266 lines (1138 loc) · 54 KB
/
ExtensionDescriptorMojo.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
package io.quarkus.maven;
import com.fasterxml.jackson.core.json.JsonReadFeature;
import com.fasterxml.jackson.core.util.DefaultIndenter;
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import io.quarkus.bootstrap.BootstrapConstants;
import io.quarkus.bootstrap.model.AppArtifactCoords;
import io.quarkus.bootstrap.model.AppArtifactKey;
import io.quarkus.bootstrap.model.ApplicationModelBuilder;
import io.quarkus.bootstrap.resolver.maven.BootstrapMavenContext;
import io.quarkus.bootstrap.resolver.maven.BootstrapMavenException;
import io.quarkus.bootstrap.resolver.maven.MavenArtifactResolver;
import io.quarkus.bootstrap.resolver.maven.workspace.LocalProject;
import io.quarkus.bootstrap.resolver.maven.workspace.LocalWorkspace;
import io.quarkus.bootstrap.util.DependencyNodeUtils;
import io.quarkus.fs.util.ZipUtils;
import io.quarkus.maven.capabilities.CapabilitiesConfig;
import io.quarkus.maven.capabilities.CapabilityConfig;
import io.quarkus.maven.dependency.ArtifactCoords;
import io.quarkus.maven.dependency.ArtifactKey;
import io.quarkus.maven.dependency.GACTV;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.maven.project.MavenProject;
import org.eclipse.aether.DefaultRepositorySystemSession;
import org.eclipse.aether.RepositorySystem;
import org.eclipse.aether.RepositorySystemSession;
import org.eclipse.aether.artifact.DefaultArtifact;
import org.eclipse.aether.collection.CollectRequest;
import org.eclipse.aether.collection.CollectResult;
import org.eclipse.aether.graph.Dependency;
import org.eclipse.aether.graph.DependencyNode;
import org.eclipse.aether.graph.DependencyVisitor;
import org.eclipse.aether.impl.RemoteRepositoryManager;
import org.eclipse.aether.repository.RemoteRepository;
import org.eclipse.aether.resolution.ArtifactDescriptorException;
import org.eclipse.aether.resolution.ArtifactDescriptorRequest;
import org.eclipse.aether.resolution.ArtifactDescriptorResult;
import org.eclipse.aether.resolution.DependencyRequest;
import org.eclipse.aether.resolution.DependencyResult;
import org.eclipse.aether.util.artifact.JavaScopes;
/**
* Generates Quarkus extension descriptor for the runtime artifact.
* <p>
* <p/>
* Also generates META-INF/quarkus-extension.json which includes properties of
* the extension such as name, labels, maven coordinates, etc that are used by
* the tools.
*
* @author Alexey Loubyansky
*/
@Mojo(name = "extension-descriptor", defaultPhase = LifecyclePhase.PROCESS_RESOURCES, requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME, threadSafe = true)
public class ExtensionDescriptorMojo extends AbstractMojo {
public static class RemovedResources {
String key;
String resources;
}
private static final String GROUP_ID = "group-id";
private static final String ARTIFACT_ID = "artifact-id";
private static final String METADATA = "metadata";
/**
* The entry point to Aether, i.e. the component doing all the work.
*
* @component
*/
@Component
private RepositorySystem repoSystem;
@Component
RemoteRepositoryManager remoteRepoManager;
@Component
BootstrapWorkspaceProvider workspaceProvider;
@Parameter(defaultValue = "${session}", readonly = true)
MavenSession session;
/**
* The current repository/network configuration of Maven.
*
* @parameter default-value="${repositorySystemSession}"
* @readonly
*/
@Parameter(defaultValue = "${repositorySystemSession}", readonly = true)
private RepositorySystemSession repoSession;
/**
* The project's remote repositories to use for the resolution of artifacts and
* their dependencies.
*
* @parameter default-value="${project.remoteProjectRepositories}"
* @readonly
*/
@Parameter(defaultValue = "${project.remoteProjectRepositories}", readonly = true, required = true)
private List<RemoteRepository> repos;
/**
* The directory for compiled classes.
*/
@Parameter(readonly = true, required = true, defaultValue = "${project.build.outputDirectory}")
private File outputDirectory;
/**
* Coordinates of the corresponding deployment artifact.
*/
@Parameter(required = true, defaultValue = "${project.groupId}:${project.artifactId}-deployment:${project.version}")
private String deployment;
/**
* Provided and required <a href="https://quarkus.io/guides/capabilities">extension capabilities</a>.
*/
@Parameter(required = false)
CapabilitiesConfig capabilities = new CapabilitiesConfig();
/**
* Extension metadata template file
*/
@Parameter(required = true, defaultValue = "${project.build.outputDirectory}/META-INF/quarkus-extension.yaml")
private File extensionFile;
@Parameter(defaultValue = "${project}")
protected MavenProject project;
/**
* Artifacts that should never end up in the final build. Usually this should only be set if we know
* this extension provides a newer version of a given artifact that is under a different GAV. E.g. this
* can be used to make sure that the legacy javax API's are not included if an extension is using the new
* Jakarta version.
*/
@Parameter
List<String> excludedArtifacts;
/**
* Resources that should excluded from the classloader and the packaged application.
* It is an equivalent of {@code quarkus.class-loading.removed-resources} from {@code application.properties}
* but in the `META-INF/quarkus-extension.properties`.
*/
@Parameter
List<RemovedResources> removedResources = List.of();
/**
* Artifacts that are always loaded parent first when running in dev or test mode. This is an advanced option
* and should only be used if you are sure that this is the correct solution for the use case.
* <p>
* A possible example of this would be logging libraries, as these need to be loaded by the system class loader.
*/
@Parameter
List<String> parentFirstArtifacts;
/**
* Artifacts that are always loaded parent when the fast-jar is used. This is an advanced option
* and should only be used if you are sure that this is the correct solution for the use case.
* <p>
* A possible example of this would be logging libraries, as these need to be loaded by the system class loader.
*/
@Parameter
List<String> runnerParentFirstArtifacts;
/**
* Artifacts that will only be used to load a class or resource if no other normal element exists.
* This is an advanced option that should only be used when there is a case of multiple jars
* containing the same classes and we need to control which jars is actually used to load the classes.
*/
@Parameter
List<String> lesserPriorityArtifacts;
/**
* Whether to skip validation of extension's runtime and deployment dependencies.
*/
@Parameter(required = false, defaultValue = "${skipExtensionValidation}")
private boolean skipExtensionValidation;
/**
* Whether to ignore failure detecting the Quarkus core version used to build the extension,
* which would be recorded in the extension's metadata.
*/
@Parameter(required = false, defaultValue = "${ignoreNotDetectedQuarkusCoreVersion")
boolean ignoreNotDetectedQuarkusCoreVersion;
/**
* <a href="https://quarkus.io/guides/conditional-extension-dependencies">Conditional dependencies</a> that should be
* enabled in case certain classpath conditions have been satisfied.
*/
@Parameter
private List<String> conditionalDependencies = new ArrayList<>(0);
/**
* <a href="https://quarkus.io/guides/conditional-extension-dependencies">Extension dependency condition</a> that should be
* satisfied for this extension to be enabled
* in case it is added as a conditional dependency of another extension.
*/
@Parameter
private List<String> dependencyCondition = new ArrayList<>(0);
/**
* Whether to skip validation of the codestart artifact, in case its configured
*/
@Parameter(property = "skipCodestartValidation")
boolean skipCodestartValidation;
AppArtifactCoords deploymentCoords;
CollectResult collectedDeploymentDeps;
DependencyResult runtimeDeps;
MavenArtifactResolver resolver;
@Override
public void execute() throws MojoExecutionException {
if (!skipExtensionValidation) {
validateExtensionDeps();
}
if (conditionalDependencies.isEmpty()) {
// if conditional dependencies haven't been configured
// we check whether there are direct optional dependencies on extensions
// that are configured with a dependency condition
// such dependencies will be registered as conditional
StringBuilder buf = null;
for (org.apache.maven.model.Dependency d : project.getDependencies()) {
if (!d.isOptional()) {
continue;
}
if (!d.getScope().isEmpty()
&& !(d.getScope().equals(JavaScopes.COMPILE) || d.getScope().equals(JavaScopes.RUNTIME))) {
continue;
}
final Properties props = getExtensionDescriptor(
new DefaultArtifact(d.getGroupId(), d.getArtifactId(), d.getClassifier(), d.getType(), d.getVersion()),
false);
if (props == null || !props.containsKey(BootstrapConstants.DEPENDENCY_CONDITION)) {
continue;
}
if (buf == null) {
buf = new StringBuilder();
} else {
buf.setLength(0);
}
buf.append(d.getGroupId()).append(':').append(d.getArtifactId()).append(':');
if (d.getClassifier() != null) {
buf.append(d.getClassifier());
}
buf.append(':').append(d.getType()).append(':').append(d.getVersion());
conditionalDependencies.add(buf.toString());
}
}
final Properties props = new Properties();
props.setProperty(BootstrapConstants.PROP_DEPLOYMENT_ARTIFACT, deployment);
if (!conditionalDependencies.isEmpty()) {
final StringBuilder buf = new StringBuilder();
int i = 0;
buf.append(AppArtifactCoords.fromString(conditionalDependencies.get(i++)).toString());
while (i < conditionalDependencies.size()) {
buf.append(' ').append(AppArtifactCoords.fromString(conditionalDependencies.get(i++)).toString());
}
props.setProperty(BootstrapConstants.CONDITIONAL_DEPENDENCIES, buf.toString());
}
if (!dependencyCondition.isEmpty()) {
final StringBuilder buf = new StringBuilder();
int i = 0;
buf.append(AppArtifactKey.fromString(dependencyCondition.get(i++)).toGacString());
while (i < dependencyCondition.size()) {
buf.append(' ').append(AppArtifactKey.fromString(dependencyCondition.get(i++)).toGacString());
}
props.setProperty(BootstrapConstants.DEPENDENCY_CONDITION, buf.toString());
}
if (!capabilities.getProvides().isEmpty()) {
final StringBuilder buf = new StringBuilder();
final Iterator<CapabilityConfig> i = capabilities.getProvides().iterator();
appendCapability(i.next(), buf);
while (i.hasNext()) {
appendCapability(i.next(), buf.append(','));
}
props.setProperty(BootstrapConstants.PROP_PROVIDES_CAPABILITIES, buf.toString());
}
if (!capabilities.getRequires().isEmpty()) {
final StringBuilder buf = new StringBuilder();
final Iterator<CapabilityConfig> i = capabilities.getRequires().iterator();
appendCapability(i.next(), buf);
while (i.hasNext()) {
appendCapability(i.next(), buf.append(','));
}
props.setProperty(BootstrapConstants.PROP_REQUIRES_CAPABILITIES, buf.toString());
}
if (parentFirstArtifacts != null && !parentFirstArtifacts.isEmpty()) {
String val = String.join(",", parentFirstArtifacts);
props.put(ApplicationModelBuilder.PARENT_FIRST_ARTIFACTS, val);
}
if (runnerParentFirstArtifacts != null && !runnerParentFirstArtifacts.isEmpty()) {
String val = String.join(",", runnerParentFirstArtifacts);
props.put(ApplicationModelBuilder.RUNNER_PARENT_FIRST_ARTIFACTS, val);
}
if (excludedArtifacts != null && !excludedArtifacts.isEmpty()) {
String val = String.join(",", excludedArtifacts);
props.put(ApplicationModelBuilder.EXCLUDED_ARTIFACTS, val);
}
if (!removedResources.isEmpty()) {
for (RemovedResources entry : removedResources) {
final ArtifactKey key;
try {
key = ArtifactKey.fromString(entry.key);
} catch (IllegalArgumentException e) {
throw new MojoExecutionException(
"Failed to parse removed resource '" + entry.key + '=' + entry.resources + "'", e);
}
if (entry.resources == null || entry.resources.isBlank()) {
continue;
}
final String[] resources = entry.resources.split(",");
if (resources.length == 0) {
continue;
}
final String value;
if (resources.length == 1) {
value = resources[0];
} else {
final StringBuilder sb = new StringBuilder();
sb.append(resources[0]);
for (int i = 1; i < resources.length; ++i) {
final String resource = resources[i];
if (!resource.isBlank()) {
sb.append(',').append(resource);
}
}
value = sb.toString();
}
props.setProperty(ApplicationModelBuilder.REMOVED_RESOURCES_DOT + key.toString(), value);
}
}
if (lesserPriorityArtifacts != null && !lesserPriorityArtifacts.isEmpty()) {
String val = String.join(",", lesserPriorityArtifacts);
props.put(ApplicationModelBuilder.LESSER_PRIORITY_ARTIFACTS, val);
}
final Path output = outputDirectory.toPath().resolve(BootstrapConstants.META_INF);
try {
Files.createDirectories(output);
try (BufferedWriter writer = Files
.newBufferedWriter(output.resolve(BootstrapConstants.DESCRIPTOR_FILE_NAME))) {
props.store(writer, "Generated by extension-descriptor");
}
} catch (IOException e) {
throw new MojoExecutionException(
"Failed to persist extension descriptor " + output.resolve(BootstrapConstants.DESCRIPTOR_FILE_NAME),
e);
}
// extension.json
if (extensionFile == null) {
extensionFile = output.resolve(BootstrapConstants.QUARKUS_EXTENSION_FILE_NAME).toFile();
}
ObjectNode extObject;
if (!extensionFile.exists()) {
// if does not exist look for fallback .json
extensionFile = new File(extensionFile.getParent(), "quarkus-extension.json");
}
ObjectMapper mapper = null;
if (extensionFile.exists()) {
mapper = getMapper(extensionFile.toString().endsWith(".yaml"));
extObject = readExtensionDescriptorFile(extensionFile.toPath(), mapper);
} else {
mapper = getMapper(true);
extObject = getMapper(true).createObjectNode();
}
transformLegacyToNew(extObject, mapper);
ensureArtifactCoords(extObject);
if (extObject.get("name") == null) {
if (project.getName() != null) {
extObject.put("name", project.getName());
} else {
JsonNode node = extObject.get(ARTIFACT_ID);
String defaultName = node.asText();
int i = 0;
if (defaultName.startsWith("quarkus-")) {
i = "quarkus-".length();
}
final StringBuilder buf = new StringBuilder();
boolean startWord = true;
while (i < defaultName.length()) {
final char c = defaultName.charAt(i++);
if (c == '-') {
if (!startWord) {
buf.append(' ');
startWord = true;
}
} else if (startWord) {
buf.append(Character.toUpperCase(c));
startWord = false;
} else {
buf.append(c);
}
}
defaultName = buf.toString();
getLog().warn("Extension name has not been provided for " + extObject.get(GROUP_ID).asText("") + ":"
+ extObject.get(ARTIFACT_ID).asText("") + "! Using '" + defaultName
+ "' as the default one.");
extObject.put("name", defaultName);
}
}
if (!extObject.has("description") && project.getDescription() != null) {
extObject.put("description", project.getDescription());
}
setBuiltWithQuarkusCoreVersion(extObject);
addCapabilities(extObject);
addExtensionDependencies(extObject);
completeCodestartArtifact(mapper, extObject);
final DefaultPrettyPrinter prettyPrinter = new DefaultPrettyPrinter();
prettyPrinter.indentArraysWith(DefaultIndenter.SYSTEM_LINEFEED_INSTANCE);
try (BufferedWriter bw = Files
.newBufferedWriter(output.resolve(BootstrapConstants.QUARKUS_EXTENSION_FILE_NAME))) {
bw.write(getMapper(true).writer(prettyPrinter).writeValueAsString(extObject));
} catch (IOException e) {
throw new MojoExecutionException(
"Failed to persist " + output.resolve(BootstrapConstants.QUARKUS_EXTENSION_FILE_NAME), e);
}
}
private void ensureArtifactCoords(ObjectNode extObject) {
String groupId = null;
String artifactId = null;
String version = null;
final JsonNode artifactNode = extObject.get("artifact");
if (artifactNode == null) {
groupId = getRealValueOrNull(extObject.has("groupId") ? extObject.get("groupId").asText() : null,
"${project.groupId");
artifactId = getRealValueOrNull(extObject.has("artifactId") ? extObject.get("artifactId").asText() : null,
"${project.artifactId");
version = getRealValueOrNull(extObject.has("version") ? extObject.get("version").asText() : null,
"${project.version");
} else {
final String[] coordsArr = artifactNode.asText().split(":");
if (coordsArr.length > 0) {
groupId = getRealValueOrNull(coordsArr[0], "${project.groupId}");
if (coordsArr.length > 1) {
artifactId = getRealValueOrNull(coordsArr[1], "${project.artifactId}");
if (coordsArr.length > 2) {
version = getRealValueOrNull(coordsArr[2], "${project.version}");
}
}
}
}
if (artifactNode == null || groupId == null || artifactId == null || version == null) {
final AppArtifactCoords coords = new AppArtifactCoords(
groupId == null ? project.getGroupId() : groupId,
artifactId == null ? project.getArtifactId() : artifactId,
null,
"jar",
version == null ? project.getVersion() : version);
extObject.put("artifact", coords.toString());
}
}
private static String getRealValueOrNull(String s, String propertyExpr) {
return s != null && !s.isBlank() && !s.equals(propertyExpr) ? s : null;
}
private ObjectNode readExtensionDescriptorFile(Path extensionFile, ObjectMapper mapper) throws MojoExecutionException {
try (InputStream is = Files.newInputStream(extensionFile)) {
return mapper.readValue(is, ObjectNode.class);
} catch (IOException io) {
throw new MojoExecutionException("Failed to parse " + extensionFile, io);
}
}
private void completeCodestartArtifact(ObjectMapper mapper, ObjectNode extObject) throws MojoExecutionException {
JsonNode mvalue = getJsonElement(extObject, METADATA, "codestart");
if (mvalue == null || !mvalue.isObject()) {
return;
}
final ObjectNode codestartObject = (ObjectNode) mvalue;
mvalue = mvalue.get("artifact");
if (mvalue == null) {
if (!skipCodestartValidation) {
throw new MojoExecutionException("Codestart artifact is missing from the " + extensionFile);
}
return;
}
String codestartArtifact = getCodestartArtifact(mvalue.asText(), project.getVersion());
final ArtifactCoords codestartArtifactCoords = GACTV.fromString(codestartArtifact);
codestartObject.put("artifact", codestartArtifactCoords.toString());
if (!skipCodestartValidation) {
// first we look for it in the workspace, if it's in there we don't need to actually resolve the artifact, because it might not have been built yet
if (workspaceProvider.getProject(codestartArtifactCoords.getGroupId(),
codestartArtifactCoords.getArtifactId()) != null) {
return;
}
for (Artifact attached : project.getAttachedArtifacts()) {
if (codestartArtifactCoords.getArtifactId().equals(attached.getArtifactId()) &&
codestartArtifactCoords.getClassifier().equals(attached.getClassifier()) &&
codestartArtifactCoords.getType().equals(attached.getType()) &&
codestartArtifactCoords.getVersion().equals(attached.getVersion()) &&
codestartArtifactCoords.getGroupId().equals(attached.getGroupId())) {
return;
}
}
try {
resolve(new DefaultArtifact(codestartArtifact));
} catch (MojoExecutionException e) {
throw new MojoExecutionException("Failed to resolve codestart artifact " + codestartArtifactCoords, e);
}
}
}
/**
* If artifact contains "G:A" the project version is added to have "G:A:V" <br>
* else the version must be defined either with ${project.version} or hardcoded <br>
* to be compatible with AppArtifactCoords.fromString
*
* @param originalArtifact
* @param projectVersion
* @return
*/
static String getCodestartArtifact(String originalArtifact, String projectVersion) {
if (originalArtifact.matches("^[^:]+:[^:]+$")) {
return originalArtifact + ":" + projectVersion;
}
return originalArtifact.replace("${project.version}", projectVersion);
}
private static JsonNode getJsonElement(ObjectNode extObject, String... elements) {
JsonNode mvalue = extObject.get(elements[0]);
int i = 1;
while (i < elements.length) {
if (mvalue == null || !mvalue.isObject()) {
return null;
}
final String element = elements[i++];
extObject = (ObjectNode) mvalue;
mvalue = extObject.get(element);
}
return mvalue;
}
private static void appendCapability(CapabilityConfig capability, StringBuilder buf) {
buf.append(capability.getName());
if (!capability.getOnlyIf().isEmpty()) {
for (String onlyIf : capability.getOnlyIf()) {
buf.append('?').append(onlyIf);
}
}
if (!capability.getOnlyIfNot().isEmpty()) {
for (String onlyIfNot : capability.getOnlyIfNot()) {
buf.append("?!").append(onlyIfNot);
}
}
}
private void setBuiltWithQuarkusCoreVersion(ObjectNode extObject) throws MojoExecutionException {
final QuarkusCoreDeploymentVersionLocator coreVersionLocator = new QuarkusCoreDeploymentVersionLocator();
final DependencyNode root;
try {
root = repoSystem.collectDependencies(repoSession, newCollectRuntimeDepsRequest()).getRoot();
} catch (MojoExecutionException e) {
throw e;
} catch (Exception e) {
throw new MojoExecutionException("Failed to collect runtime dependencies of " + project.getArtifact(), e);
}
root.accept(coreVersionLocator);
if (coreVersionLocator.coreVersion != null) {
ObjectNode metadata = getMetadataNode(extObject);
metadata.put("built-with-quarkus-core", coreVersionLocator.coreVersion);
} else if (!ignoreNotDetectedQuarkusCoreVersion) {
throw new MojoExecutionException("Failed to determine the Quarkus core version used to build the extension");
}
}
private void addExtensionDependencies(ObjectNode extObject) throws MojoExecutionException {
final AtomicReference<ArrayNode> extensionDeps = new AtomicReference<>();
final DependencyVisitor capabilityCollector = new DependencyVisitor() {
@Override
public boolean visitEnter(DependencyNode node) {
final org.eclipse.aether.artifact.Artifact a = node.getArtifact();
if (a != null && a.getFile() != null && a.getExtension().equals("jar")) {
Path p = a.getFile().toPath();
boolean isExtension = false;
if (Files.isDirectory(p)) {
isExtension = getExtensionDescriptorOrNull(p) != null;
} else {
// in some cases a local dependency might not producing the classes directory
// but assembling the JAR directly using maven plugins
if (!Files.exists(p)) {
final Path workspaceJar = p.getParent().resolve(LocalWorkspace.getFileName(a));
if (!Files.exists(workspaceJar)) {
getLog().warn("Failed to resolve " + a + ", " + p + " does not exist");
return true;
}
p = workspaceJar;
}
try (FileSystem fs = ZipUtils.newFileSystem(p)) {
isExtension = getExtensionDescriptorOrNull(fs.getPath("")) != null;
} catch (IOException e) {
throw new RuntimeException("Failed to read " + p, e);
}
}
if (isExtension) {
ArrayNode deps = extensionDeps.get();
if (deps == null) {
deps = getMetadataNode(extObject).putArray("extension-dependencies");
extensionDeps.set(deps);
}
deps.add(new AppArtifactKey(a.getGroupId(), a.getArtifactId(), a.getClassifier(), a.getExtension())
.toGacString());
}
}
return true;
}
@Override
public boolean visitLeave(DependencyNode node) {
return true;
}
};
final DependencyNode rootNode = resolveRuntimeDeps().getRoot();
rootNode.accept(capabilityCollector);
}
private void addCapabilities(ObjectNode extObject) throws MojoExecutionException {
ObjectNode capsNode = null;
if (!capabilities.getProvides().isEmpty()) {
capsNode = getMetadataNode(extObject).putObject("capabilities");
final ArrayNode provides = capsNode.putArray("provides");
for (CapabilityConfig cap : capabilities.getProvides()) {
provides.add(cap.getName());
}
}
if (!capabilities.getRequires().isEmpty()) {
if (capsNode == null) {
capsNode = getMetadataNode(extObject).putObject("capabilities");
}
final ArrayNode requires = capsNode.putArray("requires");
for (CapabilityConfig cap : capabilities.getRequires()) {
requires.add(cap.getName());
}
}
}
private static ObjectNode getMetadataNode(ObjectNode extObject) {
JsonNode mvalue = extObject.get(METADATA);
ObjectNode metadata;
if (mvalue != null && mvalue.isObject()) {
metadata = (ObjectNode) mvalue;
} else {
metadata = extObject.putObject(METADATA);
}
return metadata;
}
private void validateExtensionDeps() throws MojoExecutionException {
final AppArtifactKey rootDeploymentGact = getDeploymentCoords().getKey();
final RootNode rootDeployment = new RootNode(rootDeploymentGact, 2);
final Artifact artifact = project.getArtifact();
final Node rootRuntime = rootDeployment.newChild(new AppArtifactKey(artifact.getGroupId(), artifact.getArtifactId(),
artifact.getClassifier(), artifact.getType()), 1);
rootDeployment.expectedDeploymentNodes.put(rootDeployment.gact, rootDeployment);
rootDeployment.expectedDeploymentNodes.put(rootRuntime.gact, rootRuntime);
// collect transitive extension deps
final DependencyResult resolvedDeps;
resolvedDeps = resolveRuntimeDeps();
for (DependencyNode node : resolvedDeps.getRoot().getChildren()) {
rootDeployment.directRuntimeDeps.add(toKey(node.getArtifact()));
}
visitRuntimeDeps(rootDeployment, rootDeployment, rootDeployment.id, resolvedDeps.getRoot());
final DependencyNode deploymentNode = collectDeploymentDeps().getRoot();
visitDeploymentDeps(rootDeployment, deploymentNode);
if (rootDeployment.hasErrors()) {
final Log log = getLog();
log.error("Quarkus Extension Dependency Verification Error");
final StringBuilder buf = new StringBuilder();
if (rootDeployment.deploymentDepsTotal != 0) {
log.error("Deployment artifact " + getDeploymentCoords() +
" was found to be missing dependencies on the Quarkus extension artifacts marked with '-' below:");
final List<AppArtifactKey> missing = rootDeployment.collectMissingDeploymentDeps(log);
buf.append("Deployment artifact ");
buf.append(getDeploymentCoords());
buf.append(" is missing the following dependencies from its configuration: ");
final Iterator<AppArtifactKey> i = missing.iterator();
buf.append(i.next());
while (i.hasNext()) {
buf.append(", ").append(i.next());
}
}
if (!rootDeployment.deploymentsOnRtCp.isEmpty()) {
if (rootDeployment.runtimeCp > 0) {
log.error("The following deployment artifact(s) appear on the runtime classpath: ");
rootDeployment.collectDeploymentsOnRtCp(log);
}
if (buf.length() > 0) {
buf.append(System.lineSeparator());
}
buf.append("The following deployment artifact(s) appear on the runtime classpath: ");
final Iterator<AppArtifactKey> i = rootDeployment.deploymentsOnRtCp.iterator();
buf.append(i.next());
while (i.hasNext()) {
buf.append(", ").append(i.next());
}
}
if (!rootDeployment.unexpectedDeploymentDeps.isEmpty()) {
final List<AppArtifactKey> unexpectedRtDeps = new ArrayList<>(0);
final List<AppArtifactKey> unexpectedDeploymentDeps = new ArrayList<>(0);
for (Map.Entry<AppArtifactKey, org.eclipse.aether.artifact.Artifact> e : rootDeployment.unexpectedDeploymentDeps
.entrySet()) {
if (rootDeployment.allDeploymentDeps.contains(e.getKey())) {
unexpectedDeploymentDeps.add(e.getKey());
} else {
unexpectedRtDeps.add(toKey(e.getValue()));
}
}
if (!unexpectedRtDeps.isEmpty()) {
if (buf.length() > 0) {
buf.append(System.lineSeparator());
}
buf.append("The deployment artifact " + rootDeploymentGact
+ " depends on the following Quarkus extension runtime artifacts that weren't found among the dependencies of "
+ project.getArtifact() + ":");
for (AppArtifactKey a : unexpectedRtDeps) {
buf.append(' ').append(a);
}
log.error("The deployment artifact " + rootDeploymentGact
+ " depends on the following Quarkus extension runtime artifacts that weren't found among the dependencies of "
+ project.getArtifact() + ":");
highlightInTree(deploymentNode, unexpectedRtDeps);
}
if (!unexpectedDeploymentDeps.isEmpty()) {
if (buf.length() > 0) {
buf.append(System.lineSeparator());
}
buf.append("The deployment artifact " + rootDeploymentGact
+ " depends on the following Quarkus extension deployment artifacts whose corresponding runtime artifacts were not found among the dependencies of "
+ project.getArtifact() + ":");
for (AppArtifactKey a : unexpectedDeploymentDeps) {
buf.append(' ').append(a);
}
log.error("The deployment artifact " + rootDeploymentGact
+ " depends on the following Quarkus extension deployment artifacts whose corresponding runtime artifacts were not found among the dependencies of "
+ project.getArtifact() + ":");
highlightInTree(deploymentNode, unexpectedDeploymentDeps);
}
}
throw new MojoExecutionException(buf.toString());
}
}
private DependencyResult resolveRuntimeDeps() throws MojoExecutionException {
if (runtimeDeps == null) {
try {
runtimeDeps = repoSystem.resolveDependencies(repoSession,
new DependencyRequest().setCollectRequest(newCollectRuntimeDepsRequest()));
} catch (Exception e) {
throw new MojoExecutionException("Failed to resolve dependencies of " + project.getArtifact(), e);
}
}
return runtimeDeps;
}
private void highlightInTree(DependencyNode node, Collection<AppArtifactKey> keys) {
highlightInTree(0, node, keys, new HashSet<>(), new StringBuilder(), new ArrayList<>());
}
private void highlightInTree(int depth, DependencyNode node, Collection<AppArtifactKey> keysToHighlight,
Set<AppArtifactKey> visited, StringBuilder buf, List<String> branch) {
final AppArtifactKey key = toKey(node.getArtifact());
if (!visited.add(key)) {
return;
}
buf.setLength(0);
final boolean highlighted = keysToHighlight.contains(key);
if (highlighted) {
buf.append('*');
} else {
buf.append(' ');
}
for (int i = 0; i < depth; ++i) {
buf.append(" ");
}
buf.append(node.getArtifact());
branch.add(buf.toString());
if (!highlighted) {
for (DependencyNode child : node.getChildren()) {
highlightInTree(depth + 1, child, keysToHighlight, visited, buf, branch);
}
} else {
for (String line : branch) {
getLog().error(line);
}
}
branch.remove(branch.size() - 1);
}
private void visitDeploymentDeps(RootNode rootDeployment, DependencyNode dep) throws MojoExecutionException {
for (DependencyNode child : dep.getChildren()) {
visitDeploymentDep(rootDeployment, child);
}
}
private void visitDeploymentDep(RootNode rootDeployment, DependencyNode dep) throws MojoExecutionException {
org.eclipse.aether.artifact.Artifact artifact = dep.getArtifact();
if (artifact == null) {
return;
}
final AppArtifactKey key = toKey(artifact);
if (!rootDeployment.allDeploymentDeps.add(key)) {
return;
}
final Node node = rootDeployment.expectedDeploymentNodes.get(key);
if (node != null) {
if (!node.present) {
node.present = true;
--rootDeployment.deploymentDepsTotal;
if (rootDeployment.allRtDeps.contains(key)) {
rootDeployment.deploymentsOnRtCp.add(key);
}
}
} else if (!rootDeployment.allRtDeps.contains(key)) {
final AppArtifactKey deployment = getDeploymentKey(artifact);
if (deployment != null) {
rootDeployment.unexpectedDeploymentDeps.put(deployment, artifact);
}
}
visitDeploymentDeps(rootDeployment, dep);
}
private void visitRuntimeDep(RootNode root, Node currentNode, int currentId,
DependencyNode node) throws MojoExecutionException {
final org.eclipse.aether.artifact.Artifact a = node.getArtifact();
root.allRtDeps.add(toKey(a));
final AppArtifactKey deployment = getDeploymentKey(a);
if (deployment != null) {
currentNode = currentNode.newChild(deployment, ++currentId);
root.expectedDeploymentNodes.put(currentNode.gact, currentNode);
++root.deploymentDepsTotal;
if (root.allRtDeps.contains(deployment)) {
root.deploymentsOnRtCp.add(deployment);
if (root.directRuntimeDeps.contains(deployment)) {
currentNode.runtimeCp = 2; // actual rt dep
Node n = currentNode.parent;
while (n != null) {
if (n.runtimeCp != 0) {
break;
} else {
n.runtimeCp = 1; // path to the actual rt dep
}
n = n.parent;
}
}
}
}
visitRuntimeDeps(root, currentNode, currentId, node);
}
private void visitRuntimeDeps(RootNode root, Node currentNode, int currentId, DependencyNode node)
throws MojoExecutionException {
for (DependencyNode child : node.getChildren()) {
visitRuntimeDep(root, currentNode, currentId, child);
}
}
private AppArtifactKey getDeploymentKey(org.eclipse.aether.artifact.Artifact a) throws MojoExecutionException {
final org.eclipse.aether.artifact.Artifact deployment = getDeploymentArtifact(a);
return deployment == null ? null : toKey(deployment);
}
private org.eclipse.aether.artifact.Artifact getDeploymentArtifact(org.eclipse.aether.artifact.Artifact a)
throws MojoExecutionException {
final Properties props = getExtensionDescriptor(a, false);
if (props == null) {
return null;
}
final String deploymentStr = props.getProperty(BootstrapConstants.PROP_DEPLOYMENT_ARTIFACT);
if (deploymentStr == null) {
throw new IllegalStateException("Quarkus extension runtime artifact " + a + " is missing "
+ BootstrapConstants.PROP_DEPLOYMENT_ARTIFACT + " property in its "
+ BootstrapConstants.DESCRIPTOR_PATH);
}
return DependencyNodeUtils.toArtifact(deploymentStr);
}
private Properties getExtensionDescriptor(org.eclipse.aether.artifact.Artifact a, boolean packaged) {
final File f;
try {
f = resolve(a);
} catch (Exception e) {
getLog().warn("Failed to resolve " + a);
return null;
}
// if it hasn't been packaged yet, we skip it, we are not packaging yet
if (!a.getExtension().equals(ArtifactCoords.TYPE_JAR) || packaged && !isJarFile(f)) {
return null;
}
try {
if (f.isDirectory()) {
return readExtensionDescriptorIfExists(f.toPath());
}
// In case of a parallel build, the resolved JAR might not have been fully written, which may result in a failure to read it
// so we try the classes dir first
if (session.isParallel()) {
final LocalProject localProject = workspaceProvider.getProject(a.getGroupId(), a.getArtifactId());
final Path classesDir = localProject == null ? null : localProject.getClassesDir();
if (classesDir != null && Files.exists(classesDir)) {
return readExtensionDescriptorIfExists(classesDir);
}
}
try (FileSystem fs = ZipUtils.newFileSystem(f.toPath())) {
return readExtensionDescriptorIfExists(fs.getPath(""));
}
} catch (Throwable e) {
throw new IllegalStateException("Failed to read " + f, e);
}
}
private Properties readExtensionDescriptorIfExists(final Path classesDir) throws IOException {
final Path p = getExtensionDescriptorOrNull(classesDir);
return p == null ? null : readExtensionDescriptor(p);
}
private Path getExtensionDescriptorOrNull(Path runtimeExtRootDir) {
final Path p = runtimeExtRootDir.resolve(BootstrapConstants.DESCRIPTOR_PATH);
return Files.exists(p) ? p : null;
}
private Properties readExtensionDescriptor(final Path extDescr) throws IOException {
final Properties props = new Properties();
try (BufferedReader reader = Files.newBufferedReader(extDescr)) {
props.load(reader);
}
return props;
}