Allow handling of legact model artifacts
[aai/model-loader.git] / src / main / java / org / openecomp / modelloader / notification / EventCallback.java
1 /**
2  * ============LICENSE_START=======================================================
3  * Model Loader
4  * ================================================================================
5  * Copyright © 2017 AT&T Intellectual Property.
6  * Copyright © 2017 Amdocs
7  * All rights reserved.
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  * http://www.apache.org/licenses/LICENSE-2.0
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  *
20  * ECOMP and OpenECOMP are trademarks
21  * and service marks of AT&T Intellectual Property.
22  */
23 package org.openecomp.modelloader.notification;
24
25 import org.openecomp.sdc.api.IDistributionClient;
26 import org.openecomp.sdc.api.consumer.IDistributionStatusMessage;
27 import org.openecomp.sdc.api.consumer.INotificationCallback;
28 import org.openecomp.sdc.api.notification.IArtifactInfo;
29 import org.openecomp.sdc.api.notification.INotificationData;
30 import org.openecomp.sdc.api.notification.IResourceInstance;
31 import org.openecomp.sdc.api.results.IDistributionClientDownloadResult;
32 import org.openecomp.sdc.api.results.IDistributionClientResult;
33 import org.openecomp.sdc.utils.ArtifactTypeEnum;
34 import org.openecomp.sdc.utils.DistributionActionResultEnum;
35 import org.openecomp.sdc.utils.DistributionStatusEnum;
36
37 import org.openecomp.cl.api.Logger;
38 import org.openecomp.cl.eelf.LoggerFactory;
39 import org.openecomp.cl.mdc.MdcContext;
40 import org.openecomp.cl.mdc.MdcOverride;
41 import org.openecomp.modelloader.config.ModelLoaderConfig;
42 import org.openecomp.modelloader.entity.Artifact;
43 import org.openecomp.modelloader.entity.catalog.VnfCatalogArtifact;
44 import org.openecomp.modelloader.entity.catalog.VnfCatalogArtifactHandler;
45 import org.openecomp.modelloader.entity.model.IModelParser;
46 import org.openecomp.modelloader.entity.model.ModelArtifactHandler;
47 import org.openecomp.modelloader.entity.model.ModelParserFactory;
48 import org.openecomp.modelloader.service.ModelLoaderMsgs;
49 import org.slf4j.MDC;
50
51 import java.text.SimpleDateFormat;
52 import java.util.ArrayList;
53 import java.util.List;
54
55 public class EventCallback implements INotificationCallback {
56
57   private IDistributionClient client;
58   private ModelLoaderConfig config;
59   private static Logger logger = LoggerFactory.getInstance()
60       .getLogger(EventCallback.class.getName());
61   private static Logger auditLogger = LoggerFactory.getInstance()
62       .getAuditLogger(EventCallback.class.getName());
63   private static Logger metricsLogger = LoggerFactory.getInstance()
64       .getMetricsLogger(EventCallback.class.getName());
65
66   private static SimpleDateFormat dateFormatter = new SimpleDateFormat(
67       "yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
68
69   public EventCallback(IDistributionClient client, ModelLoaderConfig config) {
70     this.client = client;
71     this.config = config;
72   }
73
74   @Override
75   public void activateCallback(INotificationData data) {
76     // Init MDC
77     MdcContext.initialize(data.getDistributionID(), "ModelLoader", "", "Event-Bus", "");
78
79     logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT,
80         "Received distribution " + data.getDistributionID());
81
82     boolean success = true;
83     List<IArtifactInfo> artifacts = getArtifacts(data);
84     List<Artifact> modelArtifacts = new ArrayList<Artifact>();
85     List<Artifact> catalogArtifacts = new ArrayList<Artifact>();
86
87     for (IArtifactInfo artifact : artifacts) {
88       // Grab the current time so we can measure the download time for the
89       // metrics log
90       long startTimeInMs = System.currentTimeMillis();
91       MdcOverride override = new MdcOverride();
92       override.addAttribute(MdcContext.MDC_START_TIME, dateFormatter.format(startTimeInMs));
93
94       // Download Artifact
95       IDistributionClientDownloadResult downloadResult = client.download(artifact);
96
97       // Generate metrics log
98       metricsLogger.info(ModelLoaderMsgs.DOWNLOAD_COMPLETE, null, override,
99           artifact.getArtifactName(), downloadResult.getDistributionActionResult().toString());
100
101       if (downloadResult.getDistributionActionResult() != DistributionActionResultEnum.SUCCESS) {
102         publishDownloadFailure(data, artifact, downloadResult.getDistributionMessageResult());
103         success = false;
104         break;
105       }
106
107       logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT,
108                 "Downloaded artifact: " + artifact.getArtifactName() + "  Payload:\n" + new String(downloadResult.getArtifactPayload()));
109       
110       publishDownloadSuccess(data, artifact, downloadResult);
111
112       if ((artifact.getArtifactType().compareToIgnoreCase(ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.toString()) == 0)
113           || (artifact.getArtifactType().compareToIgnoreCase(ArtifactTypeEnum.MODEL_QUERY_SPEC.toString()) == 0)) {
114         IModelParser parser = ModelParserFactory.createModelParser(downloadResult.getArtifactPayload(), downloadResult.getArtifactName());
115         List<Artifact> parsedArtifacts = parser.parse(downloadResult.getArtifactPayload(), downloadResult.getArtifactName());
116         if (parsedArtifacts != null && !parsedArtifacts.isEmpty()) {
117           modelArtifacts.addAll(parsedArtifacts);
118         } else {
119           success = false;
120           publishDeployFailure(data, artifact);
121           break;
122         }
123       } else if (artifact.getArtifactType()
124           .compareToIgnoreCase(ArtifactTypeEnum.VNF_CATALOG.toString()) == 0) {
125         catalogArtifacts
126             .add(new VnfCatalogArtifact(new String(downloadResult.getArtifactPayload())));
127       }
128     }
129
130     String statusString = "SUCCESS";
131     if (success) {
132       ModelArtifactHandler modelHandler = new ModelArtifactHandler(config);
133       boolean modelDeploySuccess = modelHandler.pushArtifacts(modelArtifacts,
134           data.getDistributionID());
135
136       VnfCatalogArtifactHandler catalogHandler = new VnfCatalogArtifactHandler(config);
137       boolean catalogDeploySuccess = catalogHandler.pushArtifacts(catalogArtifacts,
138           data.getDistributionID());
139
140       for (IArtifactInfo artifact : artifacts) {
141         if ((artifact.getArtifactType()
142             .compareToIgnoreCase(ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.toString()) == 0)
143             || (artifact.getArtifactType()
144                 .compareToIgnoreCase(ArtifactTypeEnum.MODEL_QUERY_SPEC.toString()) == 0)) {
145           if (modelDeploySuccess) {
146             publishDeploySuccess(data, artifact);
147           } else {
148             publishDeployFailure(data, artifact);
149             statusString = "FAILURE";
150           }
151         } else if (artifact.getArtifactType()
152             .compareToIgnoreCase(ArtifactTypeEnum.VNF_CATALOG.toString()) == 0) {
153           if (catalogDeploySuccess) {
154             publishDeploySuccess(data, artifact);
155           } else {
156             publishDeployFailure(data, artifact);
157             statusString = "FAILURE";
158           }
159         }
160       }
161     } else {
162       statusString = "FAILURE";
163     }
164
165     auditLogger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT,
166         "Processed distribution " + data.getDistributionID() + "  (" + statusString + ")");
167     MDC.clear();
168   }
169
170   private List<IArtifactInfo> getArtifacts(INotificationData data) {
171     List<IArtifactInfo> artifacts = new ArrayList<IArtifactInfo>();
172     List<IResourceInstance> resources = data.getResources();
173
174     if (data.getServiceArtifacts() != null) {
175       artifacts.addAll(data.getServiceArtifacts());
176     }
177
178     if (resources != null) {
179       for (IResourceInstance resource : resources) {
180         if (resource.getArtifacts() != null) {
181           artifacts.addAll(resource.getArtifacts());
182         }
183       }
184     }
185
186     return artifacts;
187   }
188
189   private void publishDownloadFailure(INotificationData data, IArtifactInfo artifact,
190       String errorMessage) {
191     // Grab the current time so we can measure the download time for the metrics
192     // log
193     long startTimeInMs = System.currentTimeMillis();
194     MdcOverride override = new MdcOverride();
195     override.addAttribute(MdcContext.MDC_START_TIME, dateFormatter.format(startTimeInMs));
196
197     IDistributionClientResult sendDownloadStatus = client.sendDownloadStatus(
198         buildStatusMessage(client, data, artifact, DistributionStatusEnum.DOWNLOAD_ERROR));
199     metricsLogger.info(ModelLoaderMsgs.EVENT_PUBLISHED, null, override, "download failure",
200         artifact.getArtifactName(), sendDownloadStatus.getDistributionActionResult().toString());
201
202     if (sendDownloadStatus.getDistributionActionResult() != DistributionActionResultEnum.SUCCESS) {
203       logger.error(ModelLoaderMsgs.DISTRIBUTION_EVENT_ERROR,
204           "Failed to publish download failure status: "
205               + sendDownloadStatus.getDistributionMessageResult());
206     }
207
208     logger.error(ModelLoaderMsgs.DISTRIBUTION_EVENT_ERROR,
209         "Failed to download artifact " + artifact.getArtifactName() + ": " + errorMessage);
210   }
211
212   private void publishDownloadSuccess(INotificationData data, IArtifactInfo artifact,
213       IDistributionClientDownloadResult downloadResult) {
214     // Grab the current time so we can measure the download time for the metrics
215     // log
216     long startTimeInMs = System.currentTimeMillis();
217     MdcOverride override = new MdcOverride();
218     override.addAttribute(MdcContext.MDC_START_TIME, dateFormatter.format(startTimeInMs));
219
220     IDistributionClientResult sendDownloadStatus = client.sendDownloadStatus(
221         buildStatusMessage(client, data, artifact, DistributionStatusEnum.DOWNLOAD_OK));
222     metricsLogger.info(ModelLoaderMsgs.EVENT_PUBLISHED, null, override, "download success",
223         artifact.getArtifactName(), sendDownloadStatus.getDistributionActionResult().toString());
224
225     if (sendDownloadStatus.getDistributionActionResult() != DistributionActionResultEnum.SUCCESS) {
226       logger.error(ModelLoaderMsgs.DISTRIBUTION_EVENT_ERROR,
227           "Failed to publish download success status: "
228               + sendDownloadStatus.getDistributionMessageResult());
229     }
230
231     if (logger.isDebugEnabled()) {
232       StringBuilder sb = new StringBuilder();
233       sb.append("Downloaded artifact:\n");
234       sb.append("ArtInfo_Art_Name: " + artifact.getArtifactName());
235       sb.append("\nArtInfo_Art_description: " + artifact.getArtifactDescription());
236       sb.append("\nArtInfo_Art_CheckSum: " + artifact.getArtifactChecksum());
237       sb.append("\nArtInfo_Art_Url: " + artifact.getArtifactURL());
238       sb.append("\nArtInfo_Art_Type: " + artifact.getArtifactType());
239       sb.append("\nArtInfo_Serv_description: " + data.getServiceDescription());
240       sb.append("\nArtInfo_Serv_Name: " + data.getServiceName());
241       sb.append("\nGet_serviceVersion: " + data.getServiceVersion());
242       sb.append("\nGet_Service_UUID: " + data.getServiceUUID());
243       sb.append("\nArtInfo_DistributionId: " + data.getDistributionID());
244       logger.debug(sb.toString());
245     }
246   }
247
248   private void publishDeployFailure(INotificationData data, IArtifactInfo artifact) {
249     // Grab the current time so we can measure the download time for the metrics
250     // log
251     long startTimeInMs = System.currentTimeMillis();
252     MdcOverride override = new MdcOverride();
253     override.addAttribute(MdcContext.MDC_START_TIME, dateFormatter.format(startTimeInMs));
254
255     IDistributionClientResult sendStatus = client.sendDeploymentStatus(
256         buildStatusMessage(client, data, artifact, DistributionStatusEnum.DEPLOY_ERROR));
257     metricsLogger.info(ModelLoaderMsgs.EVENT_PUBLISHED, null, override, "deploy failure",
258         artifact.getArtifactName(), sendStatus.getDistributionActionResult().toString());
259
260     if (sendStatus.getDistributionActionResult() != DistributionActionResultEnum.SUCCESS) {
261       logger.error(ModelLoaderMsgs.DISTRIBUTION_EVENT_ERROR,
262           "Failed to publish deploy failure status: " + sendStatus.getDistributionMessageResult());
263     }
264   }
265
266   private void publishDeploySuccess(INotificationData data, IArtifactInfo artifact) {
267     // Grab the current time so we can measure the download time for the metrics
268     // log
269     long startTimeInMs = System.currentTimeMillis();
270     MdcOverride override = new MdcOverride();
271     override.addAttribute(MdcContext.MDC_START_TIME, dateFormatter.format(startTimeInMs));
272
273     IDistributionClientResult sendStatus = client.sendDownloadStatus(
274         buildStatusMessage(client, data, artifact, DistributionStatusEnum.DEPLOY_OK));
275     metricsLogger.info(ModelLoaderMsgs.EVENT_PUBLISHED, null, override, "deploy success",
276         artifact.getArtifactName(), sendStatus.getDistributionActionResult().toString());
277
278     if (sendStatus.getDistributionActionResult() != DistributionActionResultEnum.SUCCESS) {
279       logger.error(ModelLoaderMsgs.DISTRIBUTION_EVENT_ERROR,
280           "Failed to publish deploy success status: " + sendStatus.getDistributionMessageResult());
281     }
282   }
283
284   private IDistributionStatusMessage buildStatusMessage(IDistributionClient client,
285       INotificationData data, IArtifactInfo artifact, DistributionStatusEnum status) {
286     IDistributionStatusMessage statusMessage = new DistributionStatusMsg(status,
287         data.getDistributionID(), client.getConfiguration().getConsumerID(),
288         artifact.getArtifactURL());
289
290     return statusMessage;
291   }
292
293 }