3b32315478aa6c17c2be3e7f35b058ab8caec415
[aai/model-loader.git] / src / main / java / org / openecomp / modelloader / notification / EventCallback.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * MODEL LOADER SERVICE
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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
21 package org.openecomp.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
35 import org.openecomp.cl.api.Logger;
36 import org.openecomp.cl.eelf.LoggerFactory;
37 import org.openecomp.cl.mdc.MdcContext;
38 import org.openecomp.cl.mdc.MdcOverride;
39 import org.openecomp.modelloader.config.ModelLoaderConfig;
40 import org.openecomp.modelloader.entity.Artifact;
41 import org.openecomp.modelloader.entity.catalog.VnfCatalogArtifact;
42 import org.openecomp.modelloader.entity.catalog.VnfCatalogArtifactHandler;
43 import org.openecomp.modelloader.entity.model.ModelArtifactHandler;
44 import org.openecomp.modelloader.entity.model.ModelArtifactParser;
45 import org.openecomp.modelloader.service.ModelLoaderMsgs;
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     ModelArtifactParser modelArtParser = new ModelArtifactParser();
84
85     for (IArtifactInfo artifact : artifacts) {
86       // Grab the current time so we can measure the download time for the
87       // metrics log
88       long startTimeInMs = System.currentTimeMillis();
89       MdcOverride override = new MdcOverride();
90       override.addAttribute(MdcContext.MDC_START_TIME, dateFormatter.format(startTimeInMs));
91
92       // Download Artifact
93       IDistributionClientDownloadResult downloadResult = client.download(artifact);
94
95       // Generate metrics log
96       metricsLogger.info(ModelLoaderMsgs.DOWNLOAD_COMPLETE, null, override,
97           artifact.getArtifactName(), downloadResult.getDistributionActionResult().toString());
98
99       if (downloadResult.getDistributionActionResult() != DistributionActionResultEnum.SUCCESS) {
100         publishDownloadFailure(data, artifact, downloadResult.getDistributionMessageResult());
101         success = false;
102         break;
103       }
104
105       logger.debug("Artifact: " + artifact.getArtifactName() + "  Payload:\n" + new String(downloadResult.getArtifactPayload()));
106       
107       publishDownloadSuccess(data, artifact, downloadResult);
108
109       if ((artifact.getArtifactType()
110           .compareToIgnoreCase(ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.toString()) == 0)
111           || (artifact.getArtifactType()
112               .compareToIgnoreCase(ArtifactTypeEnum.MODEL_QUERY_SPEC.toString()) == 0)) {
113         modelArtifacts.addAll(modelArtParser.parse(downloadResult.getArtifactPayload(),
114             downloadResult.getArtifactName()));
115       } else if (artifact.getArtifactType()
116           .compareToIgnoreCase(ArtifactTypeEnum.VNF_CATALOG.toString()) == 0) {
117         catalogArtifacts
118             .add(new VnfCatalogArtifact(new String(downloadResult.getArtifactPayload())));
119       }
120     }
121
122     String statusString = "SUCCESS";
123     if (success) {
124       ModelArtifactHandler modelHandler = new ModelArtifactHandler(config);
125       boolean modelDeploySuccess = modelHandler.pushArtifacts(modelArtifacts,
126           data.getDistributionID());
127
128       VnfCatalogArtifactHandler catalogHandler = new VnfCatalogArtifactHandler(config);
129       boolean catalogDeploySuccess = catalogHandler.pushArtifacts(catalogArtifacts,
130           data.getDistributionID());
131
132       for (IArtifactInfo artifact : artifacts) {
133         if ((artifact.getArtifactType()
134             .compareToIgnoreCase(ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.toString()) == 0)
135             || (artifact.getArtifactType()
136                 .compareToIgnoreCase(ArtifactTypeEnum.MODEL_QUERY_SPEC.toString()) == 0)) {
137           if (modelDeploySuccess) {
138             publishDeploySuccess(data, artifact);
139           } else {
140             publishDeployFailure(data, artifact);
141             statusString = "FAILURE";
142           }
143         } else if (artifact.getArtifactType()
144             .compareToIgnoreCase(ArtifactTypeEnum.VNF_CATALOG.toString()) == 0) {
145           if (catalogDeploySuccess) {
146             publishDeploySuccess(data, artifact);
147           } else {
148             publishDeployFailure(data, artifact);
149             statusString = "FAILURE";
150           }
151         }
152       }
153     }
154
155     auditLogger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT,
156         "Processed distribution " + data.getDistributionID() + "  (" + statusString + ")");
157     MDC.clear();
158   }
159
160   private List<IArtifactInfo> getArtifacts(INotificationData data) {
161     List<IArtifactInfo> artifacts = new ArrayList<IArtifactInfo>();
162     List<IResourceInstance> resources = data.getResources();
163
164     if (data.getServiceArtifacts() != null) {
165       artifacts.addAll(data.getServiceArtifacts());
166     }
167
168     if (resources != null) {
169       for (IResourceInstance resource : resources) {
170         if (resource.getArtifacts() != null) {
171           artifacts.addAll(resource.getArtifacts());
172         }
173       }
174     }
175
176     return artifacts;
177   }
178
179   private void publishDownloadFailure(INotificationData data, IArtifactInfo artifact,
180       String errorMessage) {
181     // Grab the current time so we can measure the download time for the metrics
182     // log
183     long startTimeInMs = System.currentTimeMillis();
184     MdcOverride override = new MdcOverride();
185     override.addAttribute(MdcContext.MDC_START_TIME, dateFormatter.format(startTimeInMs));
186
187     IDistributionClientResult sendDownloadStatus = client.sendDownloadStatus(
188         buildStatusMessage(client, data, artifact, DistributionStatusEnum.DOWNLOAD_ERROR));
189     metricsLogger.info(ModelLoaderMsgs.EVENT_PUBLISHED, null, override, "download failure",
190         artifact.getArtifactName(), sendDownloadStatus.getDistributionActionResult().toString());
191
192     if (sendDownloadStatus.getDistributionActionResult() != DistributionActionResultEnum.SUCCESS) {
193       logger.error(ModelLoaderMsgs.DISTRIBUTION_EVENT_ERROR,
194           "Failed to publish download failure status: "
195               + sendDownloadStatus.getDistributionMessageResult());
196     }
197
198     logger.error(ModelLoaderMsgs.DISTRIBUTION_EVENT_ERROR,
199         "Failed to download artifact " + artifact.getArtifactName() + ": " + errorMessage);
200   }
201
202   private void publishDownloadSuccess(INotificationData data, IArtifactInfo artifact,
203       IDistributionClientDownloadResult downloadResult) {
204     // Grab the current time so we can measure the download time for the metrics
205     // log
206     long startTimeInMs = System.currentTimeMillis();
207     MdcOverride override = new MdcOverride();
208     override.addAttribute(MdcContext.MDC_START_TIME, dateFormatter.format(startTimeInMs));
209
210     IDistributionClientResult sendDownloadStatus = client.sendDownloadStatus(
211         buildStatusMessage(client, data, artifact, DistributionStatusEnum.DOWNLOAD_OK));
212     metricsLogger.info(ModelLoaderMsgs.EVENT_PUBLISHED, null, override, "download success",
213         artifact.getArtifactName(), sendDownloadStatus.getDistributionActionResult().toString());
214
215     logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT,
216         "Downloaded artifact: " + artifact.getArtifactName());
217
218     if (sendDownloadStatus.getDistributionActionResult() != DistributionActionResultEnum.SUCCESS) {
219       logger.error(ModelLoaderMsgs.DISTRIBUTION_EVENT_ERROR,
220           "Failed to publish download success status: "
221               + sendDownloadStatus.getDistributionMessageResult());
222     }
223
224     if (logger.isDebugEnabled()) {
225       StringBuilder sb = new StringBuilder();
226       sb.append("Downloaded artifact:\n");
227       sb.append("ArtInfo_Art_Name: " + artifact.getArtifactName());
228       sb.append("\nArtInfo_Art_description: " + artifact.getArtifactDescription());
229       sb.append("\nArtInfo_Art_CheckSum: " + artifact.getArtifactChecksum());
230       sb.append("\nArtInfo_Art_Url: " + artifact.getArtifactURL());
231       sb.append("\nArtInfo_Art_Type: " + artifact.getArtifactType());
232       sb.append("\nArtInfo_Serv_description: " + data.getServiceDescription());
233       sb.append("\nArtInfo_Serv_Name: " + data.getServiceName());
234       sb.append("\nGet_serviceVersion: " + data.getServiceVersion());
235       sb.append("\nGet_Service_UUID: " + data.getServiceUUID());
236       sb.append("\nArtInfo_DistributionId: " + data.getDistributionID());
237       logger.debug(sb.toString());
238     }
239   }
240
241   private void publishDeployFailure(INotificationData data, IArtifactInfo artifact) {
242     // Grab the current time so we can measure the download time for the metrics
243     // log
244     long startTimeInMs = System.currentTimeMillis();
245     MdcOverride override = new MdcOverride();
246     override.addAttribute(MdcContext.MDC_START_TIME, dateFormatter.format(startTimeInMs));
247
248     IDistributionClientResult sendStatus = client.sendDeploymentStatus(
249         buildStatusMessage(client, data, artifact, DistributionStatusEnum.DEPLOY_ERROR));
250     metricsLogger.info(ModelLoaderMsgs.EVENT_PUBLISHED, null, override, "deploy failure",
251         artifact.getArtifactName(), sendStatus.getDistributionActionResult().toString());
252
253     if (sendStatus.getDistributionActionResult() != DistributionActionResultEnum.SUCCESS) {
254       logger.error(ModelLoaderMsgs.DISTRIBUTION_EVENT_ERROR,
255           "Failed to publish deploy failure status: " + sendStatus.getDistributionMessageResult());
256     }
257   }
258
259   private void publishDeploySuccess(INotificationData data, IArtifactInfo artifact) {
260     // Grab the current time so we can measure the download time for the metrics
261     // log
262     long startTimeInMs = System.currentTimeMillis();
263     MdcOverride override = new MdcOverride();
264     override.addAttribute(MdcContext.MDC_START_TIME, dateFormatter.format(startTimeInMs));
265
266     IDistributionClientResult sendStatus = client.sendDownloadStatus(
267         buildStatusMessage(client, data, artifact, DistributionStatusEnum.DEPLOY_OK));
268     metricsLogger.info(ModelLoaderMsgs.EVENT_PUBLISHED, null, override, "deploy success",
269         artifact.getArtifactName(), sendStatus.getDistributionActionResult().toString());
270
271     if (sendStatus.getDistributionActionResult() != DistributionActionResultEnum.SUCCESS) {
272       logger.error(ModelLoaderMsgs.DISTRIBUTION_EVENT_ERROR,
273           "Failed to publish deploy success status: " + sendStatus.getDistributionMessageResult());
274     }
275   }
276
277   private IDistributionStatusMessage buildStatusMessage(IDistributionClient client,
278       INotificationData data, IArtifactInfo artifact, DistributionStatusEnum status) {
279     IDistributionStatusMessage statusMessage = new DistributionStatusMsg(status,
280         data.getDistributionID(), client.getConfiguration().getConsumerID(),
281         artifact.getArtifactURL());
282
283     return statusMessage;
284   }
285
286 }