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