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