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