Return List<Artifact> in ArtifactDownloadManager
[aai/model-loader.git] / src / main / java / org / onap / aai / modelloader / notification / ArtifactDownloadManager.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * Copyright © 2017-2018 European Software Marketing Ltd.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *       http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21 package org.onap.aai.modelloader.notification;
22
23 import java.time.ZonedDateTime;
24 import java.time.format.DateTimeFormatter;
25 import java.util.ArrayList;
26 import java.util.Base64;
27 import java.util.List;
28 import java.util.stream.Collectors;
29 import java.util.stream.Stream;
30
31 import org.onap.aai.babel.service.data.BabelRequest;
32 import org.onap.aai.cl.api.Logger;
33 import org.onap.aai.cl.eelf.LoggerFactory;
34 import org.onap.aai.cl.mdc.MdcContext;
35 import org.onap.aai.cl.mdc.MdcOverride;
36 import org.onap.aai.modelloader.babel.BabelArtifactService;
37 import org.onap.aai.modelloader.entity.Artifact;
38 import org.onap.aai.modelloader.entity.ArtifactType;
39 import org.onap.aai.modelloader.entity.catalog.VnfCatalogArtifact;
40 import org.onap.aai.modelloader.entity.model.BabelArtifactParsingException;
41 import org.onap.aai.modelloader.entity.model.IModelParser;
42 import org.onap.aai.modelloader.entity.model.NamedQueryArtifactParser;
43 import org.onap.aai.modelloader.extraction.InvalidArchiveException;
44 import org.onap.aai.modelloader.extraction.VnfCatalogExtractor;
45 import org.onap.aai.modelloader.service.ModelLoaderMsgs;
46 import org.onap.sdc.api.IDistributionClient;
47 import org.onap.sdc.api.notification.IArtifactInfo;
48 import org.onap.sdc.api.notification.INotificationData;
49 import org.onap.sdc.api.results.IDistributionClientDownloadResult;
50 import org.onap.sdc.utils.ArtifactTypeEnum;
51 import org.onap.sdc.utils.DistributionActionResultEnum;
52 import org.springframework.stereotype.Component;
53
54 /**
55  * This class is responsible for downloading the artifacts from the ASDC.
56  *
57  * The downloads can be TOSCA_CSAR files or VNF_CATALOG files.
58  *
59  * The status of the download is published. The status of the extraction of yml files from a TOSCA_CSAR file is also
60  * published as a deployment event.
61  *
62  * TOSCA_CSAR file artifacts will be converted into XML and returned as model artifacts.
63  */
64 @Component
65 public class ArtifactDownloadManager {
66
67     private static Logger logger = LoggerFactory.getInstance().getLogger(ArtifactDownloadManager.class);
68
69     private final IDistributionClient client;
70     private final NotificationPublisher notificationPublisher;
71     private final VnfCatalogExtractor vnfCatalogExtractor;
72     private final BabelArtifactService babelArtifactService;
73
74     public ArtifactDownloadManager(IDistributionClient client,
75             NotificationPublisher notificationPublisher, VnfCatalogExtractor vnfCatalogExtractor, BabelArtifactService babelArtifactService) {
76         this.client = client;
77         this.notificationPublisher = notificationPublisher;
78         this.vnfCatalogExtractor = vnfCatalogExtractor;
79         this.babelArtifactService = babelArtifactService;
80     }
81
82     /**
83      * This method downloads the artifacts from the ASDC.
84      *
85      * @param data data about the notification that is being processed
86      * @param artifacts the specific artifacts found in the data.
87      * @param modelArtifacts collection of artifacts for model query specs
88      * @param catalogArtifacts collection of artifacts that represent vnf catalog files
89      * @return boolean <code>true</code> if the download process was successful otherwise <code>false</code>
90      * @throws Exception 
91      */
92     List<Artifact> downloadArtifacts(INotificationData data, List<IArtifactInfo> artifacts) throws Exception {
93
94         List<Artifact> allArtifacts = new ArrayList<>();
95         for (IArtifactInfo artifact : artifacts) {
96             try {
97                 IDistributionClientDownloadResult downloadResult = downloadIndividualArtifacts(data, artifact);
98                 List<Artifact> processedArtifacts = processDownloadedArtifacts(artifact, downloadResult, data);
99                 allArtifacts.addAll(processedArtifacts);
100             } catch (DownloadFailureException e) {
101                 notificationPublisher.publishDownloadFailure(client, data, artifact, e.getMessage());
102                 throw e;
103             } catch (ProcessToscaArtifactsException | InvalidArchiveException | BabelArtifactParsingException e) {
104                 notificationPublisher.publishDeployFailure(client, data, artifact);
105                 throw e;
106             }
107         }
108         return allArtifacts;
109     }
110
111     private IDistributionClientDownloadResult downloadIndividualArtifacts(INotificationData data,
112             IArtifactInfo artifact) throws DownloadFailureException {
113         // Grab the current time so we can measure the download time for the metrics log
114         DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
115         MdcOverride override = new MdcOverride();
116         override.addAttribute(MdcContext.MDC_START_TIME, ZonedDateTime.now().format(formatter));
117
118         IDistributionClientDownloadResult downloadResult = client.download(artifact);
119
120         logger.info(ModelLoaderMsgs.DOWNLOAD_COMPLETE, downloadResult.getDistributionActionResult().toString(),
121                 downloadResult.getArtifactPayload() == null ? "null"
122                         : Base64.getEncoder().encodeToString(downloadResult.getArtifactPayload()));
123
124         if (DistributionActionResultEnum.SUCCESS.equals(downloadResult.getDistributionActionResult())) {
125             logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Downloaded artifact: " + artifact.getArtifactName());
126             notificationPublisher.publishDownloadSuccess(client, data, artifact);
127         } else {
128             throw new DownloadFailureException(downloadResult.getDistributionMessageResult());
129         }
130
131         return downloadResult;
132     }
133
134     private List<Artifact> processDownloadedArtifacts(
135             IArtifactInfo artifactInfo, IDistributionClientDownloadResult downloadResult, INotificationData data)
136             throws ProcessToscaArtifactsException, InvalidArchiveException, BabelArtifactParsingException {
137         List<Artifact> artifacts = new ArrayList<>();
138         List<Artifact> querySpecArtifacts = new ArrayList<>();
139         if ("TOSCA_CSAR".equalsIgnoreCase(artifactInfo.getArtifactType())) {
140             artifacts = processToscaArtifacts(downloadResult.getArtifactPayload(), artifactInfo,
141                     data.getDistributionID(), data.getServiceVersion());
142             
143         } else if (ArtifactTypeEnum.MODEL_QUERY_SPEC.toString().equalsIgnoreCase(artifactInfo.getArtifactType())) {
144             querySpecArtifacts = processModelQuerySpecArtifact(downloadResult);
145         } else {
146             logger.info(ModelLoaderMsgs.UNSUPPORTED_ARTIFACT_TYPE, artifactInfo.getArtifactName(),
147                     artifactInfo.getArtifactType());
148             throw new InvalidArchiveException("Unsupported artifact type: " + artifactInfo.getArtifactType());
149         }
150         return Stream
151             .concat(artifacts.stream(), querySpecArtifacts.stream())
152             .collect(Collectors.toList());
153     }
154
155     public List<Artifact> processToscaArtifacts(byte[] payload, IArtifactInfo artifactInfo, String distributionId, String serviceVersion)
156             throws ProcessToscaArtifactsException, InvalidArchiveException {
157         // Get translated artifacts from Babel Service
158         BabelRequest babelRequest = new BabelRequest();
159         babelRequest.setArtifactName(artifactInfo.getArtifactName());
160         babelRequest.setCsar(Base64.getEncoder().encodeToString(payload));
161         babelRequest.setArtifactVersion(serviceVersion);
162         List<Artifact> artifacts = babelArtifactService.invokeBabelService(babelRequest, distributionId);
163
164         // Get VNF Catalog artifacts directly from CSAR
165         List<Artifact> csarCatalogArtifacts = vnfCatalogExtractor.extract(payload, artifactInfo.getArtifactName());
166
167         // Throw an error if VNF Catalog data is present in the Babel payload and directly in the CSAR
168         if (isDuplicateVnfCatalogData(artifacts, csarCatalogArtifacts)) {
169             logger.error(ModelLoaderMsgs.DUPLICATE_VNFC_DATA_ERROR, artifactInfo.getArtifactName());
170             throw new InvalidArchiveException("CSAR: " + artifactInfo.getArtifactName()
171                     + " contains VNF Catalog data in the format of both TOSCA and XML files. Only one format can be used for each CSAR file.");
172         }
173         return Stream
174                 .concat(artifacts.stream(), csarCatalogArtifacts.stream())
175                 .collect(Collectors.toList());
176
177     }
178
179     private boolean isDuplicateVnfCatalogData(List<Artifact> babelArtifacts, List<Artifact> csarCatalogArtifacts) {
180         boolean babelIsEmpty = babelArtifacts.stream()
181             .filter(VnfCatalogArtifact.class::isInstance)
182             .findAny().isEmpty();
183         return !csarCatalogArtifacts.isEmpty() && !babelIsEmpty;
184     }
185
186     private List<Artifact> processModelQuerySpecArtifact(IDistributionClientDownloadResult downloadResult) throws BabelArtifactParsingException {
187         logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Processing named query artifact.");
188
189         IModelParser parser = new NamedQueryArtifactParser();
190
191         List<Artifact> parsedArtifacts =
192                 parser.parse(new String(downloadResult.getArtifactPayload()), downloadResult.getArtifactFilename());
193
194         if (parsedArtifacts != null && !parsedArtifacts.isEmpty()) {
195             return parsedArtifacts;
196         } else {
197             throw new BabelArtifactParsingException(
198                     "Could not parse generated XML: " + new String(downloadResult.getArtifactPayload()));
199         }
200     }
201 }