Merge "Sonar fixes"
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / DoAllocateCoreNonSharedSlice.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2020  Tech Mahindra
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
25 import groovy.json.JsonOutput
26
27 import static org.hamcrest.CoreMatchers.instanceOf
28
29 import javax.json.JsonArray
30 import javax.ws.rs.core.Response
31 import org.apache.commons.collections.map.HashedMap
32 import org.apache.commons.lang.StringEscapeUtils
33 import org.camunda.bpm.engine.delegate.BpmnError
34 import org.camunda.bpm.engine.delegate.DelegateExecution
35 import org.json.JSONArray
36 import org.json.JSONObject
37 import org.onap.aaiclient.client.aai.AAIResourcesClient
38 import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
39 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
40 import org.onap.so.bpmn.common.scripts.CatalogDbUtils
41 import org.onap.so.bpmn.common.scripts.CatalogDbUtilsFactory
42 import org.onap.so.bpmn.common.scripts.ExceptionUtil
43 import org.onap.so.bpmn.common.scripts.ExternalAPIUtil
44 import org.onap.so.bpmn.common.scripts.ExternalAPIUtilFactory
45 import org.onap.so.bpmn.common.scripts.RequestDBUtil
46 import org.onap.so.db.request.beans.OperationStatus
47 import org.onap.so.db.request.beans.ResourceOperationStatus
48 import org.onap.so.client.HttpClient
49 import org.onap.so.client.HttpClientFactory
50 import org.onap.logging.filter.base.ONAPComponents
51 import org.onap.so.bpmn.core.UrnPropertiesReader
52 import org.onap.aai.domain.yang.v19.ServiceInstance
53 import org.onap.aaiclient.client.aai.AAIObjectType
54 import org.onap.aaiclient.client.aai.entities.AAIResultWrapper
55 import org.onap.aaiclient.client.aai.entities.AAIEdgeLabel
56 import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
57 import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder
58 import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder.Types
59 import org.onap.so.bpmn.core.domain.ServiceDecomposition
60 import org.onap.so.bpmn.core.domain.ServiceProxy
61 import org.onap.so.bpmn.core.json.JsonUtils
62 import org.slf4j.Logger
63 import org.slf4j.LoggerFactory
64 import org.springframework.http.HttpEntity
65
66 import javax.ws.rs.NotFoundException
67
68 class DoAllocateCoreNonSharedSlice extends AbstractServiceTaskProcessor {
69     String Prefix="DACNSNSSI_"
70     private static final Logger logger = LoggerFactory.getLogger( DoAllocateCoreNonSharedSlice.class);
71     private CatalogDbUtils catalogDbUtils = new CatalogDbUtilsFactory().create()
72     private RequestDBUtil requestDBUtil = new RequestDBUtil()
73     private ExceptionUtil exceptionUtil = new ExceptionUtil()
74     private JsonUtils jsonUtil = new JsonUtils()
75
76     @Override
77     public void preProcessRequest(DelegateExecution execution) {
78         logger.debug(Prefix+ "**** Enter DoAllocateCoreNonSharedSlice:::  preProcessRequest ****")
79         String nssiServiceInstanceId= execution.getVariable("serviceInstanceId")
80         execution.setVariable("nssiServiceInstanceId", nssiServiceInstanceId)
81         //Set orchestration-status as created
82         execution.setVariable("orchestrationStatus", "created")
83         //networkServiceName
84         String networkServiceName = jsonUtil.getJsonValue(execution.getVariable("networkServiceModelInfo"), "modelName") ?: ""
85         execution.setVariable("networkServiceName", networkServiceName.replaceAll(" Service Proxy", ""))
86         //networkServiceModelUuid
87         String networkServiceModelUuid = jsonUtil.getJsonValue(execution.getVariable("networkServiceModelInfo"), "modelUuid") ?: ""
88         execution.setVariable("networkServiceModelUuid", networkServiceModelUuid)
89         logger.debug(Prefix+ " **** Exit DoAllocateCoreNonSharedSlice:::  preProcessRequest ****")
90     }
91
92     void createNSSIinAAI(DelegateExecution execution) {
93         logger.debug(Prefix+ " ****  Enter DoAllocateCoreNonSharedSlice ::: Enter createNSSIinAAI ****")
94         String msg=""
95         String serviceInstanceId= execution.getVariable("nssiServiceInstanceId")
96         logger.debug("ServiceInstanceId: "+serviceInstanceId)
97         try {
98             String serviceType = execution.getVariable("subscriptionServiceType")
99             String oStatus = execution.getVariable("orchestrationStatus")
100             //Get workload context and environment context from DB
101             String environmentContext = ""
102             String workloadContext =""
103             String modelInvariantUuid = execution.getVariable("modelInvariantUuid")
104             try{
105                 String json = catalogDbUtils.getServiceResourcesByServiceModelInvariantUuidString(execution,modelInvariantUuid )
106                 logger.debug("JSON Response from DB: "+json)
107                 environmentContext = jsonUtil.getJsonValue(json, "serviceResources.environmentContext") ?: ""
108                 workloadContext = jsonUtil.getJsonValue(json, "serviceResources.workloadContext") ?: ""
109                 logger.debug("Env Context is: "+ environmentContext)
110                 logger.debug("Workload Context is: "+ workloadContext)
111             } catch(BpmnError e){
112                 throw e
113             } catch (Exception ex){
114                 msg = "Exception in createNSSIinAAI ::: DoAllocateCoreNonSharedSlice  " + ex.getMessage()
115                 logger.debug(msg)
116                 exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
117             }
118             String serviceInstanceName = "nssi_"+execution.getVariable("nsstName")
119             ServiceInstance si = new ServiceInstance()
120             si.setServiceInstanceId(execution.getVariable("nssiServiceInstanceId"))
121             si.setServiceInstanceName(serviceInstanceName)
122             si.setServiceType(serviceType)
123             si.setServiceRole("nssi")
124             si.setOrchestrationStatus(oStatus)
125             si.setModelInvariantId(modelInvariantUuid)
126             si.setModelVersionId(execution.getVariable("modelUuid"))
127             si.setEnvironmentContext(environmentContext)
128             si.setWorkloadContext(workloadContext)
129             logger.debug("AAI service Instance Request Payload : "+si.toString())
130             AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(execution.getVariable("globalSubscriberId")).serviceSubscription(serviceType).serviceInstance(serviceInstanceId))
131             Response response = getAAIClient().create(uri, si)
132             if(response.getStatus()!=200) {
133                 exceptionUtil.buildAndThrowWorkflowException(execution, response.getStatus(), "AAI instance creation failed")
134             }
135             execution.setVariable("nssiServiceInstance", si)
136         } catch (BpmnError e) {
137             throw e;
138         } catch (Exception ex) {
139             msg = "Exception in create AAI Instance" + ex.getMessage()
140             logger.debug(msg)
141             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
142         }
143         logger.debug(Prefix+ " Exit DoAllocateCoreNonSharedSlice ::: Enter createNSSIinAAI ****")
144     }
145
146     public void prepareServiceOrderRequest(DelegateExecution execution) {
147         logger.debug("**** Enter DoAllocateCoreNonSharedSlice :::  prepareServiceOrderRequest ****")
148         String extAPIPath = UrnPropertiesReader.getVariable("extapi.endpoint", execution) + '/serviceOrder'
149         execution.setVariable("ExternalAPIURL", extAPIPath)
150         ObjectMapper objectMapper = new ObjectMapper();
151         Map<String, Object> serviceOrder = new LinkedHashMap()
152         //ExternalId
153         serviceOrder.put("externalId", "ONAP001")
154         //Requested Start Date
155         String requestedStartDate = utils.generateCurrentTimeInUtc()
156         String requestedCompletionDate = utils.generateCurrentTimeInUtc()
157         serviceOrder.put("requestedStartDate", requestedStartDate)
158         serviceOrder.put("requestedCompletionDate", requestedCompletionDate)
159         //RelatedParty Fields
160         String relatedPartyId = execution.getVariable("globalSubscriberId")
161         String relatedPartyRole = "ONAPcustomer"
162         Map<String, String> relatedParty = new LinkedHashMap()
163         relatedParty.put("id", relatedPartyId)
164         relatedParty.put("role", relatedPartyRole)
165         List<Map<String, String>> relatedPartyList = new ArrayList()
166         relatedPartyList.add(relatedParty)
167         serviceOrder.put("relatedParty", relatedPartyList)
168         Map<String, Object> orderItem = new LinkedHashMap()
169         //orderItem id
170         String orderItemId = "1"
171         orderItem.put("id", orderItemId)
172         //order item action will always be add as we are triggering request for instantiation
173         String orderItemAction = "add"
174         orderItem.put("action", orderItemAction)
175         // service Details
176         Map<String, Object> service = new LinkedHashMap()
177         //ServiceName
178         String serviceName= "nsi_"+execution.getVariable("networkServiceName")
179         service.put("name",  serviceName)
180         // Service Type
181         service.put("serviceType", execution.getVariable("serviceType"))
182         //Service State
183         service.put("serviceState", "active")
184         Map<String, String> serviceSpecification = new LinkedHashMap()
185         serviceSpecification.put("id", execution.getVariable("networkServiceModelUuid"))
186         service.put("serviceSpecification", serviceSpecification)
187         //serviceCharacteristic List
188         List serviceCharacteristicList = new ArrayList()
189         Map<String, Object> serviceCharacteristic = objectMapper.readValue(execution.getVariable("sliceProfile"), Map.class);
190         List serviceCharacteristicListMap = retrieveServiceCharacteristicsAsKeyValue(serviceCharacteristic)
191         logger.debug("serviceCharacteristicListMap  "+serviceCharacteristicListMap)
192         serviceCharacteristicList.add(serviceCharacteristic)
193         //service.put("serviceCharacteristic", serviceCharacteristicList)
194         service.put("serviceCharacteristic", serviceCharacteristicListMap)
195         orderItem.put("service", service)
196         List<Map<String, String>> orderItemList = new ArrayList()
197         orderItemList.add(orderItem)
198         serviceOrder.put("orderItem", orderItemList)
199         String jsonServiceOrder = objectMapper.writeValueAsString(serviceOrder);
200         logger.debug("******* ServiceOrder :: "+jsonServiceOrder)
201         execution.setVariable("serviceOrderRequest", jsonServiceOrder)
202         logger.debug(Prefix+ " **** Exit DoAllocateCoreNonSharedSlice ::: prepareServiceOrderRequest****")
203     }
204
205     private List retrieveServiceCharacteristicsAsKeyValue(Map serviceCharacteristics) {
206         logger.debug(Prefix+ " **** Enter DoAllocateCoreNonSharedSlice ::: retrieveServiceCharacteristicsAsKeyValue ****")
207         List serviceCharacteristicsList = new ArrayList()
208         ObjectMapper mapperObj = new ObjectMapper();
209         Map<String, Object> serviceCharacteristicsObject = new LinkedHashMap()
210         for (Map.Entry<String, Integer> entry : serviceCharacteristics.entrySet()) {
211             Map<String, Object> ServiceCharacteristicValueObject = new LinkedHashMap<>()
212             System.out.println(entry.getKey() + ":" + entry.getValue());
213             //For G Release we are sending single value from  snssaiList
214             if(entry.getKey().equals("snssaiList")) {
215                 List sNssaiValue = entry.getValue()
216                 serviceCharacteristicsObject.put("name", "snssai")
217                 ServiceCharacteristicValueObject.put("serviceCharacteristicValue", sNssaiValue.get(0))
218                 serviceCharacteristicsObject.put("value", ServiceCharacteristicValueObject)
219             }
220         }
221         serviceCharacteristicsList.add(serviceCharacteristicsObject)
222         logger.debug(Prefix+ " **** Exit DoAllocateCoreNonSharedSlice ::: retrieveServiceCharacteristicsAsKeyValue ****")
223         return serviceCharacteristicsList
224     }
225
226     public void postNBIServiceOrder(DelegateExecution execution) {
227         logger.debug(Prefix+ " **** Enter DoAllocateCoreNonSharedSlice ::: postNBIServiceOrder ****")
228         String msg=""
229         try {
230             String extAPIPath = execution.getVariable("ExternalAPIURL")
231             String payload = execution.getVariable("serviceOrderRequest")
232             logger.debug("externalAPIURL is: " + extAPIPath)
233             logger.debug("ServiceOrder payload is: " + payload)
234             ExternalAPIUtil externalAPIUtil = new ExternalAPIUtilFactory().create()
235             execution.setVariable("ServiceOrderId", "")
236             Response response = externalAPIUtil.executeExternalAPIPostCall(execution, extAPIPath, payload)
237             int responseCode = response.getStatus()
238             execution.setVariable("PostServiceOrderResponseCode", responseCode)
239             logger.debug("Post ServiceOrder response code is: " + responseCode)
240             String extApiResponse = response.readEntity(String.class)
241             JSONObject responseObj = new JSONObject(extApiResponse)
242             execution.setVariable("PostServiceOrderResponse", extApiResponse)
243             logger.debug("ServiceOrder response body is: " + extApiResponse)
244             //Process Response
245             if(responseCode == 200 || responseCode == 201 || responseCode == 202 )
246                 //200 OK 201 CREATED 202 ACCEPTED
247             {
248                 logger.debug("Post ServiceOrder Received a Good Response")
249                 String serviceOrderId = responseObj.get("id")
250                 execution.setVariable("ServiceOrderId", serviceOrderId)
251                 logger.info("Post ServiceOrderid is: " + serviceOrderId)
252             }
253             else{
254                 exceptionUtil.buildAndThrowWorkflowException(execution, responseCode, "Post ServiceOrder Received a bad response from extAPI serviceOrder API")
255             }
256         }catch (BpmnError e) {
257             throw e;
258         } catch (Exception ex) {
259             msg = "Exception in ServiceOrder ExtAPI" + ex.getMessage()
260             logger.debug(msg)
261             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
262         }
263         logger.debug("**** Exit DoAllocateCoreNonSharedSlice ::: postNBIServiceOrder ****")
264     }
265
266     public void getNBIServiceOrderProgress(DelegateExecution execution) {
267         logger.debug(Prefix+ " **** Enter DoAllocateCoreNonSharedSlice ::: getNBIServiceOrderProgress ****")
268         String msg=""
269         try {
270             String extAPIPath = execution.getVariable("ExternalAPIURL")
271             extAPIPath += "/" + execution.getVariable("ServiceOrderId")
272             logger.debug("getNBIServiceOrderProgress externalAPIURL is: " + extAPIPath)
273             ExternalAPIUtil externalAPIUtil = new ExternalAPIUtilFactory().create()
274             Response response = externalAPIUtil.executeExternalAPIGetCall(execution, extAPIPath)
275             int responseCode = response.getStatus()
276             execution.setVariable("GetServiceOrderResponseCode", responseCode)
277             logger.debug("Get ServiceOrder response code is: " + responseCode)
278             String extApiResponse = response.readEntity(String.class)
279             JSONObject responseObj = new JSONObject(extApiResponse)
280             execution.setVariable("GetServiceOrderResponse", extApiResponse)
281             logger.debug("Create response body is: " + extApiResponse)
282             //Process Response //200 OK 201 CREATED 202 ACCEPTED
283             if(responseCode == 200 || responseCode == 201 || responseCode == 202 )
284             {
285                 logger.debug("Get Create ServiceOrder Received a Good Response")
286                 String orderState = responseObj.get("state")
287                 if("REJECTED".equalsIgnoreCase(orderState)) {
288                     prepareFailedOperationStatusUpdate(execution)
289                     return
290                 }
291                 JSONArray items = responseObj.getJSONArray("orderItem")
292                 JSONObject item = items.get(0)
293                 JSONObject service = item.get("service")
294                 String networkServiceId = service.get("id")
295                 if (networkServiceId == null || networkServiceId.equals("null")) {
296                     prepareFailedOperationStatusUpdate(execution)
297                     return
298                 }
299                 execution.setVariable("networkServiceId", networkServiceId)
300                 String serviceOrderState = item.get("state")
301                 execution.setVariable("ServiceOrderState", serviceOrderState)
302                 // Get serviceOrder State and process progress
303                 if("ACKNOWLEDGED".equalsIgnoreCase(serviceOrderState)) {
304                     execution.setVariable("status", "processing")
305                 }
306                 else if("INPROGRESS".equalsIgnoreCase(serviceOrderState)) {
307                     execution.setVariable("status", "processing")
308                 }
309                 else if("COMPLETED".equalsIgnoreCase(serviceOrderState)) {
310                     execution.setVariable("status", "completed")
311                 }
312                 else if("FAILED".equalsIgnoreCase(serviceOrderState)) {
313                     msg = "ServiceOrder failed"
314                     exceptionUtil.buildAndThrowWorkflowException(execution, 7000,  msg)
315                 }
316                 else {
317                     msg = "ServiceOrder failed"
318                     exceptionUtil.buildAndThrowWorkflowException(execution, 7000,  msg)
319                 }
320             }
321             else{
322                 msg = "Get ServiceOrder Received a Bad Response Code. Response Code is: " + responseCode
323                 prepareFailedOperationStatusUpdate(execution)
324             }
325
326         }catch(Exception e){
327             exceptionUtil.buildAndThrowWorkflowException(execution, 7000,  e.getMessage())
328         }
329         logger.debug(Prefix+ " **** Exit DoAllocateCoreNonSharedSlice ::: getNBIServiceOrderProgress ****")
330     }
331
332     /**
333      * delay 5 sec
334      */
335     public void timeDelay(DelegateExecution execution) {
336         try {
337             logger.debug(Prefix+ " **** DoAllocateCoreNonSharedSlice ::: timeDelay going to sleep for 5 sec")
338             Thread.sleep(5000)
339             logger.debug("**** DoAllocateCoreNonSharedSlice ::: timeDelay wakeup after 5 sec")
340         } catch(InterruptedException e) {
341             logger.error(Prefix+ " **** DoAllocateCoreNonSharedSlice ::: timeDelay exception" + e)
342         }
343     }
344
345
346     void updateRelationship(DelegateExecution execution) {
347         logger.debug(Prefix+ " **** Enter DoAllocateCoreNonSharedSlice ::: updateRelationship ****")
348
349         String networkServiceInstanceId = execution.getVariable("networkServiceId")
350         String nssiId = execution.getVariable("nssiServiceInstanceId")
351         String globalCustId = execution.getVariable("globalSubscriberId")
352         String serviceType = execution.getVariable("serviceType")
353         try{
354             //Update NSSI orchestration status nssiServiceInstance
355             ServiceInstance si = execution.getVariable("nssiServiceInstance")
356             si.setOrchestrationStatus("activated")
357
358             AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(globalCustId).serviceSubscription(serviceType).serviceInstance(networkServiceInstanceId))
359             try {
360                 getAAIClient().update(uri, si)
361             } catch (Exception e) {
362                 logger.info("Update OrchestrationStatus in AAI failed")
363                 String msg = "Update OrchestrationStatus in AAI failed, " + e.getMessage()
364                 exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
365             }
366
367             //URI for NSSI
368             AAIResourceUri nssiUri = AAIUriFactory.createResourceUri(Types.SERVICE_INSTANCE.getFragment(nssiId));
369
370             //URI for Network Service Instance
371             AAIResourceUri networkServiceInstanceUri = AAIUriFactory.createResourceUri(Types.SERVICE_INSTANCE.getFragment(networkServiceInstanceId))
372
373             // Update Relationship in AAI
374             Response response = getAAIClient().connect(nssiUri, networkServiceInstanceUri, AAIEdgeLabel.COMPOSED_OF);
375
376             if(response.getStatus()!=200 || response.getStatus()!=201 || response.getStatus()!=202) {
377                 exceptionUtil.buildAndThrowWorkflowException(execution, response.getStatus(), "Set association of NSSI and Network service instance has failed in AAI")
378             } else {
379                 execution.setVariable("progress", 100)
380                 execution.setVariable("status", "finished")
381                 execution.setVariable("statusDescription", "DoAllocateCoreNonSharedNSSI success")
382                 setResourceOperationStatus(execution)
383             }
384         }catch(Exception ex) {
385             String msg = "Exception while creating relationship " + ex.getMessage()
386             logger.info(msg)
387             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
388         }
389         logger.debug(Prefix+ " **** Exit DoAllocateCoreNonSharedSlice ::: updateRelationship ****")
390     }
391
392     /**
393      * prepare ResourceOperation status
394      * @param execution
395      * @param operationType
396      */
397     private void setResourceOperationStatus(DelegateExecution execution) {
398         logger.debug(Prefix+ " **** Enter DoAllocateCoreNonSharedSlice ::: setResourceOperationStatus ****")
399         String serviceId = execution.getVariable("nssiId")
400         String jobId = execution.getVariable("jobId")
401         String nsiId = execution.getVariable("nsiId")
402         String operationType = execution.getVariable("operationType")
403         ResourceOperationStatus resourceOperationStatus = new ResourceOperationStatus()
404         resourceOperationStatus.setServiceId(serviceId)
405         resourceOperationStatus.setOperationId(jobId)
406         resourceOperationStatus.setResourceTemplateUUID(nsiId)
407         resourceOperationStatus.setOperType(operationType)
408         resourceOperationStatus.setStatus(execution.getVariable("status"))
409         resourceOperationStatus.setProgress(execution.getVariable("progress"))
410         resourceOperationStatus.setStatusDescription(execution.getVariable("statusDescription"))
411         requestDBUtil.prepareUpdateResourceOperationStatus(execution, resourceOperationStatus)
412         logger.debug(Prefix+ " **** Exit DoAllocateCoreNonSharedSlice ::: setResourceOperationStatus ****")
413     }
414
415     void prepareFailedOperationStatusUpdate(DelegateExecution execution){
416         logger.debug(Prefix + " **** Enter DoAllocateCoreNonSharedSlice ::: prepareFailedOperationStatusUpdate ****")
417         String serviceId = execution.getVariable("nssiId")
418         String jobId = execution.getVariable("jobId")
419         String nsiId = execution.getVariable("nsiId")
420         String operationType = execution.getVariable("operationType")
421
422         ResourceOperationStatus resourceOperationStatus = new ResourceOperationStatus()
423         resourceOperationStatus.setServiceId(serviceId)
424         resourceOperationStatus.setOperationId(jobId)
425         resourceOperationStatus.setResourceTemplateUUID(nsiId)
426         resourceOperationStatus.setOperType(operationType)
427         resourceOperationStatus.setProgress(0)
428         resourceOperationStatus.setStatus("failed")
429         resourceOperationStatus.setStatusDescription("Core NSSI Allocate Failed")
430         requestDBUtil.prepareUpdateResourceOperationStatus(execution, resourceOperationStatus)
431         logger.debug(Prefix + " **** Exit DoAllocateCoreNonSharedSlice ::: prepareFailedOperationStatusUpdate ****")
432     }
433 }