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