22c4b04ff47a0d135dff746683b35edaea84451c
[so.git] / asdc-controller / src / main / java / org / openecomp / mso / asdc / client / ASDCController.java
1 /*-\r
2  * ============LICENSE_START=======================================================\r
3  * ONAP - SO\r
4  * ================================================================================\r
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.\r
6  * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights 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 package org.openecomp.mso.asdc.client;\r
23 \r
24 \r
25 import java.io.File;\r
26 import java.io.FileOutputStream;\r
27 import java.io.IOException;\r
28 import java.io.UnsupportedEncodingException;\r
29 import java.util.List;\r
30 \r
31 import org.openecomp.sdc.api.IDistributionClient;\r
32 import org.openecomp.sdc.api.consumer.IDistributionStatusMessage;\r
33 import org.openecomp.sdc.api.consumer.INotificationCallback;\r
34 import org.openecomp.sdc.api.notification.IArtifactInfo;\r
35 import org.openecomp.sdc.api.notification.INotificationData;\r
36 import org.openecomp.sdc.api.notification.IResourceInstance;\r
37 import org.openecomp.sdc.api.results.IDistributionClientDownloadResult;\r
38 import org.openecomp.sdc.api.results.IDistributionClientResult;\r
39 import org.openecomp.sdc.impl.DistributionClientFactory;\r
40 import org.openecomp.sdc.utils.DistributionActionResultEnum;\r
41 import org.openecomp.sdc.utils.DistributionStatusEnum;\r
42 import org.openecomp.mso.asdc.client.exceptions.ASDCControllerException;\r
43 import org.openecomp.mso.asdc.client.exceptions.ASDCDownloadException;\r
44 import org.openecomp.mso.asdc.client.exceptions.ASDCParametersException;\r
45 import org.openecomp.mso.asdc.client.exceptions.ArtifactInstallerException;\r
46 import org.openecomp.mso.asdc.installer.IVfResourceInstaller;\r
47 import org.openecomp.mso.asdc.installer.ToscaResourceStructure;\r
48 import org.openecomp.mso.asdc.installer.VfResourceStructure;\r
49 import org.openecomp.mso.asdc.installer.heat.ToscaResourceInstaller;\r
50 import org.openecomp.mso.asdc.installer.heat.VfResourceInstaller;\r
51 import org.openecomp.mso.asdc.util.ASDCNotificationLogging;\r
52 import org.openecomp.mso.logger.MessageEnum;\r
53 import org.openecomp.mso.logger.MsoAlarmLogger;\r
54 import org.openecomp.mso.logger.MsoLogger;\r
55 import org.openecomp.mso.utils.UUIDChecker;\r
56 \r
57 public class ASDCController {\r
58 \r
59     protected static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.ASDC);\r
60 \r
61     protected static MsoAlarmLogger alarmLogger = new MsoAlarmLogger ();\r
62 \r
63     protected boolean isAsdcClientAutoManaged = false;\r
64 \r
65     protected String controllerName;\r
66 \r
67     protected ToscaResourceInstaller toscaInstaller;\r
68     \r
69 \r
70     /**\r
71      * Inner class for Notification callback\r
72      *\r
73      *\r
74      */\r
75     private final class ASDCNotificationCallBack implements INotificationCallback {\r
76 \r
77         private ASDCController asdcController;\r
78 \r
79         ASDCNotificationCallBack (ASDCController controller) {\r
80             asdcController = controller;\r
81         }\r
82 \r
83         /**\r
84          * This method can be called multiple times at the same moment.\r
85          * The controller must be thread safe !\r
86          */\r
87         @Override\r
88         public void activateCallback (INotificationData iNotif) {\r
89             long startTime = System.currentTimeMillis ();\r
90             UUIDChecker.generateUUID (LOGGER);\r
91             MsoLogger.setServiceName ("NotificationHandler");\r
92             MsoLogger.setLogContext (iNotif.getDistributionID (), iNotif.getServiceUUID ());\r
93             String event = "Receive a callback notification in ASDC, nb of resources: " + iNotif.getResources ().size ();\r
94             LOGGER.debug(event);\r
95             asdcController.treatNotification (iNotif);\r
96             LOGGER.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Completed the treatment of the notification");\r
97         }\r
98     }\r
99 \r
100     // ***** Controller STATUS code\r
101 \r
102     protected int nbOfNotificationsOngoing = 0;\r
103 \r
104     public int getNbOfNotificationsOngoing () {\r
105         return nbOfNotificationsOngoing;\r
106     }\r
107 \r
108     private ASDCControllerStatus controllerStatus = ASDCControllerStatus.STOPPED;\r
109 \r
110     protected synchronized final void changeControllerStatus (ASDCControllerStatus newControllerStatus) {\r
111         switch (newControllerStatus) {\r
112 \r
113             case BUSY:\r
114                 ++this.nbOfNotificationsOngoing;\r
115                 this.controllerStatus = newControllerStatus;\r
116                 break;\r
117 \r
118             case IDLE:\r
119                 if (this.nbOfNotificationsOngoing > 1) {\r
120                     --this.nbOfNotificationsOngoing;\r
121                 } else {\r
122                     this.nbOfNotificationsOngoing = 0;\r
123                     this.controllerStatus = newControllerStatus;\r
124                 }\r
125 \r
126                 break;\r
127             default:\r
128                 this.controllerStatus = newControllerStatus;\r
129                 break;\r
130 \r
131         }\r
132     }\r
133 \r
134     public synchronized final ASDCControllerStatus getControllerStatus () {\r
135         return this.controllerStatus;\r
136     }\r
137 \r
138     // ***** END of Controller STATUS code\r
139 \r
140     protected ASDCConfiguration asdcConfig;\r
141     private IDistributionClient distributionClient;\r
142     private IVfResourceInstaller resourceInstaller;\r
143 \r
144     public ASDCController (String controllerConfigName) {\r
145         isAsdcClientAutoManaged = true;\r
146         this.controllerName = controllerConfigName;\r
147         this.resourceInstaller = new VfResourceInstaller();\r
148         toscaInstaller = new ToscaResourceInstaller();\r
149     }\r
150 \r
151     public ASDCController (String controllerConfigName, IDistributionClient asdcClient, IVfResourceInstaller resourceinstaller) {\r
152 \r
153         distributionClient = asdcClient;\r
154         this.resourceInstaller = resourceinstaller;\r
155         this.controllerName = controllerConfigName;\r
156     }\r
157 \r
158     public ASDCController (String controllerConfigName,IDistributionClient asdcClient) {\r
159         distributionClient = asdcClient;\r
160         this.controllerName = controllerConfigName;\r
161         this.resourceInstaller = new VfResourceInstaller();\r
162         toscaInstaller = new ToscaResourceInstaller();\r
163     }\r
164 \r
165     /**\r
166      * This method refresh the ASDC Controller config and restart the client.\r
167      *\r
168      * @return true if config has been reloaded, false otherwise\r
169      * @throws ASDCControllerException If case of issue with the init or close called during the config reload\r
170      * @throws ASDCParametersException If there is an issue with the parameters\r
171      * @throws IOException In case of the key file could not be loaded properly\r
172      */\r
173     public boolean updateConfigIfNeeded () throws ASDCParametersException, ASDCControllerException, IOException {\r
174         LOGGER.debug ("Checking whether ASDC config must be reloaded");\r
175 \r
176         try {\r
177             if (this.asdcConfig != null && this.asdcConfig.hasASDCConfigChanged ()) {\r
178                 LOGGER.debug ("ASDC Config must be reloaded");\r
179                 this.closeASDC ();\r
180                 this.asdcConfig.refreshASDCConfig ();\r
181                 this.initASDC ();\r
182                 return true;\r
183             } else {\r
184                 LOGGER.debug ("ASDC Config must NOT be reloaded");\r
185                 return false;\r
186             }\r
187         } catch (ASDCParametersException ep) {\r
188             // Try to close it at least to make it consistent with the file specified\r
189             // We cannot let it run with a different config file, even if it's bad.\r
190             // This call could potentially throw a ASDCController exception if the controller is currently BUSY.\r
191             this.closeASDC ();\r
192 \r
193             throw ep;\r
194         }\r
195     }\r
196 \r
197     /**\r
198      * This method initializes the ASDC Controller and the ASDC Client.\r
199      *\r
200      * @throws ASDCControllerException It throws an exception if the ASDC Client cannot be instantiated or if an init\r
201      *         attempt is done when already initialized\r
202      * @throws ASDCParametersException If there is an issue with the parameters provided\r
203      * @throws IOException In case of issues when trying to load the key file\r
204      */\r
205     public void initASDC () throws ASDCControllerException, ASDCParametersException, IOException {\r
206         String event = "Initialize the ASDC Controller";\r
207         MsoLogger.setServiceName ("InitASDC");\r
208         LOGGER.debug (event);\r
209         if (this.getControllerStatus () != ASDCControllerStatus.STOPPED) {\r
210             String endEvent = "The controller is already initialized, call the closeASDC method first";\r
211             throw new ASDCControllerException (endEvent);\r
212         }\r
213 \r
214         if (asdcConfig == null) {\r
215             asdcConfig = new ASDCConfiguration (this.controllerName);\r
216 \r
217         }\r
218         // attempt to refresh during init as MsoProperties is may be pointing to an old file\r
219         // Be careful this is static in MsoProperties\r
220         asdcConfig.refreshASDCConfig ();\r
221 \r
222         if (this.distributionClient == null) {\r
223             distributionClient = DistributionClientFactory.createDistributionClient ();\r
224         }\r
225         long initStartTime = System.currentTimeMillis ();\r
226         IDistributionClientResult result = this.distributionClient.init (asdcConfig,\r
227                                                                          new ASDCNotificationCallBack (this));\r
228         if (!result.getDistributionActionResult ().equals (DistributionActionResultEnum.SUCCESS)) {\r
229             String endEvent = "ASDC distribution client init failed with reason:"\r
230                               + result.getDistributionMessageResult ();\r
231             LOGGER.recordMetricEvent (initStartTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.UnknownError, "Initialization of the ASDC Controller failed with reason:" + result.getDistributionMessageResult (), "ASDC", "init", null);\r
232             LOGGER.debug (endEvent);\r
233             asdcConfig = null;\r
234 \r
235             this.changeControllerStatus (ASDCControllerStatus.STOPPED);\r
236             throw new ASDCControllerException ("Initialization of the ASDC Controller failed with reason: "\r
237                                                + result.getDistributionMessageResult ());\r
238         }\r
239         LOGGER.recordMetricEvent (initStartTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully initialize ASDC Controller", "ASDC", "init", null);\r
240 \r
241         long clientstartStartTime = System.currentTimeMillis ();\r
242         result = this.distributionClient.start ();\r
243         if (!result.getDistributionActionResult ().equals (DistributionActionResultEnum.SUCCESS)) {\r
244             String endEvent = "ASDC distribution client start failed with reason:"\r
245                               + result.getDistributionMessageResult ();\r
246             LOGGER.recordMetricEvent (clientstartStartTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.UnknownError, endEvent, "ASDC", "start", null);\r
247             LOGGER.debug (endEvent);\r
248             asdcConfig = null;\r
249             this.changeControllerStatus (ASDCControllerStatus.STOPPED);\r
250             throw new ASDCControllerException ("Startup of the ASDC Controller failed with reason: "\r
251                                                + result.getDistributionMessageResult ());\r
252         }\r
253         LOGGER.recordMetricEvent (clientstartStartTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully start ASDC distribution client", "ASDC", "start", null);\r
254 \r
255 \r
256         this.changeControllerStatus (ASDCControllerStatus.IDLE);\r
257         LOGGER.info (MessageEnum.ASDC_INIT_ASDC_CLIENT_SUC, "ASDC", "changeControllerStatus");\r
258     }\r
259 \r
260     /**\r
261      * This method closes the ASDC Controller and the ASDC Client.\r
262      *\r
263      * @throws ASDCControllerException It throws an exception if the ASDC Client cannot be closed because\r
264      *         it's currently BUSY in processing notifications.\r
265      */\r
266     public void closeASDC () throws ASDCControllerException {\r
267 \r
268         MsoLogger.setServiceName ("CloseController");\r
269         if (this.getControllerStatus () == ASDCControllerStatus.BUSY) {\r
270             throw new ASDCControllerException ("Cannot close the ASDC controller as it's currently in BUSY state");\r
271         }\r
272         if (this.distributionClient != null) {\r
273             this.distributionClient.stop ();\r
274             // If auto managed we can set it to Null, ASDCController controls it.\r
275             // In the other case the client of this class has specified it, so we can't reset it\r
276             if (isAsdcClientAutoManaged) {\r
277                 // Next init will initialize it with a new ASDC Client\r
278                 this.distributionClient = null;\r
279             }\r
280 \r
281         }\r
282         this.changeControllerStatus (ASDCControllerStatus.STOPPED);\r
283     }\r
284 \r
285     private boolean checkResourceAlreadyDeployed (VfResourceStructure resource) throws ArtifactInstallerException {\r
286 \r
287         if (toscaInstaller.isResourceAlreadyDeployed (resource)) {\r
288             LOGGER.info (MessageEnum.ASDC_ARTIFACT_ALREADY_EXIST,\r
289                     resource.getResourceInstance().getResourceInstanceName(),\r
290                     resource.getResourceInstance().getResourceUUID(),\r
291                     resource.getResourceInstance().getResourceName(), "", "");\r
292 \r
293             this.sendDeployNotificationsForResource(resource,DistributionStatusEnum.ALREADY_DOWNLOADED,null);\r
294             this.sendDeployNotificationsForResource(resource,DistributionStatusEnum.ALREADY_DEPLOYED,null);\r
295 \r
296             return true;\r
297         } else {\r
298             return false;\r
299         }\r
300 \r
301     }\r
302 \r
303     private final static String UUID_PARAM = "(UUID:";\r
304 \r
305     private IDistributionClientDownloadResult downloadTheArtifact (IArtifactInfo artifact,\r
306                                                                    String distributionId) throws ASDCDownloadException {\r
307 \r
308         LOGGER.debug ("Trying to download the artifact : " + artifact.getArtifactURL ()\r
309                       + UUID_PARAM\r
310                       + artifact.getArtifactUUID ()\r
311                       + ")");\r
312         IDistributionClientDownloadResult downloadResult;\r
313 \r
314 \r
315         try {\r
316             downloadResult = distributionClient.download (artifact);\r
317             if (null == downloadResult) {\r
318                 LOGGER.info (MessageEnum.ASDC_ARTIFACT_NULL, artifact.getArtifactUUID (), "", "");\r
319                 return downloadResult;\r
320             }\r
321         } catch (RuntimeException e) {\r
322             LOGGER.debug ("Not able to download the artifact due to an exception: " + artifact.getArtifactURL ());\r
323             this.sendASDCNotification (NotificationType.DOWNLOAD,\r
324                                        artifact.getArtifactURL (),\r
325                                        asdcConfig.getConsumerID (),\r
326                                        distributionId,\r
327                                        DistributionStatusEnum.DOWNLOAD_ERROR,\r
328                                        e.getMessage (),\r
329                                        System.currentTimeMillis ());\r
330 \r
331             throw new ASDCDownloadException ("Exception caught when downloading the artifact", e);\r
332         }\r
333 \r
334         if (DistributionActionResultEnum.SUCCESS.equals(downloadResult.getDistributionActionResult ())) {\r
335 \r
336             LOGGER.info (MessageEnum.ASDC_ARTIFACT_DOWNLOAD_SUC,\r
337                          artifact.getArtifactURL (),\r
338                          artifact.getArtifactUUID (),\r
339                          String.valueOf (downloadResult.getArtifactPayload ().length), "", "");\r
340 \r
341         } else {\r
342 \r
343             LOGGER.error (MessageEnum.ASDC_ARTIFACT_DOWNLOAD_FAIL,\r
344                           artifact.getArtifactName (),\r
345                           artifact.getArtifactURL (),\r
346                           artifact.getArtifactUUID (),\r
347                           downloadResult.getDistributionMessageResult (), "", "", MsoLogger.ErrorCode.DataError, "ASDC artifact download fail");\r
348 \r
349             this.sendASDCNotification (NotificationType.DOWNLOAD,\r
350                                        artifact.getArtifactURL (),\r
351                                        asdcConfig.getConsumerID (),\r
352                                        distributionId,\r
353                                        DistributionStatusEnum.DOWNLOAD_ERROR,\r
354                                        downloadResult.getDistributionMessageResult (),\r
355                                        System.currentTimeMillis ());\r
356 \r
357             throw new ASDCDownloadException ("Artifact " + artifact.getArtifactName ()\r
358                                              + " could not be downloaded from ASDC URL "\r
359                                              + artifact.getArtifactURL ()\r
360                                              + UUID_PARAM\r
361                                              + artifact.getArtifactUUID ()\r
362                                              + ")"\r
363                                              + System.lineSeparator ()\r
364                                              + "Error message is "\r
365                                              + downloadResult.getDistributionMessageResult ()\r
366                                              + System.lineSeparator ());\r
367 \r
368         }\r
369 \r
370         this.sendASDCNotification (NotificationType.DOWNLOAD,\r
371                                    artifact.getArtifactURL (),\r
372                                    asdcConfig.getConsumerID (),\r
373                                    distributionId,\r
374                                    DistributionStatusEnum.DOWNLOAD_OK,\r
375                                    null,\r
376                                    System.currentTimeMillis ());\r
377         return downloadResult;\r
378 \r
379     }\r
380 \r
381     private void writeArtifactToFile (IArtifactInfo artifact,\r
382                 IDistributionClientDownloadResult resultArtifact) throws ASDCDownloadException {\r
383 \r
384         LOGGER.debug ("Trying to download the artifact : " + artifact.getArtifactURL ()\r
385                         + UUID_PARAM\r
386                         + artifact.getArtifactUUID ()\r
387                         + ")");\r
388         \r
389         File spoolFile = new File(System.getProperty("mso.config.path") + "/ASDC" + "/" + artifact.getArtifactName()); \r
390                 \r
391         \r
392         byte[] payloadBytes = resultArtifact.getArtifactPayload();\r
393         \r
394         try {\r
395                 LOGGER.info(MessageEnum.ASDC_RECEIVE_SERVICE_NOTIF, "***WRITE FILE ARTIFACT NAME", "ASDC", artifact.getArtifactName());\r
396 \r
397                 FileOutputStream outFile = new FileOutputStream(System.getProperty("mso.config.path") + "/ASDC" + "/" + artifact.getArtifactName());\r
398                 outFile.write(payloadBytes, 0, payloadBytes.length);\r
399                 outFile.close();\r
400                 } catch (Exception e) { \r
401                         LOGGER.debug("Exception :",e);\r
402                 LOGGER.error(MessageEnum.ASDC_ARTIFACT_DOWNLOAD_FAIL,\r
403                                         artifact.getArtifactName (),\r
404                                         artifact.getArtifactURL (),\r
405                                         artifact.getArtifactUUID (),\r
406                                         resultArtifact.getDistributionMessageResult (), "", "", MsoLogger.ErrorCode.DataError, "ASDC write to file failed"); \r
407             } \r
408         \r
409     }\r
410 \r
411 \r
412     private void sendDeployNotificationsForResource(VfResourceStructure vfResourceStructure,DistributionStatusEnum distribStatus, String errorReason) {\r
413 \r
414         for (IArtifactInfo artifactInfo : vfResourceStructure.getResourceInstance().getArtifacts()) {\r
415 \r
416                 if (DistributionStatusEnum.DEPLOY_OK.equals(distribStatus)\r
417                                 // This could be NULL if the artifact is a VF module artifact, this won't be present in the MAP\r
418                                 && vfResourceStructure.getArtifactsMapByUUID().get(artifactInfo.getArtifactUUID()) != null\r
419                                 && vfResourceStructure.getArtifactsMapByUUID().get(artifactInfo.getArtifactUUID()).getDeployedInDb() == 0) {\r
420                         this.sendASDCNotification (NotificationType.DEPLOY,\r
421                                         artifactInfo.getArtifactURL (),\r
422                           asdcConfig.getConsumerID (),\r
423                           vfResourceStructure.getNotification().getDistributionID(),\r
424                           DistributionStatusEnum.DEPLOY_ERROR,\r
425                           "The artifact has not been used by the modules defined in the resource",\r
426                           System.currentTimeMillis ());\r
427                 } else {\r
428                         this.sendASDCNotification (NotificationType.DEPLOY,\r
429                                         artifactInfo.getArtifactURL (),\r
430                           asdcConfig.getConsumerID (),\r
431                           vfResourceStructure.getNotification().getDistributionID(),\r
432                           distribStatus,\r
433                           errorReason,\r
434                           System.currentTimeMillis ());\r
435                 }\r
436         }\r
437     }\r
438 \r
439     private void deployResourceStructure (VfResourceStructure resourceStructure, ToscaResourceStructure toscaResourceStructure) throws ArtifactInstallerException {\r
440 \r
441         LOGGER.info (MessageEnum.ASDC_START_DEPLOY_ARTIFACT, resourceStructure.getResourceInstance().getResourceInstanceName(), resourceStructure.getResourceInstance().getResourceUUID(), "ASDC", "deployResourceStructure");\r
442         try {\r
443                 String resourceType = resourceStructure.getResourceInstance().getResourceType();\r
444                 String category = resourceStructure.getResourceInstance().getCategory();\r
445                 if("VF".equals(resourceType) && !"Allotted Resource".equalsIgnoreCase(category)){\r
446                         resourceStructure.createVfModuleStructures();\r
447                 }\r
448                 //resourceInstaller.installTheResource (resourceStructure);\r
449                                 \r
450                         //ToscaResourceInstaller tri = new ToscaResourceInstaller();\r
451                 toscaInstaller.installTheResource(toscaResourceStructure, resourceStructure);\r
452                         \r
453                 /*      if(toscaResourceStructure.isVnfAlreadyInstalled()){\r
454                     LOGGER.info (MessageEnum.ASDC_ARTIFACT_ALREADY_EXIST,\r
455                                 toscaResourceStructure.getCatalogVnfResource().getModelName(),\r
456                                 toscaResourceStructure.getCatalogVnfResource().getModelUuid(),\r
457                                 toscaResourceStructure.getCatalogVnfResource().getModelUuid(),"","");\r
458 \r
459             \r
460                     this.sendDeployNotificationsForResource(resourceStructure,DistributionStatusEnum.ALREADY_DOWNLOADED,null);\r
461                     this.sendDeployNotificationsForResource(resourceStructure,DistributionStatusEnum.ALREADY_DEPLOYED,null);\r
462                         } */\r
463 \r
464         } catch (ArtifactInstallerException e) {\r
465                 LOGGER.info (MessageEnum.ASDC_ARTIFACT_DOWNLOAD_FAIL,\r
466                                 resourceStructure.getResourceInstance().getResourceName(),\r
467                                 resourceStructure.getResourceInstance().getResourceUUID(),\r
468                         String.valueOf (resourceStructure.getVfModuleStructure().size()), "ASDC", "deployResourceStructure");\r
469                 sendDeployNotificationsForResource(resourceStructure,DistributionStatusEnum.DEPLOY_ERROR,e.getMessage());\r
470                 throw e;\r
471         }\r
472 \r
473         if (resourceStructure.isDeployedSuccessfully()) {\r
474                 LOGGER.info (MessageEnum.ASDC_ARTIFACT_DEPLOY_SUC,\r
475                                 resourceStructure.getResourceInstance().getResourceName(),\r
476                                 resourceStructure.getResourceInstance().getResourceUUID(),\r
477                         String.valueOf (resourceStructure.getVfModuleStructure().size()), "ASDC", "deployResourceStructure");\r
478                 sendDeployNotificationsForResource(resourceStructure,DistributionStatusEnum.DEPLOY_OK ,null);\r
479         }\r
480 \r
481     }\r
482 \r
483     private enum NotificationType {\r
484         DOWNLOAD, DEPLOY\r
485     }\r
486 \r
487     private void sendASDCNotification (NotificationType notificationType,\r
488                                        String artifactURL,\r
489                                        String consumerID,\r
490                                        String distributionID,\r
491                                        DistributionStatusEnum status,\r
492                                        String errorReason,\r
493                                        long timestamp) {\r
494 \r
495         String event = "Sending " + notificationType.name ()\r
496                        + "("\r
497                        + status.name ()\r
498                        + ")"\r
499                        + " notification to ASDC for artifact:"\r
500                        + artifactURL;\r
501 \r
502         if (errorReason != null) {\r
503                 event=event+"("+errorReason+")";\r
504         }\r
505         LOGGER.info (MessageEnum.ASDC_SEND_NOTIF_ASDC, notificationType.name (), status.name (), artifactURL, "ASDC", "sendASDCNotification");\r
506         LOGGER.debug (event);\r
507 \r
508         long subStarttime = System.currentTimeMillis ();\r
509         String action = "";\r
510         try {\r
511             IDistributionStatusMessage message = new DistributionStatusMessage (artifactURL,\r
512                                                                                 consumerID,\r
513                                                                                 distributionID,\r
514                                                                                 status,\r
515                                                                                 timestamp);\r
516 \r
517             switch (notificationType) {\r
518                 case DOWNLOAD:\r
519                     if (errorReason != null) {\r
520                         this.distributionClient.sendDownloadStatus (message, errorReason);\r
521                     } else {\r
522                         this.distributionClient.sendDownloadStatus (message);\r
523                     }\r
524                     action = "sendDownloadStatus";\r
525                     break;\r
526                 case DEPLOY:\r
527                     if (errorReason != null) {\r
528                         this.distributionClient.sendDeploymentStatus (message, errorReason);\r
529                     } else {\r
530                         this.distributionClient.sendDeploymentStatus (message);\r
531                     }\r
532                     action = "sendDeploymentdStatus";\r
533                     break;\r
534                 default:\r
535                         break;\r
536             }\r
537         } catch (RuntimeException e) {\r
538             // TODO: May be a list containing the unsent notification should be\r
539             // kept\r
540             LOGGER.warn (MessageEnum.ASDC_SEND_NOTIF_ASDC_EXEC, "ASDC", "sendASDCNotification", MsoLogger.ErrorCode.SchemaError, "RuntimeException - sendASDCNotification", e);\r
541         }\r
542         LOGGER.recordMetricEvent (subStarttime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully sent notification to ASDC", "ASDC", action, null);\r
543     }\r
544 \r
545     public void treatNotification (INotificationData iNotif) {\r
546 \r
547         int noOfArtifacts = 0;\r
548         for (IResourceInstance resource : iNotif.getResources ()) {\r
549                 noOfArtifacts += resource.getArtifacts ().size ();\r
550         }\r
551         LOGGER.info (MessageEnum.ASDC_RECEIVE_CALLBACK_NOTIF,\r
552                      String.valueOf (noOfArtifacts),\r
553                      iNotif.getServiceUUID (), "ASDC", "treatNotification");\r
554 \r
555         try {\r
556                 LOGGER.debug(ASDCNotificationLogging.dumpASDCNotification(iNotif));\r
557                         LOGGER.info(MessageEnum.ASDC_RECEIVE_SERVICE_NOTIF, iNotif.getServiceUUID(), "ASDC", "treatNotification");\r
558                         this.changeControllerStatus(ASDCControllerStatus.BUSY);\r
559                         \r
560                         \r
561                                                 \r
562                         // Process only the Resource artifacts in MSO\r
563                         for (IResourceInstance resource : iNotif.getResources()) {\r
564 \r
565                                 // We process only VNF(VF) and Network(VL) resources on MSO Side\r
566                                 // We process only VNF resource on MSO Side\r
567                                 if ("VF".equals(resource.getResourceType()) || "VL".equals(resource.getResourceType())) {\r
568                                         this.processResourceNotification(iNotif,resource);\r
569                                 }\r
570 \r
571                         }\r
572 \r
573 \r
574 \r
575         } catch (RuntimeException e) {\r
576             LOGGER.error (MessageEnum.ASDC_GENERAL_EXCEPTION_ARG,\r
577                           "Unexpected exception caught during the notification processing", "ASDC", "treatNotification", MsoLogger.ErrorCode.SchemaError, "RuntimeException in treatNotification",\r
578                           e);\r
579         } finally {\r
580             this.changeControllerStatus (ASDCControllerStatus.IDLE);\r
581         }\r
582     }\r
583 \r
584 \r
585     private void processResourceNotification (INotificationData iNotif,IResourceInstance resource) {\r
586                 // For each artifact, create a structure describing the VFModule in a ordered flat level\r
587         VfResourceStructure resourceStructure = new VfResourceStructure(iNotif,resource);\r
588         ToscaResourceStructure toscaResourceStructure = new ToscaResourceStructure();\r
589 \r
590                 try {\r
591 \r
592                         if (!this.checkResourceAlreadyDeployed(resourceStructure)) {\r
593                                 for (IArtifactInfo artifact : resource.getArtifacts()) {\r
594 \r
595                                                 IDistributionClientDownloadResult resultArtifact = this.downloadTheArtifact(artifact,\r
596                                                                 iNotif.getDistributionID());\r
597 \r
598                                                 if (resultArtifact != null) {\r
599                                                         if (ASDCConfiguration.VF_MODULES_METADATA.equals(artifact.getArtifactType())) {\r
600                                                                 LOGGER.debug("VF_MODULE_ARTIFACT: "+new String(resultArtifact.getArtifactPayload(),"UTF-8"));\r
601                                                                 LOGGER.debug(ASDCNotificationLogging.dumpVfModuleMetaDataList(resourceStructure.decodeVfModuleArtifact(resultArtifact.getArtifactPayload())));\r
602                                                         }\r
603                                                         resourceStructure.addArtifactToStructure(distributionClient,artifact, resultArtifact);\r
604 \r
605                                                 }\r
606 \r
607                                 }\r
608 \r
609                                 this.processCsarServiceArtifacts(iNotif, toscaResourceStructure);\r
610                                 \r
611                                 this.deployResourceStructure(resourceStructure, toscaResourceStructure);\r
612 \r
613                         }\r
614                 } catch (ArtifactInstallerException | ASDCDownloadException | UnsupportedEncodingException e) {\r
615                         LOGGER.error(MessageEnum.ASDC_GENERAL_EXCEPTION_ARG,\r
616                                         "Exception caught during Installation of artifact", "ASDC", "processResourceNotification", MsoLogger.ErrorCode.BusinessProcesssError, "Exception in processResourceNotification", e);\r
617                 }\r
618     }\r
619 \r
620     private void processCsarServiceArtifacts (INotificationData iNotif, ToscaResourceStructure toscaResourceStructure) {\r
621         \r
622         List<IArtifactInfo> serviceArtifacts = iNotif.getServiceArtifacts();\r
623         \r
624                 for(IArtifactInfo artifact : serviceArtifacts){\r
625                 \r
626                         if(artifact.getArtifactType().equals(ASDCConfiguration.TOSCA_CSAR)){\r
627                                 \r
628                                 try{\r
629                                         \r
630                                         toscaResourceStructure.setToscaArtifact(artifact);\r
631                                         \r
632                                         IDistributionClientDownloadResult resultArtifact = this.downloadTheArtifact(artifact,iNotif.getDistributionID());\r
633                                         \r
634                                         writeArtifactToFile(artifact, resultArtifact);\r
635                                         \r
636                                         toscaResourceStructure.updateResourceStructure(artifact);\r
637                                         \r
638                                         toscaResourceStructure.setServiceVersion(iNotif.getServiceVersion());\r
639                                         \r
640                                         LOGGER.debug(ASDCNotificationLogging.dumpCSARNotification(iNotif, toscaResourceStructure));\r
641                                         \r
642 \r
643                                 } catch(Exception e){\r
644                                         System.out.println("Whats the error " + e.getMessage());\r
645                                         LOGGER.error(MessageEnum.ASDC_GENERAL_EXCEPTION_ARG,\r
646                                                         "Exception caught during processCsarServiceArtifacts", "ASDC", "processCsarServiceArtifacts", MsoLogger.ErrorCode.BusinessProcesssError, "Exception in processCsarServiceArtifacts", e);\r
647                                 }\r
648                         }\r
649                                 \r
650                 }\r
651     }\r
652     \r
653     private static final String UNKNOWN="Unknown";\r
654 \r
655     /**\r
656      * @return the address of the ASDC we are connected to.\r
657      */\r
658     public String getAddress () {\r
659         if (asdcConfig != null) {\r
660             return asdcConfig.getAsdcAddress ();\r
661         }\r
662         return UNKNOWN;\r
663     }\r
664 \r
665     /**\r
666      * @return the environment name of the ASDC we are connected to.\r
667      */\r
668     public String getEnvironment () {\r
669         if (asdcConfig != null) {\r
670             return asdcConfig.getEnvironmentName ();\r
671         }\r
672         return UNKNOWN;\r
673     }\r
674 \r
675 }\r