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