a0449a32f08c1865aaec2ffb54010610b961291e
[clamp.git] / src / main / java / org / onap / clamp / clds / sdc / controller / SdcSingleController.java
1 /*-\r
2  * ============LICENSE_START=======================================================\r
3  * ONAP CLAMP\r
4  * ================================================================================\r
5  * Copyright (C) 2018 AT&T Intellectual Property. All rights\r
6  *                             reserved.\r
7  * ================================================================================\r
8  * Licensed under the Apache License, Version 2.0 (the "License");\r
9  * you may not use this file except in compliance with the License.\r
10  * You may obtain a copy of the License at\r
11  *\r
12  * http://www.apache.org/licenses/LICENSE-2.0\r
13  *\r
14  * Unless required by applicable law or agreed to in writing, software\r
15  * distributed under the License is distributed on an "AS IS" BASIS,\r
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
17  * See the License for the specific language governing permissions and\r
18  * limitations under the License.\r
19  * ============LICENSE_END============================================\r
20  * ===================================================================\r
21  * ECOMP is a trademark and service mark of AT&T Intellectual Property.\r
22  */\r
23 \r
24 package org.onap.clamp.clds.sdc.controller;\r
25 \r
26 import com.att.eelf.configuration.EELFLogger;\r
27 import com.att.eelf.configuration.EELFManager;\r
28 \r
29 import java.util.Date;\r
30 \r
31 import org.onap.clamp.clds.config.ClampProperties;\r
32 import org.onap.clamp.clds.config.sdc.SdcSingleControllerConfiguration;\r
33 import org.onap.clamp.clds.exception.sdc.controller.CsarHandlerException;\r
34 import org.onap.clamp.clds.exception.sdc.controller.SdcArtifactInstallerException;\r
35 import org.onap.clamp.clds.exception.sdc.controller.SdcControllerException;\r
36 import org.onap.clamp.clds.exception.sdc.controller.SdcDownloadException;\r
37 import org.onap.clamp.clds.exception.sdc.controller.SdcParametersException;\r
38 import org.onap.clamp.clds.sdc.controller.installer.CsarHandler;\r
39 import org.onap.clamp.clds.sdc.controller.installer.CsarInstaller;\r
40 import org.onap.clamp.clds.util.LoggingUtils;\r
41 import org.onap.sdc.api.IDistributionClient;\r
42 import org.onap.sdc.api.consumer.IDistributionStatusMessage;\r
43 import org.onap.sdc.api.consumer.INotificationCallback;\r
44 import org.onap.sdc.api.notification.IArtifactInfo;\r
45 import org.onap.sdc.api.notification.INotificationData;\r
46 import org.onap.sdc.api.results.IDistributionClientDownloadResult;\r
47 import org.onap.sdc.api.results.IDistributionClientResult;\r
48 import org.onap.sdc.impl.DistributionClientFactory;\r
49 import org.onap.sdc.tosca.parser.exceptions.SdcToscaParserException;\r
50 import org.onap.sdc.utils.DistributionActionResultEnum;\r
51 import org.onap.sdc.utils.DistributionStatusEnum;\r
52 \r
53 /**\r
54  * This class handles one sdc controller defined in the config.\r
55  */\r
56 public class SdcSingleController {\r
57 \r
58     private static final EELFLogger logger = EELFManager.getInstance().getLogger(SdcSingleController.class);\r
59     private boolean isSdcClientAutoManaged = false;\r
60     private CsarInstaller csarInstaller;\r
61     private ClampProperties refProp;\r
62     public static final String CONFIG_SDC_FOLDER = "sdc.csarFolder";\r
63     private int nbOfNotificationsOngoing = 0;\r
64     private SdcSingleControllerStatus controllerStatus = SdcSingleControllerStatus.STOPPED;\r
65     private SdcSingleControllerConfiguration sdcConfig;\r
66     private IDistributionClient distributionClient;\r
67 \r
68     /**\r
69      * Inner class for Notification callback\r
70      */\r
71     private final class SdcNotificationCallBack implements INotificationCallback {\r
72 \r
73         private SdcSingleController sdcController;\r
74 \r
75         SdcNotificationCallBack(SdcSingleController controller) {\r
76             sdcController = controller;\r
77         }\r
78 \r
79         /**\r
80          * This method can be called multiple times at the same moment. The\r
81          * controller must be thread safe !\r
82          */\r
83         @Override\r
84         public void activateCallback(INotificationData iNotif) {\r
85             Date startTime = new Date();\r
86             String event = "Receive a callback notification in SDC, nb of resources: " + iNotif.getResources().size();\r
87             logger.debug(event);\r
88             sdcController.treatNotification(iNotif);\r
89             LoggingUtils.setTimeContext(startTime, new Date());\r
90             LoggingUtils.setResponseContext("0", "SDC Notification received and processed successfully",\r
91                     this.getClass().getName());\r
92         }\r
93     }\r
94 \r
95     public int getNbOfNotificationsOngoing() {\r
96         return nbOfNotificationsOngoing;\r
97     }\r
98 \r
99     private void changeControllerStatusIdle() {\r
100         if (this.nbOfNotificationsOngoing > 1) {\r
101             --this.nbOfNotificationsOngoing;\r
102         } else {\r
103             this.nbOfNotificationsOngoing = 0;\r
104             this.controllerStatus = SdcSingleControllerStatus.IDLE;\r
105         }\r
106     }\r
107 \r
108     protected final synchronized void changeControllerStatus(SdcSingleControllerStatus newControllerStatus) {\r
109         switch (newControllerStatus) {\r
110             case BUSY:\r
111                 ++this.nbOfNotificationsOngoing;\r
112                 this.controllerStatus = newControllerStatus;\r
113                 break;\r
114             case IDLE:\r
115                 this.changeControllerStatusIdle();\r
116                 break;\r
117             default:\r
118                 this.controllerStatus = newControllerStatus;\r
119                 break;\r
120         }\r
121     }\r
122 \r
123     public final synchronized SdcSingleControllerStatus getControllerStatus() {\r
124         return this.controllerStatus;\r
125     }\r
126 \r
127     public SdcSingleController(ClampProperties clampProp, CsarInstaller csarInstaller,\r
128             SdcSingleControllerConfiguration sdcSingleConfig, boolean isClientAutoManaged) {\r
129         this.isSdcClientAutoManaged = isClientAutoManaged;\r
130         this.sdcConfig = sdcSingleConfig;\r
131         this.refProp = clampProp;\r
132         this.csarInstaller = csarInstaller;\r
133     }\r
134 \r
135     /**\r
136      * This method initializes the SDC Controller and the SDC Client.\r
137      *\r
138      * @throws SdcControllerException\r
139      *             It throws an exception if the SDC Client cannot be\r
140      *             instantiated or if an init attempt is done when already\r
141      *             initialized\r
142      * @throws SdcParametersException\r
143      *             If there is an issue with the parameters provided\r
144      */\r
145     public void initSdc() throws SdcControllerException {\r
146         logger.debug("Attempt to initialize the SDC Controller");\r
147         if (this.getControllerStatus() != SdcSingleControllerStatus.STOPPED) {\r
148             throw new SdcControllerException("The controller is already initialized, call the closeSDC method first");\r
149         }\r
150         if (this.distributionClient == null) {\r
151             distributionClient = DistributionClientFactory.createDistributionClient();\r
152         }\r
153         IDistributionClientResult result = this.distributionClient.init(sdcConfig, new SdcNotificationCallBack(this));\r
154         if (!result.getDistributionActionResult().equals(DistributionActionResultEnum.SUCCESS)) {\r
155             logger.error("SDC distribution client init failed with reason:" + result.getDistributionMessageResult());\r
156             this.changeControllerStatus(SdcSingleControllerStatus.STOPPED);\r
157             throw new SdcControllerException("Initialization of the SDC Controller failed with reason: "\r
158                     + result.getDistributionMessageResult());\r
159         }\r
160         result = this.distributionClient.start();\r
161         if (!result.getDistributionActionResult().equals(DistributionActionResultEnum.SUCCESS)) {\r
162             logger.debug("SDC distribution client start failed with reason:" + result.getDistributionMessageResult());\r
163             this.changeControllerStatus(SdcSingleControllerStatus.STOPPED);\r
164             throw new SdcControllerException(\r
165                     "Startup of the SDC Controller failed with reason: " + result.getDistributionMessageResult());\r
166         }\r
167         this.changeControllerStatus(SdcSingleControllerStatus.IDLE);\r
168     }\r
169 \r
170     /**\r
171      * This method closes the SDC Controller and the SDC Client.\r
172      *\r
173      * @throws SdcControllerException\r
174      *             It throws an exception if the SDC Client cannot be closed\r
175      *             because it's currently BUSY in processing notifications.\r
176      */\r
177     public void closeSdc() throws SdcControllerException {\r
178         if (this.getControllerStatus() == SdcSingleControllerStatus.BUSY) {\r
179             throw new SdcControllerException("Cannot close the SDC controller as it's currently in BUSY state");\r
180         }\r
181         if (this.distributionClient != null) {\r
182             this.distributionClient.stop();\r
183             // If auto managed we can set it to Null, SdcController controls it.\r
184             // In the other case the client of this class has specified it, so\r
185             // we can't reset it\r
186             if (isSdcClientAutoManaged) {\r
187                 // Next init will initialize it with a new SDC Client\r
188                 this.distributionClient = null;\r
189             }\r
190         }\r
191         this.changeControllerStatus(SdcSingleControllerStatus.STOPPED);\r
192     }\r
193 \r
194     /**\r
195      * This method processes the notification received from Sdc.\r
196      * \r
197      * @param iNotif\r
198      *            The INotificationData\r
199      */\r
200     public void treatNotification(INotificationData iNotif) {\r
201         CsarHandler csar = null;\r
202         try {\r
203             logger.info("Notification received for service UUID:" + iNotif.getServiceUUID());\r
204             this.changeControllerStatus(SdcSingleControllerStatus.BUSY);\r
205             csar = new CsarHandler(iNotif, this.sdcConfig.getSdcControllerName(),\r
206                     refProp.getStringValue(CONFIG_SDC_FOLDER));\r
207             csar.save(downloadTheArtifact(csar.getArtifactElement()));\r
208             if (csarInstaller.isCsarAlreadyDeployed(csar)) {\r
209                 this.sendSdcNotification(NotificationType.DOWNLOAD, csar.getArtifactElement().getArtifactURL(),\r
210                         sdcConfig.getConsumerID(), iNotif.getDistributionID(), DistributionStatusEnum.DOWNLOAD_OK, null,\r
211                         System.currentTimeMillis());\r
212                 csarInstaller.installTheCsar(csar);\r
213                 this.sendSdcNotification(NotificationType.DEPLOY, csar.getArtifactElement().getArtifactURL(),\r
214                         sdcConfig.getConsumerID(), iNotif.getDistributionID(), DistributionStatusEnum.DEPLOY_OK, null,\r
215                         System.currentTimeMillis());\r
216             } else {\r
217                 this.sendSdcNotification(NotificationType.DOWNLOAD, csar.getArtifactElement().getArtifactURL(),\r
218                         sdcConfig.getConsumerID(), iNotif.getDistributionID(),\r
219                         DistributionStatusEnum.ALREADY_DOWNLOADED, null, System.currentTimeMillis());\r
220                 this.sendSdcNotification(NotificationType.DOWNLOAD, csar.getArtifactElement().getArtifactURL(),\r
221                         sdcConfig.getConsumerID(), iNotif.getDistributionID(), DistributionStatusEnum.ALREADY_DEPLOYED,\r
222                         null, System.currentTimeMillis());\r
223             }\r
224         } catch (SdcArtifactInstallerException e) {\r
225             logger.error("SdcArtifactInstallerException exception caught during the notification processing", e);\r
226             this.sendSdcNotification(NotificationType.DEPLOY, csar.getArtifactElement().getArtifactURL(),\r
227                     sdcConfig.getConsumerID(), iNotif.getDistributionID(), DistributionStatusEnum.DEPLOY_ERROR,\r
228                     e.getMessage(), System.currentTimeMillis());\r
229         } catch (SdcDownloadException e) {\r
230             logger.error("SdcDownloadException exception caught during the notification processing", e);\r
231             this.sendSdcNotification(NotificationType.DOWNLOAD, csar.getArtifactElement().getArtifactURL(),\r
232                     sdcConfig.getConsumerID(), iNotif.getDistributionID(), DistributionStatusEnum.DOWNLOAD_ERROR,\r
233                     e.getMessage(), System.currentTimeMillis());\r
234         } catch (CsarHandlerException e) {\r
235             logger.error("CsarHandlerException exception caught during the notification processing", e);\r
236             this.sendSdcNotification(NotificationType.DOWNLOAD, null, sdcConfig.getConsumerID(),\r
237                     iNotif.getDistributionID(), DistributionStatusEnum.DOWNLOAD_ERROR, e.getMessage(),\r
238                     System.currentTimeMillis());\r
239         } catch (SdcToscaParserException e) {\r
240             logger.error("SdcToscaParserException exception caught during the notification processing", e);\r
241             this.sendSdcNotification(NotificationType.DEPLOY, csar.getArtifactElement().getArtifactURL(),\r
242                     sdcConfig.getConsumerID(), iNotif.getDistributionID(), DistributionStatusEnum.DEPLOY_ERROR,\r
243                     e.getMessage(), System.currentTimeMillis());\r
244         } catch (RuntimeException e) {\r
245             logger.error("Unexpected exception caught during the notification processing", e);\r
246         } finally {\r
247             this.changeControllerStatus(SdcSingleControllerStatus.IDLE);\r
248         }\r
249     }\r
250 \r
251     private enum NotificationType {\r
252         DOWNLOAD, DEPLOY\r
253     }\r
254 \r
255     private IDistributionClientDownloadResult downloadTheArtifact(IArtifactInfo artifact) throws SdcDownloadException {\r
256         logger.debug("Trying to download the artifact : " + artifact.getArtifactURL() + " UUID: "\r
257                 + artifact.getArtifactUUID());\r
258         IDistributionClientDownloadResult downloadResult;\r
259         try {\r
260             downloadResult = distributionClient.download(artifact);\r
261             if (null == downloadResult) {\r
262                 logger.info("downloadResult is Null for: " + artifact.getArtifactUUID());\r
263                 return null;\r
264             }\r
265         } catch (RuntimeException e) {\r
266             throw new SdcDownloadException("Exception caught when downloading the artifact", e);\r
267         }\r
268         if (DistributionActionResultEnum.SUCCESS.equals(downloadResult.getDistributionActionResult())) {\r
269             logger.info("Successfully downloaded the artifact " + artifact.getArtifactURL() + " UUID "\r
270                     + artifact.getArtifactUUID() + "Size of payload " + downloadResult.getArtifactPayload().length);\r
271         } else {\r
272             throw new SdcDownloadException("Artifact " + artifact.getArtifactName()\r
273                     + " could not be downloaded from SDC URL " + artifact.getArtifactURL() + " UUID "\r
274                     + artifact.getArtifactUUID() + ")" + System.lineSeparator() + "Error message is "\r
275                     + downloadResult.getDistributionMessageResult() + System.lineSeparator());\r
276         }\r
277         return downloadResult;\r
278     }\r
279 \r
280     private void sendSdcNotification(NotificationType notificationType, String artifactURL, String consumerID,\r
281             String distributionID, DistributionStatusEnum status, String errorReason, long timestamp) {\r
282         String event = "Sending " + notificationType.name() + "(" + status.name() + ")"\r
283                 + " notification to SDC for artifact:" + artifactURL;\r
284         if (errorReason != null) {\r
285             event = event + "(" + errorReason + ")";\r
286         }\r
287         logger.info(event);\r
288         String action = "";\r
289         try {\r
290             IDistributionStatusMessage message = new DistributionStatusMessage(artifactURL, consumerID, distributionID,\r
291                     status, timestamp);\r
292             switch (notificationType) {\r
293                 case DOWNLOAD:\r
294                     this.sendDownloadStatus(message, errorReason);\r
295                     action = "sendDownloadStatus";\r
296                     break;\r
297                 case DEPLOY:\r
298                     this.sendDeploymentStatus(message, errorReason);\r
299                     action = "sendDeploymentdStatus";\r
300                     break;\r
301                 default:\r
302                     break;\r
303             }\r
304         } catch (RuntimeException e) {\r
305             logger.warn("Unable to send the SDC Notification (" + action + ") due to an exception", e);\r
306         }\r
307         logger.info("SDC Notification sent successfully(" + action + ")");\r
308     }\r
309 \r
310     private void sendDownloadStatus(IDistributionStatusMessage message, String errorReason) {\r
311         if (errorReason != null) {\r
312             this.distributionClient.sendDownloadStatus(message, errorReason);\r
313         } else {\r
314             this.distributionClient.sendDownloadStatus(message);\r
315         }\r
316     }\r
317 \r
318     private void sendDeploymentStatus(IDistributionStatusMessage message, String errorReason) {\r
319         if (errorReason != null) {\r
320             this.distributionClient.sendDeploymentStatus(message, errorReason);\r
321         } else {\r
322             this.distributionClient.sendDeploymentStatus(message);\r
323         }\r
324     }\r
325 }\r