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