63cd3c72f9d15e7f9f44911d592a979ef0c7dac9
[so.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  # Copyright (c) 2019, 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.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
45
46 import javax.ws.rs.core.Response
47 import java.lang.reflect.Type
48
49 /**
50  * This class supports the DoCreateVnf building block subflow
51  * with the creation of a generic vnf for
52  * infrastructure.
53  *
54  */
55 class DoSendCommandToNSSMF extends AbstractServiceTaskProcessor {
56
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()
64
65         /**
66          * This method gets and validates the incoming
67          * request.
68          *
69          * @param - execution
70          *
71          */
72         public void preProcessRequest(DelegateExecution execution) {
73
74                 execution.setVariable("prefix",Prefix)
75                 logger.debug("STARTED Do sendcommandtoNssmf PreProcessRequest Process")
76
77                 /*******************/
78                 try{
79                         // Get Variables
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)
85
86                         String NSIserviceid =  execution.getVariable("NSIserviceid")
87                         execution.setVariable("NSIserviceid", NSIserviceid)
88                         logger.debug("Incoming NSI id is: " + NSIserviceid)
89
90
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)
97
98                         String requestId = execution.getVariable("msoRequestId")
99                         execution.setVariable("msoRequestId", requestId)
100
101                         String operationType = execution.getVariable("operationType")
102                         execution.setVariable("operationType", operationType)
103                         logger.debug("Incoming operationType is: " + operationType)
104
105             if (operationType == "activation") {
106                                 execution.setVariable("activationSequence","an,tn,cn")
107                         }else {
108                                 execution.setVariable("activationSequence","cn,tn,an")
109                         }
110                         execution.setVariable("activationIndex",0)
111                         execution.setVariable("miniute", "0")
112                         execution.setVariable("activateNumberSlice",0)
113
114                         logger.info("the end !!")
115                 }catch(BpmnError b){
116                         logger.debug("Rethrowing MSOWorkflowException")
117                         throw b
118                 }catch(Exception e){
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")
122
123                 }
124                 logger.trace("COMPLETED DoSendCommandToNSSMF PreProcessRequest Process")
125         }
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())
129         {
130             map.put(child.getKey(), child.getValue())
131         }
132         return new Gson().toJson(map)
133     }
134         public  void getNSSIformlist(DelegateExecution execution) {
135
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")
140
141                 String activationSequence01 = execution.getVariable("activationSequence")
142             String[] strlist = activationSequence01.split(",")
143
144                 int  activationIndex = execution.getVariable("activationIndex")
145                 int indexcurrent = 0
146                 if (isNSSIActivate == "true")
147                 {
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}",
164             "modelVersion":""
165              }"""
166                                 execution.setVariable("serviceModelInfo", serviceModelInfo)
167                                 indexcurrent = index
168                                 execution.setVariable("activationIndex", indexcurrent)
169                                 break
170                         }else
171                         {
172                                 indexcurrent = index + 1
173
174                         }
175                 }
176                         if ( activationIndex > 2) {
177                                 execution.setVariable("isGetSuccessfull", "false")
178                         }
179                         execution.setVariable("activationIndex", indexcurrent)}
180
181         }
182         /**
183          * get vendor Info
184          * @param execution
185          */
186         private void processDecomposition(DelegateExecution execution) {
187                 logger.debug("***** processDecomposition *****")
188
189                 try {
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")
195
196                         execution.setVariable("vendor", vendor)
197                 //      currentNSSI['domainType'] = domainType
198                         logger.info("processDecomposition, current vendor-domainType:" +  vendor)
199
200                 } catch (any) {
201                         String exceptionMessage = "Bpmn error encountered in deallocate nssi. processDecomposition() - " + any.getMessage()
202                         logger.debug(exceptionMessage)
203                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
204                 }
205                 logger.debug("***** Exit processDecomposition *****")
206         }
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
213                 if (rate == 100)
214                 {
215                         execution.setVariable("isNSSIActivate","true")
216                 }
217                 else{
218                         execution.setVariable("isNSSIActivate","false")
219                 }
220                 activationIndex = activationIndex + 1
221                 execution.setVariable("activationIndex",activationIndex)
222                 logger.trace("the Progress of activation is " + rate.toString() + "%" )
223                 try{
224                         String serviceId = execution.getVariable("serviceInstanceId")
225                         String operationId = UUID.randomUUID().toString()
226                         String operationType =  execution.getVariable("operationType")
227                         String userId = ""
228                         String result = (operationType.equals("activation"))? "ACTIVATING": "DEACTIVATING"
229                         int progress = rate
230                         String reason = ""
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)
237
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)
241
242                         String payload =
243                                         """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
244                         xmlns:ns="http://org.onap.so/requestsdb">
245                         <soapenv:Header/>
246                         <soapenv:Body>
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>
257                     </soapenv:Body>
258                 </soapenv:Envelope>"""
259
260                         payload = utils.formatXml(payload)
261                         execution.setVariable("CVFMI_updateServiceOperStatusRequest", payload)
262                         logger.debug("Outgoing CVFMI_updateServiceOperStatusRequest: \n" + payload)
263
264                 }catch(Exception e){
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())
269                 }
270                 logger.trace("finished Activate Slice")
271         }
272         public void WaitForReturn(DelegateExecution execution) {
273                 //logger.debug("Query : "+ Jobid)
274                 def miniute=execution.getVariable("miniute")
275                 Thread.sleep(10000)
276                 int miniute01  = Integer.parseInt(miniute) + 1
277                 logger.debug("waiting for : "+ miniute + "miniutes")
278                 execution.setVariable("miniute", String.valueOf(miniute01))
279         }
280         public void GetTheStatusOfActivation(DelegateExecution execution) {
281
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"
290
291
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)
296
297         JobStatusRequest jobStatusRequest = new JobStatusRequest()
298
299         EsrInfo info = new EsrInfo()
300                 info.setNetworkType(NetworkType.fromString(domaintype))
301                 info.setVendor(vendor)
302
303                 jobStatusRequest.setNsiId(NSIserviceid)
304                 jobStatusRequest.setNssiId(nssiId)
305                 jobStatusRequest.setEsrInfo(info)
306
307
308                 ObjectMapper mapper = new ObjectMapper()
309                 String Reqjson = mapper.writeValueAsString(jobStatusRequest)
310                 String isActivateSuccessfull=false
311
312                 String urlString = UrnPropertiesReader.getVariable("mso.adapters.nssmf.endpoint", execution)
313                 String nssmfRequest = urlString + "/api/rest/provMns/v1/NSS/jobs/" +Jobid
314
315                 //send request to active  NSSI TN option
316                 URL url = new URL(nssmfRequest)
317
318         HttpClient httpClient = new HttpClientFactory().newJsonClient(url,  ONAPComponents.EXTERNAL)
319                 Response httpResponse = httpClient.post(Reqjson)
320
321                 int responseCode = httpResponse.getStatus()
322                 logger.debug("NSSMF activation response code is: " + responseCode)
323
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)
328                         jobstatus="error"
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()
334                                 switch(jobstatus) {
335                                         case "started":
336                                         case "processing":
337                                                 isActivateSuccessfull = "waitting"
338                                                 execution.setVariable("isActivateSuccessfull", isActivateSuccessfull)
339                                                 break
340                                         case "finished":
341                                                 isActivateSuccessfull = "true"
342                                                 execution.setVariable("isActivateSuccessfull", isActivateSuccessfull)
343                                                 execution.setVariable("activateNumberSlice",execution.getVariable("activateNumberSlice")+ 1)
344                                                 break
345                                         case "error":
346                                         default:
347                                                 isActivateSuccessfull = "false"
348                                                 execution.setVariable("isActivateSuccessfull", isActivateSuccessfull)
349
350                                 }
351                                 if(Integer.parseInt(miniute) > 6 )
352                                 {
353                                         isActivateSuccessfull = "false"
354                                         execution.setVariable("isActivateSuccessfull", isActivateSuccessfull)
355                                         exceptionUtil.buildAndThrowWorkflowException(execution, responseCode, "Received a timeout job status Response from NSSMF.")
356                                 }
357                         }else
358                         {
359                                 exceptionUtil.buildAndThrowWorkflowException(execution, responseCode, "Received a Bad job status Response from NSSMF.")
360                                 isActivateSuccessfull = false
361                                 execution.setVariable("isActivateSuccessfull", isActivateSuccessfull)
362                         }
363                 } else {
364                         isActivateSuccessfull = false
365                         execution.setVariable("isActivateSuccessfull", isActivateSuccessfull)
366                         exceptionUtil.buildAndThrowWorkflowException(execution, responseCode, "Received a Bad job status Response from NSSMF.")
367                 }
368         }
369         public void SendCommandToNssmf(DelegateExecution execution) {
370
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")
376
377
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)
382
383         EsrInfo esr = new EsrInfo();
384                 esr.setNetworkType(NetworkType.fromString(domaintype))
385                 esr.setVendor(vendor)
386
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)
393
394                 ObjectMapper mapper = new ObjectMapper();
395                 String json = mapper.writeValueAsString(actRequest);
396
397
398                 String urlString = UrnPropertiesReader.getVariable("mso.adapters.nssmf.endpoint", execution)
399
400                 //Prepare auth for NSSMF - Begin
401                 def authHeader = ""
402                 String basicAuth = UrnPropertiesReader.getVariable("mso.nssmf.auth", execution)
403                 String operationType = execution.getVariable("operationType")
404
405                 String nssmfRequest = urlString + "/api/rest/provMns/v1/NSS/" + snssai + "/" + operationType
406
407                 //send request to active  NSSI TN option
408                 URL url = new URL(nssmfRequest)
409
410         HttpClient httpClient = new HttpClientFactory().newJsonClient(url, ONAPComponents.EXTERNAL)
411                 Response httpResponse = httpClient.post(json)
412
413                 int responseCode = httpResponse.getStatus()
414                 logger.debug("NSSMF activate response code is: " + responseCode)
415                 checkNssmfResponse(httpResponse, execution)
416
417         NssiResponse nssmfResponse = httpResponse.readEntity(NssiResponse.class)
418                 String jobId  = nssmfResponse.getJobId() ?: ""
419                 execution.setVariable("JobId", jobId)
420
421         }
422         private void checkNssmfResponse(Response httpResponse, DelegateExecution execution) {
423                 int responseCode = httpResponse.getStatus()
424                 logger.debug("NSSMF response code is: " + responseCode)
425
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")
431                 }else{
432                         String  isNSSIActivated = "true"
433                         execution.setVariable("isNSSIActivated", isNSSIActivated)
434                 }
435         }
436
437
438         void sendSyncError (DelegateExecution execution) {
439                 logger.trace("start sendSyncError")
440                 try {
441                         String errorMessage = ""
442                         if (execution.getVariable("WorkflowException") instanceof WorkflowException) {
443                                 WorkflowException wfe = execution.getVariable("WorkflowException")
444                                 errorMessage = wfe.getErrorMessage()
445                         } else {
446                                 errorMessage = "Sending Sync Error."
447                         }
448
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>"""
454
455                         logger.debug(buildworkflowException)
456                         sendWorkflowResponse(execution, 500, buildworkflowException)
457
458                 } catch (Exception ex) {
459                         logger.debug("Sending Sync Error Activity Failed. " + "\n" + ex.getMessage())
460                 }
461                 logger.trace("finished sendSyncError")
462         }
463 }