View Javadoc
1   package io.apicurio.registry.maven;
2   
3   import com.fasterxml.jackson.databind.JsonNode;
4   import com.fasterxml.jackson.databind.ObjectMapper;
5   import io.apicurio.registry.content.ContentHandle;
6   import io.apicurio.registry.content.TypedContent;
7   import io.apicurio.registry.content.refs.ExternalReference;
8   import io.apicurio.registry.content.refs.ReferenceFinder;
9   import io.apicurio.registry.maven.refs.IndexedResource;
10  import io.apicurio.registry.maven.refs.ReferenceIndex;
11  import io.apicurio.registry.rest.client.RegistryClient;
12  import io.apicurio.registry.rest.client.models.*;
13  import io.apicurio.registry.types.ArtifactType;
14  import io.apicurio.registry.types.ContentTypes;
15  import io.apicurio.registry.types.provider.ArtifactTypeUtilProvider;
16  import io.apicurio.registry.types.provider.DefaultArtifactTypeUtilProviderImpl;
17  import io.vertx.core.Vertx;
18  import org.apache.commons.io.FileUtils;
19  import org.apache.maven.plugin.MojoExecutionException;
20  import org.apache.maven.plugin.MojoFailureException;
21  import org.apache.maven.plugins.annotations.Mojo;
22  import org.apache.maven.plugins.annotations.Parameter;
23  
24  import java.io.*;
25  import java.nio.charset.StandardCharsets;
26  import java.nio.file.Files;
27  import java.nio.file.Path;
28  import java.nio.file.Paths;
29  import java.util.*;
30  import java.util.concurrent.ExecutionException;
31  import java.util.stream.Collectors;
32  
33  /**
34   * Register artifacts against registry.
35   */
36  @Mojo(name = "register")
37  public class RegisterRegistryMojo extends AbstractRegistryMojo {
38  
39      /**
40       * The list of pre-registered artifacts that can be used as references.
41       */
42      @Parameter(required = false)
43      List<ExistingReference> existingReferences;
44  
45      /**
46       * The list of artifacts to register.
47       */
48      @Parameter(required = true)
49      List<RegisterArtifact> artifacts;
50  
51      /**
52       * Set this to 'true' to skip registering the artifact(s). Convenient in case you want to skip for specific occasions.
53       */
54      @Parameter(property = "skipRegister", defaultValue = "false")
55      boolean skip;
56  
57      /**
58       * Set this to 'true' to perform the action with the "dryRun" option enabled. This will effectively test
59       * whether registration *would have worked*. But it results in no changes made on the server.
60       */
61      @Parameter(property = "dryRun", defaultValue = "false")
62      boolean dryRun;
63  
64      private RegisterArtifact.AvroAutoRefsNamingStrategy avroAutoRefsNamingStrategy;
65  
66      DefaultArtifactTypeUtilProviderImpl utilProviderFactory = new DefaultArtifactTypeUtilProviderImpl(true);
67  
68      /**
69       * Validate the configuration.
70       */
71      protected boolean validate() throws MojoExecutionException {
72          if (skip) {
73              getLog().info("register is skipped.");
74              return false;
75          }
76  
77          if (artifacts == null || artifacts.isEmpty()) {
78              getLog().warn("No artifacts are configured for registration.");
79              return false;
80          }
81  
82          if (existingReferences == null) {
83              existingReferences = new ArrayList<>();
84          }
85  
86          int idx = 0;
87          int errorCount = 0;
88          for (RegisterArtifact artifact : artifacts) {
89              if (artifact.getGroupId() == null) {
90                  getLog().error(String.format(
91                          "GroupId is required when registering an artifact.  Missing from artifacts[%d].",
92                          idx));
93                  errorCount++;
94              }
95              if (artifact.getArtifactId() == null) {
96                  getLog().error(String.format(
97                          "ArtifactId is required when registering an artifact.  Missing from artifacts[%s].",
98                          idx));
99                  errorCount++;
100             }
101             if (artifact.getFile() == null) {
102                 getLog().error(String.format(
103                         "File is required when registering an artifact.  Missing from artifacts[%s].", idx));
104                 errorCount++;
105             } else if (!artifact.getFile().exists()) {
106                 getLog().error(
107                         String.format("Artifact file to register is configured but file does not exist: %s",
108                                 artifact.getFile().getPath()));
109                 errorCount++;
110             }
111 
112             idx++;
113         }
114 
115         if (errorCount > 0) {
116             throw new MojoExecutionException(
117                     "Invalid configuration of the Register Artifact(s) mojo. See the output log for details.");
118         }
119         return true;
120     }
121 
122     @Override
123     protected void executeInternal() throws MojoExecutionException {
124         int errorCount = 0;
125         if (validate()) {
126             Vertx vertx = createVertx();
127             RegistryClient registryClient = createClient(vertx);
128 
129             for (RegisterArtifact artifact : artifacts) {
130                 String groupId = artifact.getGroupId();
131                 String artifactId = artifact.getArtifactId();
132                 try {
133                     if (artifact.getAutoRefs() != null && artifact.getAutoRefs()) {
134                         // If we have references, then we'll need to create the local resource index and then
135                         // process all refs.
136                         ReferenceIndex index = createIndex(artifact);
137                         addExistingReferencesToIndex(registryClient, index, existingReferences);
138                         addExistingReferencesToIndex(registryClient, index, artifact.getExistingReferences());
139                         Stack<RegisterArtifact> registrationStack = new Stack<>();
140 
141                         this.avroAutoRefsNamingStrategy = artifact.getAvroAutoRefsNamingStrategy();
142                         registerWithAutoRefs(registryClient, artifact, index, registrationStack);
143                     } else {
144                         List<ArtifactReference> references = new ArrayList<>();
145                         // First, we check if the artifact being processed has references defined
146                         if (hasReferences(artifact)) {
147                             references = processArtifactReferences(registryClient, artifact.getReferences());
148                         }
149                         registerArtifact(registryClient, artifact, references);
150                     }
151                 } catch (Exception e) {
152                     errorCount++;
153                     getLog().error(String.format("Exception while registering artifact [%s] / [%s]", groupId,
154                             artifactId), e);
155                 }
156 
157             }
158 
159             if (errorCount > 0) {
160                 throw new MojoExecutionException("Errors while registering artifacts ...");
161             }
162         }
163     }
164 
165     private VersionMetaData registerWithAutoRefs(RegistryClient registryClient, RegisterArtifact artifact,
166                                                  ReferenceIndex index, Stack<RegisterArtifact> registrationStack) throws IOException,
167             ExecutionException, InterruptedException, MojoExecutionException, MojoFailureException {
168         if (loopDetected(artifact, registrationStack)) {
169             throw new MojoExecutionException(
170                     "Artifact reference loop detected (not supported): " + printLoop(registrationStack));
171         }
172         registrationStack.push(artifact);
173 
174         // Read the artifact content.
175         ContentHandle artifactContent = readContent(artifact.getFile());
176         String artifactContentType = getContentTypeByExtension(artifact.getFile().getName());
177         TypedContent typedArtifactContent = TypedContent.create(artifactContent, artifactContentType);
178 
179         // Find all references in the content
180         ArtifactTypeUtilProvider provider = this.utilProviderFactory
181                 .getArtifactTypeProvider(artifact.getArtifactType());
182         ReferenceFinder referenceFinder = provider.getReferenceFinder();
183         var referenceArtifactIdentifierExtractor = provider.getReferenceArtifactIdentifierExtractor();
184         Set<ExternalReference> externalReferences = referenceFinder
185                 .findExternalReferences(typedArtifactContent);
186 
187         // Register all the references first, then register the artifact.
188         List<ArtifactReference> registeredReferences = new ArrayList<>(externalReferences.size());
189         for (ExternalReference externalRef : externalReferences) {
190             IndexedResource iresource = index.lookup(externalRef.getResource(),
191                     Paths.get(artifact.getFile().toURI()));
192 
193             // TODO: need a way to resolve references that are not local (already registered in the registry)
194             if (iresource == null) {
195                 throw new MojoExecutionException("Reference could not be resolved.  From: "
196                         + artifact.getFile().getName() + "  To: " + externalRef.getFullReference());
197             }
198 
199             // If the resource isn't already registered, then register it now.
200             if (!iresource.isRegistered()) {
201                 String groupId = artifact.getGroupId(); // default is same group as root artifact
202                 // TODO: determine the artifactId better (type-specific logic here?)
203                 String artifactId = referenceArtifactIdentifierExtractor.extractArtifactId(externalRef.getResource());
204                 if (ArtifactType.AVRO.equals(iresource.getType())) {
205                     if (avroAutoRefsNamingStrategy == RegisterArtifact.AvroAutoRefsNamingStrategy.USE_AVRO_NAMESPACE) {
206                         groupId = referenceArtifactIdentifierExtractor.extractGroupId(externalRef.getResource());
207                         artifactId = referenceArtifactIdentifierExtractor.extractArtifactId(externalRef.getResource());
208                     }
209                     if (avroAutoRefsNamingStrategy == RegisterArtifact.AvroAutoRefsNamingStrategy.INHERIT_PARENT_GROUP) {
210                         groupId = artifact.getGroupId(); // same group as root artifact
211                         artifactId = iresource.getResourceName(); // fq name
212                     }
213                 }
214                 File localFile = getLocalFile(iresource.getPath());
215                 RegisterArtifact refArtifact = buildFromRoot(artifact, artifactId, groupId);
216                 refArtifact.setArtifactType(iresource.getType());
217                 refArtifact.setVersion(null);
218                 refArtifact.setFile(localFile);
219                 refArtifact.setContentType(getContentTypeByExtension(localFile.getName()));
220                 try {
221                     var car = registerWithAutoRefs(registryClient, refArtifact, index, registrationStack);
222                     iresource.setRegistration(car);
223                 } catch (IOException | ExecutionException | InterruptedException e) {
224                     throw new RuntimeException(e);
225                 }
226             }
227 
228             var reference = new ArtifactReference();
229             reference.setName(externalRef.getFullReference());
230             reference.setVersion(iresource.getRegistration().getVersion());
231             reference.setGroupId(iresource.getRegistration().getGroupId());
232             reference.setArtifactId(iresource.getRegistration().getArtifactId());
233             registeredReferences.add(reference);
234         }
235         registeredReferences.sort((ref1, ref2) -> ref1.getName().compareTo(ref2.getName()));
236 
237         registrationStack.pop();
238         return registerArtifact(registryClient, artifact, registeredReferences);
239     }
240 
241     private VersionMetaData registerArtifact(RegistryClient registryClient, RegisterArtifact artifact,
242                                              List<ArtifactReference> references) throws FileNotFoundException, ExecutionException,
243             InterruptedException, MojoExecutionException, MojoFailureException {
244         if (artifact.getFile() != null) {
245             return registerArtifact(registryClient, artifact, new FileInputStream(artifact.getFile()),
246                     references);
247         } else {
248             return getArtifactVersionMetadata(registryClient, artifact);
249         }
250     }
251 
252     private VersionMetaData getArtifactVersionMetadata(RegistryClient registryClient,
253                                                        RegisterArtifact artifact) {
254         String groupId = artifact.getGroupId();
255         String artifactId = artifact.getArtifactId();
256         String version = artifact.getVersion();
257 
258         VersionMetaData amd = registryClient.groups().byGroupId(groupId).artifacts().byArtifactId(artifactId)
259                 .versions().byVersionExpression(version).get();
260         getLog().info(String.format("Successfully processed artifact [%s] / [%s].  GlobalId is [%d]", groupId,
261                 artifactId, amd.getGlobalId()));
262 
263         return amd;
264     }
265 
266     private VersionMetaData registerArtifact(RegistryClient registryClient, RegisterArtifact artifact,
267                                              InputStream artifactContent, List<ArtifactReference> references)
268             throws ExecutionException, InterruptedException, MojoFailureException, MojoExecutionException {
269         String groupId = artifact.getGroupId();
270         String artifactId = artifact.getArtifactId();
271         String version = artifact.getVersion();
272         String type = artifact.getArtifactType();
273         Boolean canonicalize = artifact.getCanonicalize();
274         Boolean isDraft = artifact.getIsDraft();
275         String ct = artifact.getContentType() == null ? ContentTypes.APPLICATION_JSON
276                 : artifact.getContentType();
277         String data = null;
278         try {
279             if (artifact.getMinify() != null && artifact.getMinify()) {
280                 ObjectMapper objectMapper = new ObjectMapper();
281                 JsonNode jsonNode = objectMapper.readValue(artifactContent, JsonNode.class);
282                 data = jsonNode.toString();
283             } else {
284                 data = new String(artifactContent.readAllBytes(), StandardCharsets.UTF_8);
285             }
286         } catch (IOException e) {
287             throw new RuntimeException(e);
288         }
289 
290         CreateArtifact createArtifact = new CreateArtifact();
291         createArtifact.setArtifactId(artifactId);
292         createArtifact.setArtifactType(type);
293 
294         CreateVersion createVersion = new CreateVersion();
295         createVersion.setVersion(version);
296         createVersion.setIsDraft(isDraft);
297         createArtifact.setFirstVersion(createVersion);
298 
299         VersionContent content = new VersionContent();
300         content.setContent(data);
301         content.setContentType(ct);
302         content.setReferences(references.stream().map(r -> {
303             ArtifactReference ref = new ArtifactReference();
304             ref.setArtifactId(r.getArtifactId());
305             ref.setGroupId(r.getGroupId());
306             ref.setVersion(r.getVersion());
307             ref.setName(r.getName());
308             return ref;
309         }).collect(Collectors.toList()));
310         createVersion.setContent(content);
311 
312         try {
313             var vmd = registryClient.groups().byGroupId(groupId).artifacts().post(createArtifact, config -> {
314                 if (artifact.getIfExists() != null) {
315                     config.queryParameters.ifExists = IfArtifactExists
316                             .forValue(artifact.getIfExists().value());
317                     if (dryRun) {
318                         config.queryParameters.dryRun = true;
319                     }
320                 }
321                 config.queryParameters.canonical = canonicalize;
322             });
323 
324             getLog().info(String.format("Successfully registered artifact [%s] / [%s].  GlobalId is [%d]",
325                     groupId, artifactId, vmd.getVersion().getGlobalId()));
326 
327 
328             return vmd.getVersion();
329         } catch (RuleViolationProblemDetails | ProblemDetails e) {
330 
331             // If this is a draft, and we got a 409, then we should try to update the artifact content instead.
332             if (Boolean.TRUE.equals(artifact.getIsDraft()) && e.getResponseStatusCode() == 409) {
333                 try {
334                     registryClient.groups().byGroupId(groupId).artifacts().byArtifactId(artifactId)
335                             .versions().byVersionExpression(version).content()
336                             .put(content, config -> {
337 
338                     });
339                     getLog().info(String.format("Successfully updated artifact [%s] / [%s].",
340                             groupId, artifactId));
341                     // Return version metadata
342                     return registryClient.groups().byGroupId(groupId).artifacts().byArtifactId(artifactId).versions().byVersionExpression(version).get();
343                 } catch (RuleViolationProblemDetails | ProblemDetails pd) {
344                     logAndThrow(pd);
345                     return null;
346                 }
347             } else {
348                 logAndThrow(e);
349                 return null;
350             }
351         }
352     }
353 
354     private static boolean hasReferences(RegisterArtifact artifact) {
355         return artifact.getReferences() != null && !artifact.getReferences().isEmpty();
356     }
357 
358     private List<ArtifactReference> processArtifactReferences(RegistryClient registryClient,
359                                                               List<RegisterArtifactReference> referencedArtifacts) throws FileNotFoundException,
360             ExecutionException, InterruptedException, MojoExecutionException, MojoFailureException {
361         List<ArtifactReference> references = new ArrayList<>();
362         for (RegisterArtifactReference artifact : referencedArtifacts) {
363             List<ArtifactReference> nestedReferences = new ArrayList<>();
364             // First, we check if the artifact being processed has references defined, and register them if
365             // needed
366             if (hasReferences(artifact)) {
367                 nestedReferences = processArtifactReferences(registryClient, artifact.getReferences());
368             }
369             final VersionMetaData artifactMetaData = registerArtifact(registryClient, artifact,
370                     nestedReferences);
371             references.add(buildReferenceFromMetadata(artifactMetaData, artifact.getName()));
372         }
373         return references;
374     }
375 
376     public void setArtifacts(List<RegisterArtifact> artifacts) {
377         this.artifacts = artifacts;
378     }
379 
380     public void setSkip(boolean skip) {
381         this.skip = skip;
382     }
383 
384     private static ArtifactReference buildReferenceFromMetadata(VersionMetaData metaData,
385                                                                 String referenceName) {
386         ArtifactReference reference = new ArtifactReference();
387         reference.setName(referenceName);
388         reference.setArtifactId(metaData.getArtifactId());
389         reference.setGroupId(metaData.getGroupId());
390         reference.setVersion(metaData.getVersion());
391         return reference;
392     }
393 
394     private static boolean isFileAllowedInIndex(File file) {
395         return file.isFile() && (
396                 file.getName().toLowerCase().endsWith(".json") ||
397                         file.getName().toLowerCase().endsWith(".yml") ||
398                         file.getName().toLowerCase().endsWith(".yaml") ||
399                         file.getName().toLowerCase().endsWith(".xml") ||
400                         file.getName().toLowerCase().endsWith(".xsd") ||
401                         file.getName().toLowerCase().endsWith(".wsdl") ||
402                         file.getName().toLowerCase().endsWith(".graphql") ||
403                         file.getName().toLowerCase().endsWith(".avsc") ||
404                         file.getName().toLowerCase().endsWith(".proto")
405         );
406     }
407 
408     /**
409      * Create a local index relative to the given file location.
410      *
411      * @param artifact
412      */
413     private static ReferenceIndex createIndex(RegisterArtifact artifact) {
414         File file = artifact.getFile();
415         ReferenceIndex index = new ReferenceIndex(file.getParentFile().toPath());
416         if (artifact.getProtoPaths() != null) {
417             artifact.getProtoPaths().forEach(path -> index.addSchemaPath(path.toPath()));
418         }
419 
420         HashSet<File> roots = new HashSet<>();
421         if (artifact.getProtoPaths() != null) {
422             roots.addAll(artifact.getProtoPaths());
423         } else {
424             roots.add(file.getParentFile());
425         }
426 
427         Collection<File> allFiles = new HashSet<>();
428         for (File root : roots) {
429             allFiles.addAll(FileUtils.listFiles(root, null, true));
430             allFiles.stream().filter(RegisterRegistryMojo::isFileAllowedInIndex).forEach(f -> {
431                 index.index(f.toPath(), readContent(f));
432             });
433         }
434 
435         return index;
436     }
437 
438     private void addExistingReferencesToIndex(RegistryClient registryClient, ReferenceIndex index,
439                                               List<ExistingReference> existingReferences) throws ExecutionException, InterruptedException {
440         if (existingReferences != null && !existingReferences.isEmpty()) {
441             for (ExistingReference ref : existingReferences) {
442                 VersionMetaData vmd;
443                 if (ref.getVersion() == null || "LATEST".equalsIgnoreCase(ref.getVersion())) {
444                     vmd = registryClient.groups().byGroupId(ref.getGroupId()).artifacts()
445                             .byArtifactId(ref.getArtifactId()).versions().byVersionExpression("branch=latest")
446                             .get();
447                 } else {
448                     vmd = new VersionMetaData();
449                     vmd.setGroupId(ref.getGroupId());
450                     vmd.setArtifactId(ref.getArtifactId());
451                     vmd.setVersion(ref.getVersion());
452                 }
453                 index.index(ref.getResourceName(), vmd);
454             }
455         }
456     }
457 
458     protected static ContentHandle readContent(File file) {
459         try {
460             return ContentHandle.create(Files.readAllBytes(file.toPath()));
461         } catch (IOException e) {
462             throw new RuntimeException("Failed to read schema file: " + file, e);
463         }
464     }
465 
466     protected static RegisterArtifact buildFromRoot(RegisterArtifact rootArtifact, String artifactId, String groupId) {
467         RegisterArtifact nestedSchema = new RegisterArtifact();
468         nestedSchema.setCanonicalize(rootArtifact.getCanonicalize());
469         nestedSchema.setArtifactId(artifactId);
470         nestedSchema.setGroupId(groupId == null ? rootArtifact.getGroupId() : groupId);
471         nestedSchema.setContentType(rootArtifact.getContentType());
472         nestedSchema.setArtifactType(rootArtifact.getArtifactType());
473         nestedSchema.setMinify(rootArtifact.getMinify());
474         nestedSchema.setContentType(rootArtifact.getContentType());
475         nestedSchema.setIfExists(rootArtifact.getIfExists());
476         nestedSchema.setAutoRefs(rootArtifact.getAutoRefs());
477         return nestedSchema;
478     }
479 
480     private static File getLocalFile(Path path) {
481         return path.toFile();
482     }
483 
484     /**
485      * Detects a loop by looking for the given artifact in the registration stack.
486      *
487      * @param artifact
488      * @param registrationStack
489      */
490     private static boolean loopDetected(RegisterArtifact artifact,
491                                         Stack<RegisterArtifact> registrationStack) {
492         for (RegisterArtifact stackArtifact : registrationStack) {
493             if (artifact.getFile().equals(stackArtifact.getFile())) {
494                 return true;
495             }
496         }
497         return false;
498     }
499 
500     private static String printLoop(Stack<RegisterArtifact> registrationStack) {
501         return registrationStack.stream().map(artifact -> artifact.getFile().getName())
502                 .collect(Collectors.joining(" -> "));
503     }
504 
505 }