2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END============================================
20 * Modifications copyright (c) 2018 Nokia
21 * ===================================================================
25 package org.onap.clamp.clds.sdc.controller;
27 import com.att.eelf.configuration.EELFLogger;
28 import com.att.eelf.configuration.EELFManager;
30 import java.util.Date;
31 import java.util.Map.Entry;
32 import java.util.concurrent.ThreadLocalRandom;
34 import org.onap.clamp.clds.config.ClampProperties;
35 import org.onap.clamp.clds.config.sdc.SdcSingleControllerConfiguration;
36 import org.onap.clamp.clds.exception.policy.PolicyModelException;
37 import org.onap.clamp.clds.exception.sdc.controller.CsarHandlerException;
38 import org.onap.clamp.clds.exception.sdc.controller.SdcArtifactInstallerException;
39 import org.onap.clamp.clds.exception.sdc.controller.SdcControllerException;
40 import org.onap.clamp.clds.exception.sdc.controller.SdcDownloadException;
41 import org.onap.clamp.clds.exception.sdc.controller.SdcParametersException;
42 import org.onap.clamp.clds.sdc.controller.installer.BlueprintArtifact;
43 import org.onap.clamp.clds.sdc.controller.installer.CsarHandler;
44 import org.onap.clamp.clds.sdc.controller.installer.CsarInstaller;
45 import org.onap.clamp.clds.util.LoggingUtils;
46 import org.onap.sdc.api.IDistributionClient;
47 import org.onap.sdc.api.consumer.IDistributionStatusMessage;
48 import org.onap.sdc.api.consumer.INotificationCallback;
49 import org.onap.sdc.api.notification.IArtifactInfo;
50 import org.onap.sdc.api.notification.INotificationData;
51 import org.onap.sdc.api.results.IDistributionClientDownloadResult;
52 import org.onap.sdc.api.results.IDistributionClientResult;
53 import org.onap.sdc.impl.DistributionClientFactory;
54 import org.onap.sdc.tosca.parser.exceptions.SdcToscaParserException;
55 import org.onap.sdc.utils.DistributionActionResultEnum;
56 import org.onap.sdc.utils.DistributionStatusEnum;
59 * This class handles one sdc controller defined in the config.
61 public class SdcSingleController {
63 private static final EELFLogger logger = EELFManager.getInstance().getLogger(SdcSingleController.class);
64 private boolean isSdcClientAutoManaged = false;
65 private CsarInstaller csarInstaller;
66 private ClampProperties refProp;
68 * The constant CONFIG_SDC_FOLDER.
70 public static final String CONFIG_SDC_FOLDER = "sdc.csarFolder";
71 private int nbOfNotificationsOngoing = 0;
72 private SdcSingleControllerStatus controllerStatus = SdcSingleControllerStatus.STOPPED;
73 private SdcSingleControllerConfiguration sdcConfig;
74 private IDistributionClient distributionClient;
77 * Inner class for Notification callback.
79 private final class SdcNotificationCallBack implements INotificationCallback {
81 private SdcSingleController sdcController;
84 * Instantiates a new Sdc notification call back.
86 * @param controller the controller
88 SdcNotificationCallBack(SdcSingleController controller) {
89 sdcController = controller;
93 * This method can be called multiple times at the same moment. The controller
94 * must be thread safe !
97 public void activateCallback(INotificationData notificationData) {
98 Date startTime = new Date();
99 logger.info("Receive a callback notification in SDC, nb of resources: "
100 + notificationData.getResources().size());
101 sdcController.treatNotification(notificationData);
102 LoggingUtils.setTimeContext(startTime, new Date());
103 LoggingUtils.setResponseContext("0", "SDC Notification received and processed successfully",
104 this.getClass().getName());
109 * Gets nb of notifications ongoing.
111 * @return the nb of notifications ongoing
113 public int getNbOfNotificationsOngoing() {
114 return nbOfNotificationsOngoing;
117 private void changeControllerStatusIdle() {
118 if (this.nbOfNotificationsOngoing > 1) {
119 --this.nbOfNotificationsOngoing;
121 this.nbOfNotificationsOngoing = 0;
122 this.controllerStatus = SdcSingleControllerStatus.IDLE;
127 * Change controller status.
129 * @param newControllerStatus the new controller status
131 protected final synchronized void changeControllerStatus(SdcSingleControllerStatus newControllerStatus) {
132 switch (newControllerStatus) {
134 ++this.nbOfNotificationsOngoing;
135 this.controllerStatus = newControllerStatus;
138 this.changeControllerStatusIdle();
141 this.controllerStatus = newControllerStatus;
147 * Gets controller status.
149 * @return the controller status
151 public final synchronized SdcSingleControllerStatus getControllerStatus() {
152 return this.controllerStatus;
156 * Instantiates a new Sdc single controller.
158 * @param clampProp the clamp prop
159 * @param csarInstaller the csar installer
160 * @param sdcSingleConfig the sdc single config
161 * @param distributionClient the distribution client
163 public SdcSingleController(ClampProperties clampProp, CsarInstaller csarInstaller,
164 SdcSingleControllerConfiguration sdcSingleConfig,
165 IDistributionClient distributionClient) {
166 this.distributionClient = distributionClient;
167 isSdcClientAutoManaged = (distributionClient == null);
168 this.sdcConfig = sdcSingleConfig;
169 this.refProp = clampProp;
170 this.csarInstaller = csarInstaller;
174 * This method initializes the SDC Controller and the SDC Client.
176 * @throws SdcControllerException It throws an exception if the SDC Client cannot be instantiated or if
177 * an init attempt is done when already initialized
179 public void initSdc() throws SdcControllerException {
180 logger.info("Attempt to initialize the SDC Controller: " + sdcConfig.getSdcControllerName());
181 if (this.getControllerStatus() != SdcSingleControllerStatus.STOPPED) {
182 throw new SdcControllerException("The controller is already initialized, call the closeSDC method first");
184 if (distributionClient == null) {
185 distributionClient = DistributionClientFactory.createDistributionClient();
187 IDistributionClientResult result = distributionClient.init(sdcConfig,
188 new SdcNotificationCallBack(this));
189 if (!result.getDistributionActionResult().equals(DistributionActionResultEnum.SUCCESS)) {
190 logger.error("SDC distribution client init failed with reason:" + result.getDistributionMessageResult());
191 this.changeControllerStatus(SdcSingleControllerStatus.STOPPED);
192 throw new SdcControllerException(
193 "Initialization of the SDC Controller failed with reason: "
194 + result.getDistributionMessageResult());
196 logger.info("SDC Controller successfully initialized: " + sdcConfig.getSdcControllerName());
197 logger.info("Attempt to start the SDC Controller: " + sdcConfig.getSdcControllerName());
198 result = this.distributionClient.start();
199 if (!result.getDistributionActionResult().equals(DistributionActionResultEnum.SUCCESS)) {
200 logger.error("SDC distribution client start failed with reason:" + result.getDistributionMessageResult());
201 this.changeControllerStatus(SdcSingleControllerStatus.STOPPED);
202 throw new SdcControllerException(
203 "Startup of the SDC Controller failed with reason: " + result.getDistributionMessageResult());
205 logger.info("SDC Controller successfully started: " + sdcConfig.getSdcControllerName());
206 this.changeControllerStatus(SdcSingleControllerStatus.IDLE);
210 * This method closes the SDC Controller and the SDC Client.
212 * @throws SdcControllerException It throws an exception if the SDC Client cannot be closed because
213 * it's currently BUSY in processing notifications.
215 public void closeSdc() throws SdcControllerException {
216 if (this.getControllerStatus() == SdcSingleControllerStatus.BUSY) {
217 throw new SdcControllerException("Cannot close the SDC controller as it's currently in BUSY state");
219 if (this.distributionClient != null) {
220 this.distributionClient.stop();
221 // If auto managed we can set it to Null, SdcController controls it.
222 // In the other case the client of this class has specified it, so
224 if (isSdcClientAutoManaged) {
225 // Next init will initialize it with a new SDC Client
226 this.distributionClient = null;
229 this.changeControllerStatus(SdcSingleControllerStatus.STOPPED);
232 private void sendAllNotificationForCsarHandler(INotificationData notificationData, CsarHandler csar,
233 NotificationType notificationType,
234 DistributionStatusEnum distributionStatus, String errorMessage) {
236 // Notify for the CSAR
237 this.sendSdcNotification(notificationType, csar.getArtifactElement().getArtifactURL(),
238 sdcConfig.getConsumerID(), notificationData.getDistributionID(), distributionStatus, errorMessage,
239 System.currentTimeMillis());
240 // Notify for all VF resources found
241 for (Entry<String, BlueprintArtifact> blueprint : csar.getMapOfBlueprints().entrySet()) {
242 // Normally always 1 artifact in resource for Clamp as we
244 // only VF_METADATA type
245 this.sendSdcNotification(notificationType,
246 blueprint.getValue().getResourceAttached().getArtifacts().get(0).getArtifactURL(),
247 sdcConfig.getConsumerID(), notificationData.getDistributionID(), distributionStatus,
249 System.currentTimeMillis());
252 this.sendSdcNotification(notificationType, null, sdcConfig.getConsumerID(),
253 notificationData.getDistributionID(),
254 distributionStatus, errorMessage, System.currentTimeMillis());
259 * This method processes the notification received from Sdc.
261 * @param notificationData The INotificationData
263 public void treatNotification(INotificationData notificationData) {
264 CsarHandler csar = null;
266 // wait for a random time, so that 2 running Clamp will not treat
267 // the same Notification at the same time
268 Thread.sleep(ThreadLocalRandom.current().nextInt(1, 10) * 1000L);
269 logger.info("Notification received for service UUID:" + notificationData.getServiceUUID());
270 this.changeControllerStatus(SdcSingleControllerStatus.BUSY);
271 csar = new CsarHandler(notificationData, this.sdcConfig.getSdcControllerName(),
272 refProp.getStringValue(CONFIG_SDC_FOLDER));
273 csar.save(downloadTheArtifact(csar.getArtifactElement()));
274 if (csarInstaller.isCsarAlreadyDeployed(csar)) {
275 sendAllNotificationForCsarHandler(notificationData, csar, NotificationType.DOWNLOAD,
276 DistributionStatusEnum.ALREADY_DOWNLOADED, null);
277 sendAllNotificationForCsarHandler(notificationData, csar, NotificationType.DEPLOY,
278 DistributionStatusEnum.ALREADY_DEPLOYED, null);
280 sendAllNotificationForCsarHandler(notificationData, csar, NotificationType.DOWNLOAD,
281 DistributionStatusEnum.DOWNLOAD_OK, null);
282 csarInstaller.installTheCsar(csar);
283 sendAllNotificationForCsarHandler(notificationData, csar, NotificationType.DEPLOY,
284 DistributionStatusEnum.DEPLOY_OK, null);
286 } catch (SdcArtifactInstallerException | SdcToscaParserException e) {
287 logger.error("SdcArtifactInstallerException exception caught during the notification processing", e);
288 sendAllNotificationForCsarHandler(notificationData, csar, NotificationType.DEPLOY,
289 DistributionStatusEnum.DEPLOY_ERROR, e.getMessage());
290 } catch (SdcDownloadException | CsarHandlerException e) {
291 logger.error("SdcDownloadException exception caught during the notification processing", e);
292 sendAllNotificationForCsarHandler(notificationData, csar, NotificationType.DOWNLOAD,
293 DistributionStatusEnum.DOWNLOAD_ERROR, e.getMessage());
294 } catch (PolicyModelException e) {
295 logger.error("PolicyModelException exception caught during the notification processing", e);
296 sendAllNotificationForCsarHandler(notificationData, csar, NotificationType.DEPLOY,
297 DistributionStatusEnum.DEPLOY_ERROR, e.getMessage());
298 } catch (InterruptedException e) {
299 logger.error("Interrupt exception caught during the notification processing", e);
300 sendAllNotificationForCsarHandler(notificationData, csar, NotificationType.DEPLOY,
301 DistributionStatusEnum.DEPLOY_ERROR, e.getMessage());
302 Thread.currentThread().interrupt();
303 } catch (RuntimeException e) {
304 logger.error("Unexpected exception caught during the notification processing", e);
305 sendAllNotificationForCsarHandler(notificationData, csar, NotificationType.DEPLOY,
306 DistributionStatusEnum.DEPLOY_ERROR, e.getMessage());
308 this.changeControllerStatus(SdcSingleControllerStatus.IDLE);
312 private enum NotificationType {
314 * Download notification type.
318 * Deploy notification type.
323 private IDistributionClientDownloadResult downloadTheArtifact(IArtifactInfo artifact) throws SdcDownloadException {
325 "Trying to download the artifact : " + artifact.getArtifactURL() + " UUID: "
326 + artifact.getArtifactUUID());
327 IDistributionClientDownloadResult downloadResult;
329 downloadResult = distributionClient.download(artifact);
330 if (null == downloadResult) {
331 logger.info("downloadResult is Null for: " + artifact.getArtifactUUID());
334 } catch (RuntimeException e) {
335 throw new SdcDownloadException("Exception caught when downloading the artifact", e);
337 if (DistributionActionResultEnum.SUCCESS.equals(downloadResult.getDistributionActionResult())) {
338 logger.info("Successfully downloaded the artifact " + artifact.getArtifactURL() + " UUID "
339 + artifact.getArtifactUUID() + "Size of payload " + downloadResult.getArtifactPayload().length);
341 throw new SdcDownloadException(
342 "Artifact " + artifact.getArtifactName() + " could not be downloaded from SDC URL "
343 + artifact.getArtifactURL() + " UUID " + artifact.getArtifactUUID() + ")"
344 + System.lineSeparator()
345 + "Error message is " + downloadResult.getDistributionMessageResult()
346 + System.lineSeparator());
348 return downloadResult;
351 private void sendSdcNotification(NotificationType notificationType, String artifactUrl, String consumerID,
352 String distributionID, DistributionStatusEnum status, String errorReason,
354 String event = "Sending " + notificationType.name() + "(" + status.name() + ")"
355 + " notification to SDC for artifact:" + artifactUrl;
356 if (errorReason != null) {
357 event = event + "(" + errorReason + ")";
362 IDistributionStatusMessage message = new DistributionStatusMessage(artifactUrl, consumerID, distributionID,
364 switch (notificationType) {
366 this.sendDownloadStatus(message, errorReason);
367 action = "sendDownloadStatus";
370 this.sendDeploymentStatus(message, errorReason);
371 action = "sendDeploymentdStatus";
376 } catch (RuntimeException e) {
377 logger.warn("Unable to send the SDC Notification (" + action + ") due to an exception", e);
379 logger.info("SDC Notification sent successfully(" + action + ")");
382 private void sendDownloadStatus(IDistributionStatusMessage message, String errorReason) {
383 if (errorReason != null) {
384 this.distributionClient.sendDownloadStatus(message, errorReason);
386 this.distributionClient.sendDownloadStatus(message);
390 private void sendDeploymentStatus(IDistributionStatusMessage message, String errorReason) {
391 if (errorReason != null) {
392 this.distributionClient.sendDeploymentStatus(message, errorReason);
394 this.distributionClient.sendDeploymentStatus(message);