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