Fix some AN NSSMF issues
[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 com.fasterxml.jackson.databind.ObjectMapper
24 import com.google.gson.Gson
25 import com.google.gson.reflect.TypeToken
26 import org.apache.commons.lang3.StringUtils
27 import org.camunda.bpm.engine.delegate.BpmnError
28 import org.camunda.bpm.engine.delegate.DelegateExecution
29 import org.onap.logging.filter.base.ErrorCode
30 import org.onap.so.beans.nsmf.*
31 import org.onap.so.beans.nsmf.oof.SubnetType
32 import org.onap.so.bpmn.common.scripts.*
33 import org.onap.so.bpmn.core.UrnPropertiesReader
34 import org.onap.so.bpmn.core.WorkflowException
35 import org.onap.so.bpmn.core.domain.ServiceArtifact
36 import org.onap.so.bpmn.core.domain.ServiceDecomposition
37 import org.onap.so.bpmn.core.json.JsonUtils
38 import org.onap.so.logger.LoggingAnchor
39 import org.onap.so.logger.MessageEnum
40 import org.slf4j.Logger
41 import org.slf4j.LoggerFactory
42 import org.springframework.web.util.UriUtils
43
44 import java.lang.reflect.Type
45
46 /**
47  * This class supports the DoCreateVnf building block subflow
48  * with the creation of a generic vnf for
49  * infrastructure.
50  *
51  */
52 class DoActivateSliceService extends AbstractServiceTaskProcessor {
53
54     private static final Logger logger = LoggerFactory.getLogger(DoActivateSliceService.class)
55
56     private static final NSSMF_ACTIVATION_URL = "/api/rest/provMns/v1/NSS/%s/activation"
57
58     private static final NSSMF_DEACTIVATION_URL = "/api/rest/provMns/v1/NSS/%s/deactivation"
59
60     private static final NSSMF_QUERY_JOB_STATUS_URL = "/api/rest/provMns/v1/NSS/jobs/%s"
61
62     String Prefix="DoCNSSMF_"
63     ExceptionUtil exceptionUtil = new ExceptionUtil()
64
65     JsonUtils jsonUtil = new JsonUtils()
66
67     ObjectMapper objectMapper = new ObjectMapper()
68
69     SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils()
70
71     private NssmfAdapterUtils nssmfAdapterUtils = new NssmfAdapterUtils(httpClientFactory, jsonUtil)
72
73         /**
74          * This method gets and validates the incoming
75          * request.
76          *
77          * @param - execution
78          *
79          */
80         public void preProcessRequest(DelegateExecution execution) {
81
82                 execution.setVariable("prefix",Prefix)
83                 logger.debug("STARTED Do sendcommandtoNssmf PreProcessRequest Process")
84
85                 /*******************/
86                 try{
87             Queue<NssInstance> nssInstances = execution.getVariable("nssInstances") as Queue<NssInstance>
88             NssInstance nssInstance = nssInstances.poll()
89             execution.setVariable("nssInstances", nssInstances)
90             execution.setVariable("nssInstance", nssInstance)
91
92                         logger.info("the end !!")
93                 }catch(BpmnError b){
94                         logger.debug("Rethrowing MSOWorkflowException")
95                         throw b
96                 }catch(Exception e){
97                         logger.info("the end of catch !!")
98                         logger.debug(" Error Occured in DoSendCommandToNSSMF PreProcessRequest method!" + e.getMessage())
99                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DoSendCommandToNSSMF PreProcessRequest")
100
101                 }
102                 logger.trace("COMPLETED DoSendCommandToNSSMF PreProcessRequest Process")
103         }
104
105     void prepareCompose(DelegateExecution execution) {
106         NssInstance nssInstance = execution.getVariable("nssInstance") as NssInstance
107         execution.setVariable("nssInstanceId", nssInstance.nssiId)
108         String serviceModelInfo = """{
109                         "modelInvariantUuid":"${nssInstance.modelInvariantId}",
110                         "modelUuid":"${nssInstance.modelVersionId}",
111                         "modelVersion":""
112                     }"""
113         execution.setVariable("serviceModelInfo", serviceModelInfo)
114     }
115
116         /**
117          * get vendor Info
118          * @param execution
119          */
120         void processDecomposition(DelegateExecution execution) {
121                 logger.debug("***** processDecomposition *****")
122
123                 try {
124                         ServiceDecomposition serviceDecomposition =
125                     execution.getVariable("serviceDecomposition") as ServiceDecomposition
126
127                         String vendor = serviceDecomposition.getServiceRole()
128             CustomerInfo customerInfo = execution.getVariable("customerInfo") as CustomerInfo
129             NssInstance nssInstance = execution.getVariable("nssInstance") as NssInstance
130             String reqUrl
131             String actionType
132             if (OperationType.ACTIVATE == nssInstance.operationType) {
133                 reqUrl = String.format(NSSMF_ACTIVATION_URL, nssInstance.snssai)
134                 actionType = "activate"
135             } else {
136                 reqUrl = String.format(NSSMF_DEACTIVATION_URL, nssInstance.snssai)
137                 actionType = "deactivate"
138             }
139             execution.setVariable("reqUrl", reqUrl)
140
141             NssmfAdapterNBIRequest nbiRequest = new NssmfAdapterNBIRequest()
142
143             EsrInfo esrInfo = new EsrInfo()
144             esrInfo.setVendor(vendor)
145             esrInfo.setNetworkType(nssInstance.networkType)
146
147             ServiceInfo serviceInfo = ServiceInfo.builder()
148                     .nssiId(nssInstance.nssiId)
149                     .subscriptionServiceType(customerInfo.subscriptionServiceType)
150                     .globalSubscriberId(customerInfo.globalSubscriberId)
151                     .nsiId(customerInfo.nsiId)
152                     .serviceInvariantUuid(nssInstance.modelInvariantId)
153                     .serviceUuid(nssInstance.modelVersionId)
154                     .serviceType(nssInstance.serviceType)
155                     .actionType(actionType)
156                     .build()
157
158             ActDeActNssi actDeActNssi = new ActDeActNssi()
159             actDeActNssi.setNsiId(customerInfo.nsiId)
160             actDeActNssi.setNssiId(nssInstance.nssiId)
161             actDeActNssi.setSnssaiList(Arrays.asList(customerInfo.snssai))
162
163
164                         nbiRequest.setEsrInfo(esrInfo)
165             nbiRequest.setServiceInfo(serviceInfo)
166             nbiRequest.setActDeActNssi(actDeActNssi)
167             execution.setVariable("nbiRequest", nbiRequest)
168             execution.setVariable("esrInfo", esrInfo)
169             execution.setVariable("serviceInfo", serviceInfo)
170
171                 } catch (any) {
172                         String exceptionMessage = "Bpmn error encountered in deallocate nssi. processDecomposition() - " + any.getMessage()
173                         logger.debug(exceptionMessage)
174                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
175                 }
176                 logger.debug("***** Exit processDecomposition *****")
177         }
178
179     /**
180      * send Create Request NSSMF
181      * @param execution
182      */
183     void sendCreateRequestNSSMF(DelegateExecution execution) {
184         NssmfAdapterNBIRequest nbiRequest = execution.getVariable("nbiRequest") as NssmfAdapterNBIRequest
185         String nssmfRequest = objectMapper.writeValueAsString(nbiRequest)
186         logger.debug("sendCreateRequestNSSMF: " + nssmfRequest)
187
188         String reqUrl = execution.getVariable("reqUrl")
189         String response = nssmfAdapterUtils.sendPostRequestNSSMF(execution, reqUrl, nssmfRequest)
190
191         if (response != null) {
192             NssiResponse nssiResponse = objectMapper.readValue(response, NssiResponse.class)
193             execution.setVariable("nssiAllocateResult", nssiResponse)
194         }
195         //todo: error
196     }
197
198     /**
199      * query nssi allocate status
200      * @param execution
201      */
202     void queryNSSIStatus(DelegateExecution execution) {
203         NssmfAdapterNBIRequest nbiRequest = new NssmfAdapterNBIRequest()
204         EsrInfo esrInfo = execution.getVariable("esrInfo") as EsrInfo
205         ServiceInfo serviceInfo = execution.getVariable("serviceInfo") as ServiceInfo
206         nbiRequest.setEsrInfo(esrInfo)
207         nbiRequest.setServiceInfo(serviceInfo)
208
209         NssiResponse nssiAllocateResult = execution.getVariable("nssiAllocateResult") as NssiResponse
210         String jobId = nssiAllocateResult.getJobId()
211
212         String endpoint = String.format(NSSMF_QUERY_JOB_STATUS_URL, jobId)
213
214         String response =
215                 nssmfAdapterUtils.sendPostRequestNSSMF(execution, endpoint, objectMapper.writeValueAsString(nbiRequest))
216
217         logger.debug("nssmf response nssiAllocateStatus:" + response)
218
219         if (response != null) {
220             JobStatusResponse jobStatusResponse = objectMapper.readValue(response, JobStatusResponse.class)
221
222             execution.setVariable("nssiAllocateStatus", jobStatusResponse)
223             if (jobStatusResponse.getResponseDescriptor().getProgress() == 100) {
224                 execution.setVariable("jobFinished", true)
225             }
226         }
227     }
228
229     void timeDelay(DelegateExecution execution) {
230         logger.trace("Enter timeDelay in DoAllocateNSSI()")
231         try {
232             Thread.sleep(60000)
233
234             int currentCycle = execution.hasVariable("currentCycle") ?
235                     execution.getVariable("currentCycle") as Integer : 1
236
237             currentCycle = currentCycle + 1
238             if(currentCycle >  60)
239             {
240                 logger.trace("Completed all the retry times... but still nssmf havent completed the creation process...")
241                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, "NSSMF creation didnt complete by time...")
242             }
243             execution.setVariable("currentCycle", currentCycle)
244         } catch(InterruptedException e) {
245             logger.info("Time Delay exception" + e)
246         }
247         logger.trace("Exit timeDelay in DoAllocateNSSI()")
248     }
249
250     void sendSyncError (DelegateExecution execution) {
251                 logger.trace("start sendSyncError")
252                 try {
253                         String errorMessage = ""
254                         if (execution.getVariable("WorkflowException") instanceof WorkflowException) {
255                                 WorkflowException wfe = execution.getVariable("WorkflowException")
256                                 errorMessage = wfe.getErrorMessage()
257                         } else {
258                                 errorMessage = "Sending Sync Error."
259                         }
260
261                         String buildworkflowException =
262                                         """<aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1">
263                                         <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorMessage)}</aetgt:ErrorMessage>
264                                         <aetgt:ErrorCode>7000</aetgt:ErrorCode>
265                                    </aetgt:WorkflowException>"""
266
267                         logger.debug(buildworkflowException)
268                         sendWorkflowResponse(execution, 500, buildworkflowException)
269
270                 } catch (Exception ex) {
271                         logger.debug("Sending Sync Error Activity Failed. " + "\n" + ex.getMessage())
272                 }
273                 logger.trace("finished sendSyncError")
274         }
275 }