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