resolve issues due to conflict
[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 \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     protected boolean isAsdcClientAutoManaged = false;\r
60     protected CsarInstaller csarInstaller;\r
61     protected ClampProperties refProp;\r
62     public static final String CONFIG_SDC_FOLDER = "sdc.csarFolder";\r
63 \r
64     /**\r
65      * Inner class for Notification callback\r
66      */\r
67     private final class ASDCNotificationCallBack implements INotificationCallback {\r
68 \r
69         private SdcSingleController asdcController;\r
70 \r
71         ASDCNotificationCallBack(SdcSingleController controller) {\r
72             asdcController = controller;\r
73         }\r
74 \r
75         /**\r
76          * This method can be called multiple times at the same moment. The\r
77          * controller must be thread safe !\r
78          */\r
79         @Override\r
80         public void activateCallback(INotificationData iNotif) {\r
81             Date startTime = new Date();\r
82             String event = "Receive a callback notification in ASDC, nb of resources: " + iNotif.getResources().size();\r
83             logger.debug(event);\r
84             asdcController.treatNotification(iNotif);\r
85             LoggingUtils.setTimeContext(startTime, new Date());\r
86             LoggingUtils.setResponseContext("0", "SDC Notification received and processed successfully",\r
87                     this.getClass().getName());\r
88         }\r
89     }\r
90 \r
91     // ***** Controller STATUS code\r
92     protected int nbOfNotificationsOngoing = 0;\r
93 \r
94     public int getNbOfNotificationsOngoing() {\r
95         return nbOfNotificationsOngoing;\r
96     }\r
97 \r
98     private SdcSingleControllerStatus controllerStatus = SdcSingleControllerStatus.STOPPED;\r
99 \r
100     protected final synchronized void changeControllerStatus(SdcSingleControllerStatus newControllerStatus) {\r
101         switch (newControllerStatus) {\r
102             case BUSY:\r
103                 ++this.nbOfNotificationsOngoing;\r
104                 this.controllerStatus = newControllerStatus;\r
105                 break;\r
106             case IDLE:\r
107                 if (this.nbOfNotificationsOngoing > 1) {\r
108                     --this.nbOfNotificationsOngoing;\r
109                 } else {\r
110                     this.nbOfNotificationsOngoing = 0;\r
111                     this.controllerStatus = newControllerStatus;\r
112                 }\r
113                 break;\r
114             default:\r
115                 this.controllerStatus = newControllerStatus;\r
116                 break;\r
117         }\r
118     }\r
119 \r
120     public final synchronized SdcSingleControllerStatus getControllerStatus() {\r
121         return this.controllerStatus;\r
122     }\r
123 \r
124     // ***** END of Controller STATUS code\r
125     protected SdcSingleControllerConfiguration sdcConfig;\r
126     private IDistributionClient distributionClient;\r
127 \r
128     public SdcSingleController(ClampProperties clampProp, CsarInstaller csarInstaller,\r
129             SdcSingleControllerConfiguration sdcSingleConfig, boolean isClientAutoManaged) {\r
130         this.isAsdcClientAutoManaged = isClientAutoManaged;\r
131         this.sdcConfig = sdcSingleConfig;\r
132         this.refProp = clampProp;\r
133         this.csarInstaller = csarInstaller;\r
134     }\r
135 \r
136     /**\r
137      * This method initializes the SDC Controller and the SDC Client.\r
138      *\r
139      * @throws SdcControllerException\r
140      *             It throws an exception if the SDC Client cannot be\r
141      *             instantiated or if an init attempt is done when already\r
142      *             initialized\r
143      * @throws SdcParametersException\r
144      *             If there is an issue with the parameters provided\r
145      */\r
146     public void initSdc() throws SdcControllerException {\r
147         logger.debug("Attempt to initialize the SDC Controller");\r
148         if (this.getControllerStatus() != SdcSingleControllerStatus.STOPPED) {\r
149             throw new SdcControllerException("The controller is already initialized, call the closeSDC method first");\r
150         }\r
151         if (this.distributionClient == null) {\r
152             distributionClient = DistributionClientFactory.createDistributionClient();\r
153         }\r
154         IDistributionClientResult result = this.distributionClient.init(sdcConfig, new ASDCNotificationCallBack(this));\r
155         if (!result.getDistributionActionResult().equals(DistributionActionResultEnum.SUCCESS)) {\r
156             logger.error("ASDC distribution client init failed with reason:" + result.getDistributionMessageResult());\r
157             this.changeControllerStatus(SdcSingleControllerStatus.STOPPED);\r
158             throw new SdcControllerException("Initialization of the SDC Controller failed with reason: "\r
159                     + result.getDistributionMessageResult());\r
160         }\r
161         result = this.distributionClient.start();\r
162         if (!result.getDistributionActionResult().equals(DistributionActionResultEnum.SUCCESS)) {\r
163             logger.debug("SDC distribution client start failed with reason:" + result.getDistributionMessageResult());\r
164             this.changeControllerStatus(SdcSingleControllerStatus.STOPPED);\r
165             throw new SdcControllerException(\r
166                     "Startup of the SDC Controller failed with reason: " + result.getDistributionMessageResult());\r
167         }\r
168         this.changeControllerStatus(SdcSingleControllerStatus.IDLE);\r
169     }\r
170 \r
171     /**\r
172      * This method closes the SDC Controller and the SDC Client.\r
173      *\r
174      * @throws SdcControllerException\r
175      *             It throws an exception if the SDC Client cannot be closed\r
176      *             because it's currently BUSY in processing notifications.\r
177      */\r
178     public void closeSdc() throws SdcControllerException {\r
179         if (this.getControllerStatus() == SdcSingleControllerStatus.BUSY) {\r
180             throw new SdcControllerException("Cannot close the ASDC controller as it's currently in BUSY state");\r
181         }\r
182         if (this.distributionClient != null) {\r
183             this.distributionClient.stop();\r
184             // If auto managed we can set it to Null, SdcController controls it.\r
185             // In the other case the client of this class has specified it, so\r
186             // we can't reset it\r
187             if (isAsdcClientAutoManaged) {\r
188                 // Next init will initialize it with a new Sdc Client\r
189                 this.distributionClient = null;\r
190             }\r
191         }\r
192         this.changeControllerStatus(SdcSingleControllerStatus.STOPPED);\r
193     }\r
194 \r
195     /**\r
196      * This method processes the notification received from Sdc.\r
197      * \r
198      * @param iNotif\r
199      *            The INotificationData\r
200      */\r
201     public void treatNotification(INotificationData iNotif) {\r
202         CsarHandler csar = null;\r
203         try {\r
204             logger.info("Notification received for service UUID:" + iNotif.getServiceUUID());\r
205             this.changeControllerStatus(SdcSingleControllerStatus.BUSY);\r
206             csar = new CsarHandler(iNotif, this.sdcConfig.getSdcControllerName(),\r
207                     refProp.getStringValue(CONFIG_SDC_FOLDER));\r
208             if (csarInstaller.isCsarAlreadyDeployed(csar)) {\r
209                 csar.save(downloadTheArtifact(csar.getArtifactElement()));\r
210                 this.sendASDCNotification(NotificationType.DOWNLOAD, csar.getArtifactElement().getArtifactURL(),\r
211                         sdcConfig.getConsumerID(), iNotif.getDistributionID(), DistributionStatusEnum.DOWNLOAD_OK, null,\r
212                         System.currentTimeMillis());\r
213                 csarInstaller.installTheCsar(csar);\r
214                 this.sendASDCNotification(NotificationType.DEPLOY, csar.getArtifactElement().getArtifactURL(),\r
215                         sdcConfig.getConsumerID(), iNotif.getDistributionID(), DistributionStatusEnum.DEPLOY_OK, null,\r
216                         System.currentTimeMillis());\r
217             } else {\r
218                 this.sendASDCNotification(NotificationType.DOWNLOAD, csar.getArtifactElement().getArtifactURL(),\r
219                         sdcConfig.getConsumerID(), iNotif.getDistributionID(),\r
220                         DistributionStatusEnum.ALREADY_DOWNLOADED, null, System.currentTimeMillis());\r
221                 this.sendASDCNotification(NotificationType.DOWNLOAD, csar.getArtifactElement().getArtifactURL(),\r
222                         sdcConfig.getConsumerID(), iNotif.getDistributionID(), DistributionStatusEnum.ALREADY_DEPLOYED,\r
223                         null, System.currentTimeMillis());\r
224             }\r
225         } catch (SdcArtifactInstallerException e) {\r
226             logger.error("SdcArtifactInstallerException exception caught during the notification processing", e);\r
227             this.sendASDCNotification(NotificationType.DEPLOY, csar.getArtifactElement().getArtifactURL(),\r
228                     sdcConfig.getConsumerID(), iNotif.getDistributionID(), DistributionStatusEnum.DEPLOY_ERROR,\r
229                     e.getMessage(), System.currentTimeMillis());\r
230         } catch (SdcDownloadException e) {\r
231             logger.error("SdcDownloadException exception caught during the notification processing", e);\r
232             this.sendASDCNotification(NotificationType.DOWNLOAD, csar.getArtifactElement().getArtifactURL(),\r
233                     sdcConfig.getConsumerID(), iNotif.getDistributionID(), DistributionStatusEnum.DOWNLOAD_ERROR,\r
234                     e.getMessage(), System.currentTimeMillis());\r
235         } catch (CsarHandlerException e) {\r
236             logger.error("CsarHandlerException exception caught during the notification processing", e);\r
237             this.sendASDCNotification(NotificationType.DOWNLOAD, csar.getArtifactElement().getArtifactURL(),\r
238                     sdcConfig.getConsumerID(), iNotif.getDistributionID(), DistributionStatusEnum.DOWNLOAD_ERROR,\r
239                     e.getMessage(), System.currentTimeMillis());\r
240         } catch (SdcToscaParserException e) {\r
241             this.sendASDCNotification(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 ASDC 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 sendASDCNotification(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 ASDC 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                     if (errorReason != null) {\r
295                         this.distributionClient.sendDownloadStatus(message, errorReason);\r
296                     } else {\r
297                         this.distributionClient.sendDownloadStatus(message);\r
298                     }\r
299                     action = "sendDownloadStatus";\r
300                     break;\r
301                 case DEPLOY:\r
302                     if (errorReason != null) {\r
303                         this.distributionClient.sendDeploymentStatus(message, errorReason);\r
304                     } else {\r
305                         this.distributionClient.sendDeploymentStatus(message);\r
306                     }\r
307                     action = "sendDeploymentdStatus";\r
308                     break;\r
309                 default:\r
310                     break;\r
311             }\r
312         } catch (RuntimeException e) {\r
313             logger.warn("Unable to send the Sdc Notification (" + action + ") due to an exception", e);\r
314         }\r
315         logger.info("Sdc Notification sent successfully(" + action + ")");\r
316     }\r
317 }\r