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