Merge of new rebased code
[appc.git] / appc-asdc-listener / appc-asdc-listener-bundle / src / main / java / org / openecomp / appc / sdc / listener / DownloadAndStoreOp.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * openECOMP : APP-C
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights
6  *                                              reserved.
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
22 package org.openecomp.appc.sdc.listener;
23
24 import org.openecomp.appc.adapter.message.EventSender;
25 import org.openecomp.appc.adapter.message.MessageDestination;
26 import org.openecomp.appc.adapter.message.event.EventHeader;
27 import org.openecomp.appc.adapter.message.event.EventMessage;
28 import org.openecomp.appc.adapter.message.event.EventStatus;
29 import org.openecomp.appc.exceptions.APPCException;
30 import org.openecomp.appc.licmgr.Constants;
31 import org.openecomp.appc.licmgr.LicenseManager;
32 import org.openecomp.sdc.api.IDistributionClient;
33 import org.openecomp.sdc.api.notification.IArtifactInfo;
34 import org.openecomp.sdc.api.notification.INotificationData;
35 import org.openecomp.sdc.api.notification.IResourceInstance;
36 import org.openecomp.sdc.api.results.IDistributionClientDownloadResult;
37 import org.openecomp.sdc.utils.DistributionActionResultEnum;
38 import org.openecomp.sdc.utils.DistributionStatusEnum;
39 import com.att.eelf.configuration.EELFLogger;
40 import com.att.eelf.configuration.EELFManager;
41 import org.osgi.framework.BundleContext;
42 import org.osgi.framework.FrameworkUtil;
43 import org.osgi.framework.ServiceReference;
44
45 import static org.openecomp.appc.licmgr.Constants.ASDC_ARTIFACTS_FIELDS.*;
46
47 import java.io.UnsupportedEncodingException;
48 import java.net.MalformedURLException;
49 import java.net.URI;
50 import java.text.DateFormat;
51 import java.text.SimpleDateFormat;
52 import java.util.Date;
53 import java.util.HashMap;
54 import java.util.Map;
55
56 @SuppressWarnings("JavaDoc")
57 public class DownloadAndStoreOp implements Runnable {
58
59     public static final String PAYLOAD_CHARSET = "UTF-8";
60
61     private static final String DATE_FORMAT = "yyyy/MM/dd HH:mm:ss";
62
63     private final EELFLogger logger = EELFManager.getInstance().getLogger(DownloadAndStoreOp.class);
64
65     private IDistributionClient client;
66     private EventSender eventSender;
67
68     private INotificationData notification;
69     private IResourceInstance resource;
70     private IArtifactInfo artifact;
71
72     private URI storeUri;
73
74     public DownloadAndStoreOp(IDistributionClient client, EventSender eventSender, INotificationData notification, IResourceInstance resource,
75                               IArtifactInfo artifact, URI storeUri) {
76         this.client = client;
77         this.eventSender = eventSender;
78         this.notification = notification;
79         this.resource = resource;
80         this.artifact = artifact;
81         this.storeUri = storeUri;
82     }
83
84     @Override
85     public void run() {
86         logger.info(String.format("Attempting to download artifact %s", artifact));
87         // Download artifact
88         IDistributionClientDownloadResult download = client.download(artifact);
89         logger.info(String.format("Download of artifact %s completed with status %s", artifact.getArtifactUUID(), download));
90
91         // Notify of download status
92         if (download.getDistributionActionResult() != DistributionActionResultEnum.SUCCESS) {
93             client.sendDownloadStatus(Util.buildDistributionStatusMessage(client, notification, artifact,
94                             DistributionStatusEnum.DOWNLOAD_ERROR), download.getDistributionMessageResult());
95             sendDCAEEvent(notification.getDistributionID(), notification.getServiceName(), notification.getServiceVersion(), "Download is failed.");
96             return;
97         }
98
99         client.sendDownloadStatus(Util.buildDistributionStatusMessage(client, notification, artifact, DistributionStatusEnum.DOWNLOAD_OK));
100
101         String data = null;
102         try {
103             if (download.getArtifactPayload() != null) {
104                 data = new String(download.getArtifactPayload(), PAYLOAD_CHARSET);
105             }
106         } catch (UnsupportedEncodingException e) {
107             e.printStackTrace();
108         }
109
110         boolean providerSuccess = false;
111         String providerReason = "Unknown Error";
112         // Send data to provider
113         if (data != null && artifact != null) {
114             switch(artifact.getArtifactType()) {
115                 case "APPC_CONFIG":
116                     String postData = Util.toAsdcStoreDocumentInput(notification, resource, artifact, data);
117                     try {
118                         ProviderResponse result = ProviderOperations.post(storeUri.toURL(), postData, null);
119                         if (result.getStatus() == 200) {
120                             providerSuccess = Util.parseResponse(result.getBody());
121                             providerReason = "Success";
122                         }
123                     } catch (MalformedURLException | APPCException e) {
124                         providerReason = e.getMessage();
125                         e.printStackTrace();
126                     }
127                     break;
128
129                 case "VF_LICENSE":
130                     BundleContext bctx = FrameworkUtil.getBundle(this.getClass()).getBundleContext();
131                     ServiceReference srefLicenseService = bctx.getServiceReference(LicenseManager.class);
132                     LicenseManager licenseService = (LicenseManager) bctx.getService(srefLicenseService);
133
134                     Map<String, String> artifactPayload = prepareArtifactPayloadParamsMap(data);
135
136                     String vnfType = artifactPayload.get(RESOURCE_NAME.name());
137                     String version = artifactPayload.get(RESOURCE_VERSION.name());
138                     String packageArtifactID = artifactPayload.get(ARTIFACT_UUID.name());
139
140                     try {
141                         if (null == vnfType || null == version || null == packageArtifactID || vnfType.isEmpty() || version.isEmpty() || packageArtifactID.isEmpty()) {
142                             throw new APPCException(String.format("Missing information in ASDC request. Details: resource_type='%s', resource_version='%s', artifactID='%s'", vnfType, version, packageArtifactID));
143                         }
144
145                         Map<String, String> existingArtifactPayload = licenseService.retrieveLicenseModelData(vnfType, version);
146
147                         if (existingArtifactPayload.isEmpty()) { // new resource
148                             licenseService.storeArtifactPayload(artifactPayload);
149                         } else { // duplicate
150                             logger.warn(String.format("Artifact of type '%s' already deployed for resource_type='%s' and resource_version='%s'", Constants.VF_LICENSE, vnfType, version));
151                         }
152
153                         providerSuccess = true;
154
155                     } catch (Exception e) {
156                         providerSuccess = false;
157                         providerReason = e.getMessage();
158                     }
159                     break;
160
161                 default:
162                     throw new UnsupportedOperationException("Artifact type " + artifact.getArtifactType() + " is not supported");
163             }
164
165         }
166
167         // Notify of provider's response
168         if (providerSuccess) {
169             client.sendDeploymentStatus(
170                             Util.buildDistributionStatusMessage(client, notification, artifact, DistributionStatusEnum.DEPLOY_OK));
171         } else {
172             client.sendDeploymentStatus(Util.buildDistributionStatusMessage(client, notification, artifact,
173                             DistributionStatusEnum.DEPLOY_ERROR), providerReason);
174             sendDCAEEvent(notification.getDistributionID(), notification.getServiceName(), notification.getServiceVersion(), providerReason);
175         }
176
177     }
178
179     /**
180      * Prepares Artifact Payload params map
181      * @param data
182      * @return Map<String,String>
183      */
184     private Map<String, String> prepareArtifactPayloadParamsMap(String data) {
185         Map<String, String> paramsMap = new HashMap<>();
186
187         paramsMap.put(SERVICE_UUID.name(), this.notification.getServiceUUID());
188         paramsMap.put(DISTRIBUTION_ID.name(), this.notification.getDistributionID());
189         paramsMap.put(SERVICE_NAME.name(), this.notification.getServiceName());
190         paramsMap.put(SERVICE_DESCRIPTION.name(), this.notification.getServiceDescription());
191         paramsMap.put(RESOURCE_UUID.name(), this.resource.getResourceUUID());
192         paramsMap.put(RESOURCE_INSTANCE_NAME.name(), this.resource.getResourceInstanceName());
193         paramsMap.put(RESOURCE_NAME.name(), this.resource.getResourceName());
194         paramsMap.put(RESOURCE_VERSION.name(), this.resource.getResourceVersion());
195         paramsMap.put(RESOURCE_TYPE.name(), this.resource.getResourceType());
196         paramsMap.put(ARTIFACT_UUID.name(), this.artifact.getArtifactUUID());
197         paramsMap.put(ARTIFACT_TYPE.name(), this.artifact.getArtifactType());
198         paramsMap.put(ARTIFACT_VERSION.name(), this.artifact.getArtifactVersion());
199         paramsMap.put(ARTIFACT_DESCRIPTION.name(), this.artifact.getArtifactDescription());
200         paramsMap.put(CREATION_DATE.name(), getCurrentDateTime());
201         paramsMap.put(ARTIFACT_NAME.name(), this.artifact.getArtifactName());
202         paramsMap.put(ARTIFACT_CONTENT.name(), data);
203
204         return paramsMap;
205     }
206
207
208     private String getCurrentDateTime() {
209         DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
210         Date date = new Date();
211         return dateFormat.format(date);
212     }
213
214     private void sendDCAEEvent(String distributionID, String serviceName, String serviceVersion, String errorMessage) {
215         if (null == eventSender) return;
216         String errorDescription = String.format("ASDC distribution of service '%s', version '%s' is failed with reason: '%s'",
217                         serviceName, serviceVersion, errorMessage);
218
219         EventMessage eventMessage = new EventMessage(
220                         new EventHeader((new java.util.Date()).toString(), serviceVersion, distributionID),
221                         new EventStatus(401, errorDescription));
222
223         eventSender.sendEvent(MessageDestination.DCAE, eventMessage);
224     }
225
226 }