Fix issues in AN NSSMF for allocate &modify flow
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / DoModifyAccessNSSI.groovy
1 /*
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  # Copyright (c) 2020, Wipro Limited.
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 org.camunda.bpm.engine.delegate.BpmnError
24 import org.camunda.bpm.engine.delegate.DelegateExecution
25 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
26 import org.onap.so.bpmn.common.scripts.ExceptionUtil
27 import org.onap.so.bpmn.common.scripts.NssmfAdapterUtils
28 import org.onap.so.bpmn.common.scripts.OofUtils
29 import org.onap.so.bpmn.common.scripts.RequestDBUtil
30 import org.onap.so.bpmn.core.json.JsonUtils
31 import org.onap.so.beans.nsmf.PerfReqEmbb
32 import org.onap.so.beans.nsmf.PerfReq
33 import org.onap.so.db.request.beans.ResourceOperationStatus
34 import org.slf4j.Logger
35 import org.slf4j.LoggerFactory
36 import java.sql.Timestamp
37 import java.util.List
38 import static org.apache.commons.lang3.StringUtils.isBlank
39 import com.google.gson.JsonObject
40 import com.fasterxml.jackson.databind.ObjectMapper
41 import com.google.gson.JsonArray
42 import org.onap.so.beans.nsmf.AllocateTnNssi
43 import org.onap.so.beans.nsmf.EsrInfo
44 import org.onap.so.bpmn.core.UrnPropertiesReader
45 import org.onap.so.bpmn.core.domain.ServiceDecomposition
46 import org.onap.so.bpmn.core.domain.ServiceProxy
47 import com.google.gson.JsonParser
48 import org.onap.aai.domain.yang.Relationship
49 import org.onap.aai.domain.yang.ServiceInstance
50 import org.onap.aai.domain.yang.SliceProfile
51 import org.onap.aai.domain.yang.SliceProfiles
52 import org.onap.aai.domain.yang.AllottedResource
53 import org.onap.aai.domain.yang.AllottedResources
54 import org.onap.aaiclient.client.graphinventory.entities.uri.Depth
55 import org.onap.aaiclient.client.aai.entities.uri.AAISimplePluralUri
56 import com.fasterxml.jackson.annotation.JsonInclude
57 import com.fasterxml.jackson.databind.SerializationFeature
58 import org.onap.aaiclient.client.aai.AAIObjectType
59 import org.onap.aaiclient.client.aai.AAIResourcesClient
60 import org.onap.aaiclient.client.aai.entities.AAIResultWrapper
61 import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
62 import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
63 import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder
64 import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder.Types
65 import javax.ws.rs.NotFoundException
66
67 class DoModifyAccessNSSI extends AbstractServiceTaskProcessor {
68
69         String Prefix="MASS_"
70         ExceptionUtil exceptionUtil = new ExceptionUtil()
71         RequestDBUtil requestDBUtil = new RequestDBUtil()
72         JsonUtils jsonUtil = new JsonUtils()
73         OofUtils oofUtils = new OofUtils()
74         ObjectMapper objectMapper = new ObjectMapper();
75         AnNssmfUtils anNssmfUtils = new AnNssmfUtils()
76         private NssmfAdapterUtils nssmfAdapterUtils = new NssmfAdapterUtils(httpClientFactory, jsonUtil)
77
78         private static final Logger logger = LoggerFactory.getLogger(DoModifyAccessNSSI.class)
79
80         @Override
81         void preProcessRequest(DelegateExecution execution) {
82                 logger.debug(Prefix + "preProcessRequest Start")
83                 execution.setVariable("prefix", Prefix)
84                 execution.setVariable("startTime", System.currentTimeMillis())
85                 def msg
86                 try {
87
88                         logger.debug("input variables : msoRequestId - "+execution.getVariable("msoRequestId")+
89                                         " globalSubscriberId - "+execution.getVariable("globalSubscriberId")+
90                                         " serviceInstanceID - "+execution.getVariable("serviceInstanceID")+
91                                         " nsiId - "+execution.getVariable("nsiId")+
92                                         " networkType - "+execution.getVariable("networkType")+
93                                         " subscriptionServiceType - "+execution.getVariable("subscriptionServiceType")+
94                                         " jobId - "+execution.getVariable("jobId")+
95                                         " sliceParams - "+execution.getVariable("sliceParams")+
96                                         " servicename - "+ execution.getVariable("servicename"))
97
98                         //validate slice subnet inputs
99
100                         String sliceParams = execution.getVariable("sliceParams")
101                         String modifyAction = jsonUtil.getJsonValue(sliceParams, "modifyAction")
102                         if (isBlank(modifyAction)) {
103                                 msg = "Input modifyAction is null"
104                                 logger.debug(msg)
105                                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
106                         } else {
107                                 execution.setVariable("modifyAction", modifyAction)
108                                 switch(modifyAction) {
109                                         case "allocate":
110                                                 execution.setVariable("isModifyallocate", true)
111                                                 break
112                                         case "deallocate":
113                                                 execution.setVariable("isModifydeallocate", true)
114                                                 break
115                                         case "reconfigure":
116                                                 execution.setVariable("isModifyreconfigure", true)
117                                                 String resourceConfig = jsonUtil.getJsonValue(sliceParams, "resourceConfig")
118                                                 execution.setVariable("additionalProperties", resourceConfig)
119                                                 break
120                                         default:
121                                                 logger.debug("Invalid modify Action")
122                                                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Invalid modify Action : "+modifyAction)
123                                 }
124                         }
125                         String modelUuid = execution.getVariable("modelUuid")
126                         if (isBlank(modelUuid)) {
127                                  modelUuid = anNssmfUtils.getModelUuid(execution, execution.getVariable("serviceInstanceID"))
128                         }
129                         execution.setVariable("modelUuid",modelUuid)
130                         List<String> snssaiList = jsonUtil.StringArrayToList(jsonUtil.getJsonValue(sliceParams, "snssaiList"))
131                         String sliceProfileId = jsonUtil.getJsonValue(sliceParams, "sliceProfileId")
132                         if (isBlank(sliceProfileId) || (snssaiList.empty)) {
133                                 msg = "Mandatory fields are empty"
134                                 logger.debug(msg)
135                                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
136                         } else {
137                                 execution.setVariable("sliceProfileId", sliceProfileId)
138                                 execution.setVariable("snssaiList", snssaiList)
139                         }
140                         String nsiName = jsonUtil.getJsonValue(sliceParams, "nsiInfo.nsiName")
141                         String scriptName = jsonUtil.getJsonValue(sliceParams, "scriptName")
142                         execution.setVariable("nsiName", nsiName)
143                         execution.setVariable("scriptName", scriptName)
144                         execution.setVariable("job_timeout", 10)
145                         execution.setVariable("ranNssiPreferReuse", false)
146                 } catch(BpmnError e) {
147                         throw e
148                 } catch(Exception ex) {
149                         msg = "Exception in DoModifyAccessNSSI.preProcessRequest " + ex.getMessage()
150                         logger.debug(msg)
151                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
152                 }
153                 logger.debug(Prefix + "preProcessRequest Exit")
154         }
155         
156         def getSliceProfile = { DelegateExecution execution ->
157                 logger.debug(Prefix + "getSliceProfiles Start")
158                 String instanceId = execution.getVariable("sliceProfileId")
159                 ServiceInstance sliceProfileInstance = getServiceInstance(execution, instanceId)
160                 String globalSubscriberId = execution.getVariable("globalSubscriberId")
161                 String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
162                 SliceProfile ranSliceProfile = new SliceProfile()
163                 AAIResourcesClient client = new AAIResourcesClient()
164                 AAISimplePluralUri uri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business()
165                  .customer(globalSubscriberId)
166                  .serviceSubscription(subscriptionServiceType)
167                  .serviceInstance(instanceId)
168                  .sliceProfiles())
169         
170         if (!client.exists(uri)) {
171                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Slice Profiles of service Instance was not found in aai : ${instanceId}")
172                 }
173
174                 AAIResultWrapper wrapper = client.get(uri, NotFoundException.class)
175                 Optional<SliceProfiles> si = wrapper.asBean(SliceProfiles.class)
176                 if(si.isPresent()) {
177                  ranSliceProfile = si.get().getSliceProfile().get(0)
178                 }
179                 objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
180                 objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL)
181                 logger.debug("RAN slice profile : "+objectMapper.writeValueAsString(ranSliceProfile))
182                 execution.setVariable("RANSliceProfile", objectMapper.writeValueAsString(ranSliceProfile))
183                 execution.setVariable("ranSliceProfileInstance", sliceProfileInstance)
184         }
185         
186         /*
187          * Function to subnet capabilities from nssmf adapter
188          */
189         def getSubnetCapabilities = { DelegateExecution execution ->
190                 logger.debug(Prefix+"getSubnetCapabilities method start")
191
192                 String tnNssmfRequest = anNssmfUtils.buildCreateTNNSSMFSubnetCapabilityRequest()
193
194                 String urlString = "/api/rest/provMns/v1/NSS/subnetCapabilityQuery"
195
196                 String tnNssmfResponse = nssmfAdapterUtils.sendPostRequestNSSMF(execution, urlString, tnNssmfRequest)
197
198                 if (tnNssmfResponse != null) {
199                         String FHCapabilities= jsonUtil.getJsonValue(tnNssmfResponse, "TN_FH")
200                         String MHCapabilities = jsonUtil.getJsonValue(tnNssmfResponse, "TN_MH")
201                         execution.setVariable("FHCapabilities",FHCapabilities)
202                         execution.setVariable("MHCapabilities",MHCapabilities)
203
204                 } else {
205                         logger.error("received error message from NSSMF : "+ tnNssmfResponse)
206                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"Received a Bad Sync Response from NSSMF.")
207                 }
208                 String anNssmfRequest = anNssmfUtils.buildCreateANNFNSSMFSubnetCapabilityRequest()
209
210                 String anNssmfResponse = nssmfAdapterUtils.sendPostRequestNSSMF(execution, urlString, anNssmfRequest)
211
212                 if (anNssmfResponse != null) {
213                         String ANNFCapabilities = jsonUtil.getJsonValue(anNssmfResponse, "AN_NF")
214                         execution.setVariable("ANNFCapabilities",ANNFCapabilities)
215
216                 } else {
217                         logger.error("received error message from NSSMF : "+ anNssmfResponse)
218                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"Received a Bad Sync Response from NSSMF.")
219                 }
220         }
221
222         
223         /*
224          * prepare OOF request for RAN NSSI selection
225          */
226         def prepareOofRequestForRanNSS = { DelegateExecution execution ->
227                 logger.debug(Prefix+"prepareOofRequestForRanNSS method start")
228
229                 String urlString = UrnPropertiesReader.getVariable("mso.oof.endpoint", execution)
230                 logger.debug( "get NSSI option OOF Url: " + urlString)
231                 JsonParser parser = new JsonParser()
232                 //build oof request body
233                 boolean ranNssiPreferReuse = execution.getVariable("ranNssiPreferReuse");
234                 String requestId = execution.getVariable("msoRequestId")
235                 String messageType = "NSISelectionResponse"
236                 Map<String, Object> profileInfo = objectMapper.readValue(execution.getVariable("RANSliceProfile"), Map.class)
237                 ServiceInstance ranSliceProfileInstance = execution.getVariable("ranSliceProfileInstance")
238                 profileInfo.put("sST",ranSliceProfileInstance.getServiceType())
239                 profileInfo.put("snssaiList",execution.getVariable("snssaiList"))
240                 profileInfo.put("plmnIdList",Arrays.asList(ranSliceProfileInstance.getServiceInstanceLocationId()))
241                 profileInfo.put("uEMobilityLevel",profileInfo.get("ueMobilityLevel"))
242                 profileInfo.put("cSAvailabilityTarget",profileInfo.get("csAvailabilityTarget"))
243                 profileInfo.put("maxNumberofPDUSession",profileInfo.get("maxNumberOfPDUSession"))
244                 profileInfo.put("maxNumberofUEs",profileInfo.get("maxNumberOfUEs"))
245
246                 PerfReq perfReq = new PerfReq();
247                 List<PerfReqEmbb> perfReqEmbbs = new ArrayList<>();
248                 PerfReqEmbb perfReqEmbb = new PerfReqEmbb();
249                 perfReqEmbb.setExpDataRateDL(profileInfo.get("expDataRateDL"));
250                 perfReqEmbb.setExpDataRateUL(profileInfo.get("expDataRateUL"));
251                 perfReqEmbbs.add(perfReqEmbb);
252                 perfReq.setPerfReqEmbbList(perfReqEmbbs);
253                 profileInfo.put("perfReq",perfReq)
254
255                 profileInfo.remove("maxNumberOfUEs")
256                 profileInfo.remove("resourceVersion")
257                 profileInfo.remove("csAvailabilityTarget")
258                 profileInfo.remove("ueMobilityLevel")
259                 profileInfo.remove("maxNumberOfPDUSession")
260                 profileInfo.remove("profileId")
261                 String modelUuid = ranSliceProfileInstance.getModelVersionId()
262                 String modelInvariantUuid = ranSliceProfileInstance.getModelInvariantId()
263                 String modelName = execution.getVariable("servicename")
264                 String timeout = UrnPropertiesReader.getVariable("mso.adapters.oof.timeout", execution);
265                 List<String> nsstInfoList =  new ArrayList<>()
266                 JsonArray capabilitiesList = new JsonArray()
267                 String FHCapabilities = execution.getVariable("FHCapabilities")
268                 String MHCapabilities = execution.getVariable("MHCapabilities")
269                 String ANNFCapabilities = execution.getVariable("ANNFCapabilities")
270                 JsonObject FH = new JsonObject()
271                 JsonObject MH = new JsonObject()
272                 JsonObject ANNF = new JsonObject()
273                 FH.addProperty("domainType", "TN_FH")
274                 FH.add("capabilityDetails", (JsonObject) parser.parse(FHCapabilities))
275                 MH.addProperty("domainType", "TN_MH")
276                 MH.add("capabilityDetails", (JsonObject) parser.parse(MHCapabilities))
277                 ANNF.addProperty("domainType", "AN_NF")
278                 ANNF.add("capabilityDetails", (JsonObject) parser.parse(ANNFCapabilities))
279                 capabilitiesList.add(FH)
280                 capabilitiesList.add(MH)
281                 capabilitiesList.add(ANNF)
282
283                 execution.setVariable("nssiSelection_Url", "/api/oof/selection/nsi/v1")
284                 execution.setVariable("nssiSelection_messageType",messageType)
285                 execution.setVariable("nssiSelection_correlator",requestId)
286                 execution.setVariable("nssiSelection_timeout",timeout)
287                 String oofRequest = anNssmfUtils.buildSelectRANNSSIRequest(requestId, messageType, modelUuid,modelInvariantUuid,
288                                 modelName, profileInfo, nsstInfoList, capabilitiesList, ranNssiPreferReuse)
289
290                 execution.setVariable("nssiSelection_oofRequest",oofRequest)
291                 logger.debug("Sending request to OOF: " + oofRequest)
292         }
293         
294         /*
295          * process OOF response for RAN NSSI selection
296          */
297         def processOofResponseForRanNSS = { DelegateExecution execution ->
298                 logger.debug(Prefix+"processOofResponseForRanNSS method start")
299                 String oofResponse = execution.getVariable("nssiSelection_asyncCallbackResponse")
300                 String requestStatus = jsonUtil.getJsonValue(oofResponse, "requestStatus")
301                 if(requestStatus.equals("completed")) {
302                         String solutions = jsonUtil.getJsonValue(oofResponse, "solutions")
303                         logger.debug("solutions value : "+solutions)
304                         JsonParser parser = new JsonParser()
305                         JsonArray solution = parser.parse(solutions)
306                         boolean existingNSI = solution.get(0).get("existingNSI").getAsBoolean()
307                         logger.debug("existingNSI value : "+existingNSI)
308                         if(!existingNSI) {
309                                 JsonObject newNSISolution =  solution.get(0).get("newNSISolution").getAsJsonObject()
310                                 JsonArray sliceProfiles =  newNSISolution.get("sliceProfiles")
311                                 logger.debug("sliceProfiles: "+ sliceProfiles.toString())
312                                 execution.setVariable("RanConstituentSliceProfiles", sliceProfiles.toString())
313                                 List<String> ranConstituentSliceProfiles = jsonUtil.StringArrayToList(sliceProfiles.toString())
314                                 anNssmfUtils.createDomainWiseSliceProfiles(ranConstituentSliceProfiles, execution)
315                                 logger.debug("RanConstituentSliceProfiles list from OOF "+sliceProfiles)
316                         }else {
317                                 String statusMessage = jsonUtil.getJsonValue(oofResponse, "statusMessage")
318                                 logger.error("failed to get slice profiles from oof "+ statusMessage)
319                                 exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"failed to get slice profiles from oof "+statusMessage)
320                         }
321                 }else {
322                         String statusMessage = jsonUtil.getJsonValue(oofResponse, "statusMessage")
323                         logger.error("received failed status from oof "+ statusMessage)
324                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"Received a failed Async Response from OOF : "+statusMessage)
325                 }
326
327         }
328         def getNssisFromAai = { DelegateExecution execution ->
329                 logger.debug(Prefix+"getNssisFromAai method start")
330                 String instanceId = execution.getVariable("serviceInstanceID")
331                 String role = "nssi"
332                 Map<String,ServiceInstance> ranConstituentNssis = getRelatedInstancesByRole(execution, role, instanceId)
333                 logger.debug("getNssisFromAai ranConstituentNssis : "+ranConstituentNssis.toString())
334                 ranConstituentNssis.each { key, val -> 
335                         switch(key) {
336                                 case "AN_NF":
337                                         execution.setVariable("ANNF_NSSI", val.getServiceInstanceId())
338                                         execution.setVariable("ANNF_nssiName", val.getServiceInstanceName())
339                                         execution.setVariable("ANNF_modelInvariantUuid", val.getModelInvariantId())
340                                         execution.setVariable("ANNF_modelUuid", val.getModelVersionId())
341                                         break
342                                 case "TN_FH":
343                                         execution.setVariable("TNFH_NSSI", val.getServiceInstanceId())
344                                         execution.setVariable("TNFH_nssiName", val.getServiceInstanceName())
345                                         execution.setVariable("TNFH_modelInvariantUuid", val.getModelInvariantId())
346                                         execution.setVariable("TNFH_modelUuid", val.getModelVersionId())
347                                         getConnectionLinks(execution, key, val)
348                                         break
349                                 case "TN_MH":
350                                         execution.setVariable("TNMH_NSSI", val.getServiceInstanceId())
351                                         execution.setVariable("TNMH_nssiName", val.getServiceInstanceName())
352                                         execution.setVariable("TNMH_modelInvariantUuid", val.getModelInvariantId())
353                                         execution.setVariable("TNMH_modelUuid", val.getModelVersionId())
354                                         getConnectionLinks(execution, key, val)
355                                         break
356                                 default:
357                                         logger.error("No expected match found for current domainType "+ key)
358                                         exceptionUtil.buildAndThrowWorkflowException(execution, 1000,"No expected match found for current domainType "+ key)
359                         }
360                 }
361                 
362         }
363
364         private void getConnectionLinks(DelegateExecution execution, String domainType, ServiceInstance instance) {
365                 AllottedResources allottedResources = instance.getAllottedResources()
366                                 if(allottedResources == null) {
367                                 String msg = "AllottedResourceFromAAI doesn't exist. " + instance
368                 logger.debug(msg)
369                 exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
370                                 }
371
372                 List<AllottedResource> AllottedResourceList = allottedResources.getAllottedResource()
373                 for(AllottedResource allottedResource : AllottedResourceList) {
374                 List<Relationship> relationshipList = allottedResource.getRelationshipList().getRelationship()
375                     for (Relationship relationship : relationshipList) {
376                         String relatedTo = relationship.getRelatedTo()
377                         if (relatedTo.toLowerCase() == "logical-link") {
378                                 String relatioshipurl = relationship.getRelatedLink()
379                                 String logicalLinkId=
380                                                 relatioshipurl.substring(relatioshipurl.lastIndexOf("/") + 1, relatioshipurl.length())
381                                 AAIResourcesClient client = new AAIResourcesClient()
382                                 AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.network().logicalLink(logicalLinkId))
383                                 if (!client.exists(uri)) {
384                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500,
385                                                         "Resource was not found in aai: ${logicalLinkId}")
386                                 }
387                                 AAIResultWrapper wrapper01 = client.get(uri, NotFoundException.class)
388                                 Optional<org.onap.aai.domain.yang.LogicalLink> resource = wrapper01.asBean(org.onap.aai.domain.yang.LogicalLink.class)
389                                 if (resource.isPresent()) {
390                                         org.onap.aai.domain.yang.LogicalLink logicalLinkInstance = resource.get()
391                                         if(domainType.equalsIgnoreCase("TN-FH"))
392                                         {
393                                         execution.setVariable("tranportEp_ID_RU",logicalLinkInstance.getLinkName())
394                                         execution.setVariable("tranportEp_ID_DUIN",logicalLinkInstance.getLinkName2())
395                                         }
396                                         else if(domainType.equalsIgnoreCase("TN-MH"))
397                                         {
398                                         execution.setVariable("tranportEp_ID_DUEG",logicalLinkInstance.getLinkName())
399                                         execution.setVariable("tranportEp_ID_CUIN",logicalLinkInstance.getLinkName2())
400                                         }
401                                 }
402                         }
403                     }
404                 }
405         }
406
407         def createSliceProfiles = { DelegateExecution execution ->
408                 logger.debug(Prefix+"createSliceProfiles method start")
409                 anNssmfUtils.createSliceProfilesInAai(execution)
410         }
411         def updateRelationshipInAai = { DelegateExecution execution ->
412                 logger.debug(Prefix+"updateRelationshipInAai method start")
413                 String msg = ""
414                 try {
415                         def ANNF_serviceInstanceId = execution.getVariable("ANNF_NSSI")
416                         def TNFH_serviceInstanceId = execution.getVariable("TNFH_NSSI")
417                         def TNMH_serviceInstanceId = execution.getVariable("TNMH_NSSI")
418                         def AN_profileInstanceId = execution.getVariable("sliceProfileId")
419                         def ANNF_profileInstanceId = execution.getVariable("ANNF_sliceProfileInstanceId")
420                         def TNFH_profileInstanceId = execution.getVariable("TNFH_sliceProfileInstanceId")
421                         def TNMH_profileInstanceId = execution.getVariable("TNMH_sliceProfileInstanceId")
422                         String globalSubscriberId = execution.getVariable("globalSubscriberId")
423                         String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
424
425                         Relationship ANNF_relationship = new Relationship()
426                         Relationship TNFH_relationship = new Relationship()
427                         Relationship TNMH_relationship = new Relationship()
428                         
429                         String ANNF_relatedLink = "aai/v16/business/customers/customer/${globalSubscriberId}/service-subscriptions/service-subscription/${subscriptionServiceType}/service-instances/service-instance/${ANNF_profileInstanceId}"
430                         String TNFH_relatedLink = "aai/v16/business/customers/customer/${globalSubscriberId}/service-subscriptions/service-subscription/${subscriptionServiceType}/service-instances/service-instance/${TNFH_profileInstanceId}"
431                         String TNMH_relatedLink = "aai/v16/business/customers/customer/${globalSubscriberId}/service-subscriptions/service-subscription/${subscriptionServiceType}/service-instances/service-instance/${TNMH_profileInstanceId}"
432                         
433                         ANNF_relationship.setRelatedLink(ANNF_relatedLink)
434                         ANNF_relationship.setRelatedTo("service-instance")
435                         ANNF_relationship.setRelationshipLabel("org.onap.relationships.inventory.ComposedOf")
436                         TNFH_relationship.setRelatedLink(TNFH_relatedLink)
437                         TNFH_relationship.setRelatedTo("service-instance")
438                         TNFH_relationship.setRelationshipLabel("org.onap.relationships.inventory.ComposedOf")
439                         TNMH_relationship.setRelatedLink(TNMH_relatedLink)
440                         TNMH_relationship.setRelatedTo("service-instance")
441                         TNMH_relationship.setRelationshipLabel("org.onap.relationships.inventory.ComposedOf")
442                         
443                         // create SliceProfile and NSSI relationship in AAI
444                         anNssmfUtils.createRelationShipInAAI(execution, ANNF_relationship,ANNF_serviceInstanceId)
445                         anNssmfUtils.createRelationShipInAAI(execution, TNFH_relationship,TNFH_serviceInstanceId)
446                         anNssmfUtils.createRelationShipInAAI(execution, TNMH_relationship,TNMH_serviceInstanceId)
447                         anNssmfUtils.createRelationShipInAAI(execution, ANNF_relationship,AN_profileInstanceId)
448                         anNssmfUtils.createRelationShipInAAI(execution, TNFH_relationship,AN_profileInstanceId)
449                         anNssmfUtils.createRelationShipInAAI(execution, TNMH_relationship,AN_profileInstanceId)
450
451                 } catch (BpmnError e) {
452                         throw e
453                 } catch (Exception ex) {
454
455                         msg = "Exception in DoCreateE2EServiceInstance.createCustomRelationship. " + ex.getMessage()
456                         logger.info(msg)
457                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
458                 }
459         }
460         
461         def processRanNfModifyRsp = { DelegateExecution execution ->
462                 logger.debug(Prefix+"processRanNfModifyRsp method start")
463                 anNssmfUtils.processRanNfModifyRsp(execution)
464         }
465         
466         def prepareTnFhRequest = { DelegateExecution execution ->
467                 logger.debug(Prefix+"prepareTnFhRequest method start")
468
469                 String nssmfRequest = anNssmfUtils.buildCreateNSSMFRequest(execution, "TN_FH", "modify-allocate")
470                 String urlString = "/api/rest/provMns/v1/NSS/SliceProfiles"
471                 String nssmfResponse = nssmfAdapterUtils.sendPostRequestNSSMF(execution, urlString, nssmfRequest)
472
473                 if (nssmfResponse != null) {
474                         execution.setVariable("nssmfResponse", nssmfResponse)
475                         String jobId = jsonUtil.getJsonValue(nssmfResponse, "jobId")
476                         execution.setVariable("TNFH_jobId",jobId)
477                 } else {
478                         logger.error("received error message from NSSMF : "+ nssmfResponse)
479                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"Received a Bad Sync Response from NSSMF.")
480                 }
481                 logger.debug("Exit prepareTnFhRequest")
482
483         }
484         def prepareTnMhRequest = { DelegateExecution execution ->
485                 logger.debug(Prefix+"prepareTnMhRequest method start")
486
487                 String nssmfRequest = anNssmfUtils.buildCreateNSSMFRequest(execution, "TN_MH", "modify-allocate")
488                 String urlString = "/api/rest/provMns/v1/NSS/SliceProfiles"
489                 String nssmfResponse = nssmfAdapterUtils.sendPostRequestNSSMF(execution, urlString, nssmfRequest)
490
491                 if (nssmfResponse != null) {
492                         execution.setVariable("nssmfResponse", nssmfResponse)
493                         String jobId = jsonUtil.getJsonValue(nssmfResponse, "jobId")
494                         execution.setVariable("TNMH_jobId",jobId)
495                 } else {
496                         logger.error("received error message from NSSMF : "+ nssmfResponse)
497                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"Received a Bad Sync Response from NSSMF.")
498                 }
499                 logger.debug("Exit prepareTnMhRequest")
500         }
501         
502         def createFhAllocateNssiJobQuery = { DelegateExecution execution ->
503                 logger.debug(Prefix+"createModifyNssiQueryJobStatus method start")
504                 createTnAllocateNssiJobQuery(execution, "TN_FH")
505         }
506         
507         def createMhAllocateNssiJobQuery = { DelegateExecution execution ->
508                 logger.debug(Prefix+"createModifyNssiQueryJobStatus method start")
509                 createTnAllocateNssiJobQuery(execution, "TN_MH")
510         }
511         
512         private void createTnAllocateNssiJobQuery(DelegateExecution execution, String domainType) {
513                 JsonObject esrInfo = new JsonObject()
514                 esrInfo.addProperty("networkType", "tn")
515                 esrInfo.addProperty("vendor", "ONAP_internal")
516                 execution.setVariable("esrInfo", esrInfo.toString())
517                 JsonObject serviceInfo = new JsonObject()
518                 
519                 serviceInfo.addProperty("nsiId", execution.getVariable("nsiId"))
520                 serviceInfo.addProperty("PLMNIdList", objectMapper.writeValueAsString(execution.getVariable("plmnIdList")))
521                 serviceInfo.addProperty("globalSubscriberId", execution.getVariable("globalSubscriberId"))
522                 serviceInfo.addProperty("subscriptionServiceType", execution.getVariable("subscriptionServiceType"))
523                 if(domainType.equals("TN_FH")) {
524                         serviceInfo.addProperty("nssiId", execution.getVariable("TNFH_NSSI"))
525                         serviceInfo.addProperty("nssiName", execution.getVariable("TNFH_nssiName"))
526                         serviceInfo.addProperty("serviceInvariantUuid", execution.getVariable("TNFH_modelInvariantUuid"))
527                         serviceInfo.addProperty("serviceUuid", execution.getVariable("TNFH_modelUuid"))
528                 }else if(domainType.equals("TN_MH")) {
529                         serviceInfo.addProperty("nssiId", execution.getVariable("TNMH_NSSI"))
530                         serviceInfo.addProperty("nssiName", execution.getVariable("TNMH_nssiName"))
531                         serviceInfo.addProperty("serviceInvariantUuid", execution.getVariable("TNMH_modelInvariantUuid"))
532                         serviceInfo.addProperty("serviceUuid", execution.getVariable("TNMH_modelUuid"))
533                 }
534                 execution.setVariable("serviceInfo", serviceInfo.toString())
535                 execution.setVariable("responseId", "")
536         }
537         
538         def processFhAllocateNssiJobStatusRsp = { DelegateExecution execution ->
539                 logger.debug(Prefix+"processJobStatusRsp method start")
540                 String jobResponse = execution.getVariable("TNFH_jobResponse")
541                 logger.debug("Job status response "+jobResponse)
542                 String status = jsonUtil.getJsonValue(jobResponse, "status")
543                 String nssi = jsonUtil.getJsonValue(jobResponse, "nssi")
544                 if(status.equalsIgnoreCase("finished")) {
545                         logger.debug("Job successfully completed ... proceeding with flow for nssi : "+nssi)
546                 }
547                 else {
548                         String statusDescription = jsonUtil.getJsonValue(jobResponse, "statusDescription")
549                         logger.error("received failed status from job status query for nssi : "+nssi+" with status description : "+ statusDescription)
550                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"received failed status from job status query for nssi : "+nssi+" with status description : "+ statusDescription)
551                 }
552         }
553
554         def processMhAllocateNssiJobStatusRsp = { DelegateExecution execution ->
555                 logger.debug(Prefix+"processJobStatusRsp method start")
556                 String jobResponse = execution.getVariable("TNMH_jobResponse")
557                 logger.debug("Job status response "+jobResponse)
558                 String status = jsonUtil.getJsonValue(jobResponse, "status")
559                 String nssi = jsonUtil.getJsonValue(jobResponse, "nssi")
560                 if(status.equalsIgnoreCase("finished")) {
561                         logger.debug("Job successfully completed ... proceeding with flow for nssi : "+nssi)
562                 }
563                 else {
564                         String statusDescription = jsonUtil.getJsonValue(jobResponse, "statusDescription")
565                         logger.error("received failed status from job status query for nssi : "+nssi+" with status description : "+ statusDescription)
566                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"received failed status from job status query for nssi : "+nssi+" with status description : "+ statusDescription)
567                 }
568         }
569         
570         def getSliceProfilesFromAai = { DelegateExecution execution ->
571                 logger.debug(Prefix+"getSliceProfilesFromAai method start")
572                 String instanceId = execution.getVariable("sliceProfileId")
573                 String role = "slice-profile-instance"
574                 Map<String,ServiceInstance> ranConstituentSliceProfiles = getRelatedInstancesByRole(execution, role, instanceId)
575                 logger.debug("getSliceProfilesFromAai ranConstituentSliceProfiles : "+ranConstituentSliceProfiles.toString())
576                 ranConstituentSliceProfiles.each { key, val ->
577                         switch(key) {
578                                 case "AN_NF":
579                                         execution.setVariable("ANNF_sliceProfileInstanceId", val.getServiceInstanceId())
580                                         break
581                                 case "TN_FH":
582                                         execution.setVariable("TNFH_sliceProfileInstanceId", val.getServiceInstanceId())
583                                         break
584                                 case "TN_MH":
585                                         execution.setVariable("TNMH_sliceProfileInstanceId", val.getServiceInstanceId())
586                                         break
587                                 default:
588                                         logger.error("No expected match found for current domainType "+ key)
589                                         exceptionUtil.buildAndThrowWorkflowException(execution, 1000,"No expected match found for current domainType "+ key)
590                         }
591                 }
592         }
593         
594         def prepareTnFhDeallocateRequest = { DelegateExecution execution ->
595                 logger.debug(Prefix+"prepareTnFhDeallocateRequest method start")
596                 String nssmfRequest = anNssmfUtils.buildDeallocateNssiRequest(execution, "TN_FH")
597                 String nssiId = execution.getVariable("TNFH_NSSI")
598                 execution.setVariable("tnFHNSSIId", nssiId)
599                 String urlString = "/api/rest/provMns/v1/NSS/SliceProfiles/" + nssiId
600                                 String nssmfResponse = nssmfAdapterUtils.sendPostRequestNSSMF(execution, urlString, nssmfRequest)
601                                 if (nssmfResponse != null) {
602                                         String jobId = jsonUtil.getJsonValue(nssmfResponse, "jobId")
603                                         execution.setVariable("TN_FH_jobId",jobId)
604                                 } else {
605                                         logger.error("received error message from NSSMF : "+ nssmfResponse)
606                                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"Received a Bad Sync Response from NSSMF.")
607                                 }
608         }
609         
610         def prepareTnMhDeallocateRequest = { DelegateExecution execution ->
611                 logger.debug(Prefix+"prepareTnFhDeallocateRequest method start")
612                 String nssmfRequest = anNssmfUtils.buildDeallocateNssiRequest(execution, "TN_FH")
613                 String nssiId = execution.getVariable("TNFH_NSSI")
614                 execution.setVariable("tnFHNSSIId", nssiId)
615                 String urlString = "/api/rest/provMns/v1/NSS/SliceProfiles/" + nssiId
616                                 String nssmfResponse = nssmfAdapterUtils.sendPostRequestNSSMF(execution, urlString, nssmfRequest)
617                                 if (nssmfResponse != null) {
618                                         String jobId = jsonUtil.getJsonValue(nssmfResponse, "jobId")
619                                         execution.setVariable("TN_MH_jobId",jobId)
620                                 } else {
621                                         logger.error("received error message from NSSMF : "+ nssmfResponse)
622                                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000,"Received a Bad Sync Response from NSSMF.")
623                                 }
624         }
625         
626         def createFhDeAllocateNssiJobQuery = { DelegateExecution execution ->
627                 logger.debug(Prefix+"createModifyNssiQueryJobStatus method start")
628                 createTnAllocateNssiJobQuery(execution, "TN_FH")
629         }
630         
631         def createMhDeAllocateNssiJobQuery = { DelegateExecution execution ->
632                 logger.debug(Prefix+"createModifyNssiQueryJobStatus method start")
633                 createTnAllocateNssiJobQuery(execution, "TN_MH")
634         }
635         def deleteFhSliceProfile = { DelegateExecution execution ->
636                 logger.debug(Prefix+"deleteFhSliceProfile method start")
637                 deleteServiceInstanceInAAI(execution,execution.getVariable("TNFH_sliceProfileInstanceId"))
638         }
639         def deleteMhSliceProfile = { DelegateExecution execution ->
640                 logger.debug(Prefix+"deleteMhSliceProfile method start")
641                 deleteServiceInstanceInAAI(execution,execution.getVariable("TNMH_sliceProfileInstanceId"))      
642         }
643         def deleteAnSliceProfile = { DelegateExecution execution ->
644                 logger.debug(Prefix+"deleteAnSliceProfile method start")
645                 deleteServiceInstanceInAAI(execution,execution.getVariable("ANNF_sliceProfileInstanceId"))
646         }
647         /**
648          * update operation status in request db
649          *
650          */
651         def prepareOperationStatusUpdate = { DelegateExecution execution ->
652                 logger.debug(Prefix + "prepareOperationStatusUpdate Start")
653
654                 String jobId = execution.getVariable("jobId")
655                 String nsiId = execution.getVariable("nsiId")
656                 String nssiId = execution.getVariable("serviceInstanceID")
657                 String modelUuid = execution.getVariable("modelUuid")
658                 logger.debug("Service Instance serviceId:" + nsiId + " jobId:" + jobId)
659
660                 ResourceOperationStatus updateStatus = new ResourceOperationStatus()
661                 updateStatus.setServiceId(nsiId)
662                 updateStatus.setOperationId(jobId)
663                 updateStatus.setResourceTemplateUUID(modelUuid)
664                 updateStatus.setResourceInstanceID(nssiId)
665                 updateStatus.setOperType("Modify")
666                 updateStatus.setProgress("100")
667                 updateStatus.setStatus("finished")
668                 requestDBUtil.prepareUpdateResourceOperationStatus(execution, updateStatus)
669
670                 logger.debug(Prefix + "prepareOperationStatusUpdate Exit")
671         }
672
673         def prepareFailedOperationStatusUpdate = { DelegateExecution execution ->
674                 logger.debug(Prefix + "prepareFailedOperationStatusUpdate Start")
675                 String jobId = execution.getVariable("jobId")
676                 String nsiId = execution.getVariable("nsiId")
677                 String nssiId = execution.getVariable("serviceInstanceID")
678                 String modelUuid = execution.getVariable("modelUuid")
679                 logger.debug("Service Instance serviceId:" + nsiId + " jobId:" + jobId)
680
681                 ResourceOperationStatus updateStatus = new ResourceOperationStatus()
682                 updateStatus.setServiceId(nsiId)
683                 updateStatus.setOperationId(jobId)
684                 updateStatus.setResourceTemplateUUID(modelUuid)
685                 updateStatus.setResourceInstanceID(nssiId)
686                 updateStatus.setOperType("Modify")
687                 updateStatus.setProgress("0")
688                 updateStatus.setStatus("failed")
689                 requestDBUtil.prepareUpdateResourceOperationStatus(execution, updateStatus)
690         }
691         
692         /**
693          * @param execution
694          * @param role            - nssi/slice profile instance
695          * @param instanceId    - id to which the related list to be found
696          * @return
697          */
698         private Map<String,ServiceInstance> getRelatedInstancesByRole(DelegateExecution execution,String role,String instanceId) {
699                 logger.debug("${Prefix} - Fetching related ${role} from AAI")
700                 String globalSubscriberId = execution.getVariable("globalSubscriberId")
701                 String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
702                 
703                 Map<String,ServiceInstance> relatedInstances = new HashMap<>()
704                 
705                 AAIResourcesClient client = new AAIResourcesClient()
706                 AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(globalSubscriberId).serviceSubscription(subscriptionServiceType).serviceInstance(instanceId))
707                 if (!client.exists(uri)) {
708                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Service Instance was not found in aai : ${instanceId}")
709                 }
710                 AAIResultWrapper wrapper = client.get(uri, NotFoundException.class)
711                 Optional<ServiceInstance> si = wrapper.asBean(ServiceInstance.class)
712                 if(si.isPresent()) {
713                 List<Relationship> relationshipList = si.get().getRelationshipList().getRelationship()
714                 for (Relationship relationship : relationshipList) {
715                         String relatedTo = relationship.getRelatedTo()
716                         if (relatedTo.toLowerCase() == "service-instance") {
717                                 String relatioshipurl = relationship.getRelatedLink()
718                                 String serviceInstanceId =
719                                                 relatioshipurl.substring(relatioshipurl.lastIndexOf("/") + 1, relatioshipurl.length())
720
721                                 AAIResourcesClient client01 = new AAIResourcesClient()
722                                 AAIResourceUri uri01 = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(globalSubscriberId).serviceSubscription(subscriptionServiceType).serviceInstance(serviceInstanceId))
723                                 if (!client.exists(uri01)) {
724                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500,
725                                                         "Service Instance was not found in aai: ${serviceInstanceId} related to ${instanceId}")
726                                 }
727                                 AAIResultWrapper wrapper01 = client01.get(uri01.depth(Depth.TWO), NotFoundException.class)
728                                 Optional<ServiceInstance> serviceInstance = wrapper01.asBean(ServiceInstance.class)
729                                 if (serviceInstance.isPresent()) {
730                                         ServiceInstance instance = serviceInstance.get()
731                                         if (role.equalsIgnoreCase(instance.getServiceRole())) {
732                                                 relatedInstances.put(instance.getWorkloadContext(),instance)
733                                         }
734                                 }
735                         }
736                 }
737                 }
738                 logger.debug("Found ${relatedInstances.size()} ${role} related to ${instanceId} ")
739                 return relatedInstances
740         }
741         
742         private ServiceInstance getServiceInstance(DelegateExecution execution, String instanceId) {
743                 String globalSubscriberId = execution.getVariable("globalSubscriberId")
744                 String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
745                 ServiceInstance serviceInstance = new ServiceInstance()
746                 AAIResourcesClient client = new AAIResourcesClient()
747                 AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(globalSubscriberId).serviceSubscription(subscriptionServiceType).serviceInstance(instanceId))
748                 if (!client.exists(uri)) {
749                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Service Instance was not found in aai : ${instanceId}")
750                 }
751                 AAIResultWrapper wrapper = client.get(uri, NotFoundException.class)
752                 Optional<ServiceInstance> si = wrapper.asBean(ServiceInstance.class)
753                 
754                 if(si.isPresent()) {
755                         serviceInstance = si.get()
756                 }
757                 return serviceInstance
758         }
759         private void deleteServiceInstanceInAAI(DelegateExecution execution,String instanceId) {
760                 try {
761                         AAIResourceUri serviceInstanceUri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(execution.getVariable("globalSubscriberId")).serviceSubscription(execution.getVariable("serviceType")).serviceInstance(instanceId))
762                         getAAIClient().delete(serviceInstanceUri)
763                         logger.debug("${Prefix} Exited deleteServiceInstance")
764                 }catch(Exception e){
765                         logger.debug("Error occured within deleteServiceInstance method: " + e)
766                 }
767         }
768 }