Draft single controller
[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.openecomp.sdc.api.IDistributionClient;\r
42 import org.openecomp.sdc.api.consumer.IDistributionStatusMessage;\r
43 import org.openecomp.sdc.api.consumer.INotificationCallback;\r
44 import org.openecomp.sdc.api.notification.IArtifactInfo;\r
45 import org.openecomp.sdc.api.notification.INotificationData;\r
46 import org.openecomp.sdc.api.results.IDistributionClientDownloadResult;\r
47 import org.openecomp.sdc.api.results.IDistributionClientResult;\r
48 import org.openecomp.sdc.impl.DistributionClientFactory;\r
49 import org.openecomp.sdc.tosca.parser.exceptions.SdcToscaParserException;\r
50 import org.openecomp.sdc.utils.DistributionActionResultEnum;\r
51 import org.openecomp.sdc.utils.DistributionStatusEnum;\r
52 import org.springframework.beans.factory.annotation.Autowired;\r
53 import org.springframework.stereotype.Component;\r
54 \r
55 @Component\r
56 public class SdcSingleController {\r
57 \r
58     private static final EELFLogger logger = EELFManager.getInstance().getLogger(SdcSingleController.class);\r
59     protected boolean isAsdcClientAutoManaged = false;\r
60     protected CsarInstaller resourceInstaller;\r
61     @Autowired\r
62     protected ClampProperties refProp;\r
63     public static final String CONFIG_SDC_FOLDER = "sdc.csarFolder";\r
64 \r
65     /**\r
66      * Inner class for Notification callback\r
67      */\r
68     private final class ASDCNotificationCallBack implements INotificationCallback {\r
69 \r
70         private SdcSingleController asdcController;\r
71 \r
72         ASDCNotificationCallBack(SdcSingleController controller) {\r
73             asdcController = controller;\r
74         }\r
75 \r
76         /**\r
77          * This method can be called multiple times at the same moment. The\r
78          * controller must be thread safe !\r
79          */\r
80         @Override\r
81         public void activateCallback(INotificationData iNotif) {\r
82             Date startTime = new Date();\r
83             String event = "Receive a callback notification in ASDC, nb of resources: " + iNotif.getResources().size();\r
84             logger.debug(event);\r
85             asdcController.treatNotification(iNotif);\r
86             LoggingUtils.setTimeContext(startTime, new Date());\r
87             LoggingUtils.setResponseContext("0", "SDC Notification received and processed successfully",\r
88                     this.getClass().getName());\r
89         }\r
90     }\r
91 \r
92     // ***** Controller STATUS code\r
93     protected int nbOfNotificationsOngoing = 0;\r
94 \r
95     public int getNbOfNotificationsOngoing() {\r
96         return nbOfNotificationsOngoing;\r
97     }\r
98 \r
99     private SdcSingleControllerStatus controllerStatus = SdcSingleControllerStatus.STOPPED;\r
100 \r
101     protected final synchronized void changeControllerStatus(SdcSingleControllerStatus newControllerStatus) {\r
102         switch (newControllerStatus) {\r
103             case BUSY:\r
104                 ++this.nbOfNotificationsOngoing;\r
105                 this.controllerStatus = newControllerStatus;\r
106                 break;\r
107             case IDLE:\r
108                 if (this.nbOfNotificationsOngoing > 1) {\r
109                     --this.nbOfNotificationsOngoing;\r
110                 } else {\r
111                     this.nbOfNotificationsOngoing = 0;\r
112                     this.controllerStatus = newControllerStatus;\r
113                 }\r
114                 break;\r
115             default:\r
116                 this.controllerStatus = newControllerStatus;\r
117                 break;\r
118         }\r
119     }\r
120 \r
121     public final synchronized SdcSingleControllerStatus getControllerStatus() {\r
122         return this.controllerStatus;\r
123     }\r
124 \r
125     // ***** END of Controller STATUS code\r
126     protected SdcSingleControllerConfiguration sdcConfig;\r
127     private IDistributionClient distributionClient;\r
128 \r
129     /**\r
130      * This method initializes the SDC Controller and the SDC Client.\r
131      *\r
132      * @throws SdcControllerException\r
133      *             It throws an exception if the SDC Client cannot be\r
134      *             instantiated or if an init attempt is done when already\r
135      *             initialized\r
136      * @throws SdcParametersException\r
137      *             If there is an issue with the parameters provided\r
138      */\r
139     public void initSdc() throws SdcControllerException {\r
140         logger.debug("Attempt to initialize the SDC Controller");\r
141         if (this.getControllerStatus() != SdcSingleControllerStatus.STOPPED) {\r
142             throw new SdcControllerException("The controller is already initialized, call the closeSDC method first");\r
143         }\r
144         if (this.distributionClient == null) {\r
145             distributionClient = DistributionClientFactory.createDistributionClient();\r
146         }\r
147         IDistributionClientResult result = this.distributionClient.init(sdcConfig, new ASDCNotificationCallBack(this));\r
148         if (!result.getDistributionActionResult().equals(DistributionActionResultEnum.SUCCESS)) {\r
149             logger.error("ASDC distribution client init failed with reason:" + result.getDistributionMessageResult());\r
150             this.changeControllerStatus(SdcSingleControllerStatus.STOPPED);\r
151             throw new SdcControllerException("Initialization of the SDC Controller failed with reason: "\r
152                     + result.getDistributionMessageResult());\r
153         }\r
154         result = this.distributionClient.start();\r
155         if (!result.getDistributionActionResult().equals(DistributionActionResultEnum.SUCCESS)) {\r
156             logger.debug("SDC distribution client start failed with reason:" + result.getDistributionMessageResult());\r
157             this.changeControllerStatus(SdcSingleControllerStatus.STOPPED);\r
158             throw new SdcControllerException(\r
159                     "Startup of the SDC Controller failed with reason: " + result.getDistributionMessageResult());\r
160         }\r
161         this.changeControllerStatus(SdcSingleControllerStatus.IDLE);\r
162     }\r
163 \r
164     /**\r
165      * This method closes the SDC Controller and the SDC Client.\r
166      *\r
167      * @throws SdcControllerException\r
168      *             It throws an exception if the SDC Client cannot be closed\r
169      *             because it's currently BUSY in processing notifications.\r
170      */\r
171     public void closeSdc() throws SdcControllerException {\r
172         if (this.getControllerStatus() == SdcSingleControllerStatus.BUSY) {\r
173             throw new SdcControllerException("Cannot close the ASDC controller as it's currently in BUSY state");\r
174         }\r
175         if (this.distributionClient != null) {\r
176             this.distributionClient.stop();\r
177             // If auto managed we can set it to Null, SdcController controls it.\r
178             // In the other case the client of this class has specified it, so\r
179             // we can't reset it\r
180             if (isAsdcClientAutoManaged) {\r
181                 // Next init will initialize it with a new Sdc Client\r
182                 this.distributionClient = null;\r
183             }\r
184         }\r
185         this.changeControllerStatus(SdcSingleControllerStatus.STOPPED);\r
186     }\r
187 \r
188     /**\r
189      * This method processes the notification received from Sdc.\r
190      * \r
191      * @param iNotif\r
192      *            The INotificationData\r
193      */\r
194     public void treatNotification(INotificationData iNotif) {\r
195         CsarHandler csar = null;\r
196         try {\r
197             logger.info("Notification received for service UUID:" + iNotif.getServiceUUID());\r
198             this.changeControllerStatus(SdcSingleControllerStatus.BUSY);\r
199             csar = new CsarHandler(iNotif, this.sdcConfig.getSdcControllerName(),\r
200                     refProp.getStringValue(CONFIG_SDC_FOLDER));\r
201             if (resourceInstaller.isCsarAlreadyDeployed(csar)) {\r
202                 csar.save(downloadTheArtifact(csar.getArtifactElement()));\r
203                 this.sendASDCNotification(NotificationType.DOWNLOAD, csar.getArtifactElement().getArtifactURL(),\r
204                         sdcConfig.getConsumerID(), iNotif.getDistributionID(), DistributionStatusEnum.DOWNLOAD_OK, null,\r
205                         System.currentTimeMillis());\r
206                 resourceInstaller.installTheCsar(csar);\r
207                 this.sendASDCNotification(NotificationType.DEPLOY, csar.getArtifactElement().getArtifactURL(),\r
208                         sdcConfig.getConsumerID(), iNotif.getDistributionID(), DistributionStatusEnum.DEPLOY_OK, null,\r
209                         System.currentTimeMillis());\r
210             } else {\r
211                 this.sendASDCNotification(NotificationType.DOWNLOAD, csar.getArtifactElement().getArtifactURL(),\r
212                         sdcConfig.getConsumerID(), iNotif.getDistributionID(),\r
213                         DistributionStatusEnum.ALREADY_DOWNLOADED, null, System.currentTimeMillis());\r
214                 this.sendASDCNotification(NotificationType.DOWNLOAD, csar.getArtifactElement().getArtifactURL(),\r
215                         sdcConfig.getConsumerID(), iNotif.getDistributionID(), DistributionStatusEnum.ALREADY_DEPLOYED,\r
216                         null, System.currentTimeMillis());\r
217             }\r
218         } catch (SdcArtifactInstallerException e) {\r
219             logger.error("SdcArtifactInstallerException exception caught during the notification processing", e);\r
220             this.sendASDCNotification(NotificationType.DEPLOY, csar.getArtifactElement().getArtifactURL(),\r
221                     sdcConfig.getConsumerID(), iNotif.getDistributionID(), DistributionStatusEnum.DEPLOY_ERROR,\r
222                     e.getMessage(), System.currentTimeMillis());\r
223         } catch (SdcDownloadException e) {\r
224             logger.error("SdcDownloadException exception caught during the notification processing", e);\r
225             this.sendASDCNotification(NotificationType.DOWNLOAD, csar.getArtifactElement().getArtifactURL(),\r
226                     sdcConfig.getConsumerID(), iNotif.getDistributionID(), DistributionStatusEnum.DOWNLOAD_ERROR,\r
227                     e.getMessage(), System.currentTimeMillis());\r
228         } catch (CsarHandlerException e) {\r
229             logger.error("CsarHandlerException exception caught during the notification processing", e);\r
230             this.sendASDCNotification(NotificationType.DOWNLOAD, csar.getArtifactElement().getArtifactURL(),\r
231                     sdcConfig.getConsumerID(), iNotif.getDistributionID(), DistributionStatusEnum.DOWNLOAD_ERROR,\r
232                     e.getMessage(), System.currentTimeMillis());\r
233         } catch (SdcToscaParserException e) {\r
234             this.sendASDCNotification(NotificationType.DEPLOY, csar.getArtifactElement().getArtifactURL(),\r
235                     sdcConfig.getConsumerID(), iNotif.getDistributionID(), DistributionStatusEnum.DEPLOY_ERROR,\r
236                     e.getMessage(), System.currentTimeMillis());\r
237         } catch (RuntimeException e) {\r
238             logger.error("Unexpected exception caught during the notification processing", e);\r
239         } finally {\r
240             this.changeControllerStatus(SdcSingleControllerStatus.IDLE);\r
241         }\r
242     }\r
243 \r
244     private enum NotificationType {\r
245         DOWNLOAD, DEPLOY\r
246     }\r
247 \r
248     private IDistributionClientDownloadResult downloadTheArtifact(IArtifactInfo artifact) throws SdcDownloadException {\r
249         logger.debug("Trying to download the artifact : " + artifact.getArtifactURL() + " UUID: "\r
250                 + artifact.getArtifactUUID());\r
251         IDistributionClientDownloadResult downloadResult;\r
252         try {\r
253             downloadResult = distributionClient.download(artifact);\r
254             if (null == downloadResult) {\r
255                 logger.info("downloadResult is Null for: " + artifact.getArtifactUUID());\r
256                 return null;\r
257             }\r
258         } catch (RuntimeException e) {\r
259             throw new SdcDownloadException("Exception caught when downloading the artifact", e);\r
260         }\r
261         if (DistributionActionResultEnum.SUCCESS.equals(downloadResult.getDistributionActionResult())) {\r
262             logger.info("Successfully downloaded the artifact " + artifact.getArtifactURL() + " UUID "\r
263                     + artifact.getArtifactUUID() + "Size of payload " + downloadResult.getArtifactPayload().length);\r
264         } else {\r
265             throw new SdcDownloadException("Artifact " + artifact.getArtifactName()\r
266                     + " could not be downloaded from ASDC URL " + artifact.getArtifactURL() + " UUID "\r
267                     + artifact.getArtifactUUID() + ")" + System.lineSeparator() + "Error message is "\r
268                     + downloadResult.getDistributionMessageResult() + System.lineSeparator());\r
269         }\r
270         return downloadResult;\r
271     }\r
272 \r
273     private void sendASDCNotification(NotificationType notificationType, String artifactURL, String consumerID,\r
274             String distributionID, DistributionStatusEnum status, String errorReason, long timestamp) {\r
275         String event = "Sending " + notificationType.name() + "(" + status.name() + ")"\r
276                 + " notification to ASDC for artifact:" + artifactURL;\r
277         if (errorReason != null) {\r
278             event = event + "(" + errorReason + ")";\r
279         }\r
280         logger.info(event);\r
281         String action = "";\r
282         try {\r
283             IDistributionStatusMessage message = new DistributionStatusMessage(artifactURL, consumerID, distributionID,\r
284                     status, timestamp);\r
285             switch (notificationType) {\r
286                 case DOWNLOAD:\r
287                     if (errorReason != null) {\r
288                         this.distributionClient.sendDownloadStatus(message, errorReason);\r
289                     } else {\r
290                         this.distributionClient.sendDownloadStatus(message);\r
291                     }\r
292                     action = "sendDownloadStatus";\r
293                     break;\r
294                 case DEPLOY:\r
295                     if (errorReason != null) {\r
296                         this.distributionClient.sendDeploymentStatus(message, errorReason);\r
297                     } else {\r
298                         this.distributionClient.sendDeploymentStatus(message);\r
299                     }\r
300                     action = "sendDeploymentdStatus";\r
301                     break;\r
302                 default:\r
303                     break;\r
304             }\r
305         } catch (RuntimeException e) {\r
306             logger.warn("Unable to send the Sdc Notification (" + action + ") due to an exception", e);\r
307         }\r
308         logger.info("Sdc Notification sent successfully(" + action + ")");\r
309     }\r
310 }\r