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