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