3d9f67653b4bae4a4b6a339e8a588d131151393e
[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
162                         nbiRequest.setEsrInfo(esrInfo)
163             nbiRequest.setServiceInfo(serviceInfo)
164             nbiRequest.setActDeActNssi(actDeActNssi)
165             execution.setVariable("nbiRequest", nbiRequest)
166             execution.setVariable("esrInfo", esrInfo)
167             execution.setVariable("serviceInfo", serviceInfo)
168
169                 } catch (any) {
170                         String exceptionMessage = "Bpmn error encountered in deallocate nssi. processDecomposition() - " + any.getMessage()
171                         logger.debug(exceptionMessage)
172                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
173                 }
174                 logger.debug("***** Exit processDecomposition *****")
175         }
176
177     /**
178      * send Create Request NSSMF
179      * @param execution
180      */
181     void sendCreateRequestNSSMF(DelegateExecution execution) {
182         NssmfAdapterNBIRequest nbiRequest = execution.getVariable("nbiRequest") as NssmfAdapterNBIRequest
183         String nssmfRequest = objectMapper.writeValueAsString(nbiRequest)
184         logger.debug("sendCreateRequestNSSMF: " + nssmfRequest)
185
186         String reqUrl = execution.getVariable("reqUrl")
187         String response = nssmfAdapterUtils.sendPostRequestNSSMF(execution, reqUrl, nssmfRequest)
188
189         if (response != null) {
190             NssiResponse nssiResponse = objectMapper.readValue(response, NssiResponse.class)
191             execution.setVariable("nssiAllocateResult", nssiResponse)
192         }
193         //todo: error
194     }
195
196     /**
197      * query nssi allocate status
198      * @param execution
199      */
200     void queryNSSIStatus(DelegateExecution execution) {
201         NssmfAdapterNBIRequest nbiRequest = new NssmfAdapterNBIRequest()
202         EsrInfo esrInfo = execution.getVariable("esrInfo") as EsrInfo
203         ServiceInfo serviceInfo = execution.getVariable("serviceInfo") as ServiceInfo
204         nbiRequest.setEsrInfo(esrInfo)
205         nbiRequest.setServiceInfo(serviceInfo)
206
207         NssiResponse nssiAllocateResult = execution.getVariable("nssiAllocateResult") as NssiResponse
208         String jobId = nssiAllocateResult.getJobId()
209
210         String endpoint = String.format(NSSMF_QUERY_JOB_STATUS_URL, jobId)
211
212         String response =
213                 nssmfAdapterUtils.sendPostRequestNSSMF(execution, endpoint, objectMapper.writeValueAsString(nbiRequest))
214
215         logger.debug("nssmf response nssiAllocateStatus:" + response)
216
217         if (response != null) {
218             JobStatusResponse jobStatusResponse = objectMapper.readValue(response, JobStatusResponse.class)
219
220             execution.setVariable("nssiAllocateStatus", jobStatusResponse)
221             if (jobStatusResponse.getResponseDescriptor().getProgress() == 100) {
222                 execution.setVariable("jobFinished", true)
223             }
224         }
225     }
226
227     void timeDelay(DelegateExecution execution) {
228         logger.trace("Enter timeDelay in DoAllocateNSSI()")
229         try {
230             Thread.sleep(60000)
231
232             int currentCycle = execution.hasVariable("currentCycle") ?
233                     execution.getVariable("currentCycle") as Integer : 1
234
235             currentCycle = currentCycle + 1
236             if(currentCycle >  60)
237             {
238                 logger.trace("Completed all the retry times... but still nssmf havent completed the creation process...")
239                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, "NSSMF creation didnt complete by time...")
240             }
241             execution.setVariable("currentCycle", currentCycle)
242         } catch(InterruptedException e) {
243             logger.info("Time Delay exception" + e)
244         }
245         logger.trace("Exit timeDelay in DoAllocateNSSI()")
246     }
247
248     void sendSyncError (DelegateExecution execution) {
249                 logger.trace("start sendSyncError")
250                 try {
251                         String errorMessage = ""
252                         if (execution.getVariable("WorkflowException") instanceof WorkflowException) {
253                                 WorkflowException wfe = execution.getVariable("WorkflowException")
254                                 errorMessage = wfe.getErrorMessage()
255                         } else {
256                                 errorMessage = "Sending Sync Error."
257                         }
258
259                         String buildworkflowException =
260                                         """<aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1">
261                                         <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorMessage)}</aetgt:ErrorMessage>
262                                         <aetgt:ErrorCode>7000</aetgt:ErrorCode>
263                                    </aetgt:WorkflowException>"""
264
265                         logger.debug(buildworkflowException)
266                         sendWorkflowResponse(execution, 500, buildworkflowException)
267
268                 } catch (Exception ex) {
269                         logger.debug("Sending Sync Error Activity Failed. " + "\n" + ex.getMessage())
270                 }
271                 logger.trace("finished sendSyncError")
272         }
273 }