Merge "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: " + sdcConfig.getSdcControllerName());\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         logger.info("SDC Controller successfully initialized: " + sdcConfig.getSdcControllerName());\r
163         logger.info("Attempt to start the SDC Controller: " + sdcConfig.getSdcControllerName());\r
164         result = this.distributionClient.start();\r
165         if (!result.getDistributionActionResult().equals(DistributionActionResultEnum.SUCCESS)) {\r
166             logger.error("SDC distribution client start failed with reason:" + result.getDistributionMessageResult());\r
167             this.changeControllerStatus(SdcSingleControllerStatus.STOPPED);\r
168             throw new SdcControllerException(\r
169                     "Startup of the SDC Controller failed with reason: " + result.getDistributionMessageResult());\r
170         }\r
171         logger.info("SDC Controller successfully started: " + sdcConfig.getSdcControllerName());\r
172         this.changeControllerStatus(SdcSingleControllerStatus.IDLE);\r
173     }\r
174 \r
175     /**\r
176      * This method closes the SDC Controller and the SDC Client.\r
177      *\r
178      * @throws SdcControllerException\r
179      *             It throws an exception if the SDC Client cannot be closed\r
180      *             because it's currently BUSY in processing notifications.\r
181      */\r
182     public void closeSdc() throws SdcControllerException {\r
183         if (this.getControllerStatus() == SdcSingleControllerStatus.BUSY) {\r
184             throw new SdcControllerException("Cannot close the SDC controller as it's currently in BUSY state");\r
185         }\r
186         if (this.distributionClient != null) {\r
187             this.distributionClient.stop();\r
188             // If auto managed we can set it to Null, SdcController controls it.\r
189             // In the other case the client of this class has specified it, so\r
190             // we can't reset it\r
191             if (isSdcClientAutoManaged) {\r
192                 // Next init will initialize it with a new SDC Client\r
193                 this.distributionClient = null;\r
194             }\r
195         }\r
196         this.changeControllerStatus(SdcSingleControllerStatus.STOPPED);\r
197     }\r
198 \r
199     private void sendAllNotificationForCsarHandler(INotificationData iNotif, CsarHandler csar,\r
200             NotificationType notificationType, DistributionStatusEnum distributionStatus, String errorMessage) {\r
201         if (csar != null) {\r
202             // Notify for the CSAR\r
203             this.sendSdcNotification(notificationType, csar.getArtifactElement().getArtifactURL(),\r
204                     sdcConfig.getConsumerID(), iNotif.getDistributionID(), distributionStatus, errorMessage,\r
205                     System.currentTimeMillis());\r
206             // Notify for all VF resources found\r
207             for (Entry<String, BlueprintArtifact> blueprint : csar.getMapOfBlueprints().entrySet()) {\r
208                 // Normally always 1 artifact in resource for Clamp as we\r
209                 // specified\r
210                 // only VF_METADATA type\r
211                 this.sendSdcNotification(notificationType,\r
212                         blueprint.getValue().getResourceAttached().getArtifacts().get(0).getArtifactURL(),\r
213                         sdcConfig.getConsumerID(), iNotif.getDistributionID(), distributionStatus, errorMessage,\r
214                         System.currentTimeMillis());\r
215             }\r
216         } else {\r
217             this.sendSdcNotification(notificationType, null, sdcConfig.getConsumerID(), iNotif.getDistributionID(),\r
218                     distributionStatus, errorMessage, System.currentTimeMillis());\r
219         }\r
220     }\r
221 \r
222     /**\r
223      * This method processes the notification received from Sdc.\r
224      * \r
225      * @param iNotif\r
226      *            The INotificationData\r
227      */\r
228     public void treatNotification(INotificationData iNotif) {\r
229         CsarHandler csar = null;\r
230         try {\r
231             // wait for a random time, so that 2 running Clamp will not treat\r
232             // the same Notification at the same time\r
233             Thread.sleep(ThreadLocalRandom.current().nextInt(1, 10) * 1000L);\r
234             logger.info("Notification received for service UUID:" + iNotif.getServiceUUID());\r
235             this.changeControllerStatus(SdcSingleControllerStatus.BUSY);\r
236             csar = new CsarHandler(iNotif, this.sdcConfig.getSdcControllerName(),\r
237                     refProp.getStringValue(CONFIG_SDC_FOLDER));\r
238             csar.save(downloadTheArtifact(csar.getArtifactElement()));\r
239             if (csarInstaller.isCsarAlreadyDeployed(csar)) {\r
240                 sendAllNotificationForCsarHandler(iNotif, csar, NotificationType.DOWNLOAD,\r
241                         DistributionStatusEnum.ALREADY_DOWNLOADED, null);\r
242                 sendAllNotificationForCsarHandler(iNotif, csar, NotificationType.DEPLOY,\r
243                         DistributionStatusEnum.ALREADY_DEPLOYED, null);\r
244             } else {\r
245                 sendAllNotificationForCsarHandler(iNotif, csar, NotificationType.DOWNLOAD,\r
246                         DistributionStatusEnum.DOWNLOAD_OK, null);\r
247                 csarInstaller.installTheCsar(csar);\r
248                 sendAllNotificationForCsarHandler(iNotif, csar, NotificationType.DEPLOY,\r
249                         DistributionStatusEnum.DEPLOY_OK, null);\r
250             }\r
251         } catch (SdcArtifactInstallerException | SdcToscaParserException e) {\r
252             logger.error("SdcArtifactInstallerException exception caught during the notification processing", e);\r
253             sendAllNotificationForCsarHandler(iNotif, csar, NotificationType.DEPLOY,\r
254                     DistributionStatusEnum.DEPLOY_ERROR, e.getMessage());\r
255         } catch (SdcDownloadException | CsarHandlerException e) {\r
256             logger.error("SdcDownloadException exception caught during the notification processing", e);\r
257             sendAllNotificationForCsarHandler(iNotif, csar, NotificationType.DOWNLOAD,\r
258                     DistributionStatusEnum.DOWNLOAD_ERROR, e.getMessage());\r
259         } catch (InterruptedException e) {\r
260             logger.error("Interrupt exception caught during the notification processing", e);\r
261             sendAllNotificationForCsarHandler(iNotif, csar, NotificationType.DEPLOY,\r
262                     DistributionStatusEnum.DEPLOY_ERROR, e.getMessage());\r
263             Thread.currentThread().interrupt();\r
264         } catch (RuntimeException e) {\r
265             logger.error("Unexpected exception caught during the notification processing", e);\r
266             sendAllNotificationForCsarHandler(iNotif, csar, NotificationType.DEPLOY,\r
267                     DistributionStatusEnum.DEPLOY_ERROR, e.getMessage());\r
268         } finally {\r
269             this.changeControllerStatus(SdcSingleControllerStatus.IDLE);\r
270         }\r
271     }\r
272 \r
273     private enum NotificationType {\r
274         DOWNLOAD, DEPLOY\r
275     }\r
276 \r
277     private IDistributionClientDownloadResult downloadTheArtifact(IArtifactInfo artifact) throws SdcDownloadException {\r
278         logger.info("Trying to download the artifact : " + artifact.getArtifactURL() + " UUID: "\r
279                 + artifact.getArtifactUUID());\r
280         IDistributionClientDownloadResult downloadResult;\r
281         try {\r
282             downloadResult = distributionClient.download(artifact);\r
283             if (null == downloadResult) {\r
284                 logger.info("downloadResult is Null for: " + artifact.getArtifactUUID());\r
285                 return null;\r
286             }\r
287         } catch (RuntimeException e) {\r
288             throw new SdcDownloadException("Exception caught when downloading the artifact", e);\r
289         }\r
290         if (DistributionActionResultEnum.SUCCESS.equals(downloadResult.getDistributionActionResult())) {\r
291             logger.info("Successfully downloaded the artifact " + artifact.getArtifactURL() + " UUID "\r
292                     + artifact.getArtifactUUID() + "Size of payload " + downloadResult.getArtifactPayload().length);\r
293         } else {\r
294             throw new SdcDownloadException("Artifact " + artifact.getArtifactName()\r
295                     + " could not be downloaded from SDC URL " + artifact.getArtifactURL() + " UUID "\r
296                     + artifact.getArtifactUUID() + ")" + System.lineSeparator() + "Error message is "\r
297                     + downloadResult.getDistributionMessageResult() + System.lineSeparator());\r
298         }\r
299         return downloadResult;\r
300     }\r
301 \r
302     private void sendSdcNotification(NotificationType notificationType, String artifactURL, String consumerID,\r
303             String distributionID, DistributionStatusEnum status, String errorReason, long timestamp) {\r
304         String event = "Sending " + notificationType.name() + "(" + status.name() + ")"\r
305                 + " notification to SDC for artifact:" + artifactURL;\r
306         if (errorReason != null) {\r
307             event = event + "(" + errorReason + ")";\r
308         }\r
309         logger.info(event);\r
310         String action = "";\r
311         try {\r
312             IDistributionStatusMessage message = new DistributionStatusMessage(artifactURL, consumerID, distributionID,\r
313                     status, timestamp);\r
314             switch (notificationType) {\r
315                 case DOWNLOAD:\r
316                     this.sendDownloadStatus(message, errorReason);\r
317                     action = "sendDownloadStatus";\r
318                     break;\r
319                 case DEPLOY:\r
320                     this.sendDeploymentStatus(message, errorReason);\r
321                     action = "sendDeploymentdStatus";\r
322                     break;\r
323                 default:\r
324                     break;\r
325             }\r
326         } catch (RuntimeException e) {\r
327             logger.warn("Unable to send the SDC Notification (" + action + ") due to an exception", e);\r
328         }\r
329         logger.info("SDC Notification sent successfully(" + action + ")");\r
330     }\r
331 \r
332     private void sendDownloadStatus(IDistributionStatusMessage message, String errorReason) {\r
333         if (errorReason != null) {\r
334             this.distributionClient.sendDownloadStatus(message, errorReason);\r
335         } else {\r
336             this.distributionClient.sendDownloadStatus(message);\r
337         }\r
338     }\r
339 \r
340     private void sendDeploymentStatus(IDistributionStatusMessage message, String errorReason) {\r
341         if (errorReason != null) {\r
342             this.distributionClient.sendDeploymentStatus(message, errorReason);\r
343         } else {\r
344             this.distributionClient.sendDeploymentStatus(message);\r
345         }\r
346     }\r
347 }\r