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