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