Merge "fixed cs profile trans to ss profile"
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / DoSendCommandToNSSMF.groovy
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.so.beans.nsmf.*
29 import org.onap.so.bpmn.common.scripts.*
30 import org.onap.so.bpmn.core.UrnPropertiesReader
31 import org.onap.so.bpmn.core.WorkflowException
32 import org.onap.so.bpmn.core.domain.ServiceArtifact
33 import org.onap.so.bpmn.core.domain.ServiceDecomposition
34 import org.onap.so.bpmn.core.json.JsonUtils
35 import org.onap.logging.filter.base.ErrorCode
36 import org.onap.so.logger.LoggingAnchor
37 import org.onap.so.logger.MessageEnum
38 import org.slf4j.Logger
39 import org.slf4j.LoggerFactory
40 import org.springframework.web.util.UriUtils
41
42 import java.lang.reflect.Type
43
44 /**
45  * This class supports the DoCreateVnf building block subflow
46  * with the creation of a generic vnf for
47  * infrastructure.
48  *
49  */
50 class DoSendCommandToNSSMF extends AbstractServiceTaskProcessor {
51
52     private static final Logger logger = LoggerFactory.getLogger( DoSendCommandToNSSMF.class);
53         String Prefix="DoCNSSMF_"
54     ExceptionUtil exceptionUtil = new ExceptionUtil()
55     JsonUtils jsonUtil = new JsonUtils()
56     VidUtils vidUtils = new VidUtils(this)
57     SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils()
58
59     private NssmfAdapterUtils nssmfAdapterUtils = new NssmfAdapterUtils(httpClientFactory, jsonUtil)
60
61         /**
62          * This method gets and validates the incoming
63          * request.
64          *
65          * @param - execution
66          *
67          */
68         public void preProcessRequest(DelegateExecution execution) {
69
70                 execution.setVariable("prefix",Prefix)
71                 logger.debug("STARTED Do sendcommandtoNssmf PreProcessRequest Process")
72
73                 /*******************/
74                 try{
75                         // Get Variables
76                         String e2eserviceInstanceId = execution.getVariable("e2eserviceInstanceId")
77                         String serviceInstanceId = execution.getVariable("e2eserviceInstanceId")
78                         execution.setVariable("e2eserviceInstanceId", e2eserviceInstanceId)
79                         execution.setVariable("serviceInstanceId", serviceInstanceId)
80                         logger.debug("Incoming e2eserviceInstanceId is: " + e2eserviceInstanceId)
81
82                         String NSIserviceid =  execution.getVariable("NSIserviceid")
83                         execution.setVariable("NSIserviceid", NSIserviceid)
84                         logger.debug("Incoming NSI id is: " + NSIserviceid)
85
86
87                         String nssiMap  = execution.getVariable("nssiMap")
88                         Type type = new TypeToken<HashMap<String, NSSI>>(){}.getType()
89                         Map<String, NSSI> DonssiMap = new Gson().fromJson(nssiMap,type)
90             String strDonssiMap = mapToJsonStr(DonssiMap)
91                         execution.setVariable("DonssiMap",strDonssiMap)
92                         logger.debug("Incoming DonssiMap is: " + strDonssiMap)
93
94                         String requestId = execution.getVariable("msoRequestId")
95                         execution.setVariable("msoRequestId", requestId)
96
97                         String operationType = execution.getVariable("operationType")
98                         execution.setVariable("operationType", operationType.toLowerCase())
99                         logger.debug("Incoming operationType is: " + operationType)
100
101             if (operationType == "activation") {
102                                 execution.setVariable("activationSequence","an,tn,cn")
103                         }else {
104                                 execution.setVariable("activationSequence","cn,tn,an")
105                         }
106                         execution.setVariable("activationIndex",0)
107                         execution.setVariable("miniute", "0")
108                         execution.setVariable("activateNumberSlice",0)
109
110                         logger.info("the end !!")
111                 }catch(BpmnError b){
112                         logger.debug("Rethrowing MSOWorkflowException")
113                         throw b
114                 }catch(Exception e){
115                         logger.info("the end of catch !!")
116                         logger.debug(" Error Occured in DoSendCommandToNSSMF PreProcessRequest method!" + e.getMessage())
117                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DoSendCommandToNSSMF PreProcessRequest")
118
119                 }
120                 logger.trace("COMPLETED DoSendCommandToNSSMF PreProcessRequest Process")
121         }
122
123     private String mapToJsonStr(Map<String, NSSI> stringNSSIHashMap) {
124         HashMap<String, NSSI> map = new HashMap<String, NSSI>()
125         for(Map.Entry<String, NSSI> child:stringNSSIHashMap.entrySet())
126         {
127             map.put(child.getKey(), child.getValue())
128         }
129         return new Gson().toJson(map)
130     }
131
132         public  void getNSSIformlist(DelegateExecution execution) {
133
134                 String  nssiMap = execution.getVariable("DonssiMap")
135                 Type type = new TypeToken<HashMap<String, NSSI>>(){}.getType()
136         Map<String, NSSI> DonssiMap = new Gson().fromJson(nssiMap,type)
137                 String isNSSIActivate = execution.getVariable("isNSSIActivate")
138
139                 String activationSequence01 = execution.getVariable("activationSequence")
140             String[] strlist = activationSequence01.split(",")
141
142                 int  activationIndex = execution.getVariable("activationIndex")
143                 int indexcurrent = 0
144                 if (isNSSIActivate == "true")
145                 {
146                         execution.setVariable("isGetSuccessfull", "false")
147                 }else{for (int index = activationIndex; index < 3;index++) {
148                         String domaintype01 = strlist[index]
149                         if (DonssiMap.containsKey(domaintype01)) {
150                                 NSSI nssiobject = DonssiMap.get(domaintype01)
151                                 execution.setVariable("domainType", domaintype01)
152                                 execution.setVariable("nssiId", nssiobject.getNssiId())
153                                 execution.setVariable("modelInvariantUuid", nssiobject.getModelInvariantId())
154                                 execution.setVariable("modelUuid", nssiobject.getModelVersionId())
155                                 execution.setVariable("isGetSuccessfull", "true")
156                                 String modelInvariantUuid = execution.getVariable("modelInvariantUuid")
157                                 String modelUuid = execution.getVariable("modelUuid")
158                                 //here modelVersion is not set, we use modelUuid to decompose the service.
159                                 String serviceModelInfo = """{
160             "modelInvariantUuid":"${modelInvariantUuid}",
161             "modelUuid":"${modelUuid}",
162             "modelVersion":""
163              }"""
164                                 execution.setVariable("serviceModelInfo", serviceModelInfo)
165                                 indexcurrent = index
166                                 execution.setVariable("activationIndex", indexcurrent)
167                                 break
168                         }else
169                         {
170                                 indexcurrent = index + 1
171
172                         }
173                 }
174                         if ( activationIndex > 2) {
175                                 execution.setVariable("isGetSuccessfull", "false")
176                         }
177                         execution.setVariable("activationIndex", indexcurrent)}
178
179         }
180
181         /**
182          * get vendor Info
183          * @param execution
184          */
185         private void processDecomposition(DelegateExecution execution) {
186                 logger.debug("***** processDecomposition *****")
187
188                 try {
189                         ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition") as ServiceDecomposition
190             ServiceArtifact serviceArtifact = serviceDecomposition.getServiceInfo().getServiceArtifact().get(0)
191                         String content = serviceArtifact.getContent()
192                         String vendor = jsonUtil.getJsonValue(content, "metadata.vendor")
193                         //String domainType  = jsonUtil.getJsonValue(content, "metadata.domainType")
194
195                         execution.setVariable("vendor", vendor)
196                 //      currentNSSI['domainType'] = domainType
197                         logger.info("processDecomposition, current vendor-domainType:" +  vendor)
198
199                 } catch (any) {
200                         String exceptionMessage = "Bpmn error encountered in deallocate nssi. processDecomposition() - " + any.getMessage()
201                         logger.debug(exceptionMessage)
202                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
203                 }
204                 logger.debug("***** Exit processDecomposition *****")
205         }
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.equalsIgnoreCase("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
273         public void WaitForReturn(DelegateExecution execution) {
274                 //logger.debug("Query : "+ Jobid)
275                 String miniute = execution.getVariable("miniute")
276                 Thread.sleep(10000)
277                 int miniute01  = Integer.parseInt(miniute) + 1
278                 logger.debug("waiting for : "+ miniute + "miniutes")
279                 execution.setVariable("miniute", String.valueOf(miniute01))
280         }
281
282         public void GetTheStatusOfActivation(DelegateExecution execution) {
283
284                 String domaintype = execution.getVariable("domainType")
285                 String NSIserviceid=execution.getVariable("NSIserviceid")
286                 String nssiId = execution.getVariable("nssiId")
287                 String Jobid=execution.getVariable("JobId")
288                 String miniute=execution.getVariable("miniute")
289                 String vendor = execution.getVariable("vendor")
290                 String jobstatus
291
292
293                 logger.debug("Query the jobid activation of SNSSAI: "+ Jobid)
294                 logger.debug("the domain is : "+ domaintype)
295                 logger.debug("the NSSID is : "+nssiId)
296                 logger.debug("the NSIserviceid is : "+NSIserviceid)
297
298         JobStatusRequest jobStatusRequest = new JobStatusRequest()
299
300         EsrInfo info = new EsrInfo()
301                 info.setNetworkType(NetworkType.fromString(domaintype))
302                 info.setVendor(vendor)
303
304                 jobStatusRequest.setNsiId(NSIserviceid)
305                 jobStatusRequest.setNssiId(nssiId)
306                 jobStatusRequest.setEsrInfo(info)
307
308
309                 ObjectMapper mapper = new ObjectMapper()
310                 String nssmfRequest = mapper.writeValueAsString(jobStatusRequest)
311                 String isActivateSuccessfull
312
313         String urlString = "/api/rest/provMns/v1/NSS/jobs/" +Jobid
314
315         JobStatusResponse jobStatusResponse = nssmfAdapterUtils.sendPostRequestNSSMF(execution, urlString, nssmfRequest, JobStatusResponse.class)
316
317         if (jobStatusResponse != null) {
318             execution.setVariable("statusDescription", jobStatusResponse.getResponseDescriptor().getStatusDescription())
319             jobstatus = jobStatusResponse.getResponseDescriptor().getStatus()
320             switch(jobstatus) {
321                 case "started":
322                 case "processing":
323                     isActivateSuccessfull = "waitting"
324                     execution.setVariable("isActivateSuccessfull", isActivateSuccessfull)
325                     break
326                 case "finished":
327                     isActivateSuccessfull = "true"
328                     execution.setVariable("isActivateSuccessfull", isActivateSuccessfull)
329                     execution.setVariable("activateNumberSlice",execution.getVariable("activateNumberSlice")+ 1)
330                     break
331                 case "error":
332                 default:
333                     isActivateSuccessfull = "false"
334                     execution.setVariable("isActivateSuccessfull", isActivateSuccessfull)
335
336             }
337             if(Integer.parseInt(miniute) > 6 )
338             {
339                 isActivateSuccessfull = "false"
340                 execution.setVariable("isActivateSuccessfull", isActivateSuccessfull)
341                 exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "Received a timeout job status Response from NSSMF.")
342             }
343         } else {
344             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "Received a Bad job status Response from NSSMF.")
345             isActivateSuccessfull = false
346             execution.setVariable("isActivateSuccessfull", isActivateSuccessfull)
347         }
348         }
349
350         public void SendCommandToNssmf(DelegateExecution execution) {
351
352                 String snssai= execution.getVariable("snssai")
353                 String domaintype = execution.getVariable("domainType")
354                 String NSIserviceid=execution.getVariable("NSIserviceid")
355                 String nssiId = execution.getVariable("nssiId")
356                 String vendor = execution.getVariable("vendor")
357
358
359                 logger.debug("the domain is : "+domaintype)
360                 logger.debug("SNSSAI: "+snssai +" will be activated")
361                 logger.debug("the NSSID is : "+nssiId)
362                 logger.debug("the NSIserviceid is : "+NSIserviceid)
363
364         EsrInfo esr = new EsrInfo();
365                 esr.setNetworkType(NetworkType.fromString(domaintype))
366                 esr.setVendor(vendor)
367
368         ActDeActNssi actNssi = new ActDeActNssi();
369                 actNssi.setNsiId(NSIserviceid);
370                 actNssi.setNssiId(nssiId);
371         NssiActDeActRequest actRequest = new NssiActDeActRequest();
372                 actRequest.setActDeActNssi(actNssi);
373                 actRequest.setEsrInfo(esr)
374
375                 ObjectMapper mapper = new ObjectMapper()
376                 String nssmfRequest = mapper.writeValueAsString(actRequest)
377
378                 String operationType = execution.getVariable("operationType")
379
380                 String urlString = "/api/rest/provMns/v1/NSS/" + snssai + "/" + operationType.toLowerCase()
381
382         NssiResponse nssmfResponse = nssmfAdapterUtils.sendPostRequestNSSMF(execution, urlString, nssmfRequest, NssiResponse.class)
383
384         if (nssmfResponse != null) {
385             String  isNSSIActivated = "true"
386             execution.setVariable("isNSSIActivated", isNSSIActivated)
387             String jobId  = nssmfResponse.getJobId() ?: ""
388             execution.setVariable("JobId", jobId)
389         } else {
390             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "Received a Bad Response from NSSMF.")
391             String  isNSSIActivated = "false"
392             execution.setVariable("isNSSIActivated", isNSSIActivated)
393             execution.setVariable("isNSSIActivate","false")
394         }
395
396         }
397
398         void sendSyncError (DelegateExecution execution) {
399                 logger.trace("start sendSyncError")
400                 try {
401                         String errorMessage = ""
402                         if (execution.getVariable("WorkflowException") instanceof WorkflowException) {
403                                 WorkflowException wfe = execution.getVariable("WorkflowException")
404                                 errorMessage = wfe.getErrorMessage()
405                         } else {
406                                 errorMessage = "Sending Sync Error."
407                         }
408
409                         String buildworkflowException =
410                                         """<aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1">
411                                         <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorMessage)}</aetgt:ErrorMessage>
412                                         <aetgt:ErrorCode>7000</aetgt:ErrorCode>
413                                    </aetgt:WorkflowException>"""
414
415                         logger.debug(buildworkflowException)
416                         sendWorkflowResponse(execution, 500, buildworkflowException)
417
418                 } catch (Exception ex) {
419                         logger.debug("Sending Sync Error Activity Failed. " + "\n" + ex.getMessage())
420                 }
421                 logger.trace("finished sendSyncError")
422         }
423 }