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