Springboot 2.0 upgrade
[so.git] / bpmn / MSOCommonBPMN / src / main / groovy / org / onap / so / bpmn / common / scripts / UpdateAAIGenericVnf.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.aai.domain.yang.GenericVnf
26 import org.onap.so.bpmn.core.WorkflowException
27 import org.onap.so.client.aai.AAIObjectType
28 import org.onap.so.client.aai.entities.uri.AAIResourceUri
29 import org.onap.so.client.aai.entities.uri.AAIUriFactory
30 import org.onap.so.client.graphinventory.entities.uri.Depth
31 import org.onap.so.logger.MessageEnum
32 import org.onap.so.logger.MsoLogger
33
34
35
36
37 public class UpdateAAIGenericVnf extends AbstractServiceTaskProcessor {
38         private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, UpdateAAIGenericVnf.class)
39
40
41         private XmlParser xmlParser = new XmlParser()
42         ExceptionUtil exceptionUtil = new ExceptionUtil()
43
44         /**
45          * Initialize the flow's variables.
46          *
47          * @param execution The flow's execution instance.
48          */
49         public void initProcessVariables(DelegateExecution execution) {
50                 execution.setVariable('prefix', 'UAAIGenVnf_')
51                 execution.setVariable('UAAIGenVnf_vnfId', null)
52                 execution.setVariable('UAAIGenVnf_personaModelId', null)
53                 execution.setVariable('UAAIGenVnf_personaModelVersion', null)
54                 execution.setVariable("UAAIGenVnf_ipv4OamAddress", null)
55                 execution.setVariable('UAAIGenVnf_managementV6Address', null)
56                 execution.setVariable('UAAIGenVnf_orchestrationStatus', null)
57                 execution.setVariable('UAAIGenVnf_getGenericVnfResponseCode' ,null)
58                 execution.setVariable('UAAIGenVnf_getGenericVnfResponse', '')
59                 execution.setVariable('UAAIGenVnf_updateGenericVnfResponseCode', null)
60                 execution.setVariable('UAAIGenVnf_updateGenericVnfResponse', '')
61         }
62
63         /**
64          * Check for missing elements in the received request.
65          *
66          * @param execution The flow's execution instance.
67          */
68         public void preProcessRequest(DelegateExecution execution) {
69                 def method = getClass().getSimpleName() + '.preProcessRequest(' +
70                         'execution=' + execution.getId() +
71                         ')'
72                 msoLogger.trace('Entered ' + method)
73
74                 try {
75                         def xml = execution.getVariable('UpdateAAIGenericVnfRequest')
76                         msoLogger.debug('Received request xml:\n' + xml)
77                         msoLogger.debug("UpdateAAIGenericVnf Request XML: " + xml)
78                         initProcessVariables(execution)
79
80                         def vnfId = getRequiredNodeText(execution, xml,'vnf-id')
81                         execution.setVariable('UAAIGenVnf_vnfId', vnfId)
82
83                         def personaModelId = getNodeTextForce(xml,'persona-model-id')
84                         if (personaModelId != null && !personaModelId.isEmpty()) {
85                                 execution.setVariable('UAAIGenVnf_personaModelId', personaModelId)
86                         }
87
88                         def personaModelVersion = getNodeTextForce(xml,'persona-model-version')
89                         if (personaModelVersion != null && !personaModelVersion.isEmpty()) {
90                                 execution.setVariable('UAAIGenVnf_personaModelVersion', personaModelVersion)
91                         }
92
93                         def ipv4OamAddress = getNodeTextForce(xml, 'ipv4-oam-address')
94                         if (ipv4OamAddress != null && !ipv4OamAddress.isEmpty()) {
95                                 execution.setVariable('UAAIGenVnf_ipv4OamAddress', ipv4OamAddress)
96                         }
97
98                         def managementV6Address = getNodeTextForce(xml, 'management-v6-address')
99                         if (managementV6Address != null && !managementV6Address.isEmpty()) {
100                                 execution.setVariable('UAAIGenVnf_managementV6Address', managementV6Address)
101                         }
102                         
103                         def orchestrationStatus = getNodeTextForce(xml, 'orchestration-status')
104                         if (orchestrationStatus != null && !orchestrationStatus.isEmpty()) {
105                                 execution.setVariable('UAAIGenVnf_orchestrationStatus', orchestrationStatus)
106                         }
107
108                         msoLogger.trace('Exited ' + method)
109                 } catch (BpmnError e) {
110                         throw e
111                 } catch (Exception e) {
112                         msoLogger.error(e)
113                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in preProcessRequest(): ' + e.getMessage())
114                 }
115         }
116
117         /**
118          * Using the received vnfId, query AAI to get the corresponding Generic VNF.
119          * A 200 response is expected with the VF Module in the response body.
120          *
121          * @param execution The flow's execution instance.
122          */
123         public void getGenericVnf(DelegateExecution execution) {
124                 def method = getClass().getSimpleName() + '.getGenericVnf(' +
125                         'execution=' + execution.getId() +
126                         ')'
127                 msoLogger.trace('Entered ' + method)
128
129                 try {
130                         def vnfId = execution.getVariable('UAAIGenVnf_vnfId')
131
132                         AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId)
133                         uri.depth(Depth.ONE)
134                         try {
135                                 Optional<GenericVnf> genericVnf = getAAIClient().get(GenericVnf.class,uri)
136                                 if(genericVnf.isPresent()){
137                                         execution.setVariable('UAAIGenVnf_getGenericVnfResponseCode', 200)
138                                         execution.setVariable('UAAIGenVnf_getGenericVnfResponse', genericVnf.get())
139                                 }else{
140                                         execution.setVariable('UAAIGenVnf_getGenericVnfResponseCode', 404)
141                                         execution.setVariable('UAAIGenVnf_getGenericVnfResponse', "Generic VNF not found for VNF ID: "+vnfId)
142                                 }
143                         }catch (Exception ex) {
144                                 msoLogger.error(ex.getMessage())
145                                 msoLogger.debug('Exception occurred while executing AAI GET:' + ex.getMessage())
146                                 execution.setVariable('UAAIGenVnf_getGenericVnfResponseCode', 500)
147                                 execution.setVariable('UAAIGenVnf_getGenericVnfResponse', 'AAI GET Failed:' + ex.getMessage())
148                         }
149                         msoLogger.trace('Exited ' + method)
150                 } catch (Exception e) {
151                         msoLogger.error(e)
152                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in getGenericVnf(): ' + e.getMessage())
153                 }
154         }
155
156         /**
157          * Construct and send a PUT request to AAI to update the Generic VNF.
158          *
159          * @param execution The flow's execution instance.
160          */
161         public void updateGenericVnf(DelegateExecution execution) {
162                 def method = getClass().getSimpleName() + '.updateGenericVnf(' +
163                         'execution=' + execution.getId() +
164                         ')'
165                 msoLogger.trace('Entered ' + method)
166
167                 try {
168                         def vnfId = execution.getVariable('UAAIGenVnf_vnfId')
169                         GenericVnf genericVnf = execution.getVariable('UAAIGenVnf_getGenericVnfResponse')
170                         def origRequest = execution.getVariable('UpdateAAIGenericVnfRequest')
171
172                         msoLogger.debug("UpdateGenericVnf Request: " + origRequest)
173                         // Handle persona-model-id/persona-model-version
174
175                         String newPersonaModelId = execution.getVariable('UAAIGenVnf_personaModelId')
176                         String newPersonaModelVersion = execution.getVariable('UAAIGenVnf_personaModelVersion')
177                         String personaModelVersionEntry = ""
178                         if (newPersonaModelId != null || newPersonaModelVersion != null) {
179                                 if (newPersonaModelId != genericVnf.getModelInvariantId()) {
180                                         def msg = 'Can\'t update Generic VNF ' + vnfId + ' since there is \'persona-model-id\' mismatch between the current and new values'
181                                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "")
182                                         throw new Exception(msg)
183                                 }
184
185                                 // Construct payload
186                                 personaModelVersionEntry = updateGenericVnfNode(origRequest, genericVnfNode, 'model-version-id')
187                         }
188
189                         // Handle ipv4-oam-address
190                         String ipv4OamAddress = execution.getVariable('UAAIGenVnf_ipv4OamAddress')
191                         String ipv4OamAddressEntry = ""
192                         if (ipv4OamAddress != null) {
193                                 // Construct payload
194                                 ipv4OamAddressEntry = updateGenericVnfNode(origRequest, genericVnfNode, 'ipv4-oam-address')
195                         }
196
197                         // Handle management-v6-address
198                         String managementV6Address = execution.getVariable('UAAIGenVnf_managementV6Address')
199                         String managementV6AddressEntry = ""
200                         if (managementV6Address != null) {
201                                 // Construct payload
202                                 managementV6AddressEntry = updateGenericVnfNode(origRequest, genericVnfNode, 'management-v6-address')
203                         }
204                         
205                         // Handle orchestration-status
206                         String orchestrationStatus = execution.getVariable('UAAIGenVnf_orchestrationStatus')
207                         String orchestrationStatusEntry = ""
208                         if (orchestrationStatus != null) {
209                                 // Construct payload
210                                 orchestrationStatusEntry = updateGenericVnfNode(origRequest, genericVnfNode, 'orchestration-status')
211                         }
212
213                         def payload = """
214                                         {       ${personaModelVersionEntry}
215                                                 ${ipv4OamAddressEntry}
216                                                 ${managementV6AddressEntry}
217                                                 ${orchestrationStatusEntry}
218                                                 "vnf-id": "${vnfId}"                                    
219                                         }
220                         """
221
222                         AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId)
223
224                         try {
225                                 getAAIClient().update(uri,payload)
226                         } catch (Exception ex) {
227                                 ex.printStackTrace()
228                                 msoLogger.debug('Exception occurred while executing AAI PATCH:' + ex.getMessage())
229                                 execution.setVariable('UAAIGenVnf_updateGenericVnfResponseCode', 500)
230                                 execution.setVariable('UAAIGenVnf_updateGenericVnfResponse', 'AAI PATCH Failed:' + ex.getMessage())
231                         }
232                         msoLogger.trace('Exited ' + method)
233                 } catch (Exception e) {
234                         msoLogger.error(e)
235                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in updateGenericVnf(): ' + e.getMessage())
236                 }
237         }
238
239         /**
240          * Sets up json attributes for PATCH request for Update
241          * 
242          * @param origRequest Incoming update request with Generic VNF element(s) to be updated.
243          * @param genericVnf Current Generic VNF retrieved from AAI.
244          * @param element Name of element to be inserted.
245          */
246         public String updateGenericVnfNode(String origRequest, Node genericVnfNode, String elementName) {
247
248                 if (!utils.nodeExists(origRequest, elementName)) {
249                         return ""
250                 }
251                 def elementValue = utils.getNodeText(origRequest, elementName)
252
253                 if (elementValue == 'DELETE') {
254                         // Set the element being deleted to null
255                         return """"${elementName}": null,"""
256                 }
257                 else {
258                         return """"${elementName}": "${elementValue}","""               
259                 }
260                 
261         }
262
263         /**
264          * Generates a WorkflowException if the AAI query returns a response code other than 200.
265          *
266          * @param execution The flow's execution instance.
267          */
268         public void handleAAIQueryFailure(DelegateExecution execution) {
269                 def method = getClass().getSimpleName() + '.handleAAIQueryFailure(' +
270                         'execution=' + execution.getId() +
271                         ')'
272                 msoLogger.trace('Entered ' + method)
273
274                 msoLogger.error( 'Error occurred attempting to query AAI, Response Code ' + execution.getVariable('UAAIGenVnf_getGenericVnfResponseCode'))
275                 String processKey = getProcessKey(execution)
276                 WorkflowException exception = new WorkflowException(processKey, 5000,
277                         execution.getVariable('UAAIGenVnf_getGenericVnfResponse'))
278                 execution.setVariable('WorkflowException', exception)
279
280                 msoLogger.debug("Workflow Exception occurred when handling Quering AAI: " + exception.getErrorMessage())
281                 msoLogger.trace('Exited ' + method)
282         }
283
284         /**
285          * Generates a WorkflowException if updating a VF Module in AAI returns a response code other than 200.
286          *
287          * @param execution The flow's execution instance.
288          */
289         public void handleUpdateGenericVnfFailure(DelegateExecution execution) {
290                 def method = getClass().getSimpleName() + '.handleUpdateGenericVnfFailure(' +
291                         'execution=' + execution.getId() +
292                         ')'
293                 msoLogger.trace('Entered ' + method)
294
295                 msoLogger.error('Error occurred attempting to update Generic VNF in AAI, Response Code ' + execution.getVariable('UAAIGenVnf_updateGenericVnfResponseCode'))
296
297                 String processKey = getProcessKey(execution)
298                 WorkflowException exception = new WorkflowException(processKey, 5000,
299                         execution.getVariable('UAAIGenVnf_updateGenericVnfResponse'))
300                 execution.setVariable('WorkflowException', exception)
301
302                 msoLogger.debug("Workflow Exception occurred when Updating GenericVnf: " + exception.getErrorMessage())
303                 msoLogger.trace('Exited ' + method)
304         }
305 }