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