cc1be4702973111f2f2d50ec0e798571afec827e
[so.git] / bpmn / MSOCommonBPMN / src / main / groovy / org / onap / so / bpmn / common / scripts / CreateAAIVfModuleVolumeGroup.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.so.bpmn.common.scripts
22
23 import org.camunda.bpm.engine.delegate.BpmnError
24 import org.camunda.bpm.engine.delegate.DelegateExecution
25 import org.onap.so.bpmn.core.UrnPropertiesReader
26 import org.onap.so.client.aai.AAIObjectType
27 import org.onap.so.client.aai.entities.uri.AAIResourceUri
28 import org.onap.so.client.aai.entities.uri.AAIUriFactory
29 import org.onap.so.rest.APIResponse
30 import org.onap.so.logger.MessageEnum
31 import org.onap.so.logger.MsoLogger
32
33 public class CreateAAIVfModuleVolumeGroup extends AbstractServiceTaskProcessor {
34         private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, CreateAAIVfModuleVolumeGroup.class);
35
36         private XmlParser xmlParser = new XmlParser()
37         ExceptionUtil exceptionUtil = new ExceptionUtil()
38
39         /**
40          * Initialize the flow's variables.
41          *
42          * @param execution The flow's execution instance.
43          */
44         public void initProcessVariables(DelegateExecution execution) {
45                 execution.setVariable('prefix', 'CAAIVfModVG_')
46                 execution.setVariable('CAAIVfModVG_vnfId', null)
47                 execution.setVariable('CAAIVfModVG_vfModuleId', null)
48                 execution.setVariable('CAAIVfModVG_aicCloudRegion', null)
49                 execution.setVariable('CAAIVfModVG_volumeGroupId', null)
50                 execution.setVariable('CAAIVfModVG_getVfModuleResponseCode' ,null)
51                 execution.setVariable('CAAIVfModVG_getVfModuleResponse', '')
52                 execution.setVariable('CAAIVfModVG_updateVfModuleResponseCode', null)
53                 execution.setVariable('CAAIVfModVG_updateVfModuleResponse', '')
54         }
55
56         /**
57          * Check for missing elements in the received request.
58          *
59          * @param execution The flow's execution instance.
60          */
61         public void preProcessRequest(DelegateExecution execution) {
62                 def method = getClass().getSimpleName() + '.preProcessRequest(' +
63                         'execution=' + execution.getId() +
64                         ')'
65                 msoLogger.trace('Entered ' + method)
66
67                 try {
68                         def xml = execution.getVariable('CreateAAIVfModuleVolumeGroupRequest')
69                         msoLogger.debug('Received request xml:\n' + xml)
70                         msoLogger.debug("CreateAAIVfModuleVolume Received Request XML: " + xml)
71                         initProcessVariables(execution)
72
73                         def vnfId = getRequiredNodeText(execution, xml,'vnf-id')
74                         execution.setVariable('CAAIVfModVG_vnfId', vnfId)
75
76                         def vfModuleId = getRequiredNodeText(execution, xml,'vf-module-id')
77                         execution.setVariable('CAAIVfModVG_vfModuleId', vfModuleId)
78                         
79                         def aicCloudRegion = getRequiredNodeText(execution, xml,'aic-cloud-region')
80                         execution.setVariable('CAAIVfModVG_aicCloudRegion', aicCloudRegion)
81                         
82                         def cloudOwner = getRequiredNodeText(execution, xml,'cloud-owner')
83                         execution.setVariable('CAAIVfModVG_cloudOwner', cloudOwner)
84                         
85                         def volumeGroupId = getRequiredNodeText(execution, xml,'volume-group-id')
86                         execution.setVariable('CAAIVfModVG_volumeGroupId', volumeGroupId)
87
88                         msoLogger.trace('Exited ' + method)
89                 } catch (BpmnError e) {
90                         throw e;
91                 } catch (Exception e) {
92                         msoLogger.error(e);
93                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in preProcessRequest(): ' + e.getMessage())
94
95                 }
96         }
97
98         /**
99          * Using the received vnfId and vfModuleId, query AAI to get the corresponding VF Module.
100          * A 200 response is expected with the VF Module in the response body.
101          *
102          * @param execution The flow's execution instance.
103          */
104         public void getVfModule(DelegateExecution execution) {
105                 def method = getClass().getSimpleName() + '.getVfModule(' +
106                         'execution=' + execution.getId() +
107                         ')'
108                 msoLogger.trace('Entered ' + method)
109
110                 try {
111                         def vnfId = execution.getVariable('CAAIVfModVG_vnfId')
112                         def vfModuleId = execution.getVariable('CAAIVfModVG_vfModuleId')
113
114                         AaiUtil aaiUtil = new AaiUtil(this)
115                         AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId)
116                         String endPoint = aaiUtil.createAaiUri(uri)
117                                         
118                         try {
119                                 msoLogger.debug('sending GET to AAI endpoint \'' + endPoint + '\'')
120                                 msoLogger.debug("aaiResponse GET TO AAI Endpoint: " + endPoint)
121                                 APIResponse response = aaiUtil.executeAAIGetCall(execution, endPoint)
122                                 def responseData = response.getResponseBodyAsString()
123                                 execution.setVariable('CAAIVfModVG_getVfModuleResponseCode', response.getStatusCode())
124                                 execution.setVariable('CAAIVfModVG_getVfModuleResponse', responseData)
125                                 
126                                 msoLogger.debug("CreateAAIVfModule Response Code: " + response.getStatusCode())
127                                 msoLogger.debug("CreateAAIVfModule Response: " + response)
128                                 msoLogger.debug('Response code:' + response.getStatusCode())
129                                 msoLogger.debug('Response:' + System.lineSeparator() + responseData)
130                         } catch (Exception ex) {
131                                 ex.printStackTrace()
132                                 msoLogger.debug('Exception occurred while executing AAI GET:' + ex.getMessage())
133                                 execution.setVariable('CAAIVfModVG_getVfModuleResponseCode', 500)
134                                 execution.setVariable('CAAIVfModVG_getVfModuleResponse', 'AAI GET Failed:' + ex.getMessage())
135                         }
136                         msoLogger.trace('Exited ' + method)
137                 } catch (BpmnError e) {
138                         throw e;
139                 } catch (Exception e) {
140                         msoLogger.error(e);
141                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in getVfModule(): ' + e.getMessage())
142                 }
143         }
144
145         /**
146          * Construct and send a PUT request to AAI to update the VF Module with the
147          * created Volume Group relationship.
148          *
149          * @param execution The flow's execution instance.
150          */
151         public void updateVfModule(DelegateExecution execution) {
152                 def method = getClass().getSimpleName() + '.updateVfModule(' +
153                         'execution=' + execution.getId() +
154                         ')'
155                 msoLogger.trace('Entered ' + method)
156
157                 try {
158                         def vnfId = execution.getVariable('CAAIVfModVG_vnfId')
159                         def vfModuleId = execution.getVariable('CAAIVfModVG_vfModuleId')
160                         def vfModule = execution.getVariable('CAAIVfModVG_getVfModuleResponse')
161                         def origRequest = execution.getVariable('CreateAAIVfModuleVolumeGroupRequest')
162                         def Node vfModuleNode = xmlParser.parseText(vfModule)
163                         
164                         // Confirm resource-version is in retrieved VF Module
165                         if (utils.getChildNode(vfModuleNode, 'resource-version') == null) {
166                                 def msg = 'Can\'t update VF Module ' + vfModuleId + ' since \'resource-version\' is missing'
167                                 msoLogger.error( msg);
168                                 throw new Exception(msg)
169                         }
170                                                 
171                         // Construct payload by creating a Volume Group relationhip and inserting it into the VF Module
172                         def aicCloudRegion = execution.getVariable('CAAIVfModVG_aicCloudRegion')
173                         def cloudOwner = execution.getVariable('CAAIVfModVG_cloudOwner')
174                         def volumeGroupId = execution.getVariable('CAAIVfModVG_volumeGroupId')
175                         def Node vgRelationshipNode = createVolumeGroupRelationshipNode(cloudOwner, aicCloudRegion, volumeGroupId)
176                         insertVolumeGroupRelationshipNode(vfModuleNode, vgRelationshipNode)
177                         def payload = utils.nodeToString(vfModuleNode)
178
179                         AaiUtil aaiUtil = new AaiUtil(this)
180                         AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId)
181                         String endPoint = aaiUtil.createAaiUri(uri)
182         
183                         try {
184                                 msoLogger.debug("CreateAAIVfModuleVolume Sendind PUT to AAI Endpoint \n " + endPoint + " with payload \n " + payload)
185                                 msoLogger.debug('sending PUT to AAI endpoint \'' + endPoint + '\'' + 'with payload \n' + payload)
186                                 APIResponse response = aaiUtil.executeAAIPutCall(execution, endPoint, payload)
187                                 def responseData = response.getResponseBodyAsString()
188                                 execution.setVariable('CAAIVfModVG_updateVfModuleResponseCode', response.getStatusCode())
189                                 execution.setVariable('CAAIVfModVG_updateVfModuleResponse', responseData)
190                                 
191                                 msoLogger.debug("CreateAAIVfModule Response code: " + response.getStatusCode())
192                                 msoLogger.debug("CreateAAIVfModule Response: " + responseData)
193                                 msoLogger.debug('Response code:' + response.getStatusCode())
194                                 msoLogger.debug('Response:' + System.lineSeparator() + responseData)
195                         } catch (Exception ex) {
196                                 ex.printStackTrace()
197                                 msoLogger.debug('Exception occurred while executing AAI PUT:' + ex.getMessage())
198                                 execution.setVariable('CAAIVfModVG_updateVfModuleResponseCode', 500)
199                                 execution.setVariable('CAAIVfModVG_updateVfModuleResponse', 'AAI PUT Failed:' + ex.getMessage())
200                         }
201                         msoLogger.trace('Exited ' + method)
202                 } catch (BpmnError e) {
203                         throw e;
204                 } catch (Exception e) {
205                         msoLogger.error(e);
206                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in updateVfModule(): ' + e.getMessage())
207                 }
208         }
209
210         /**
211          * Construct a Volume Group relationship Node with the given AIC Cloud Region and
212          * Volume Group ID for insertion into a VF Module.
213          * 
214          * @param aicCloudRegion Cloud Region ID to use in the Volume Group relationship
215          * @param volumeGroupId Volume Group ID to use in the Volume Group relationship
216          * @return a Node representing the new Volume Group relationship
217          */
218         private Node createVolumeGroupRelationshipNode(String cloudOwner, String aicCloudRegion, String volumeGroupId) {
219                 
220                 def Node relatedTo = new Node(null, 'related-to', 'volume-group')
221                 
222                 def Node relationshipKeyCO = new Node(null, 'relationship-key', 'cloud-region.cloud-owner')
223                 def Node relationshipValueCO = new Node(null, 'relationship-value', cloudOwner)
224                 def Node relationshipDataCO = new Node(null, 'relationship-data')
225                 relationshipDataCO.append(relationshipKeyCO)
226                 relationshipDataCO.append(relationshipValueCO)
227                 
228                 def Node relationshipKeyCRI = new Node(null, 'relationship-key', 'cloud-region.cloud-region-id')
229                 def Node relationshipValueCRI = new Node(null, 'relationship-value', aicCloudRegion)
230                 def Node relationshipDataCRI = new Node(null, 'relationship-data')
231                 relationshipDataCRI.append(relationshipKeyCRI)
232                 relationshipDataCRI.append(relationshipValueCRI)
233
234                 def Node relationshipKeyVGI = new Node(null, 'relationship-key', 'volume-group.volume-group-id')
235                 def Node relationshipValueVGI = new Node(null, 'relationship-value', volumeGroupId)
236                 def Node relationshipDataVGI = new Node(null, 'relationship-data')
237                 relationshipDataVGI.append(relationshipKeyVGI)
238                 relationshipDataVGI.append(relationshipValueVGI)
239                 
240                 def Node volumeGroupRelationship = new Node(null, 'relationship')
241                 volumeGroupRelationship.append(relatedTo)
242                 volumeGroupRelationship.append(relationshipDataCO)
243                 volumeGroupRelationship.append(relationshipDataCRI)
244                 volumeGroupRelationship.append(relationshipDataVGI)
245                 
246                 return volumeGroupRelationship;
247         }
248         
249         /**
250          * Insert the given Volume Group relationship Node into the given VF Module.
251          * If the VF Module does NOT contain a relationship list:
252          *      - Create a relationship list containing the Volume Group relationship and insert it into the VF Module
253          * If the VF Module contains a relationship list but not a Volume Group relationship:
254          *      - Insert the the Volume Group relationship into the relationship lsit
255          * If the VF Module contains a relationship list and has a Volume Group relationship:
256          *      - Replace the existing Volume Group relationship with the new one
257          * @param vfModuleNode
258          * @param volumeGroupRelationshipNode
259          */
260         private void insertVolumeGroupRelationshipNode(Node vfModuleNode, Node volumeGroupRelationshipNode) {
261                 def Node relationshipList = utils.getChildNode(vfModuleNode, 'relationship-list')
262                 if (relationshipList == null) {
263                         relationshipList = new Node(null, 'relationship-list')
264                         relationshipList.append(volumeGroupRelationshipNode)
265                         vfModuleNode.append(relationshipList)
266                 } else {
267                         def Node currVolumeGroupRelationshipNode = getCurrVolumeGroupRelationshipNode(relationshipList)
268                         if (currVolumeGroupRelationshipNode == null) {
269                                 relationshipList.append(volumeGroupRelationshipNode)
270                         } else {
271                                 currVolumeGroupRelationshipNode.replaceNode(volumeGroupRelationshipNode)
272                         }
273                 }
274         }
275                 
276         /**
277          * Find and return the value of the Volume Group ID for the specified VF Module.  If
278          * the value of the Volume Group ID cannot be found for any reason, 'null' is returned.
279          * 
280          * @param vfModuleNode VF Module (as a Node) retrieved from AAI.
281          * @return the value of the Volume Group ID for the specified VF Module.  If the
282          * value of the Volume Group ID cannot be found for any reason, 'null' is returned.
283          */
284         private Node getCurrVolumeGroupRelationshipNode(Node relationshipList) {
285                 def Node currVolumeGroupRelationshipNode = null
286                 def NodeList relationships = utils.getIdenticalChildren(relationshipList, 'relationship')
287                 for (Node relationshipNode in relationships) {
288                         def String relatedTo = utils.getChildNodeText(relationshipNode, 'related-to')
289                         if ((relatedTo != null) && relatedTo.equals('volume-group')) {
290                                 currVolumeGroupRelationshipNode = relationshipNode
291                         }
292                 }
293                 return currVolumeGroupRelationshipNode
294         }
295
296         /**
297          * Generates a WorkflowException if the AAI query returns a response code other than 200.
298          *
299          * @param execution The flow's execution instance.
300          */
301         public void handleAAIQueryFailure(DelegateExecution execution) {
302                 def method = getClass().getSimpleName() + '.handleAAIQueryFailure(' +
303                         'execution=' + execution.getId() +
304                         ')'
305                 msoLogger.trace('Entered ' + method)
306                 msoLogger.error( 'Error occurred attempting to query AAI, Response Code ' + execution.getVariable('CAAIVfModVG_getVfModuleResponseCode'));              
307                 ExceptionUtil exceptionUtil = new ExceptionUtil()
308                 exceptionUtil.buildWorkflowException(execution, 5000, execution.getVariable('CAAIVfModVG_getVfModuleResponse'))
309
310                 msoLogger.trace('Exited ' + method)
311         }
312
313         /**
314          * Generates a WorkflowException if updating a VF Module in AAI returns a response code other than 200.
315          *
316          * @param execution The flow's execution instance.
317          */
318         public void handleUpdateVfModuleFailure(DelegateExecution execution) {
319                 def method = getClass().getSimpleName() + '.handleUpdateVfModuleFailure(' +
320                         'execution=' + execution.getId() +
321                         ')'
322                 msoLogger.trace('Entered ' + method)
323
324                 msoLogger.error('Error occurred attempting to update VF Module in AAI, Response Code ' + execution.getVariable('CAAIVfModVG_updateVfModuleResponseCode'));
325                 ExceptionUtil exceptionUtil = new ExceptionUtil()
326                 exceptionUtil.buildWorkflowException(execution, 5000, execution.getVariable('CAAIVfModVG_updateVfModuleResponse'))
327
328                 msoLogger.trace('Exited ' + method)
329         }
330 }