Removed MsoLogger class
[so.git] / bpmn / MSOCommonBPMN / src / main / groovy / org / onap / so / bpmn / common / scripts / UpdateAAIVfModule.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 javax.ws.rs.NotFoundException
26
27 import org.camunda.bpm.engine.delegate.BpmnError
28 import org.camunda.bpm.engine.delegate.DelegateExecution
29 import org.onap.so.bpmn.core.WorkflowException
30 import org.onap.so.client.aai.AAIObjectType
31 import org.onap.so.client.aai.entities.uri.AAIResourceUri
32 import org.onap.so.client.aai.entities.uri.AAIUriFactory
33 import org.slf4j.Logger
34 import org.slf4j.LoggerFactory
35
36
37 public class UpdateAAIVfModule extends AbstractServiceTaskProcessor {
38     private static final Logger logger = LoggerFactory.getLogger( UpdateAAIVfModule.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', 'UAAIVfMod_')
51                 execution.setVariable('UAAIVfMod_vnfId', null)
52                 execution.setVariable('UAAIVfMod_vfModuleId', null)
53                 execution.setVariable('UAAIVfMod_orchestrationStatus', null)
54                 execution.setVariable('UAAIVfMod_heatStackId', null)
55                 execution.setVariable('UAAIVfMod_volumeGroupId', null)
56                 execution.setVariable('UAAIVfMod_getVfModuleResponseCode' ,null)
57                 execution.setVariable('UAAIVfMod_getVfModuleResponse', '')
58                 execution.setVariable('UAAIVfMod_updateVfModuleResponseCode', null)
59                 execution.setVariable('UAAIVfMod_updateVfModuleResponse', '')
60         }
61
62         /**
63          * Check for missing elements in the received request.
64          *
65          * @param execution The flow's execution instance.
66          */
67         public void preProcessRequest(DelegateExecution execution) {
68                 def method = getClass().getSimpleName() + '.preProcessRequest(' +
69                         'execution=' + execution.getId() +
70                         ')'
71                 logger.trace('Entered ' + method)
72
73                 try {
74                         def xml = execution.getVariable('UpdateAAIVfModuleRequest')
75                         logger.debug('Received request xml:\n' + xml)
76                         initProcessVariables(execution)
77
78                         def vnfId = getRequiredNodeText(execution, xml,'vnf-id')
79                         execution.setVariable('UAAIVfMod_vnfId', vnfId)
80
81                         def vfModuleId = getRequiredNodeText(execution, xml,'vf-module-id')
82                         execution.setVariable('UAAIVfMod_vfModuleId', vfModuleId)
83
84                         logger.trace('Exited ' + method)
85                 } catch (BpmnError e) {
86                         throw e;
87                 } catch (Exception e) {
88                         logger.error(e);
89                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in preProcessRequest(): ' + e.getMessage())
90                 }
91         }
92
93         /**
94          * Using the received vnfId and vfModuleId, query AAI to get the corresponding VF Module.
95          * A 200 response is expected with the VF Module in the response body.
96          *
97          * @param execution The flow's execution instance.
98          */
99         public void getVfModule(DelegateExecution execution) {
100                 def method = getClass().getSimpleName() + '.getVfModule(' +
101                         'execution=' + execution.getId() +
102                         ')'
103                 logger.trace('Entered ' + method)
104
105                 try {
106                         def vnfId = execution.getVariable('UAAIVfMod_vnfId')
107                         def vfModuleId = execution.getVariable('UAAIVfMod_vfModuleId')
108                         try {
109                                 AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId);
110                                 Optional<org.onap.aai.domain.yang.VfModule> vfModule = getAAIClient().get(org.onap.aai.domain.yang.VfModule.class, resourceUri)
111                                 if (vfModule.isPresent()) {
112                                         execution.setVariable('UAAIVfMod_getVfModuleResponseCode', 200)
113                                         execution.setVariable('UAAIVfMod_getVfModuleResponse', vfModule.get())
114                                 } else {
115                                         execution.setVariable('UAAIVfMod_getVfModuleResponseCode', 404)
116                                         execution.setVariable('UAAIVfMod_getVfModuleResponse', "VF Module not found in AAI")
117                                 }
118                         } catch (Exception ex) {
119                                 logger.debug('Exception occurred while executing AAI GET:' + ex.getMessage())
120                                 execution.setVariable('UAAIVfMod_getVfModuleResponseCode', 500)
121                                 execution.setVariable('UAAIVfMod_getVfModuleResponse', 'AAI GET Failed:' + ex.getMessage())
122                         }
123                 } catch (BpmnError e) {
124                         throw e;
125                 } catch (Exception e) {
126                         logger.error(e);
127                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in getVfModule(): ' + e.getMessage())
128                 }
129         }
130
131         /**
132          * Construct and send a PATCH request to AAI to update the VF Module.
133          *
134          * @param execution The flow's execution instance.
135          */
136         public void updateVfModule(DelegateExecution execution) {
137                 def method = getClass().getSimpleName() + '.updateVfModule(' +
138                         'execution=' + execution.getId() +
139                         ')'
140                 logger.trace('Entered ' + method)
141
142                 try {
143                         def vnfId = execution.getVariable('UAAIVfMod_vnfId')
144                         def vfModuleId = execution.getVariable('UAAIVfMod_vfModuleId')
145                         org.onap.aai.domain.yang.VfModule vfModule = execution.getVariable('UAAIVfMod_getVfModuleResponse')
146                         def origRequest = execution.getVariable('UpdateAAIVfModuleRequest')
147
148                         logger.debug("UpdateAAIVfModule request: " + origRequest)
149                         // Handle persona-model-id/persona-model-version
150                         def boolean doPersonaModelVersion = true
151                         def String newPersonaModelId = utils.getNodeText(origRequest, 'persona-model-id')
152                         def String newPersonaModelVersion = utils.getNodeText(origRequest, 'persona-model-version')
153                         if ((newPersonaModelId == null) || (newPersonaModelVersion == null)) {
154                                 doPersonaModelVersion = false
155                         } else {
156                                 // Confirm "new" persona-model-id is same as "current" persona-model-id
157                                 def String currPersonaModelId = vfModule.getModelInvariantId()
158                                 if (currPersonaModelId == null) {
159                                         // check the old attribute name
160                                         currPersonaModelId = vfModule.getModelVersionId()
161                                 }
162                                 if (currPersonaModelId == null) {
163                                         currPersonaModelId = ''
164                                 }
165                                 if (!newPersonaModelId.equals(currPersonaModelId)) {
166                                         def msg = 'Can\'t update VF Module ' + vfModuleId + ' since there is \'persona-model-id\' mismatch between the current and new values'
167                                         logger.error(msg)
168                                         throw new Exception(msg)
169                                 }
170                         }
171
172                         // Construct payload
173                         String orchestrationStatusEntry = updateVfModuleNode(origRequest , 'orchestration-status')
174                         String heatStackIdEntry = updateVfModuleNode(origRequest,  'heat-stack-id')
175                         String personaModelVersionEntry = ""
176                         if (doPersonaModelVersion) {
177                                 personaModelVersionEntry = updateVfModuleNode(origRequest,  'persona-model-version')
178                         }
179                         String contrailServiceInstanceFqdnEntry = updateVfModuleNode(origRequest,  'contrail-service-instance-fqdn')
180                         org.onap.aai.domain.yang.VfModule payload = new org.onap.aai.domain.yang.VfModule();
181                         payload.setVfModuleId(vfModuleId)
182                         payload.setOrchestrationStatus(orchestrationStatusEntry)
183                         payload.setHeatStackId(heatStackIdEntry)
184                         payload.setPersonaModelVersion(personaModelVersionEntry)
185                         payload.setContrailServiceInstanceFqdn(contrailServiceInstanceFqdnEntry)
186
187             try {
188                 AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId)
189                 getAAIClient().update(resourceUri, payload)
190                                 execution.setVariable('UAAIVfMod_updateVfModuleResponseCode', 200)
191                                 execution.setVariable('UAAIVfMod_updateVfModuleResponse', "Success")
192             }catch(NotFoundException ignored){
193                 logger.debug("VF-Module not found!!")
194                                 execution.setVariable('UAAIVfMod_updateVfModuleResponseCode', 404)
195                 execution.setVariable('UAAIVfMod_updateVfModuleResponse', ignored.getMessage())
196                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "vf-module " + vfModuleId + " not found for under vnf " + vnfId + " in A&AI!")
197             }
198             catch(Exception ex){
199                                 execution.setVariable('UAAIVfMod_updateVfModuleResponseCode', 500)
200                                 execution.setVariable('UAAIVfMod_updateVfModuleResponse', 'AAI PATCH Failed:' + ex.getMessage())
201                                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, 'Exception occurred while executing AAI PATCH:' + ex.getMessage())
202             }
203                 } catch (BpmnError e) {
204                         throw e;
205                 } catch (Exception e) {
206                         logger.error(e);
207                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in updateVfModule(): ' + e.getMessage())
208                 }
209         }
210
211         /**
212          * Sets up json attributes for PATCH request for Update
213          *
214          * @param origRequest Incoming update request with VF Module elements to be updated.
215          * @param element Name of element to be inserted.
216          */
217         private String updateVfModuleNode(String origRequest, String elementName) {
218
219                 if (!utils.nodeExists(origRequest, elementName)) {
220                         return null
221                 }
222                 def elementValue = utils.getNodeText(origRequest, elementName)
223
224                 if (elementValue.equals('DELETE')) {
225                         // Set the element being deleted to empty string
226                         return ""
227                 }
228                 else {
229                         return elementValue
230                 }               
231         }
232
233         /**
234          * Generates a WorkflowException if the AAI query returns a response code other than 200.
235          *
236          * @param execution The flow's execution instance.
237          */
238         public void handleAAIQueryFailure(DelegateExecution execution) {
239                 def method = getClass().getSimpleName() + '.handleAAIQueryFailure(' +
240                         'execution=' + execution.getId() +
241                         ')'
242                 logger.trace('Entered ' + method)
243
244                 logger.error('Error occurred attempting to query AAI, Response Code ' + execution.getVariable('UAAIVfMod_getVfModuleResponseCode'))
245                 String processKey = getProcessKey(execution);
246                 WorkflowException exception = new WorkflowException(processKey, 5000,
247                         execution.getVariable('UAAIVfMod_getVfModuleResponse'))
248                 execution.setVariable('WorkflowException', exception)
249                 logger.debug("UpdateAAIVfModule query failure: " + exception.getErrorMessage())
250                 logger.trace('Exited ' + method)
251         }
252 }