2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 # Copyright (c) 2020, CMCC Technologies Co., Ltd.
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 static org.apache.commons.lang3.StringUtils.isBlank
24 import com.fasterxml.jackson.databind.ObjectMapper
25 import com.google.gson.Gson
26 import com.google.gson.reflect.TypeToken
27 import org.apache.commons.lang3.StringUtils
28 import org.camunda.bpm.engine.delegate.BpmnError
29 import org.camunda.bpm.engine.delegate.DelegateExecution
30 import org.onap.logging.filter.base.ErrorCode
31 import javax.ws.rs.NotFoundException
32 import org.onap.aai.domain.yang.Relationship
33 import org.onap.aai.domain.yang.ServiceInstance
34 import org.onap.aaiclient.client.aai.AAIResourcesClient
35 import org.onap.aaiclient.client.aai.entities.AAIResultWrapper
36 import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
37 import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
38 import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder
39 import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder.Types
40 import org.onap.so.beans.nsmf.*
41 import org.onap.so.beans.nsmf.oof.SubnetType
42 import org.onap.so.bpmn.common.scripts.*
43 import org.onap.so.bpmn.core.UrnPropertiesReader
44 import org.onap.so.bpmn.core.WorkflowException
45 import org.onap.so.bpmn.core.domain.ServiceArtifact
46 import org.onap.so.bpmn.core.domain.ServiceDecomposition
47 import org.onap.so.bpmn.core.json.JsonUtils
48 import org.onap.so.logger.LoggingAnchor
49 import org.onap.so.logger.MessageEnum
50 import org.slf4j.Logger
51 import org.slf4j.LoggerFactory
52 import org.springframework.web.util.UriUtils
54 import java.lang.reflect.Type
57 * This class supports the DoCreateVnf building block subflow
58 * with the creation of a generic vnf for
62 class DoActivateSliceService extends AbstractServiceTaskProcessor {
64 private static final Logger logger = LoggerFactory.getLogger(DoActivateSliceService.class)
66 private static final NSSMF_ACTIVATION_URL = "/api/rest/provMns/v1/NSS/%s/activation"
68 private static final NSSMF_DEACTIVATION_URL = "/api/rest/provMns/v1/NSS/%s/deactivation"
70 private static final NSSMF_QUERY_JOB_STATUS_URL = "/api/rest/provMns/v1/NSS/jobs/%s"
72 String Prefix="DoCNSSMF_"
73 ExceptionUtil exceptionUtil = new ExceptionUtil()
75 JsonUtils jsonUtil = new JsonUtils()
77 ObjectMapper objectMapper = new ObjectMapper()
79 SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils()
81 private NssmfAdapterUtils nssmfAdapterUtils = new NssmfAdapterUtils(httpClientFactory, jsonUtil)
84 * This method gets and validates the incoming
90 public void preProcessRequest(DelegateExecution execution) {
92 execution.setVariable("prefix",Prefix)
93 logger.debug("STARTED Do sendcommandtoNssmf PreProcessRequest Process")
97 Queue<NssInstance> nssInstances = execution.getVariable("nssInstances") as Queue<NssInstance>
98 NssInstance nssInstance = nssInstances.poll()
99 execution.setVariable("nssInstances", nssInstances)
100 execution.setVariable("nssInstance", nssInstance)
102 logger.info("the end !!")
104 logger.debug("Rethrowing MSOWorkflowException")
107 logger.info("the end of catch !!")
108 logger.debug(" Error Occured in DoSendCommandToNSSMF PreProcessRequest method!" + e.getMessage())
109 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DoSendCommandToNSSMF PreProcessRequest")
112 logger.trace("COMPLETED DoSendCommandToNSSMF PreProcessRequest Process")
115 void prepareCompose(DelegateExecution execution) {
116 NssInstance nssInstance = execution.getVariable("nssInstance") as NssInstance
117 execution.setVariable("nssInstanceId", nssInstance.nssiId)
118 String serviceModelInfo = """{
119 "modelInvariantUuid":"${nssInstance.modelInvariantId}",
120 "modelUuid":"${nssInstance.modelVersionId}",
123 execution.setVariable("serviceModelInfo", serviceModelInfo)
130 void processDecomposition(DelegateExecution execution) {
131 logger.debug("***** processDecomposition *****")
134 ServiceDecomposition serviceDecomposition =
135 execution.getVariable("serviceDecomposition") as ServiceDecomposition
137 String vendor = serviceDecomposition.getServiceRole()
138 CustomerInfo customerInfo = execution.getVariable("customerInfo") as CustomerInfo
139 NssInstance nssInstance = execution.getVariable("nssInstance") as NssInstance
142 if (OperationType.ACTIVATE == nssInstance.operationType) {
143 reqUrl = String.format(NSSMF_ACTIVATION_URL, nssInstance.snssai)
144 actionType = "activate"
146 reqUrl = String.format(NSSMF_DEACTIVATION_URL, nssInstance.snssai)
147 actionType = "deactivate"
149 execution.setVariable("reqUrl", reqUrl)
151 NssmfAdapterNBIRequest nbiRequest = new NssmfAdapterNBIRequest()
153 EsrInfo esrInfo = new EsrInfo()
154 esrInfo.setVendor(vendor)
155 esrInfo.setNetworkType(nssInstance.networkType)
157 ServiceInfo serviceInfo = ServiceInfo.builder()
158 .nssiId(nssInstance.nssiId)
159 .subscriptionServiceType(customerInfo.subscriptionServiceType)
160 .globalSubscriberId(customerInfo.globalSubscriberId)
161 .nsiId(customerInfo.nsiId)
162 .serviceInvariantUuid(nssInstance.modelInvariantId)
163 .serviceUuid(nssInstance.modelVersionId)
164 .serviceType(nssInstance.serviceType)
165 .actionType(actionType)
168 ActDeActNssi actDeActNssi = new ActDeActNssi()
169 actDeActNssi.setNsiId(customerInfo.nsiId)
170 actDeActNssi.setNssiId(nssInstance.nssiId)
171 actDeActNssi.setSnssaiList(Arrays.asList(customerInfo.snssai))
173 String sliceProfileId = getRelatedSliceProfileId(execution, customerInfo.globalSubscriberId, customerInfo.subscriptionServiceType, nssInstance.nssiId, customerInfo.snssai, "slice-profile")
174 actDeActNssi.setSliceProfileId(sliceProfileId)
176 nbiRequest.setEsrInfo(esrInfo)
177 nbiRequest.setServiceInfo(serviceInfo)
178 nbiRequest.setActDeActNssi(actDeActNssi)
179 execution.setVariable("nbiRequest", nbiRequest)
180 execution.setVariable("esrInfo", esrInfo)
181 execution.setVariable("serviceInfo", serviceInfo)
184 String exceptionMessage = "Bpmn error encountered in deallocate nssi. processDecomposition() - " + any.getMessage()
185 logger.debug(exceptionMessage)
186 exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
188 logger.debug("***** Exit processDecomposition *****")
191 private String getRelatedSliceProfileId(DelegateExecution execution, String globalSubscriberId, String subscriptionServiceType, String instanceId, String snssai, String role) {
192 logger.debug("${Prefix} - Get Related Slice Profile")
193 if( isBlank(role) || isBlank(instanceId)) {
194 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Role and instanceId are mandatory")
198 AAIResourcesClient client = getAAIClient()
199 AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(globalSubscriberId).serviceSubscription(subscriptionServiceType).serviceInstance(instanceId))
200 if (!client.exists(uri)) {
201 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Service Instance was not found in aai : ${instanceId}")
203 AAIResultWrapper wrapper = client.get(uri, NotFoundException.class)
204 Optional<ServiceInstance> si = wrapper.asBean(ServiceInstance.class)
206 List<Relationship> relationshipList = si.get().getRelationshipList().getRelationship()
207 for (Relationship relationship : relationshipList) {
208 String relatedTo = relationship.getRelatedTo()
209 if (relatedTo.toLowerCase() == "service-instance") {
210 String relatioshipurl = relationship.getRelatedLink()
211 String serviceInstanceId =
212 relatioshipurl.substring(relatioshipurl.lastIndexOf("/") + 1, relatioshipurl.length())
213 uri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(globalSubscriberId).serviceSubscription(subscriptionServiceType).serviceInstance(serviceInstanceId))
214 if (!client.exists(uri)) {
215 exceptionUtil.buildAndThrowWorkflowException(execution, 2500,
216 "Service Instance was not found in aai: ${serviceInstanceId} related to ${instanceId}")
218 AAIResultWrapper wrapper01 = client.get(uri, NotFoundException.class)
219 Optional<ServiceInstance> serviceInstance = wrapper01.asBean(ServiceInstance.class)
220 if (serviceInstance.isPresent()) {
221 ServiceInstance instance = serviceInstance.get()
222 if (role.equalsIgnoreCase(instance.getServiceRole()) && snssai.equalsIgnoreCase(instance.getEnvironmentContext())) {
223 nssiId = instance.getServiceInstanceId()
230 logger.debug("${Prefix} - Exit Get Related Slice Profile instances")
234 * send Create Request NSSMF
237 void sendCreateRequestNSSMF(DelegateExecution execution) {
238 NssmfAdapterNBIRequest nbiRequest = execution.getVariable("nbiRequest") as NssmfAdapterNBIRequest
239 String nssmfRequest = objectMapper.writeValueAsString(nbiRequest)
240 logger.debug("sendCreateRequestNSSMF: " + nssmfRequest)
242 String reqUrl = execution.getVariable("reqUrl")
243 String response = nssmfAdapterUtils.sendPostRequestNSSMF(execution, reqUrl, nssmfRequest)
245 if (response != null) {
246 NssiResponse nssiResponse = objectMapper.readValue(response, NssiResponse.class)
247 execution.setVariable("nssiAllocateResult", nssiResponse)
253 * query nssi allocate status
256 void queryNSSIStatus(DelegateExecution execution) {
257 NssmfAdapterNBIRequest nbiRequest = new NssmfAdapterNBIRequest()
258 EsrInfo esrInfo = execution.getVariable("esrInfo") as EsrInfo
259 ServiceInfo serviceInfo = execution.getVariable("serviceInfo") as ServiceInfo
260 nbiRequest.setEsrInfo(esrInfo)
261 nbiRequest.setServiceInfo(serviceInfo)
263 NssiResponse nssiAllocateResult = execution.getVariable("nssiAllocateResult") as NssiResponse
264 String jobId = nssiAllocateResult.getJobId()
266 String endpoint = String.format(NSSMF_QUERY_JOB_STATUS_URL, jobId)
269 nssmfAdapterUtils.sendPostRequestNSSMF(execution, endpoint, objectMapper.writeValueAsString(nbiRequest))
271 logger.debug("nssmf response nssiAllocateStatus:" + response)
273 if (response != null) {
274 JobStatusResponse jobStatusResponse = objectMapper.readValue(response, JobStatusResponse.class)
276 execution.setVariable("nssiAllocateStatus", jobStatusResponse)
277 if (jobStatusResponse.getResponseDescriptor().getProgress() == 100) {
278 execution.setVariable("jobFinished", true)
283 void timeDelay(DelegateExecution execution) {
284 logger.trace("Enter timeDelay in DoAllocateNSSI()")
288 int currentCycle = execution.hasVariable("currentCycle") ?
289 execution.getVariable("currentCycle") as Integer : 1
291 currentCycle = currentCycle + 1
292 if(currentCycle > 60)
294 logger.trace("Completed all the retry times... but still nssmf havent completed the creation process...")
295 exceptionUtil.buildAndThrowWorkflowException(execution, 500, "NSSMF creation didnt complete by time...")
297 execution.setVariable("currentCycle", currentCycle)
298 } catch(InterruptedException e) {
299 logger.info("Time Delay exception" + e)
301 logger.trace("Exit timeDelay in DoAllocateNSSI()")
304 void sendSyncError (DelegateExecution execution) {
305 logger.trace("start sendSyncError")
307 String errorMessage = ""
308 if (execution.getVariable("WorkflowException") instanceof WorkflowException) {
309 WorkflowException wfe = execution.getVariable("WorkflowException")
310 errorMessage = wfe.getErrorMessage()
312 errorMessage = "Sending Sync Error."
315 String buildworkflowException =
316 """<aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1">
317 <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorMessage)}</aetgt:ErrorMessage>
318 <aetgt:ErrorCode>7000</aetgt:ErrorCode>
319 </aetgt:WorkflowException>"""
321 logger.debug(buildworkflowException)
322 sendWorkflowResponse(execution, 500, buildworkflowException)
324 } catch (Exception ex) {
325 logger.debug("Sending Sync Error Activity Failed. " + "\n" + ex.getMessage())
327 logger.trace("finished sendSyncError")