2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 # Copyright (c) 2019, CMCC Technologies Co., Ltd.
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
11 # http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.so.bpmn.infrastructure.scripts
23 import com.fasterxml.jackson.databind.ObjectMapper
24 import com.google.gson.Gson
25 import com.google.gson.reflect.TypeToken
26 import org.camunda.bpm.engine.delegate.BpmnError
27 import org.camunda.bpm.engine.delegate.DelegateExecution
28 import org.onap.logging.filter.base.ONAPComponents
29 import org.onap.so.beans.nsmf.*
30 import org.onap.so.bpmn.common.scripts.*
31 import org.onap.so.bpmn.common.util.OofInfraUtils
32 import org.onap.so.bpmn.core.UrnPropertiesReader
33 import org.onap.so.bpmn.core.WorkflowException
34 import org.onap.so.bpmn.core.domain.ServiceArtifact
35 import org.onap.so.bpmn.core.domain.ServiceDecomposition
36 import org.onap.so.bpmn.core.json.JsonUtils
37 import org.onap.so.client.HttpClient
38 import org.onap.so.client.HttpClientFactory
39 import org.onap.so.logger.ErrorCode
40 import org.onap.so.logger.LoggingAnchor
41 import org.onap.so.logger.MessageEnum
42 import org.slf4j.Logger
43 import org.slf4j.LoggerFactory
44 import org.springframework.web.util.UriUtils
46 import javax.ws.rs.core.Response
47 import java.lang.reflect.Type
50 * This class supports the DoCreateVnf building block subflow
51 * with the creation of a generic vnf for
55 class DoSendCommandToNSSMF extends AbstractServiceTaskProcessor {
57 private static final Logger logger = LoggerFactory.getLogger( DoSendCommandToNSSMF.class);
58 String Prefix="DoCNSSMF_"
59 ExceptionUtil exceptionUtil = new ExceptionUtil()
60 JsonUtils jsonUtil = new JsonUtils()
61 VidUtils vidUtils = new VidUtils(this)
62 SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils()
63 OofInfraUtils oofInfraUtils = new OofInfraUtils()
66 * This method gets and validates the incoming
72 public void preProcessRequest(DelegateExecution execution) {
74 execution.setVariable("prefix",Prefix)
75 logger.debug("STARTED Do sendcommandtoNssmf PreProcessRequest Process")
80 String e2eserviceInstanceId = execution.getVariable("e2eserviceInstanceId")
81 String serviceInstanceId = execution.getVariable("e2eserviceInstanceId")
82 execution.setVariable("e2eserviceInstanceId", e2eserviceInstanceId)
83 execution.setVariable("serviceInstanceId", serviceInstanceId)
84 logger.debug("Incoming e2eserviceInstanceId is: " + e2eserviceInstanceId)
86 String NSIserviceid = execution.getVariable("NSIserviceid")
87 execution.setVariable("NSIserviceid", NSIserviceid)
88 logger.debug("Incoming NSI id is: " + NSIserviceid)
91 String nssiMap = execution.getVariable("nssiMap")
92 Type type = new TypeToken<HashMap<String, NSSI>>(){}.getType()
93 Map<String, NSSI> DonssiMap = new Gson().fromJson(nssiMap,type)
94 String strDonssiMap = mapToJsonStr(DonssiMap)
95 execution.setVariable("DonssiMap",strDonssiMap)
96 logger.debug("Incoming DonssiMap is: " + strDonssiMap)
98 String requestId = execution.getVariable("msoRequestId")
99 execution.setVariable("msoRequestId", requestId)
101 String operationType = execution.getVariable("operationType")
102 execution.setVariable("operationType", operationType)
103 logger.debug("Incoming operationType is: " + operationType)
105 if (operationType == "activation") {
106 execution.setVariable("activationSequence","an,tn,cn")
108 execution.setVariable("activationSequence","cn,tn,an")
110 execution.setVariable("activationIndex",0)
111 execution.setVariable("miniute", "0")
112 execution.setVariable("activateNumberSlice",0)
114 logger.info("the end !!")
116 logger.debug("Rethrowing MSOWorkflowException")
119 logger.info("the end of catch !!")
120 logger.debug(" Error Occured in DoSendCommandToNSSMF PreProcessRequest method!" + e.getMessage())
121 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DoSendCommandToNSSMF PreProcessRequest")
124 logger.trace("COMPLETED DoSendCommandToNSSMF PreProcessRequest Process")
126 private String mapToJsonStr(Map<String, NSSI> stringNSSIHashMap) {
127 HashMap<String, NSSI> map = new HashMap<String, NSSI>()
128 for(Map.Entry<String, NSSI> child:stringNSSIHashMap.entrySet())
130 map.put(child.getKey(), child.getValue())
132 return new Gson().toJson(map)
134 public void getNSSIformlist(DelegateExecution execution) {
136 String nssiMap = execution.getVariable("DonssiMap")
137 Type type = new TypeToken<HashMap<String, NSSI>>(){}.getType()
138 Map<String, NSSI> DonssiMap = new Gson().fromJson(nssiMap,type)
139 String isNSSIActivate = execution.getVariable("isNSSIActivate")
141 String activationSequence01 = execution.getVariable("activationSequence")
142 String[] strlist = activationSequence01.split(",")
144 int activationIndex = execution.getVariable("activationIndex")
146 if (isNSSIActivate == "true")
148 execution.setVariable("isGetSuccessfull", "false")
149 }else{for (int index = activationIndex; index < 3;index++) {
150 String domaintype01 = strlist[index]
151 if (DonssiMap.containsKey(domaintype01)) {
152 NSSI nssiobject = DonssiMap.get(domaintype01)
153 execution.setVariable("domainType", domaintype01)
154 execution.setVariable("nssiId", nssiobject.getNssiId())
155 execution.setVariable("modelInvariantUuid", nssiobject.getModelInvariantId())
156 execution.setVariable("modelUuid", nssiobject.getModelVersionId())
157 execution.setVariable("isGetSuccessfull", "true")
158 String modelInvariantUuid = execution.getVariable("modelInvariantUuid")
159 String modelUuid = execution.getVariable("modelUuid")
160 //here modelVersion is not set, we use modelUuid to decompose the service.
161 String serviceModelInfo = """{
162 "modelInvariantUuid":"${modelInvariantUuid}",
163 "modelUuid":"${modelUuid}",
166 execution.setVariable("serviceModelInfo", serviceModelInfo)
168 execution.setVariable("activationIndex", indexcurrent)
172 indexcurrent = index + 1
176 if ( activationIndex > 2) {
177 execution.setVariable("isGetSuccessfull", "false")
179 execution.setVariable("activationIndex", indexcurrent)}
186 private void processDecomposition(DelegateExecution execution) {
187 logger.debug("***** processDecomposition *****")
190 ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition") as ServiceDecomposition
191 ServiceArtifact serviceArtifact = serviceDecomposition.getServiceInfo().getServiceArtifact().get(0)
192 String content = serviceArtifact.getContent()
193 String vendor = jsonUtil.getJsonValue(content, "metadata.vendor")
194 //String domainType = jsonUtil.getJsonValue(content, "metadata.domainType")
196 execution.setVariable("vendor", vendor)
197 // currentNSSI['domainType'] = domainType
198 logger.info("processDecomposition, current vendor-domainType:" + vendor)
201 String exceptionMessage = "Bpmn error encountered in deallocate nssi. processDecomposition() - " + any.getMessage()
202 logger.debug(exceptionMessage)
203 exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
205 logger.debug("***** Exit processDecomposition *****")
207 public void UpdateIndex(DelegateExecution execution) {
208 def activationIndex = execution.getVariable("activationIndex")
209 int activateNumberSlice = execution.getVariable("activateNumberSlice") as Integer
210 def activationCount= execution.getVariable("activationCount")
211 //DecimalFormat df1 = new DecimalFormat("##%")
212 int rate = (activateNumberSlice / activationCount) * 100
215 execution.setVariable("isNSSIActivate","true")
218 execution.setVariable("isNSSIActivate","false")
220 activationIndex = activationIndex + 1
221 execution.setVariable("activationIndex",activationIndex)
222 logger.trace("the Progress of activation is " + rate.toString() + "%" )
224 String serviceId = execution.getVariable("serviceInstanceId")
225 String operationId = UUID.randomUUID().toString()
226 String operationType = execution.getVariable("operationType")
228 String result = (operationType.equals("activation"))? "ACTIVATING": "DEACTIVATING"
231 String operationContent = "Service activation in progress"
232 logger.debug("Generated new operation for Service Instance serviceId:" + serviceId + " operationId:" + operationId)
233 serviceId = UriUtils.encode(serviceId,"UTF-8")
234 execution.setVariable("e2eserviceInstanceId", serviceId)
235 execution.setVariable("operationId", operationId)
236 execution.setVariable("operationType", operationType)
238 def dbAdapterEndpoint = UrnPropertiesReader.getVariable("mso.adapters.openecomp.db.endpoint",execution)
239 execution.setVariable("CVFMI_dbAdapterEndpoint", dbAdapterEndpoint)
240 logger.debug("DB Adapter Endpoint is: " + dbAdapterEndpoint)
243 """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
244 xmlns:ns="http://org.onap.so/requestsdb">
247 <ns:initServiceOperationStatus xmlns:ns="http://org.onap.so/requestsdb">
248 <serviceId>${MsoUtils.xmlEscape(serviceId)}</serviceId>
249 <operationId>${MsoUtils.xmlEscape(operationId)}</operationId>
250 <operationType>${MsoUtils.xmlEscape(operationType)}</operationType>
251 <userId>${MsoUtils.xmlEscape(userId)}</userId>
252 <result>${MsoUtils.xmlEscape(result)}</result>
253 <operationContent>${MsoUtils.xmlEscape(operationContent)}</operationContent>
254 <progress>${MsoUtils.xmlEscape(progress)}</progress>
255 <reason>${MsoUtils.xmlEscape(reason)}</reason>
256 </ns:initServiceOperationStatus>
258 </soapenv:Envelope>"""
260 payload = utils.formatXml(payload)
261 execution.setVariable("CVFMI_updateServiceOperStatusRequest", payload)
262 logger.debug("Outgoing CVFMI_updateServiceOperStatusRequest: \n" + payload)
265 logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
266 "Exception Occured Processing Activate Slice .", "BPMN",
267 ErrorCode.UnknownError.getValue(), "Exception is:\n" + e)
268 execution.setVariable("CVFMI_ErrorResponse", "Error Occurred during Activate Slice Method:\n" + e.getMessage())
270 logger.trace("finished Activate Slice")
272 public void WaitForReturn(DelegateExecution execution) {
273 //logger.debug("Query : "+ Jobid)
274 def miniute=execution.getVariable("miniute")
276 int miniute01 = Integer.parseInt(miniute) + 1
277 logger.debug("waiting for : "+ miniute + "miniutes")
278 execution.setVariable("miniute", String.valueOf(miniute01))
280 public void GetTheStatusOfActivation(DelegateExecution execution) {
282 String snssai= execution.getVariable("snssai")
283 String domaintype = execution.getVariable("domainType")
284 String NSIserviceid=execution.getVariable("NSIserviceid")
285 String nssiId = execution.getVariable("nssiId")
286 String Jobid=execution.getVariable("JobId")
287 def miniute=execution.getVariable("miniute")
288 String vendor = execution.getVariable("vendor")
289 String jobstatus ="error"
292 logger.debug("Query the jobid activation of SNSSAI: "+ Jobid)
293 logger.debug("the domain is : "+ domaintype)
294 logger.debug("the NSSID is : "+nssiId)
295 logger.debug("the NSIserviceid is : "+NSIserviceid)
297 JobStatusRequest jobStatusRequest = new JobStatusRequest()
299 EsrInfo info = new EsrInfo()
300 info.setNetworkType(NetworkType.fromString(domaintype))
301 info.setVendor(vendor)
303 jobStatusRequest.setNsiId(NSIserviceid)
304 jobStatusRequest.setNssiId(nssiId)
305 jobStatusRequest.setEsrInfo(info)
308 ObjectMapper mapper = new ObjectMapper()
309 String Reqjson = mapper.writeValueAsString(jobStatusRequest)
310 String isActivateSuccessfull=false
312 String urlString = UrnPropertiesReader.getVariable("mso.adapters.nssmf.endpoint", execution)
313 String nssmfRequest = urlString + "/api/rest/provMns/v1/NSS/jobs/" +Jobid
315 //send request to active NSSI TN option
316 URL url = new URL(nssmfRequest)
318 HttpClient httpClient = new HttpClientFactory().newJsonClient(url, ONAPComponents.EXTERNAL)
319 Response httpResponse = httpClient.post(Reqjson)
321 int responseCode = httpResponse.getStatus()
322 logger.debug("NSSMF activation response code is: " + responseCode)
324 if (responseCode == 404) {
325 exceptionUtil.buildAndThrowWorkflowException(execution, responseCode, "Received a Bad job status Response from NSSMF.")
326 isActivateSuccessfull = false
327 execution.setVariable("isActivateSuccessfull", isActivateSuccessfull)
329 }else if(responseCode == 200) {
330 if (httpResponse.hasEntity()) {
331 JobStatusResponse jobStatusResponse = httpResponse.readEntity(JobStatusResponse.class)
332 execution.setVariable("statusDescription", jobStatusResponse.getResponseDescriptor().getStatusDescription())
333 jobstatus = jobStatusResponse.getResponseDescriptor().getStatus()
337 isActivateSuccessfull = "waitting"
338 execution.setVariable("isActivateSuccessfull", isActivateSuccessfull)
341 isActivateSuccessfull = "true"
342 execution.setVariable("isActivateSuccessfull", isActivateSuccessfull)
343 execution.setVariable("activateNumberSlice",execution.getVariable("activateNumberSlice")+ 1)
347 isActivateSuccessfull = "false"
348 execution.setVariable("isActivateSuccessfull", isActivateSuccessfull)
351 if(Integer.parseInt(miniute) > 6 )
353 isActivateSuccessfull = "false"
354 execution.setVariable("isActivateSuccessfull", isActivateSuccessfull)
355 exceptionUtil.buildAndThrowWorkflowException(execution, responseCode, "Received a timeout job status Response from NSSMF.")
359 exceptionUtil.buildAndThrowWorkflowException(execution, responseCode, "Received a Bad job status Response from NSSMF.")
360 isActivateSuccessfull = false
361 execution.setVariable("isActivateSuccessfull", isActivateSuccessfull)
364 isActivateSuccessfull = false
365 execution.setVariable("isActivateSuccessfull", isActivateSuccessfull)
366 exceptionUtil.buildAndThrowWorkflowException(execution, responseCode, "Received a Bad job status Response from NSSMF.")
369 public void SendCommandToNssmf(DelegateExecution execution) {
371 String snssai= execution.getVariable("snssai")
372 String domaintype = execution.getVariable("domainType")
373 String NSIserviceid=execution.getVariable("NSIserviceid")
374 String nssiId = execution.getVariable("nssiId")
375 String vendor = execution.getVariable("vendor")
378 logger.debug("the domain is : "+domaintype)
379 logger.debug("SNSSAI: "+snssai +" will be activated")
380 logger.debug("the NSSID is : "+nssiId)
381 logger.debug("the NSIserviceid is : "+NSIserviceid)
383 EsrInfo esr = new EsrInfo();
384 esr.setNetworkType(NetworkType.fromString(domaintype))
385 esr.setVendor(vendor)
387 ActDeActNssi actNssi = new ActDeActNssi();
388 actNssi.setNsiId(NSIserviceid);
389 actNssi.setNssiId(nssiId);
390 NssiActDeActRequest actRequest = new NssiActDeActRequest();
391 actRequest.setActDeActNssi(actNssi);
392 actRequest.setEsrInfo(esr)
394 ObjectMapper mapper = new ObjectMapper();
395 String json = mapper.writeValueAsString(actRequest);
398 String urlString = UrnPropertiesReader.getVariable("mso.adapters.nssmf.endpoint", execution)
400 //Prepare auth for NSSMF - Begin
402 String basicAuth = UrnPropertiesReader.getVariable("mso.nssmf.auth", execution)
403 String operationType = execution.getVariable("operationType")
405 String nssmfRequest = urlString + "/api/rest/provMns/v1/NSS/" + snssai + "/" + operationType
407 //send request to active NSSI TN option
408 URL url = new URL(nssmfRequest)
410 HttpClient httpClient = new HttpClientFactory().newJsonClient(url, ONAPComponents.EXTERNAL)
411 Response httpResponse = httpClient.post(json)
413 int responseCode = httpResponse.getStatus()
414 logger.debug("NSSMF activate response code is: " + responseCode)
415 checkNssmfResponse(httpResponse, execution)
417 NssiResponse nssmfResponse = httpResponse.readEntity(NssiResponse.class)
418 String jobId = nssmfResponse.getJobId() ?: ""
419 execution.setVariable("JobId", jobId)
422 private void checkNssmfResponse(Response httpResponse, DelegateExecution execution) {
423 int responseCode = httpResponse.getStatus()
424 logger.debug("NSSMF response code is: " + responseCode)
426 if ( responseCode < 200 || responseCode > 202 || !httpResponse.hasEntity()) {
427 exceptionUtil.buildAndThrowWorkflowException(execution, responseCode, "Received a Bad Response from NSSMF.")
428 String isNSSIActivated = "false"
429 execution.setVariable("isNSSIActivated", isNSSIActivated)
430 execution.setVariable("isNSSIActivate","false")
432 String isNSSIActivated = "true"
433 execution.setVariable("isNSSIActivated", isNSSIActivated)
438 void sendSyncError (DelegateExecution execution) {
439 logger.trace("start sendSyncError")
441 String errorMessage = ""
442 if (execution.getVariable("WorkflowException") instanceof WorkflowException) {
443 WorkflowException wfe = execution.getVariable("WorkflowException")
444 errorMessage = wfe.getErrorMessage()
446 errorMessage = "Sending Sync Error."
449 String buildworkflowException =
450 """<aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1">
451 <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorMessage)}</aetgt:ErrorMessage>
452 <aetgt:ErrorCode>7000</aetgt:ErrorCode>
453 </aetgt:WorkflowException>"""
455 logger.debug(buildworkflowException)
456 sendWorkflowResponse(execution, 500, buildworkflowException)
458 } catch (Exception ex) {
459 logger.debug("Sending Sync Error Activity Failed. " + "\n" + ex.getMessage())
461 logger.trace("finished sendSyncError")