Fix in e2e activation flow for option1
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / DoActivateSliceService.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  # Copyright (c) 2020, CMCC Technologies Co., Ltd.
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.isBlank
24 import com.fasterxml.jackson.databind.ObjectMapper
25 import com.google.gson.Gson
26 import com.google.gson.reflect.TypeToken
27 import org.apache.commons.lang3.StringUtils
28 import org.camunda.bpm.engine.delegate.BpmnError
29 import org.camunda.bpm.engine.delegate.DelegateExecution
30 import org.onap.logging.filter.base.ErrorCode
31 import javax.ws.rs.NotFoundException
32 import org.onap.aai.domain.yang.Relationship
33 import org.onap.aai.domain.yang.ServiceInstance
34 import org.onap.aaiclient.client.aai.AAIResourcesClient
35 import org.onap.aaiclient.client.aai.entities.AAIResultWrapper
36 import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
37 import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
38 import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder
39 import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder.Types
40 import org.onap.so.beans.nsmf.*
41 import org.onap.so.beans.nsmf.oof.SubnetType
42 import org.onap.so.bpmn.common.scripts.*
43 import org.onap.so.bpmn.core.UrnPropertiesReader
44 import org.onap.so.bpmn.core.WorkflowException
45 import org.onap.so.bpmn.core.domain.ServiceArtifact
46 import org.onap.so.bpmn.core.domain.ServiceDecomposition
47 import org.onap.so.bpmn.core.json.JsonUtils
48 import org.onap.so.logger.LoggingAnchor
49 import org.onap.so.logger.MessageEnum
50 import org.slf4j.Logger
51 import org.slf4j.LoggerFactory
52 import org.springframework.web.util.UriUtils
53
54 import java.lang.reflect.Type
55
56 /**
57  * This class supports the DoCreateVnf building block subflow
58  * with the creation of a generic vnf for
59  * infrastructure.
60  *
61  */
62 class DoActivateSliceService extends AbstractServiceTaskProcessor {
63
64     private static final Logger logger = LoggerFactory.getLogger(DoActivateSliceService.class)
65
66     private static final NSSMF_ACTIVATION_URL = "/api/rest/provMns/v1/NSS/%s/activation"
67
68     private static final NSSMF_DEACTIVATION_URL = "/api/rest/provMns/v1/NSS/%s/deactivation"
69
70     private static final NSSMF_QUERY_JOB_STATUS_URL = "/api/rest/provMns/v1/NSS/jobs/%s"
71
72     String Prefix="DoCNSSMF_"
73     ExceptionUtil exceptionUtil = new ExceptionUtil()
74
75     JsonUtils jsonUtil = new JsonUtils()
76
77     ObjectMapper objectMapper = new ObjectMapper()
78
79     SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils()
80
81     private NssmfAdapterUtils nssmfAdapterUtils = new NssmfAdapterUtils(httpClientFactory, jsonUtil)
82
83         /**
84          * This method gets and validates the incoming
85          * request.
86          *
87          * @param - execution
88          *
89          */
90         public void preProcessRequest(DelegateExecution execution) {
91
92                 execution.setVariable("prefix",Prefix)
93                 logger.debug("STARTED Do sendcommandtoNssmf PreProcessRequest Process")
94
95                 /*******************/
96                 try{
97             Queue<NssInstance> nssInstances = execution.getVariable("nssInstances") as Queue<NssInstance>
98             NssInstance nssInstance = nssInstances.poll()
99             execution.setVariable("nssInstances", nssInstances)
100             execution.setVariable("nssInstance", nssInstance)
101
102                         logger.info("the end !!")
103                 }catch(BpmnError b){
104                         logger.debug("Rethrowing MSOWorkflowException")
105                         throw b
106                 }catch(Exception e){
107                         logger.info("the end of catch !!")
108                         logger.debug(" Error Occured in DoSendCommandToNSSMF PreProcessRequest method!" + e.getMessage())
109                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DoSendCommandToNSSMF PreProcessRequest")
110
111                 }
112                 logger.trace("COMPLETED DoSendCommandToNSSMF PreProcessRequest Process")
113         }
114
115     void prepareCompose(DelegateExecution execution) {
116         NssInstance nssInstance = execution.getVariable("nssInstance") as NssInstance
117         execution.setVariable("nssInstanceId", nssInstance.nssiId)
118         String serviceModelInfo = """{
119                         "modelInvariantUuid":"${nssInstance.modelInvariantId}",
120                         "modelUuid":"${nssInstance.modelVersionId}",
121                         "modelVersion":""
122                     }"""
123         execution.setVariable("serviceModelInfo", serviceModelInfo)
124     }
125
126         /**
127          * get vendor Info
128          * @param execution
129          */
130         void processDecomposition(DelegateExecution execution) {
131                 logger.debug("***** processDecomposition *****")
132
133                 try {
134                         ServiceDecomposition serviceDecomposition =
135                     execution.getVariable("serviceDecomposition") as ServiceDecomposition
136
137                         String vendor = serviceDecomposition.getServiceRole()
138             CustomerInfo customerInfo = execution.getVariable("customerInfo") as CustomerInfo
139             NssInstance nssInstance = execution.getVariable("nssInstance") as NssInstance
140             String reqUrl
141             String actionType
142             if (OperationType.ACTIVATE == nssInstance.operationType) {
143                 reqUrl = String.format(NSSMF_ACTIVATION_URL, nssInstance.snssai)
144                 actionType = "activate"
145             } else {
146                 reqUrl = String.format(NSSMF_DEACTIVATION_URL, nssInstance.snssai)
147                 actionType = "deactivate"
148             }
149             execution.setVariable("reqUrl", reqUrl)
150
151             NssmfAdapterNBIRequest nbiRequest = new NssmfAdapterNBIRequest()
152
153             EsrInfo esrInfo = new EsrInfo()
154             esrInfo.setVendor(vendor)
155             esrInfo.setNetworkType(nssInstance.networkType)
156
157             ServiceInfo serviceInfo = ServiceInfo.builder()
158                     .nssiId(nssInstance.nssiId)
159                     .subscriptionServiceType(customerInfo.subscriptionServiceType)
160                     .globalSubscriberId(customerInfo.globalSubscriberId)
161                     .nsiId(customerInfo.nsiId)
162                     .serviceInvariantUuid(nssInstance.modelInvariantId)
163                     .serviceUuid(nssInstance.modelVersionId)
164                     .serviceType(nssInstance.serviceType)
165                     .actionType(actionType)
166                     .build()
167
168             ActDeActNssi actDeActNssi = new ActDeActNssi()
169             actDeActNssi.setNsiId(customerInfo.nsiId)
170             actDeActNssi.setNssiId(nssInstance.nssiId)
171             actDeActNssi.setSnssaiList(Arrays.asList(customerInfo.snssai))
172
173             String sliceProfileId = getRelatedSliceProfileId(execution, customerInfo.globalSubscriberId, customerInfo.subscriptionServiceType, nssInstance.nssiId, customerInfo.snssai, "slice-profile")
174             actDeActNssi.setSliceProfileId(sliceProfileId)
175
176             nbiRequest.setEsrInfo(esrInfo)
177             nbiRequest.setServiceInfo(serviceInfo)
178             nbiRequest.setActDeActNssi(actDeActNssi)
179             execution.setVariable("nbiRequest", nbiRequest)
180             execution.setVariable("esrInfo", esrInfo)
181             execution.setVariable("serviceInfo", serviceInfo)
182
183                 } catch (any) {
184                         String exceptionMessage = "Bpmn error encountered in deallocate nssi. processDecomposition() - " + any.getMessage()
185                         logger.debug(exceptionMessage)
186                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
187                 }
188                 logger.debug("***** Exit processDecomposition *****")
189         }
190
191         private String getRelatedSliceProfileId(DelegateExecution execution, String globalSubscriberId, String subscriptionServiceType, String instanceId, String snssai, String role) {
192                 logger.debug("${Prefix} - Get Related Slice Profile")
193                 if( isBlank(role) || isBlank(instanceId)) {
194                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Role and instanceId are mandatory")
195                 }
196
197                 String nssiId;
198                 AAIResourcesClient client = getAAIClient()
199                 AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(globalSubscriberId).serviceSubscription(subscriptionServiceType).serviceInstance(instanceId))
200                 if (!client.exists(uri)) {
201                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Service Instance was not found in aai : ${instanceId}")
202                 }
203                 AAIResultWrapper wrapper = client.get(uri, NotFoundException.class)
204                 Optional<ServiceInstance> si = wrapper.asBean(ServiceInstance.class)
205                 if(si.isPresent()) {
206                 List<Relationship> relationshipList = si.get().getRelationshipList().getRelationship()
207                 for (Relationship relationship : relationshipList) {
208                         String relatedTo = relationship.getRelatedTo()
209                         if (relatedTo.toLowerCase() == "service-instance") {
210                                 String relatioshipurl = relationship.getRelatedLink()
211                                 String serviceInstanceId =
212                                                 relatioshipurl.substring(relatioshipurl.lastIndexOf("/") + 1, relatioshipurl.length())
213                                 uri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(globalSubscriberId).serviceSubscription(subscriptionServiceType).serviceInstance(serviceInstanceId))
214                                 if (!client.exists(uri)) {
215                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500,
216                                                         "Service Instance was not found in aai: ${serviceInstanceId} related to ${instanceId}")
217                                 }
218                                 AAIResultWrapper wrapper01 = client.get(uri, NotFoundException.class)
219                                 Optional<ServiceInstance> serviceInstance = wrapper01.asBean(ServiceInstance.class)
220                                 if (serviceInstance.isPresent()) {
221                                         ServiceInstance instance = serviceInstance.get()
222                                         if (role.equalsIgnoreCase(instance.getServiceRole()) && snssai.equalsIgnoreCase(instance.getEnvironmentContext())) {
223                         nssiId = instance.getServiceInstanceId()
224                                         }
225                                 }
226                         }
227                 }
228                 }
229                 return nssiId
230                 logger.debug("${Prefix} - Exit Get Related Slice Profile instances")
231     }
232
233     /**
234      * send Create Request NSSMF
235      * @param execution
236      */
237     void sendCreateRequestNSSMF(DelegateExecution execution) {
238         NssmfAdapterNBIRequest nbiRequest = execution.getVariable("nbiRequest") as NssmfAdapterNBIRequest
239         String nssmfRequest = objectMapper.writeValueAsString(nbiRequest)
240         logger.debug("sendCreateRequestNSSMF: " + nssmfRequest)
241
242         String reqUrl = execution.getVariable("reqUrl")
243         String response = nssmfAdapterUtils.sendPostRequestNSSMF(execution, reqUrl, nssmfRequest)
244
245         if (response != null) {
246             NssiResponse nssiResponse = objectMapper.readValue(response, NssiResponse.class)
247             execution.setVariable("nssiAllocateResult", nssiResponse)
248         }
249         //todo: error
250     }
251
252     /**
253      * query nssi allocate status
254      * @param execution
255      */
256     void queryNSSIStatus(DelegateExecution execution) {
257         NssmfAdapterNBIRequest nbiRequest = new NssmfAdapterNBIRequest()
258         EsrInfo esrInfo = execution.getVariable("esrInfo") as EsrInfo
259         ServiceInfo serviceInfo = execution.getVariable("serviceInfo") as ServiceInfo
260         nbiRequest.setEsrInfo(esrInfo)
261         nbiRequest.setServiceInfo(serviceInfo)
262
263         NssiResponse nssiAllocateResult = execution.getVariable("nssiAllocateResult") as NssiResponse
264         String jobId = nssiAllocateResult.getJobId()
265
266         String endpoint = String.format(NSSMF_QUERY_JOB_STATUS_URL, jobId)
267
268         String response =
269                 nssmfAdapterUtils.sendPostRequestNSSMF(execution, endpoint, objectMapper.writeValueAsString(nbiRequest))
270
271         logger.debug("nssmf response nssiAllocateStatus:" + response)
272
273         if (response != null) {
274             JobStatusResponse jobStatusResponse = objectMapper.readValue(response, JobStatusResponse.class)
275
276             execution.setVariable("nssiAllocateStatus", jobStatusResponse)
277             if (jobStatusResponse.getResponseDescriptor().getProgress() == 100) {
278                 execution.setVariable("jobFinished", true)
279             }
280         }
281     }
282
283     void timeDelay(DelegateExecution execution) {
284         logger.trace("Enter timeDelay in DoAllocateNSSI()")
285         try {
286             Thread.sleep(60000)
287
288             int currentCycle = execution.hasVariable("currentCycle") ?
289                     execution.getVariable("currentCycle") as Integer : 1
290
291             currentCycle = currentCycle + 1
292             if(currentCycle >  60)
293             {
294                 logger.trace("Completed all the retry times... but still nssmf havent completed the creation process...")
295                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, "NSSMF creation didnt complete by time...")
296             }
297             execution.setVariable("currentCycle", currentCycle)
298         } catch(InterruptedException e) {
299             logger.info("Time Delay exception" + e)
300         }
301         logger.trace("Exit timeDelay in DoAllocateNSSI()")
302     }
303
304     void sendSyncError (DelegateExecution execution) {
305                 logger.trace("start sendSyncError")
306                 try {
307                         String errorMessage = ""
308                         if (execution.getVariable("WorkflowException") instanceof WorkflowException) {
309                                 WorkflowException wfe = execution.getVariable("WorkflowException")
310                                 errorMessage = wfe.getErrorMessage()
311                         } else {
312                                 errorMessage = "Sending Sync Error."
313                         }
314
315                         String buildworkflowException =
316                                         """<aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1">
317                                         <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorMessage)}</aetgt:ErrorMessage>
318                                         <aetgt:ErrorCode>7000</aetgt:ErrorCode>
319                                    </aetgt:WorkflowException>"""
320
321                         logger.debug(buildworkflowException)
322                         sendWorkflowResponse(execution, 500, buildworkflowException)
323
324                 } catch (Exception ex) {
325                         logger.debug("Sending Sync Error Activity Failed. " + "\n" + ex.getMessage())
326                 }
327                 logger.trace("finished sendSyncError")
328         }
329 }