Merge "Added scriptName for deallocation of NSSI."
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / DoUpdateVnfAndModules.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.infrastructure.scripts
24
25 import org.onap.so.logger.LoggingAnchor
26 import org.onap.so.client.HttpClientFactory
27 import org.onap.logging.filter.base.ErrorCode
28
29 import javax.ws.rs.core.Response
30 import org.camunda.bpm.engine.delegate.BpmnError
31 import org.camunda.bpm.engine.delegate.DelegateExecution;
32 import org.onap.so.bpmn.common.scripts.AaiUtil
33 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
34 import org.onap.so.bpmn.common.scripts.ExceptionUtil
35 import org.onap.so.bpmn.common.scripts.MsoUtils
36 import org.onap.so.bpmn.core.domain.ModelInfo
37 import org.onap.so.bpmn.core.domain.ModuleResource
38 import org.onap.so.bpmn.core.domain.VnfResource
39 import org.onap.so.bpmn.core.json.JsonUtils
40 import org.onap.aaiclient.client.graphinventory.entities.uri.Depth
41 import org.onap.so.client.HttpClient
42 import org.onap.aaiclient.client.aai.AAIObjectType
43 import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
44 import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory;
45 import org.onap.so.logger.MessageEnum
46 import org.slf4j.Logger
47 import org.slf4j.LoggerFactory
48 import org.onap.logging.filter.base.ONAPComponents;
49
50 /**
51  * This class supports the VID Flow
52  * with the update of a generic vnf and related VF modules.
53  */
54 class DoUpdateVnfAndModules extends AbstractServiceTaskProcessor {
55     private static final Logger logger = LoggerFactory.getLogger( DoUpdateVnfAndModules.class);
56
57         String Prefix="DUVAM_"
58         ExceptionUtil exceptionUtil = new ExceptionUtil()
59         JsonUtils jsonUtil = new JsonUtils()
60
61         /**
62          * This method gets and validates the incoming
63          * request.
64          *
65          * @param - execution
66          *
67          */
68         public void preProcessRequest(DelegateExecution execution) {
69
70                 execution.setVariable("prefix",Prefix)
71                 logger.trace("STARTED DoUpdateVnfAndModules PreProcessRequest Process")
72
73                 try{
74                         // Get Variables
75
76                         String requestId = execution.getVariable("msoRequestId")
77                         execution.setVariable("requestId", requestId)
78                         execution.setVariable("mso-request-id", requestId)
79                         logger.debug("Incoming Request Id is: " + requestId)
80
81                         String serviceInstanceId = execution.getVariable("serviceInstanceId")
82                         logger.debug("Incoming Service Instance Id is: " + serviceInstanceId)
83
84                         String vnfId = execution.getVariable("vnfId")
85                         logger.debug("Incoming Vnf Id is: " + vnfId)
86
87                         String source = "VID"
88                         execution.setVariable("DUVAM_source", source)
89                         logger.debug("Incoming Source is: " + source)
90
91                         String sdncVersion = execution.getVariable("sdncVersion")
92                         if (sdncVersion == null) {
93                                 sdncVersion = "1702"
94                         }
95                         execution.setVariable("DUVAM_sdncVersion", sdncVersion)
96                         logger.debug("Incoming Sdnc Version is: " + sdncVersion)
97
98                         VnfResource vnfResource = (VnfResource) execution.getVariable("vnfResourceDecomposition")
99
100                         String vnfModelInfo = execution.getVariable("vnfModelInfo")
101                         String serviceModelInfo = execution.getVariable("serviceModelInfo")
102
103                         String serviceId = execution.getVariable("productFamilyId")
104                         execution.setVariable("DUVAM_serviceId", serviceId)
105                         logger.debug("Incoming Service Id is: " + serviceId)
106
107                         String modelUuid = jsonUtil.getJsonValue(vnfModelInfo, "modelUuid")
108                         execution.setVariable("DUVAM_modelUuid", modelUuid)
109                         logger.debug("Incoming modelUuid is: " + modelUuid)
110
111                         String modelCustomizationUuid = jsonUtil.getJsonValue(vnfModelInfo, "modelCustomizationUuid")
112                         execution.setVariable("DUVAM_modelCustomizationUuid", modelCustomizationUuid)
113                         logger.debug("Incoming Model Customization Uuid is: " + modelCustomizationUuid)
114
115                         String cloudSiteId = execution.getVariable("lcpCloudRegionId")
116                         execution.setVariable("DUVAM_cloudSiteId", cloudSiteId)
117                         logger.debug("Incoming Cloud Site Id is: " + cloudSiteId)
118
119                         String tenantId = execution.getVariable("tenantId")
120                         execution.setVariable("DUVAM_tenantId", tenantId)
121                         logger.debug("Incoming Tenant Id is: " + tenantId)
122
123                         String globalSubscriberId = execution.getVariable("globalSubscriberId")
124                         if (globalSubscriberId == null) {
125                                 globalSubscriberId = ""
126                         }
127                         execution.setVariable("DUVAM_globalSubscriberId", globalSubscriberId)
128                         logger.debug("Incoming Global Subscriber Id is: " + globalSubscriberId)
129
130                         execution.setVariable("DUVAM_moduleCount", 0)
131                         execution.setVariable("DUVAM_nextModule", 0)
132
133
134                 }catch(BpmnError b){
135                         logger.debug("Rethrowing MSOWorkflowException")
136                         throw b
137                 }catch(Exception e){
138                         logger.debug(" Error Occured in DoUpdateVnfAndModules PreProcessRequest method!" + e.getMessage())
139                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DoUpdateVnfAndModules PreProcessRequest")
140
141                 }
142                 logger.trace("COMPLETED DoUpdateVnfAndModules PreProcessRequest Process ")
143         }
144
145         /**
146          * Using the received vnfId and vfModuleId, query AAI to get the corresponding VNF info.
147          * A 200 response is expected with the VNF info in the response body. Will find out the base module info.
148          *
149          * @param execution The flow's execution instance.
150          */
151         public void queryAAIVfModule(DelegateExecution execution) {
152
153                 def method = getClass().getSimpleName() + '.queryAAIVfModule(' +
154                         'execution=' + execution.getId() +
155                         ')'
156                 logger.trace('Entered ' + method)
157
158                 try {
159                         def vnfId = execution.getVariable('vnfId')
160
161                         AaiUtil aaiUriUtil = new AaiUtil(this)
162                         AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId).depth(Depth.ONE)
163                         String endPoint = aaiUriUtil.createAaiUri(uri)
164                         logger.debug("AAI endPoint: " + endPoint)
165
166                         try {
167                                 HttpClient client = new HttpClientFactory().newXmlClient(new URL(endPoint), ONAPComponents.AAI)
168                                 client.addAdditionalHeader('X-TransactionId', UUID.randomUUID().toString())
169                                 client.addAdditionalHeader('X-FromAppId', 'MSO')
170                                 client.addAdditionalHeader('Content-Type', 'application/xml')
171                                 client.addAdditionalHeader('Accept','application/xml')
172
173                                 def responseData = ''
174
175                                 logger.debug('sending GET to AAI endpoint \'' + endPoint + '\'')
176                                 Response response = client.get()
177                                 logger.debug("createVfModule - invoking httpGet() to AAI")
178
179                                 responseData = response.readEntity(String.class)
180                                 if (responseData != null) {
181                                         logger.debug("Received generic VNF data: " + responseData)
182
183                                 }
184
185                                 logger.debug("createVfModule - queryAAIVfModule Response: " + responseData)
186                                 logger.debug("createVfModule - queryAAIVfModule ResponseCode: " + response.getStatus())
187
188                                 execution.setVariable('DUVAM_queryAAIVfModuleResponseCode', response.getStatus())
189                                 execution.setVariable('DUVAM_queryAAIVfModuleResponse', responseData)
190                                 logger.debug('Response code:' + response.getStatus())
191                                 logger.debug('Response:' + System.lineSeparator() + responseData)
192                                 //Map<String, String>[] vfModules = new HashMap<String,String>[]
193                                 def vfModulesList = new ArrayList<Map<String,String>>()
194                                 def vfModules = null
195                                 def vfModuleBaseEntry = null
196                                 if (response.getStatus() == 200) {
197                                         // Parse the VNF record from A&AI to find base module info
198                                         logger.debug('Parsing the VNF data to find base module info')
199                                         if (responseData != null) {
200                                                 def vfModulesText = utils.getNodeXml(responseData, "vf-modules")
201                                                 logger.debug("vModulesText: " + vfModulesText)
202                                                 if (vfModulesText != null && !vfModulesText.trim().isEmpty()) {
203                                                         def xmlVfModules= new XmlSlurper().parseText(vfModulesText)
204                                                         vfModules = xmlVfModules.'**'.findAll {it.name() == "vf-module"}
205                                                         execution.setVariable("DUVAM_moduleCount", vfModules.size())
206                                                         int vfModulesSize = 0
207                                                         for (i in 0..vfModules.size()-1) {
208                                                                 def vfModuleXml = groovy.xml.XmlUtil.serialize(vfModules[i])
209
210                                                                 Map<String, String> vfModuleEntry = new HashMap<String, String>()
211                                                                 def vfModuleId = utils.getNodeText(vfModuleXml, "vf-module-id")
212                                                                 vfModuleEntry.put("vfModuleId", vfModuleId)
213                                                                 def vfModuleName = utils.getNodeText(vfModuleXml, "vf-module-name")
214                                                                 vfModuleEntry.put("vfModuleName", vfModuleName)
215                                                                 def modelInvariantUuid = utils.getNodeText(vfModuleXml, "model-invariant-id")
216                                                                 vfModuleEntry.put("modelInvariantUuid", modelInvariantUuid)
217                                                                 def modelUuid = utils.getNodeText(vfModuleXml, "model-version-id")
218                                                                 vfModuleEntry.put("modelUuid", modelUuid)
219                                                                 def modelCustomizationUuid = utils.getNodeText(vfModuleXml, "model-customization-id")
220                                                                 vfModuleEntry.put("modelCustomizationUuid", modelCustomizationUuid)
221
222                                                                 def isBaseVfModule = utils.getNodeText(vfModuleXml, "is-base-vf-module")
223                                                                 vfModuleEntry.put("isBaseVfModule", isBaseVfModule)
224
225                                                                 String volumeGroupId = ''
226
227                                                                 logger.debug("Next module!")
228                                                                 def vfModuleRelationships = vfModules[i].'**'.findAll {it.name() == 'relationship-data'}
229                                                                 if (vfModuleRelationships.size() > 0) {
230                                                                         for (j in 0..vfModuleRelationships.size()-1) {
231                                                                                 if (vfModuleRelationships[j] != null) {
232
233                                                                                         def relationshipKey = vfModuleRelationships[j].'**'.findAll {it.name() == 'relationship-key'}
234
235                                                                                         if (relationshipKey[0] == 'volume-group.volume-group-id') {
236                                                                                                 def relationshipValue = vfModuleRelationships[j].'**'.findAll {it.name() == 'relationship-value'}
237                                                                                                 volumeGroupId = relationshipValue[0]
238                                                                                                 break
239                                                                                         }
240                                                                                 }
241                                                                         }
242                                                                 }
243
244                                                                 vfModuleEntry.put("volumeGroupId", volumeGroupId)
245                                                                 logger.debug("volumeGroupId is: " + volumeGroupId)
246
247                                                                 // Save base vf module to add it to the start of the list later
248                                                                 if (isBaseVfModule == "true") {
249                                                                         vfModuleBaseEntry = vfModuleEntry
250                                                                 }
251                                                                 else {
252                                                                         vfModulesList.add(vfModuleEntry)
253                                                                 }
254                                                         }
255                                                         // Start the list with the base module if any
256                                                         if (vfModuleBaseEntry != null) {
257                                                                 vfModulesList.add(0, vfModuleBaseEntry)
258                                                         }
259                                                 }
260
261                                         }
262                                 }
263                                 else {
264                                         logger.debug('Response code from AAI GET is: ' + response.getStatusCode())
265                                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Response code from AAI GET is: ' + response.getStatusCode())
266                                 }
267                                 execution.setVariable("DUVAM_vfModules", vfModulesList)
268                         } catch (Exception ex) {
269                                 logger.debug('Exception occurred while executing AAI GET: {}', ex.getMessage(), ex)
270                                 exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'AAI GET Failed:' + ex.getMessage())
271                         }
272                         logger.trace('Exited ' + method)
273                 } catch (BpmnError e) {
274                         throw e;
275                 } catch (Exception e) {
276                         logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
277                                         'Caught exception in ' + method, "BPMN",
278                                         ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
279                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in queryAAIVfModule(): ' + e.getMessage())
280                 }
281         }
282
283         public void prepareNextModuleToUpdate(DelegateExecution execution){
284
285                 execution.setVariable("prefix", Prefix)
286                 logger.trace("STARTED prepareNextModuleToUpdate ")
287
288                 try {
289                         int i = execution.getVariable("DUVAM_nextModule")
290                         def vfModules = execution.getVariable("DUVAM_vfModules")
291                         def vfModule = vfModules[i]
292
293                         def vfModuleId = vfModule.get("vfModuleId")
294                         execution.setVariable("DUVAM_vfModuleId", vfModuleId)
295
296                         def vfModuleName = vfModule.get("vfModuleName")
297                         execution.setVariable("DUVAM_vfModuleName", vfModuleName)
298
299                         def isBaseVfModule = vfModule.get("isBaseVfModule")
300                         execution.setVariable("DUVAM_isBaseVfModule", isBaseVfModule)
301
302                         String modelInvariantUuid = vfModule.get("modelInvariantUuid")
303                         logger.debug("ModelInvariantUuid: " + modelInvariantUuid)
304
305                         def volumeGroupId = vfModule.get("volumeGroupId")
306                         execution.setVariable("DUVAM_volumeGroupId", volumeGroupId)
307
308                         execution.setVariable("DUVAM_volumeGroupName", "")
309
310                         VnfResource vnfResource = (VnfResource) execution.getVariable("vnfResourceDecomposition")
311                         List<ModuleResource> moduleResources = vnfResource.getVfModules()
312
313                         if (moduleResources != null && !moduleResources.isEmpty()) {
314
315                                 for (j in 0..moduleResources.size()-1) {
316                                         ModelInfo modelInfo = moduleResources[j].getModelInfo()
317                                         String modelInvariantUuidFromDecomposition = modelInfo.getModelInvariantUuid()
318                                         logger.debug("modelInvariantUuidFromDecomposition: " + modelInvariantUuidFromDecomposition)
319
320                                         if (modelInvariantUuid.equals(modelInvariantUuidFromDecomposition)) {
321                                                 String vfModuleModelInfo = modelInfo.toJsonString()
322                                                 String vfModuleModelInfoValue = jsonUtil.getJsonValue(vfModuleModelInfo, "modelInfo")
323                                                 execution.setVariable("DUVAM_vfModuleModelInfo", vfModuleModelInfoValue)
324                                                 logger.debug("vfModuleModelInfo: " + vfModuleModelInfoValue)
325                                                 break
326                                         }
327
328                                 }
329                         }
330
331                 }catch(Exception e){
332                         logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
333                                         "Exception Occured Processing preProcessAddOnModule. Exception is:\n" + e, "BPMN",
334                                         ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
335                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during prepareNextModuleToUpdate Method:\n" + e.getMessage())
336                 }
337                 logger.trace("COMPLETED prepareNextModuleToUpdate ")
338         }
339
340
341         /**
342          * Prepare a Request for invoking the UpdateAAIGenericVnf subflow.
343          *
344          * @param execution The flow's execution instance.
345          */
346         public void prepUpdateAAIGenericVnf(DelegateExecution execution) {
347                 def method = getClass().getSimpleName() + '.prepUpdateAAIGenericVnf(' +
348                         'execution=' + execution.getId() +
349                         ')'
350
351                 logger.trace('Entered ' + method)
352
353                 try {
354                         def vnfId = execution.getVariable('vnfId')
355                         VnfResource vnfResource = (VnfResource) execution.getVariable("vnfResourceDecomposition")
356                         ModelInfo vnfDecompModelInfo = vnfResource.getModelInfo()
357                         String vnfModelInfo = execution.getVariable("vnfModelInfo")
358                         String modelUuid = execution.getVariable("DUVAM_modelUuid")
359                         if (modelUuid == null || modelUuid.isEmpty()) {
360                                 modelUuid = vnfDecompModelInfo.getModelUuid()
361                         }
362                         String modelCustomizationUuid = execution.getVariable("DUVAM_modelCustomizationUuid")
363                         if (modelCustomizationUuid == null || modelCustomizationUuid.isEmpty()) {
364                                 modelCustomizationUuid = vnfDecompModelInfo.getModelCustomizationUuid()
365                         }
366                         String nfType = vnfResource.getNfType()
367                         String nfTypeString = ''
368                         if (nfType != null && !nfType.isEmpty()) {
369                                 nfTypeString = "<nf-type>" + nfType + "</nf-type>"
370                         }
371                         String nfRole = vnfResource.getNfRole()
372                         String nfRoleString = ''
373                         if (nfRole != null && !nfRole.isEmpty()) {
374                                 nfRoleString = "<nf-role>" + nfRole + "</nf-role>"
375                         }
376                         String nfFunction = vnfResource.getNfFunction()
377                         String nfFunctionString = ''
378                         if (nfFunction != null && !nfFunction.isEmpty()) {
379                                 nfFunctionString = "<nf-function>" + nfFunction + "</nf-function>"
380                         }
381                         String nfNamingCode = vnfResource.getNfNamingCode()
382                         String nfNamingCodeString = ''
383                         if (nfNamingCode != null && !nfNamingCode.isEmpty()) {
384                                 nfNamingCodeString = "<nf-naming-code>" + nfNamingCode + "</nf-naming-code>"
385                         }
386
387                         String updateAAIGenericVnfRequest = """
388                                         <UpdateAAIGenericVnfRequest>
389                                                 <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id>
390                                                 <model-version-id>${MsoUtils.xmlEscape(modelUuid)}</model-version-id>
391                                                 <model-customization-id>${MsoUtils.xmlEscape(modelCustomizationUuid)}</model-customization-id>
392                                                 ${nfTypeString}
393                                                 ${nfRoleString}
394                                                 ${nfFunctionString}
395                                                 ${nfNamingCodeString}
396                                         </UpdateAAIGenericVnfRequest>
397                                 """
398                                 updateAAIGenericVnfRequest = utils.formatXml(updateAAIGenericVnfRequest)
399                                 execution.setVariable('DUVAM_updateAAIGenericVnfRequest', updateAAIGenericVnfRequest)
400                                 logger.debug("updateAAIGenericVnfRequest : " + updateAAIGenericVnfRequest)
401                                 logger.debug('Request for UpdateAAIGenericVnf:\n' + updateAAIGenericVnfRequest)
402
403
404                         logger.trace('Exited ' + method)
405                 } catch (BpmnError e) {
406                         throw e;
407                 } catch (Exception e) {
408                         logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
409                                         'Caught exception in ' + method, "BPMN",
410                                         ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
411                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepUpdateAAIGenericVnf(): ' + e.getMessage())
412                 }
413         }
414
415         /**
416          * APP-C Call - placeholder.
417          *
418          * @param execution The flow's execution instance.
419          */
420         public void callAppCf(DelegateExecution execution) {
421                 def method = getClass().getSimpleName() + '.callAppC(' +
422                         'execution=' + execution.getId() +
423                         ')'
424
425                 logger.trace('Entered ' + method)
426         }
427 }