2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.onap.so.bpmn.infrastructure.scripts
23 import com.fasterxml.jackson.databind.ObjectMapper
25 import groovy.json.JsonOutput
27 import static org.hamcrest.CoreMatchers.instanceOf
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
64 import javax.ws.rs.NotFoundException
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()
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")
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 ****")
90 void createNSSIinAAI(DelegateExecution execution) {
91 logger.debug(Prefix+ " **** Enter DoAllocateCoreNonSharedSlice ::: Enter createNSSIinAAI ****")
93 String serviceInstanceId= execution.getVariable("nssiServiceInstanceId")
94 logger.debug("ServiceInstanceId: "+serviceInstanceId)
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")
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){
111 } catch (Exception ex){
112 msg = "Exception in createNSSIinAAI ::: DoAllocateCoreNonSharedSlice " + ex.getMessage()
114 exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
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")
133 execution.setVariable("nssiServiceInstance", si)
134 } catch (BpmnError e) {
136 } catch (Exception ex) {
137 msg = "Exception in create AAI Instance" + ex.getMessage()
139 exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
141 logger.debug(Prefix+ " Exit DoAllocateCoreNonSharedSlice ::: Enter createNSSIinAAI ****")
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()
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()
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)
174 Map<String, Object> service = new LinkedHashMap()
176 String serviceName= "nsi_"+execution.getVariable("networkServiceName")
177 service.put("name", serviceName)
179 service.put("serviceType", execution.getVariable("serviceType"))
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****")
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)
219 serviceCharacteristicsList.add(serviceCharacteristicsObject)
220 logger.debug(Prefix+ " **** Exit DoAllocateCoreNonSharedSlice ::: retrieveServiceCharacteristicsAsKeyValue ****")
221 return serviceCharacteristicsList
224 public void postNBIServiceOrder(DelegateExecution execution) {
225 logger.debug(Prefix+ " **** Enter DoAllocateCoreNonSharedSlice ::: postNBIServiceOrder ****")
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)
243 if(responseCode == 200 || responseCode == 201 || responseCode == 202 )
244 //200 OK 201 CREATED 202 ACCEPTED
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)
252 exceptionUtil.buildAndThrowWorkflowException(execution, responseCode, "Post ServiceOrder Received a bad response from extAPI serviceOrder API")
254 }catch (BpmnError e) {
256 } catch (Exception ex) {
257 msg = "Exception in ServiceOrder ExtAPI" + ex.getMessage()
259 exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
261 logger.debug("**** Exit DoAllocateCoreNonSharedSlice ::: postNBIServiceOrder ****")
264 public void getNBIServiceOrderProgress(DelegateExecution execution) {
265 logger.debug(Prefix+ " **** Enter DoAllocateCoreNonSharedSlice ::: getNBIServiceOrderProgress ****")
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 )
283 logger.debug("Get Create ServiceOrder Received a Good Response")
284 String orderState = responseObj.get("state")
285 if("REJECTED".equalsIgnoreCase(orderState)) {
286 prepareFailedOperationStatusUpdate(execution)
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)
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")
304 else if("INPROGRESS".equalsIgnoreCase(serviceOrderState)) {
305 execution.setVariable("status", "processing")
307 else if("COMPLETED".equalsIgnoreCase(serviceOrderState)) {
308 execution.setVariable("status", "completed")
310 else if("FAILED".equalsIgnoreCase(serviceOrderState)) {
311 msg = "ServiceOrder failed"
312 exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
315 msg = "ServiceOrder failed"
316 exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
320 msg = "Get ServiceOrder Received a Bad Response Code. Response Code is: " + responseCode
321 prepareFailedOperationStatusUpdate(execution)
325 exceptionUtil.buildAndThrowWorkflowException(execution, 7000, e.getMessage())
327 logger.debug(Prefix+ " **** Exit DoAllocateCoreNonSharedSlice ::: getNBIServiceOrderProgress ****")
333 public void timeDelay(DelegateExecution execution) {
335 logger.debug(Prefix+ " **** DoAllocateCoreNonSharedSlice ::: timeDelay going to sleep for 5 sec")
337 logger.debug("**** DoAllocateCoreNonSharedSlice ::: timeDelay wakeup after 5 sec")
338 } catch(InterruptedException e) {
339 logger.error(Prefix+ " **** DoAllocateCoreNonSharedSlice ::: timeDelay exception" + e)
344 void updateRelationship(DelegateExecution execution) {
345 logger.debug(Prefix+ " **** Enter DoAllocateCoreNonSharedSlice ::: updateRelationship ****")
347 String networkServiceInstanceId = execution.getVariable("networkServiceId")
348 String nssiId = execution.getVariable("nssiServiceInstanceId")
349 String globalCustId = execution.getVariable("globalSubscriberId")
350 String serviceType = execution.getVariable("serviceType")
352 //Update NSSI orchestration status nssiServiceInstance
353 ServiceInstance si = execution.getVariable("nssiServiceInstance")
354 si.setOrchestrationStatus("activated")
356 AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
357 globalCustId, serviceType, networkServiceInstanceId)
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)
367 AAIResourceUri nssiUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, nssiId);
369 //URI for Network Service Instance
370 AAIResourceUri networkServiceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, networkServiceInstanceId)
372 // Update Relationship in AAI
373 Response response = getAAIClient().connect(nssiUri, networkServiceInstanceUri, AAIEdgeLabel.COMPOSED_OF);
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")
378 execution.setVariable("progress", 100)
379 execution.setVariable("status", "finished")
380 execution.setVariable("statusDescription", "DoAllocateCoreNonSharedNSSI success")
381 setResourceOperationStatus(execution)
383 }catch(Exception ex) {
384 String msg = "Exception while creating relationship " + ex.getMessage()
386 exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
388 logger.debug(Prefix+ " **** Exit DoAllocateCoreNonSharedSlice ::: updateRelationship ****")
392 * prepare ResourceOperation status
394 * @param operationType
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 ****")
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")
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 ****")