Remove unnecessary use of Calendar.getInstance()
[so.git] / bpmn / MSOCommonBPMN / src / main / groovy / org / openecomp / mso / bpmn / common / scripts / UpdateAAIGenericVnf.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * OPENECOMP - MSO
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.openecomp.mso.bpmn.common.scripts
22
23 import org.camunda.bpm.engine.delegate.BpmnError
24 import org.camunda.bpm.engine.runtime.Execution
25 import org.openecomp.mso.bpmn.core.WorkflowException
26 import org.openecomp.mso.rest.APIResponse
27 import org.springframework.web.util.UriUtils
28
29
30 public class UpdateAAIGenericVnf extends AbstractServiceTaskProcessor {
31
32         private XmlParser xmlParser = new XmlParser()
33
34         /**
35          * Initialize the flow's variables.
36          *
37          * @param execution The flow's execution instance.
38          */
39         public void initProcessVariables(Execution execution) {
40                 execution.setVariable('prefix', 'UAAIGenVnf_')
41                 execution.setVariable('UAAIGenVnf_vnfId', null)
42                 execution.setVariable('UAAIGenVnf_personaModelId', null)
43                 execution.setVariable('UAAIGenVnf_personaModelVersion', null)
44                 execution.setVariable("UAAIGenVnf_ipv4OamAddress", null)
45                 execution.setVariable('UAAIGenVnf_managementV6Address', null)
46                 execution.setVariable('UAAIGenVnf_getGenericVnfResponseCode' ,null)
47                 execution.setVariable('UAAIGenVnf_getGenericVnfResponse', '')
48                 execution.setVariable('UAAIGenVnf_updateGenericVnfResponseCode', null)
49                 execution.setVariable('UAAIGenVnf_updateGenericVnfResponse', '')
50         }
51
52         /**
53          * Check for missing elements in the received request.
54          *
55          * @param execution The flow's execution instance.
56          */
57         public void preProcessRequest(Execution execution) {
58                 def method = getClass().getSimpleName() + '.preProcessRequest(' +
59                         'execution=' + execution.getId() +
60                         ')'
61                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
62                 logDebug('Entered ' + method, isDebugLogEnabled)
63
64                 try {
65                         def xml = execution.getVariable('UpdateAAIGenericVnfRequest')
66                         logDebug('Received request xml:\n' + xml, isDebugLogEnabled)
67                         utils.logAudit("UpdateAAIGenericVnf Request XML: " + xml)
68                         initProcessVariables(execution)
69
70                         def vnfId = getRequiredNodeText(execution, xml,'vnf-id')
71                         execution.setVariable('UAAIGenVnf_vnfId', vnfId)
72
73                         def personaModelId = getNodeTextForce(xml,'persona-model-id')
74                         if (personaModelId != null && !personaModelId.isEmpty()) {
75                                 execution.setVariable('UAAIGenVnf_personaModelId', personaModelId)
76                         }
77                         
78                         def personaModelVersion = getNodeTextForce(xml,'persona-model-version')
79                         if (personaModelVersion != null && !personaModelVersion.isEmpty()) {
80                                 execution.setVariable('UAAIGenVnf_personaModelVersion', personaModelVersion)
81                         }
82                         
83                         def ipv4OamAddress = getNodeTextForce(xml, 'ipv4-oam-address')
84                         if (ipv4OamAddress != null && !ipv4OamAddress.isEmpty()) {
85                                 execution.setVariable('UAAIGenVnf_ipv4OamAddress', ipv4OamAddress)
86                         }
87                         
88                         def managementV6Address = getNodeTextForce(xml, 'management-v6-address')
89                         if (managementV6Address != null && !managementV6Address.isEmpty()) {
90                                 execution.setVariable('UAAIGenVnf_managementV6Address', managementV6Address)
91                         }
92                         
93                         logDebug('Exited ' + method, isDebugLogEnabled)
94                 } catch (BpmnError e) {
95                         throw e;
96                 } catch (Exception e) {
97                         logError('Caught exception in ' + method, e)
98                         createWorkflowException(execution, 1002, 'Error in preProcessRequest(): ' + e.getMessage())
99                 }
100         }
101
102         /**
103          * Using the received vnfId, query AAI to get the corresponding Generic VNF.
104          * A 200 response is expected with the VF Module in the response body.
105          *
106          * @param execution The flow's execution instance.
107          */
108         public void getGenericVnf(Execution execution) {
109                 def method = getClass().getSimpleName() + '.getGenericVnf(' +
110                         'execution=' + execution.getId() +
111                         ')'
112                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
113                 logDebug('Entered ' + method, isDebugLogEnabled)
114
115                 try {
116                         def vnfId = execution.getVariable('UAAIGenVnf_vnfId')
117
118                         // Construct endpoint
119                         AaiUtil aaiUriUtil = new AaiUtil(this)
120                         def aai_uri = aaiUriUtil.getNetworkGenericVnfUri(execution)
121                         logDebug('AAI URI is: ' + aai_uri, isDebugLogEnabled)
122                         String endPoint = execution.getVariable('URN_aai_endpoint') + aai_uri + '/' + UriUtils.encode(vnfId, "UTF-8") + "?depth=1"
123
124                         try {
125                                 logDebug('sending GET to AAI endpoint \'' + endPoint + '\'', isDebugLogEnabled)
126                                 utils.logAudit("Sending GET to AAI endpoint: " + endPoint)
127                                 
128                                 APIResponse response = aaiUriUtil.executeAAIGetCall(execution, endPoint)
129                                 def responseData = response.getResponseBodyAsString()
130                                 execution.setVariable('UAAIGenVnf_getGenericVnfResponseCode', response.getStatusCode())
131                                 execution.setVariable('UAAIGenVnf_getGenericVnfResponse', responseData)
132                                 utils.logAudit("UpdateAAIGenericVnf Response data: " + responseData)
133                                 logDebug('Response code:' + response.getStatusCode(), isDebugLogEnabled)
134                                 logDebug('Response:' + System.lineSeparator() + responseData, isDebugLogEnabled)
135                         } catch (Exception ex) {
136                                 ex.printStackTrace()
137                                 logDebug('Exception occurred while executing AAI GET:' + ex.getMessage(),isDebugLogEnabled)
138                                 execution.setVariable('UAAIGenVnf_getGenericVnfResponseCode', 500)
139                                 execution.setVariable('UAAIGenVnf_getGenericVnfResponse', 'AAI GET Failed:' + ex.getMessage())
140                         }
141                         logDebug('Exited ' + method, isDebugLogEnabled)
142                 } catch (BpmnError e) {
143                         throw e;
144                 } catch (Exception e) {
145                         logError('Caught exception in ' + method, e)
146                         createWorkflowException(execution, 1002, 'Error in getGenericVnf(): ' + e.getMessage())
147                 }
148         }
149
150         /**
151          * Construct and send a PUT request to AAI to update the Generic VNF.
152          *
153          * @param execution The flow's execution instance.
154          */
155         public void updateGenericVnf(Execution execution) {
156                 def method = getClass().getSimpleName() + '.updateGenericVnf(' +
157                         'execution=' + execution.getId() +
158                         ')'
159                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
160                 logDebug('Entered ' + method, isDebugLogEnabled)
161
162                 try {
163                         def vnfId = execution.getVariable('UAAIGenVnf_vnfId')
164                         def genericVnf = execution.getVariable('UAAIGenVnf_getGenericVnfResponse')
165                         def origRequest = execution.getVariable('UpdateAAIGenericVnfRequest')
166                         
167                         utils.logAudit("UpdateGenericVnf Request: " + origRequest)
168                         // Confirm resource-version is in retrieved Generic VNF
169                         def Node genericVnfNode = xmlParser.parseText(genericVnf)
170                         if (utils.getChildNode(genericVnfNode, 'resource-version') == null) {
171                                 def msg = 'Can\'t update Generic VNF ' + vnfId + ' since \'resource-version\' is missing'
172                                 logError(msg)
173                                 throw new Exception(msg)
174                         }
175                         
176                         // Handle persona-model-id/persona-model-version
177                         
178                         def String newPersonaModelId = execution.getVariable('UAAIGenVnf_personaModelId')
179                         def String newPersonaModelVersion = execution.getVariable('UAAIGenVnf_personaModelVersion')
180                         if (newPersonaModelId != null || newPersonaModelVersion != null) {
181                         
182                                 // Confirm "new" persona-model-id is same as "current" persona-model-id
183                                 def Node currPersonaModelIdNode = utils.getChildNode(genericVnfNode, 'persona-model-id')
184                                 def String currPersonaModelId = ''
185                                 if (currPersonaModelIdNode != null) {
186                                         currPersonaModelId = currPersonaModelIdNode.text()
187                                 }
188                                 if (!newPersonaModelId.equals(currPersonaModelId)) {
189                                         def msg = 'Can\'t update Generic VNF ' + vnfId + ' since there is \'persona-model-id\' mismatch between the current and new values'
190                                         logError(msg)
191                                         throw new Exception(msg)
192                                 }
193                         
194                                 // Construct payload
195                                 updateGenericVnfNode(origRequest, genericVnfNode, 'persona-model-version')
196                         }
197                         
198                         // Handle ipv4-oam-address
199                         def String ipv4OamAddress = execution.getVariable('UAAIGenVnf_ipv4OamAddress')
200                         if (ipv4OamAddress != null) {
201                                 // Construct payload
202                                 updateGenericVnfNode(origRequest, genericVnfNode, 'ipv4-oam-address')
203                         }
204                         
205                         // Handle management-v6-address
206                         def String managementV6Address = execution.getVariable('UAAIGenVnf_managementV6Address')
207                         if (managementV6Address != null) {
208                                 // Construct payload
209                                 updateGenericVnfNode(origRequest, genericVnfNode, 'management-v6-address')
210                         }
211                                                 
212                         def payload = utils.nodeToString(genericVnfNode)
213
214                         // Construct endpoint
215                         AaiUtil aaiUriUtil = new AaiUtil(this)
216                         def aai_uri = aaiUriUtil.getNetworkGenericVnfUri(execution)
217                         logDebug('AAI URI is: ' + aai_uri, isDebugLogEnabled)
218                         String endPoint = execution.getVariable('URN_aai_endpoint') + aai_uri + '/' + UriUtils.encode(vnfId, "UTF-8")
219
220                         try {
221                                 logDebug('sending PUT to AAI endpoint \'' + endPoint + '\'' + 'with payload \n' + payload, isDebugLogEnabled)
222                                 utils.logAudit("Sending PUT to AAI endpoint: " + endPoint)
223                                 
224                                 APIResponse response = aaiUriUtil.executeAAIPutCall(execution, endPoint, payload)
225                                 def responseData = response.getResponseBodyAsString()
226                                 execution.setVariable('UAAIGenVnf_updateGenericVnfResponseCode', response.getStatusCode())
227                                 execution.setVariable('UAAIGenVnf_updateGenericVnfResponse', responseData)
228                                 utils.logAudit("UpdateAAIGenericVnf Response Data: " + responseData)
229                                 logDebug('Response code:' + response.getStatusCode(), isDebugLogEnabled)
230                                 logDebug('Response:' + System.lineSeparator() + responseData, isDebugLogEnabled)
231                         } catch (Exception ex) {
232                                 ex.printStackTrace()
233                                 logDebug('Exception occurred while executing AAI PUT:' + ex.getMessage(),isDebugLogEnabled)
234                                 execution.setVariable('UAAIGenVnf_updateGenericVnfResponseCode', 500)
235                                 execution.setVariable('UAAIGenVnf_updateGenericVnfResponse', 'AAI PUT Failed:' + ex.getMessage())
236                         }
237                         logDebug('Exited ' + method, isDebugLogEnabled)
238                 } catch (BpmnError e) {
239                         throw e;
240                 } catch (Exception e) {
241                         logError('Caught exception in ' + method, e)
242                         createWorkflowException(execution, 1002, 'Error in updateGenericVnf(): ' + e.getMessage())
243                 }
244         }
245
246         /**
247          * Insert a new Node, replace the value of an existing Node, or delete an existing Node in the current
248          * Generic VNF Node, as necessary.
249          *
250          * If the Node with the same name already exists in current Generic VNF, but is not being updated, then do
251          * nothing. If the element is being updated and it already exists in the current Generic VNF, then check
252          * the value specified in the original request. If the value is 'DELETE', remove that Node from the
253          * current Generic VNF.  Otherwise, change the value to the specified new value. If the element is
254          * being updated but doesn't exist in the current Generic VNF, and the new value is not 'DELETE', then
255          * create an appropriate new node and add it to the Generic VNF.
256          *
257          * @param origRequest Incoming update request with Generic VNF element(s) to be updated.
258          * @param genericVnf Current Generic VNF retrieved from AAI.
259          * @param element Name of element to be inserted.
260          */
261         public void updateGenericVnfNode(String origRequest, Node genericVnfNode, String elementName) {
262
263                 if (!utils.nodeExists(origRequest, elementName)) {
264                         return
265                 }
266                 def elementValue = utils.getNodeText(origRequest, elementName)
267
268                 def Node childNode = utils.getChildNode(genericVnfNode, elementName)
269                 if (childNode == null) {
270                         if (elementValue.equals('DELETE')) {
271                                 // Element doesn't exist but is being deleted, so do nothing
272                                 return
273                         }
274                         // Node doesn't exist, create a new Node as a child
275                         new Node(genericVnfNode, elementName, elementValue)
276                 } else {
277                         if (elementValue.equals('DELETE')) {
278                                 // Node exists, but should be deleted
279                                 genericVnfNode.remove(childNode)
280                         } else {
281                                 // Node already exists, just give it a new value
282                                 childNode.setValue(elementValue)
283                         }
284                 }
285         }
286
287         /**
288          * Generates a WorkflowException if the AAI query returns a response code other than 200.
289          *
290          * @param execution The flow's execution instance.
291          */
292         public void handleAAIQueryFailure(Execution execution) {
293                 def method = getClass().getSimpleName() + '.handleAAIQueryFailure(' +
294                         'execution=' + execution.getId() +
295                         ')'
296                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
297                 logDebug('Entered ' + method, isDebugLogEnabled)
298
299                 logError('Error occurred attempting to query AAI, Response Code ' +
300                         execution.getVariable('UAAIGenVnf_getGenericVnfResponseCode') + ', Error Response ' +
301                         execution.getVariable('UAAIGenVnf_getGenericVnfResponse'))
302                 String processKey = getProcessKey(execution);
303                 WorkflowException exception = new WorkflowException(processKey, 5000,
304                         execution.getVariable('UAAIGenVnf_getGenericVnfResponse'))
305                 execution.setVariable('WorkflowException', exception)
306
307                 utils.logAudit("Workflow Exception occurred when handling Quering AAI: " + exception.getErrorMessage())
308                 logDebug('Exited ' + method, isDebugLogEnabled)
309         }
310
311         /**
312          * Generates a WorkflowException if updating a VF Module in AAI returns a response code other than 200.
313          *
314          * @param execution The flow's execution instance.
315          */
316         public void handleUpdateGenericVnfFailure(Execution execution) {
317                 def method = getClass().getSimpleName() + '.handleUpdateGenericVnfFailure(' +
318                         'execution=' + execution.getId() +
319                         ')'
320                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
321                 logDebug('Entered ' + method, isDebugLogEnabled)
322
323                 logError('Error occurred attempting to update Generic VNF in AAI, Response Code ' +
324                         execution.getVariable('UAAIGenVnf_updateGenericVnfResponseCode') + ', Error Response ' +
325                         execution.getVariable('UAAIGenVnf_updateGenericVnfResponse'))
326                 
327                 String processKey = getProcessKey(execution);
328                 WorkflowException exception = new WorkflowException(processKey, 5000,
329                         execution.getVariable('UAAIGenVnf_updateGenericVnfResponse'))
330                 execution.setVariable('WorkflowException', exception)
331
332                 utils.logAudit("Workflow Exception occurred when Updating GenericVnf: " + exception.getErrorMessage())
333                 logDebug('Exited ' + method, isDebugLogEnabled)
334         }
335 }