9accbd8d2472ecc6487833c552e7d92b3525056f
[so.git] /
1
2 /*-
3  * ============LICENSE_START=======================================================
4  * ONAP - SO
5  * ================================================================================
6  * Copyright (C) 2018 Huawei Technologies Co., Ltd. All rights reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21 package org.onap.so.bpmn.infrastructure.scripts
22
23 import static org.apache.commons.lang3.StringUtils.isBlank
24
25 import org.apache.commons.lang3.StringUtils
26 import org.apache.http.HttpResponse
27 import org.camunda.bpm.engine.delegate.BpmnError
28 import org.camunda.bpm.engine.delegate.DelegateExecution
29 import org.json.JSONObject
30 import org.onap.so.bpmn.common.recipe.BpmnRestClient
31 import org.onap.so.bpmn.common.recipe.ResourceInput
32 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
33 import org.onap.so.bpmn.common.scripts.CatalogDbUtils
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.AllottedResource
37 import org.onap.so.bpmn.core.domain.NetworkResource
38 import org.onap.so.bpmn.core.domain.Resource
39 import org.onap.so.bpmn.core.domain.ServiceDecomposition
40 import org.onap.so.bpmn.core.domain.VnfResource
41 import org.onap.so.bpmn.core.json.JsonUtils
42 import org.onap.so.bpmn.core.UrnPropertiesReader
43 import org.onap.so.bpmn.infrastructure.properties.BPMNProperties
44 import org.onap.so.logger.MsoLogger
45
46 /**
47  * input for script :
48  * msoRequestId
49  * isDebugLogEnabled
50  * globalSubscriberId
51  * serviceType
52  * serviceInstanceId
53  * URN_mso_workflow_sdncadapter_callback
54  * serviceInputParams
55  * deleteResourceList
56  * resourceInstanceIDs
57  *
58  * output from script:
59  *
60  */
61
62 public class DoDeleteResourcesV1 extends AbstractServiceTaskProcessor {
63         private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoDeleteResourcesV1.class);
64
65     String Prefix="DDR_"
66     ExceptionUtil exceptionUtil = new ExceptionUtil()
67     JsonUtils jsonUtil = new JsonUtils()
68     CatalogDbUtils cutils = new CatalogDbUtils()
69
70     public void preProcessRequest (DelegateExecution execution) {
71         def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
72         utils.log("INFO"," ***** preProcessRequest *****",  isDebugEnabled)
73         String msg = ""
74
75         try {
76             String requestId = execution.getVariable("msoRequestId")
77             execution.setVariable("prefix",Prefix)
78
79             //Inputs
80             //requestDetails.subscriberInfo. for AAI GET & PUT & SDNC assignToplology
81             String globalSubscriberId = execution.getVariable("globalSubscriberId") //globalCustomerId
82             if (globalSubscriberId == null)
83             {
84                 execution.setVariable("globalSubscriberId", "")
85             }
86
87             //requestDetails.requestParameters. for AAI PUT & SDNC assignTopology
88             String serviceType = execution.getVariable("serviceType")
89             if (serviceType == null)
90             {
91                 execution.setVariable("serviceType", "")
92             }
93
94             //Generated in parent for AAI PUT
95             String serviceInstanceId = execution.getVariable("serviceInstanceId")
96             if (isBlank(serviceInstanceId)){
97                 msg = "Input serviceInstanceId is null"
98                 utils.log("INFO", msg, isDebugEnabled)
99                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
100             }
101
102             String sdncCallbackUrl = execution.getVariable('URN_mso_workflow_sdncadapter_callback')
103             if (isBlank(sdncCallbackUrl)) {
104                 msg = "URN_mso_workflow_sdncadapter_callback is null"
105                 utils.log("INFO", msg, isDebugEnabled)
106                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
107             }
108             execution.setVariable("sdncCallbackUrl", sdncCallbackUrl)
109             utils.log("INFO","SDNC Callback URL: " + sdncCallbackUrl, isDebugEnabled)
110
111             StringBuilder sbParams = new StringBuilder()
112             Map<String, String> paramsMap = execution.getVariable("serviceInputParams")
113             if (paramsMap != null)
114             {
115                 sbParams.append("<service-input-parameters>")
116                 for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
117                     String paramsXml
118                     String paramName = entry.getKey()
119                     String paramValue = entry.getValue()
120                     paramsXml =
121                             """ <param>
122                                                         <name>${MsoUtils.xmlEscape(paramName)}</name>
123                                                         <value>${MsoUtils.xmlEscape(paramValue)}</value>
124                                                         </param>
125                                                         """
126                     sbParams.append(paramsXml)
127                 }
128                 sbParams.append("</service-input-parameters>")
129             }
130             String siParamsXml = sbParams.toString()
131             if (siParamsXml == null)
132                 siParamsXml = ""
133             execution.setVariable("siParamsXml", siParamsXml)
134
135         } catch (BpmnError e) {
136             throw e;
137         } catch (Exception ex){
138             msg = "Exception in preProcessRequest " + ex.getMessage()
139             utils.log("INFO", msg, isDebugEnabled)
140             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
141         }
142         utils.log("INFO"," ***** Exit preProcessRequest *****",  isDebugEnabled)
143     }
144
145     public void sequenceResource(DelegateExecution execution){
146         def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
147
148         utils.log("INFO", " ======== STARTED sequenceResource Process ======== ", isDebugEnabled)
149         List<Resource> sequencedResourceList = new ArrayList<Resource>()
150         List<Resource> wanResources = new ArrayList<Resource>()
151
152         // get delete resource list and order list
153         List<Resource> delResourceList = execution.getVariable("deleteResourceList")
154
155         ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
156         String serviceModelName = serviceDecomposition.getModelInfo().getModelName();
157         
158         def resourceSequence = BPMNProperties.getResourceSequenceProp(serviceModelName)
159
160         if(resourceSequence != null) {
161             for (resourceType in resourceSequence.reverse()) {
162                 for (resource in delResourceList) {
163                     if (StringUtils.containsIgnoreCase(resource.getModelInfo().getModelName(), resourceType)) {
164                         sequencedResourceList.add(resource)
165
166                         if (resource instanceof NetworkResource) {
167                             wanResources.add(resource)
168                         }
169                     }
170                 }
171             }
172         }else {
173             //define sequenced resource list, we deploy vf first and then network and then ar
174             //this is defaule sequence
175             List<VnfResource> vnfResourceList = new ArrayList<VnfResource>()
176             List<AllottedResource> arResourceList = new ArrayList<AllottedResource>()
177             for (Resource rc : delResourceList) {
178                 if (rc instanceof VnfResource) {
179                     vnfResourceList.add(rc)
180                 } else if (rc instanceof NetworkResource) {
181                         wanResources.add(rc)
182                 } else if (rc instanceof AllottedResource) {
183                     arResourceList.add(rc)
184                 }
185             }
186
187             sequencedResourceList.addAll(arResourceList)
188             sequencedResourceList.addAll(wanResources)
189             sequencedResourceList.addAll(vnfResourceList)
190         }
191
192         String isContainsWanResource = wanResources.isEmpty() ? "false" : "true"
193         //if no networkResource, get SDNC config from properties file
194         if( "false".equals(isContainsWanResource)) {
195             String serviceNeedSDNC = "mso.workflow.custom." + serviceModelName + ".sdnc.need";
196             isContainsWanResource = BPMNProperties.getProperty(serviceNeedSDNC, isContainsWanResource)
197         }
198         execution.setVariable("isContainsWanResource", isContainsWanResource)
199         execution.setVariable("currentResourceIndex", 0)
200         execution.setVariable("sequencedResourceList", sequencedResourceList)
201         utils.log("INFO", "resourceSequence: " + resourceSequence, isDebugEnabled)
202         utils.log("INFO", " ======== END sequenceResource Process ======== ", isDebugEnabled)
203     }
204
205     /**
206      * prepare delete parameters
207      */
208     public void preResourceDelete(DelegateExecution execution){
209
210         def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
211
212         utils.log("INFO", " ======== STARTED preResourceDelete Process ======== ", isDebugEnabled)
213
214         List<Resource> sequencedResourceList = execution.getVariable("sequencedResourceList")
215
216         int currentIndex = execution.getVariable("currentResourceIndex")
217         Resource curResource = sequencedResourceList.get(currentIndex);
218
219         String resourceInstanceUUID = curResource.getResourceId()
220         String resourceTemplateUUID = curResource.getModelInfo().getModelUuid()
221         execution.setVariable("resourceInstanceId", resourceInstanceUUID)
222         execution.setVariable("currentResource", curResource)
223         utils.log("INFO", "Delete Resource Info resourceTemplate Id :" + resourceTemplateUUID + "  resourceInstanceId: "
224                 + resourceInstanceUUID + " resourceModelName: " + curResource.getModelInfo().getModelName(), isDebugEnabled)
225
226         utils.log("INFO", " ======== END preResourceDelete Process ======== ", isDebugEnabled)
227     }
228
229
230     /**
231      * Execute delete workflow for resource
232      */
233     public void executeResourceDelete(DelegateExecution execution) {
234         def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
235         utils.log("INFO", "======== Start executeResourceDelete Process ======== ", isDebugEnabled)
236                 try {
237                 String requestId = execution.getVariable("msoRequestId")
238                 String serviceInstanceId = execution.getVariable("serviceInstanceId")
239                 String serviceType = execution.getVariable("serviceType")
240         
241                 String resourceInstanceId = execution.getVariable("resourceInstanceId")
242         
243                 Resource currentResource = execution.getVariable("currentResource")
244                 String action = "deleteInstance"
245                 JSONObject resourceRecipe = cutils.getResourceRecipe(execution, currentResource.getModelInfo().getModelUuid(), action)
246                 String recipeUri = resourceRecipe.getString("orchestrationUri")
247                 int recipeTimeout = resourceRecipe.getInt("recipeTimeout")
248                 String recipeParamXsd = resourceRecipe.get("paramXSD")
249         
250         
251                 ResourceInput resourceInput = new ResourceInput();
252                 resourceInput.setServiceInstanceId(serviceInstanceId)
253                 resourceInput.setResourceInstanceName(currentResource.getResourceInstanceName())
254                 resourceInput.setResourceInstancenUuid(currentResource.getResourceId())
255                 resourceInput.setOperationId(execution.getVariable("operationId"))
256                 resourceInput.setOperationType(execution.getVariable("operationType"))
257                 String globalSubscriberId = execution.getVariable("globalSubscriberId") 
258                 resourceInput.setGlobalSubscriberId(globalSubscriberId)
259                 resourceInput.setResourceModelInfo(currentResource.getModelInfo());
260                     ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
261                         resourceInput.setServiceModelInfo(serviceDecomposition.getModelInfo());
262                 resourceInput.setServiceType(serviceType)
263         
264                 String recipeURL = BPMNProperties.getProperty("bpelURL", "http://mso:8080") + recipeUri
265         
266                 HttpResponse resp = BpmnRestClient.post(recipeURL, requestId, recipeTimeout, action, serviceInstanceId, serviceType, resourceInput.toString(), recipeParamXsd)
267                 utils.log("INFO", " ======== END executeResourceDelete Process ======== ", isDebugEnabled)
268                 }catch(BpmnError b){
269                          msoLogger.debug("Rethrowing MSOWorkflowException")
270                          throw b
271                  }catch(Exception e){
272                          msoLogger.debug("Error occured within DoDeleteResourcesV1 executeResourceDelete method: " + e)
273                          exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured during DoDeleteResourcesV1 executeResourceDelete Catalog")
274                  }
275     }
276
277
278     public void parseNextResource(DelegateExecution execution){
279         def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
280         utils.log("INFO", "======== Start parseNextResource Process ======== ", isDebugEnabled)
281         def currentIndex = execution.getVariable("currentResourceIndex")
282         def nextIndex =  currentIndex + 1
283         execution.setVariable("currentResourceIndex", nextIndex)
284         List<String> sequencedResourceList = execution.getVariable("sequencedResourceList")
285         if(nextIndex >= sequencedResourceList.size()){
286             execution.setVariable("allResourceFinished", "true")
287         }else{
288             execution.setVariable("allResourceFinished", "false")
289         }
290         utils.log("INFO", "======== COMPLETED parseNextResource Process ======== ", isDebugEnabled)
291     }
292     
293     public void prepareFinishedProgressForResource(DelegateExecution execution) {
294
295         String serviceInstanceId = execution.getVariable("serviceInstanceId")
296         String serviceType = execution.getVariable("serviceType")
297         String resourceInstanceId = execution.getVariable("resourceInstanceId")
298         Resource currentResource = execution.getVariable("currentResource")
299         String resourceCustomizationUuid = currentResource.getModelInfo().getModelCustomizationUuid()
300         String resourceModelName = currentResource.getModelInfo().getModelName()
301         String operationType = execution.getVariable("operationType")
302         String progress = "100"
303         String status = "finished"
304         String statusDescription = "The resource instance does not exist for " + resourceModelName
305         String operationId = execution.getVariable("operationId")
306
307         String body = """
308                 <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
309                         xmlns:ns="http://org.onap.so/requestsdb">
310                         <soapenv:Header/>
311                 <soapenv:Body>
312                     <ns:updateResourceOperationStatus>
313                                <operType>${MsoUtils.xmlEscape(operationType)}</operType>
314                                <operationId>${MsoUtils.xmlEscape(operationId)}</operationId>
315                                <progress>${MsoUtils.xmlEscape(progress)}</progress>
316                                <resourceTemplateUUID>${MsoUtils.xmlEscape(resourceCustomizationUuid)}</resourceTemplateUUID>
317                                <serviceId>${MsoUtils.xmlEscape(serviceInstanceId)}</serviceId>
318                                <status>${MsoUtils.xmlEscape(status)}</status>
319                                <statusDescription>${MsoUtils.xmlEscape(statusDescription)}</statusDescription>
320                     </ns:updateResourceOperationStatus>
321                 </soapenv:Body>
322                 </soapenv:Envelope>""";
323
324         def dbAdapterEndpoint = UrnPropertiesReader.getVariable("mso.adapters.openecomp.db.endpoint", execution)
325         execution.setVariable("CVFMI_dbAdapterEndpoint", dbAdapterEndpoint)
326         execution.setVariable("CVFMI_updateResOperStatusRequest", body)
327     }
328
329     public void prepareSDNCServiceDeactivateRequest (DelegateExecution execution) {
330         prepareSDNCServiceRequest (execution, "deactivate")
331     }
332     
333     public void prepareSDNCServiceDeleteRequest (DelegateExecution execution) {
334         prepareSDNCServiceRequest (execution, "delete")
335     }
336     
337     public void prepareSDNCServiceRequest (DelegateExecution execution, String svcAction) {
338         def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
339         utils.log("INFO"," ***** Started prepareSDNCServiceRequest for " + svcAction +  "*****",  isDebugEnabled)
340
341         try {
342             // get variables
343             String sdnc_svcAction = svcAction        
344             String sdncCallback = execution.getVariable("URN_mso_workflow_sdncadapter_callback")            
345             String hdrRequestId = execution.getVariable("msoRequestId")
346             String serviceInstanceId = execution.getVariable("serviceInstanceId")
347             String source = execution.getVariable("source")
348             String sdnc_service_id = serviceInstanceId
349             ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
350             String serviceType = execution.getVariable("serviceType")
351             String globalCustomerId = execution.getVariable("globalSubscriberId")
352             String serviceModelInvariantUuid = serviceDecomposition.getModelInfo().getModelInvariantUuid()
353             String serviceModelUuid = serviceDecomposition.getModelInfo().getModelUuid()
354             String serviceModelVersion = serviceDecomposition.getModelInfo().getModelVersion()
355             String serviceModelName = serviceDecomposition.getModelInfo().getModelName()
356
357             // 1. prepare assign topology via SDNC Adapter SUBFLOW call
358             String sndcTopologyDeleteRequest =
359                     """<aetgt:SDNCAdapterWorkflowRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1"
360                                                               xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1" 
361                                                               xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1">
362                                  <sdncadapter:RequestHeader>
363                                     <sdncadapter:RequestId>${MsoUtils.xmlEscape(hdrRequestId)}</sdncadapter:RequestId>
364                                     <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</sdncadapter:SvcInstanceId>
365                                     <sdncadapter:SvcAction>${MsoUtils.xmlEscape(sdnc_svcAction)}</sdncadapter:SvcAction>
366                                     <sdncadapter:SvcOperation>service-topology-operation</sdncadapter:SvcOperation>
367                                     <sdncadapter:CallbackUrl>sdncCallback</sdncadapter:CallbackUrl>
368                                     <sdncadapter:MsoAction>generic-resource</sdncadapter:MsoAction>
369                                  </sdncadapter:RequestHeader>
370                                  <sdncadapterworkflow:SDNCRequestData>
371                                      <request-information>
372                                         <request-id>${MsoUtils.xmlEscape(hdrRequestId)}</request-id>
373                                         <request-action>DeleteServiceInstance</request-action>
374                                         <source>${MsoUtils.xmlEscape(source)}</source>
375                                         <notification-url></notification-url>
376                                         <order-number></order-number>
377                                         <order-version></order-version>
378                                      </request-information>
379                                      <service-information>
380                                         <service-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-id>
381                                         <subscription-service-type>${MsoUtils.xmlEscape(serviceType)}</subscription-service-type>
382                                         <onap-model-information>
383                                              <model-invariant-uuid>${MsoUtils.xmlEscape(serviceModelInvariantUuid)}</model-invariant-uuid>
384                                              <model-uuid>${MsoUtils.xmlEscape(serviceModelUuid)}</model-uuid>
385                                              <model-version>${MsoUtils.xmlEscape(serviceModelVersion)}</model-version>
386                                              <model-name>${MsoUtils.xmlEscape(serviceModelName)}</model-name>
387                                         </onap-model-information>
388                                         <service-instance-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-instance-id>
389                                         <global-customer-id>${MsoUtils.xmlEscape(globalCustomerId)}</global-customer-id>
390                                      </service-information>
391                                      <service-request-input>
392                                      </service-request-input>
393                                 </sdncadapterworkflow:SDNCRequestData>
394                              </aetgt:SDNCAdapterWorkflowRequest>""".trim()
395             
396             String sndcTopologyDeleteRequesAsString = utils.formatXml(sndcTopologyDeleteRequest)
397             utils.logAudit(sndcTopologyDeleteRequesAsString)
398             execution.setVariable("sdncAdapterWorkflowRequest", sndcTopologyDeleteRequesAsString)
399             utils.log("INFO","sdncAdapterWorkflowRequest - " + "\n" +  sndcTopologyDeleteRequesAsString, isDebugEnabled)
400
401         } catch (Exception ex) {
402             String exceptionMessage = " Bpmn error encountered in DoDeleteResourcesV1 flow. prepareSDNCServiceRequest() - " + ex.getMessage()
403             utils.log("DEBUG", exceptionMessage, isDebugEnabled)
404             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
405
406         }
407        utils.log("INFO","***** Exit prepareSDNCServiceRequest for " + svcAction +  "*****",  isDebugEnabled)
408         }
409 }