Refactor for Sonar smells and code coverage
[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.Base64;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.stream.Collectors;
29 import org.onap.aai.babel.service.data.BabelArtifact;
30 import org.onap.aai.babel.service.data.BabelArtifact.ArtifactType;
31 import org.onap.aai.cl.api.Logger;
32 import org.onap.aai.cl.eelf.LoggerFactory;
33 import org.onap.aai.cl.mdc.MdcContext;
34 import org.onap.aai.cl.mdc.MdcOverride;
35 import org.onap.aai.modelloader.config.ModelLoaderConfig;
36 import org.onap.aai.modelloader.entity.Artifact;
37 import org.onap.aai.modelloader.entity.model.BabelArtifactParsingException;
38 import org.onap.aai.modelloader.entity.model.IModelParser;
39 import org.onap.aai.modelloader.entity.model.NamedQueryArtifactParser;
40 import org.onap.aai.modelloader.extraction.InvalidArchiveException;
41 import org.onap.aai.modelloader.restclient.BabelServiceClient;
42 import org.onap.aai.modelloader.restclient.BabelServiceClientException;
43 import org.onap.aai.modelloader.service.BabelServiceClientFactory;
44 import org.onap.aai.modelloader.service.ModelLoaderMsgs;
45 import org.onap.sdc.api.IDistributionClient;
46 import org.onap.sdc.api.notification.IArtifactInfo;
47 import org.onap.sdc.api.notification.INotificationData;
48 import org.onap.sdc.api.results.IDistributionClientDownloadResult;
49 import org.onap.sdc.utils.ArtifactTypeEnum;
50 import org.onap.sdc.utils.DistributionActionResultEnum;
51
52 /**
53  * This class is responsible for downloading the artifacts from the ASDC.
54  *
55  * The downloads can be TOSCA_CSAR files or VNF_CATALOG files.
56  *
57  * The status of the download is published. The status of the extraction of yml files from a TOSCA_CSAR file is also
58  * published as a deployment event.
59  *
60  * TOSCA_CSAR file artifacts will be converted into XML and returned as model artifacts.
61  */
62 public class ArtifactDownloadManager {
63
64     private static Logger logger = LoggerFactory.getInstance().getLogger(ArtifactDownloadManager.class);
65
66     private IDistributionClient client;
67     private NotificationPublisher notificationPublisher;
68     private BabelArtifactConverter babelArtifactConverter;
69     private ModelLoaderConfig config;
70     private BabelServiceClientFactory clientFactory;
71
72     public ArtifactDownloadManager(IDistributionClient client, ModelLoaderConfig config,
73             BabelServiceClientFactory clientFactory) {
74         this.client = client;
75         this.config = config;
76         this.clientFactory = clientFactory;
77     }
78
79     /**
80      * This method downloads the artifacts from the ASDC.
81      *
82      * @param data data about the notification that is being processed
83      * @param artifacts the specific artifacts found in the data.
84      * @param modelArtifacts collection of artifacts for model query specs
85      * @param catalogArtifacts collection of artifacts that represent vnf catalog files
86      * @return boolean <code>true</code> if the download process was successful otherwise <code>false</code>
87      */
88     boolean downloadArtifacts(INotificationData data, List<IArtifactInfo> artifacts, List<Artifact> modelArtifacts,
89             List<Artifact> catalogArtifacts) {
90         boolean success = true;
91
92         for (IArtifactInfo artifact : artifacts) {
93             try {
94                 IDistributionClientDownloadResult downloadResult = downloadIndividualArtifacts(data, artifact);
95                 processDownloadedArtifacts(modelArtifacts, catalogArtifacts, artifact, downloadResult, data);
96             } catch (DownloadFailureException e) {
97                 getNotificationPublisher().publishDownloadFailure(client, data, artifact, e.getMessage());
98                 success = false;
99             } catch (Exception e) {
100                 getNotificationPublisher().publishDeployFailure(client, data, artifact);
101                 success = false;
102             }
103
104             if (!success) {
105                 break;
106             }
107         }
108
109         return success;
110     }
111
112     private IDistributionClientDownloadResult downloadIndividualArtifacts(INotificationData data,
113             IArtifactInfo artifact) throws DownloadFailureException {
114         // Grab the current time so we can measure the download time for the metrics log
115         DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
116         MdcOverride override = new MdcOverride();
117         override.addAttribute(MdcContext.MDC_START_TIME, ZonedDateTime.now().format(formatter));
118
119         IDistributionClientDownloadResult downloadResult = client.download(artifact);
120
121         logger.info(ModelLoaderMsgs.DOWNLOAD_COMPLETE, downloadResult.getDistributionActionResult().toString(),
122                 downloadResult.getArtifactPayload() == null ? "null"
123                         : Base64.getEncoder().encodeToString(downloadResult.getArtifactPayload()));
124
125         if (DistributionActionResultEnum.SUCCESS.equals(downloadResult.getDistributionActionResult())) {
126             logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Downloaded artifact: " + artifact.getArtifactName());
127             getNotificationPublisher().publishDownloadSuccess(client, data, artifact);
128         } else {
129             throw new DownloadFailureException(downloadResult.getDistributionMessageResult());
130         }
131
132         return downloadResult;
133     }
134
135     private void processDownloadedArtifacts(List<Artifact> modelArtifacts, List<Artifact> catalogArtifacts,
136             IArtifactInfo artifactInfo, IDistributionClientDownloadResult downloadResult, INotificationData data)
137             throws ProcessToscaArtifactsException, InvalidArchiveException, BabelArtifactParsingException {
138         if ("TOSCA_CSAR".equalsIgnoreCase(artifactInfo.getArtifactType())) {
139             processToscaArtifacts(modelArtifacts, catalogArtifacts, downloadResult.getArtifactPayload(), artifactInfo,
140                     data.getDistributionID(), data.getServiceVersion());
141         } else if (ArtifactTypeEnum.MODEL_QUERY_SPEC.toString().equalsIgnoreCase(artifactInfo.getArtifactType())) {
142             processModelQuerySpecArtifact(modelArtifacts, downloadResult);
143         } else {
144             logger.info(ModelLoaderMsgs.UNSUPPORTED_ARTIFACT_TYPE, artifactInfo.getArtifactName(),
145                     artifactInfo.getArtifactType());
146             throw new InvalidArchiveException("Unsupported artifact type: " + artifactInfo.getArtifactType());
147         }
148     }
149
150     public void processToscaArtifacts(List<Artifact> modelArtifacts, List<Artifact> catalogArtifacts, byte[] payload,
151             IArtifactInfo artifactInfo, String distributionId, String serviceVersion)
152             throws ProcessToscaArtifactsException {
153         try {
154             BabelServiceClient babelClient = createBabelServiceClient(artifactInfo, serviceVersion);
155
156             logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT,
157                     "Posting artifact: " + artifactInfo.getArtifactName() + ", version: " + serviceVersion);
158
159             List<BabelArtifact> babelArtifacts =
160                     babelClient.postArtifact(payload, artifactInfo.getArtifactName(), serviceVersion, distributionId);
161
162             // Sort Babel artifacts based on type
163             Map<ArtifactType, List<BabelArtifact>> artifactMap =
164                     babelArtifacts.stream().collect(Collectors.groupingBy(BabelArtifact::getType));
165
166             if (artifactMap.containsKey(BabelArtifact.ArtifactType.MODEL)) {
167                 modelArtifacts.addAll(
168                         getBabelArtifactConverter().convertToModel(artifactMap.get(BabelArtifact.ArtifactType.MODEL)));
169                 artifactMap.remove(BabelArtifact.ArtifactType.MODEL);
170             }
171
172             if (artifactMap.containsKey(BabelArtifact.ArtifactType.VNFCATALOG)) {
173                 catalogArtifacts.addAll(getBabelArtifactConverter()
174                         .convertToCatalog(artifactMap.get(BabelArtifact.ArtifactType.VNFCATALOG)));
175                 artifactMap.remove(BabelArtifact.ArtifactType.VNFCATALOG);
176             }
177
178             // Log unexpected artifact types
179             if (!artifactMap.isEmpty()) {
180                 logger.warn(ModelLoaderMsgs.ARTIFACT_PARSE_ERROR,
181                         artifactInfo.getArtifactName() + " " + serviceVersion
182                                 + ". Unexpected artifact types returned by the babel service: "
183                                 + artifactMap.keySet().toString());
184             }
185
186         } catch (BabelArtifactParsingException e) {
187             logger.error(ModelLoaderMsgs.ARTIFACT_PARSE_ERROR,
188                     "Error for artifact " + artifactInfo.getArtifactName() + " " + serviceVersion + e);
189             throw new ProcessToscaArtifactsException(
190                     "An error occurred while trying to parse the Babel artifacts: " + e.getLocalizedMessage());
191         } catch (Exception e) {
192             logger.error(ModelLoaderMsgs.BABEL_REST_REQUEST_ERROR, e, "POST", config.getBabelBaseUrl(),
193                     "Error posting artifact " + artifactInfo.getArtifactName() + " " + serviceVersion + " to Babel: "
194                             + e.getLocalizedMessage());
195             throw new ProcessToscaArtifactsException(
196                     "An error occurred while calling the Babel service: " + e.getLocalizedMessage());
197         }
198     }
199
200     BabelServiceClient createBabelServiceClient(IArtifactInfo artifact, String serviceVersion)
201             throws ProcessToscaArtifactsException {
202         BabelServiceClient babelClient;
203         try {
204             logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Creating Babel client");
205             babelClient = clientFactory.create(config);
206         } catch (BabelServiceClientException e) {
207             logger.error(ModelLoaderMsgs.BABEL_REST_REQUEST_ERROR, e, "POST", config.getBabelBaseUrl(),
208                     "Error posting artifact " + artifact.getArtifactName() + " " + serviceVersion + " to Babel: "
209                             + e.getLocalizedMessage());
210             throw new ProcessToscaArtifactsException(
211                     "An error occurred tyring to convert the tosca artifacts to xml artifacts: "
212                             + e.getLocalizedMessage());
213         }
214
215         return babelClient;
216     }
217
218     private void processModelQuerySpecArtifact(List<Artifact> modelArtifacts,
219             IDistributionClientDownloadResult downloadResult) throws BabelArtifactParsingException {
220         logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Processing named query artifact.");
221
222         IModelParser parser = new NamedQueryArtifactParser();
223
224         List<Artifact> parsedArtifacts =
225                 parser.parse(new String(downloadResult.getArtifactPayload()), downloadResult.getArtifactFilename());
226
227         if (parsedArtifactsExist(parsedArtifacts)) {
228             modelArtifacts.addAll(parsedArtifacts);
229         } else {
230             throw new BabelArtifactParsingException(
231                     "Could not parse generated XML: " + new String(downloadResult.getArtifactPayload()));
232         }
233     }
234
235     private boolean parsedArtifactsExist(List<Artifact> parsedArtifacts) {
236         return parsedArtifacts != null && !parsedArtifacts.isEmpty();
237     }
238
239     private NotificationPublisher getNotificationPublisher() {
240         if (notificationPublisher == null) {
241             notificationPublisher = new NotificationPublisher();
242         }
243
244         return notificationPublisher;
245     }
246
247     private BabelArtifactConverter getBabelArtifactConverter() {
248         if (babelArtifactConverter == null) {
249             babelArtifactConverter = new BabelArtifactConverter();
250         }
251
252         return babelArtifactConverter;
253     }
254 }