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