Merge "[SDC] Update SDC Distribution Client"
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / DoAllocateNSIandNSSI.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2019 Huawei Technologies Co., Ltd. All rights reserved.
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.aai.domain.yang.Relationship
26 import org.onap.aai.domain.yang.RelationshipList
27 import org.onap.aai.domain.yang.ServiceInstance
28 import org.onap.so.beans.nsmf.SliceTaskParams
29 import org.onap.so.bpmn.common.scripts.ExceptionUtil
30 import org.onap.so.bpmn.common.scripts.NssmfAdapterUtils
31 import org.onap.so.bpmn.core.domain.ServiceDecomposition
32 import org.onap.so.bpmn.core.domain.ServiceProxy
33 import org.onap.so.bpmn.core.json.JsonUtils
34 import org.onap.aaiclient.client.aai.AAIObjectType
35 import org.onap.aaiclient.client.aai.AAIResourcesClient
36 import org.onap.aaiclient.client.aai.entities.AAIResultWrapper
37 import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
38 import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
39 import org.slf4j.Logger
40 import org.slf4j.LoggerFactory
41
42 import javax.ws.rs.NotFoundException
43
44 import static org.apache.commons.lang3.StringUtils.isBlank
45
46 class DoAllocateNSIandNSSI extends org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor{
47
48     private static final Logger logger = LoggerFactory.getLogger( DoAllocateNSIandNSSI.class);
49
50     ExceptionUtil exceptionUtil = new ExceptionUtil()
51
52     JsonUtils jsonUtil = new JsonUtils()
53
54     private NssmfAdapterUtils nssmfAdapterUtils = new NssmfAdapterUtils(httpClientFactory, jsonUtil)
55
56     /**
57      * Pre Process the BPMN Flow Request
58      * Inclouds:
59      * generate the nsOperationKey
60      * generate the nsParameters
61      */
62
63     void preProcessRequest (DelegateExecution execution) {
64         String msg = ""
65         logger.trace("Enter preProcessRequest()")
66         Map<String, Object> nssiMap = new HashMap<>()
67         execution.setVariable("nssiMap", nssiMap)
68         boolean isMoreNSSTtoProcess = true
69         execution.setVariable("isMoreNSSTtoProcess", isMoreNSSTtoProcess)
70         List<String> nsstSequence = new ArrayList<>(Arrays.asList("cn"))
71         execution.setVariable("nsstSequence", nsstSequence)
72         logger.trace("Exit preProcessRequest")
73     }
74
75     void retriveSliceOption(DelegateExecution execution) {
76         logger.trace("Enter retriveSliceOption() of DoAllocateNSIandNSSI")
77         String uuiRequest = execution.getVariable("uuiRequest")
78         boolean isNSIOptionAvailable = false
79         List<String> nssiAssociated = new ArrayList<>()
80         SliceTaskParams sliceParams = execution.getVariable("sliceTaskParams")
81         try
82         {
83             Map<String, Object> nstSolution = execution.getVariable("nstSolution") as Map
84             String modelUuid = nstSolution.get("UUID")
85             String modelInvariantUuid = nstSolution.get("invariantUUID")
86             String serviceModelInfo = """{
87             "modelInvariantUuid":"${modelInvariantUuid}",
88             "modelUuid":"${modelUuid}",
89             "modelVersion":""
90              }"""
91             execution.setVariable("serviceModelInfo", serviceModelInfo)
92             //Params sliceParams = new Gson().fromJson(params, new TypeToken<Params>() {}.getType());
93             execution.setVariable("sliceParams", sliceParams)
94         }catch (Exception ex) {
95             logger.debug( "Unable to get the task information from request DB: " + ex)
96             exceptionUtil.buildAndThrowWorkflowException(execution, 401, "Unable to get task information from request DB.")
97         }
98
99         if(isBlank(sliceParams.getSuggestNsiId()))
100         {
101             isNSIOptionAvailable=false
102         }
103         else
104         {
105             isNSIOptionAvailable=true
106             execution.setVariable('nsiServiceInstanceId',sliceParams.getSuggestNsiId())
107             execution.setVariable('nsiServiceInstanceName',sliceParams.getSuggestNsiName())
108         }
109         execution.setVariable("isNSIOptionAvailable",isNSIOptionAvailable)
110         logger.trace("Exit retriveSliceOption() of DoAllocateNSIandNSSI")
111     }
112
113     void updateRelationship(DelegateExecution execution) {
114         logger.trace("Enter update relationship in DoAllocateNSIandNSSI()")
115         String nsiServiceInstanceId = execution.getVariable("nsiServiceInstanceId")
116         String allottedResourceId = execution.getVariable("allottedResourceId")
117         //Need to check whether nsi exist : Begin
118         org.onap.aai.domain.yang.ServiceInstance nsiServiceInstance = new org.onap.aai.domain.yang.ServiceInstance()
119         SliceTaskParams sliceParams = execution.getVariable("sliceParams")
120
121         String nsiServiceInstanceID = sliceParams.getSuggestNsiId()
122
123         AAIResourcesClient resourceClient = new AAIResourcesClient()
124         AAIResourceUri nsiServiceuri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, execution.getVariable("globalSubscriberId"), execution.getVariable("subscriptionServiceType"), nsiServiceInstanceID)
125         //AAIResourceUri nsiServiceuri = AAIUriFactory.createResourceUri(AAIObjectType.QUERY_ALLOTTED_RESOURCE, execution.getVariable("globalSubscriberId"), execution.getVariable("serviceType"), nsiServiceInstanceID)
126
127         try {
128             AAIResultWrapper wrapper = resourceClient.get(nsiServiceuri, NotFoundException.class)
129             Optional<org.onap.aai.domain.yang.ServiceInstance> si = wrapper.asBean(org.onap.aai.domain.yang.ServiceInstance.class)
130             nsiServiceInstance = si.get()
131             //allottedResourceId=nsiServiceInstance.getAllottedResources().getAllottedResource().get(0).getId()
132
133 //            if(resourceClient.exists(nsiServiceuri)){
134 //                execution.setVariable("nsi_resourceLink", nsiServiceuri.build().toString())
135 //            }else{
136 //                exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Service instance was not found in aai to " +
137 //                        "associate for service :"+serviceInstanceId)
138 //            }
139         }catch(BpmnError e) {
140             throw e;
141         }catch (Exception ex){
142             String msg = "NSI suggested in the option doesn't exist. " + nsiServiceInstanceID
143             logger.debug(msg)
144             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
145         }
146         AAIResourceUri allottedResourceUri = AAIUriFactory.createResourceUri(AAIObjectType.ALLOTTED_RESOURCE, execution.getVariable("globalSubscriberId"), execution.getVariable("serviceType"), nsiServiceInstanceId, allottedResourceId)
147         getAAIClient().connect(allottedResourceUri,nsiServiceuri)
148
149         List<String> nssiAssociated = new ArrayList<>()
150         RelationshipList relationshipList = nsiServiceInstance.getRelationshipList()
151         List<Relationship> relationships = relationshipList.getRelationship()
152         for(Relationship relationship in relationships)
153         {
154             if(relationship.getRelatedTo().equalsIgnoreCase("service-instance"))
155             {
156                 String NSSIassociated = relationship.getRelatedLink().substring(relationship.getRelatedLink().lastIndexOf("/") + 1);
157                 if(!NSSIassociated.equals(nsiServiceInstanceID))
158                     nssiAssociated.add(NSSIassociated)
159             }
160         }
161         execution.setVariable("nssiAssociated",nssiAssociated)
162         execution.setVariable("nsiServiceInstanceName",nsiServiceInstance.getServiceInstanceName())
163         logger.trace("Exit update relationship in DoAllocateNSIandNSSI()")
164     }
165
166     void prepareNssiModelInfo(DelegateExecution execution){
167         logger.trace("Enter prepareNssiModelInfo in DoAllocateNSIandNSSI()")
168         List<String> nssiAssociated = new ArrayList<>()
169         Map<String, Object> nssiMap = new HashMap<>()
170         nssiAssociated=execution.getVariable("nssiAssociated")
171         for(String nssiID in nssiAssociated)
172         {
173             try {
174                 AAIResourcesClient resourceClient = new AAIResourcesClient()
175                 AAIResourceUri serviceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, execution.getVariable("globalSubscriberId"), execution.getVariable("subscriptionServiceType"), nssiID)
176                 AAIResultWrapper wrapper = resourceClient.get(serviceInstanceUri, NotFoundException.class)
177                 Optional<org.onap.aai.domain.yang.ServiceInstance> si = wrapper.asBean(org.onap.aai.domain.yang.ServiceInstance.class)
178                 org.onap.aai.domain.yang.ServiceInstance nssi = si.get()
179                 nssiMap.put(nssi.getEnvironmentContext(),"""{
180                     "serviceInstanceId":"${nssi.getServiceInstanceId()}",
181                     "modelUuid":"${nssi.getModelVersionId()}"
182                      }""")
183
184             }catch(NotFoundException e)
185             {
186                 logger.debug("NSSI Service Instance not found in AAI: " + nssiID)
187             }catch(Exception e)
188             {
189                 logger.debug("NSSI Service Instance not found in AAI: " + nssiID)
190             }
191             execution.setVariable("nssiMap",nssiMap)
192
193         }
194         logger.trace("Exit prepareNssiModelInfo in DoAllocateNSIandNSSI()")
195     }
196
197     void createNSIinAAI(DelegateExecution execution) {
198         logger.debug("Enter CreateNSIinAAI in DoAllocateNSIandNSSI()")
199         ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
200         org.onap.aai.domain.yang.ServiceInstance nsi = new ServiceInstance();
201         String sliceInstanceId = UUID.randomUUID().toString()
202         execution.setVariable("sliceInstanceId",sliceInstanceId)
203         nsi.setServiceInstanceId(sliceInstanceId)
204         String sliceInstanceName = "nsi_"+execution.getVariable("sliceServiceInstanceName")
205         nsi.setServiceInstanceName(sliceInstanceName)
206         String serviceType = execution.getVariable("serviceType")
207         nsi.setServiceType(serviceType)
208         String serviceStatus = "deactivated"
209         nsi.setOrchestrationStatus(serviceStatus)
210         String modelInvariantUuid = serviceDecomposition.getModelInfo().getModelInvariantUuid()
211         String modelUuid = serviceDecomposition.getModelInfo().getModelUuid()
212         nsi.setModelInvariantId(modelInvariantUuid)
213         nsi.setModelVersionId(modelUuid)
214         String uuiRequest = execution.getVariable("uuiRequest")
215         String serviceInstanceLocationid = jsonUtil.getJsonValue(uuiRequest, "service.parameters.requestInputs.plmnIdList")
216         nsi.setServiceInstanceLocationId(serviceInstanceLocationid)
217         //String snssai = jsonUtil.getJsonValue(uuiRequest, "service.requestInputs.snssai")
218         //nsi.setEnvironmentContext(snssai)
219         String serviceRole = "nsi"
220         nsi.setServiceRole(serviceRole)
221         String msg = ""
222         try {
223
224             AAIResourcesClient client = new AAIResourcesClient()
225             AAIResourceUri nsiServiceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, execution.getVariable("globalSubscriberId"), execution.getVariable("subscriptionServiceType"), sliceInstanceId)
226             client.create(nsiServiceUri, nsi)
227
228             Relationship relationship = new Relationship()
229             logger.info("Creating Allotted resource relationship, nsiServiceUri: " + nsiServiceUri.build().toString())
230             relationship.setRelatedLink(nsiServiceUri.build().toString())
231             AAIResourceUri allottedResourceUri = AAIUriFactory.createResourceUri(AAIObjectType.ALLOTTED_RESOURCE,
232                     execution.getVariable("globalSubscriberId"),execution.getVariable("subscriptionServiceType"),
233                     execution.getVariable("sliceServiceInstanceId"), execution.getVariable("allottedResourceId")).relationshipAPI()
234             client.create(allottedResourceUri, relationship)
235
236         } catch (BpmnError e) {
237             throw e
238         } catch (Exception ex) {
239             msg = "Exception in DoCreateSliceServiceInstance.instantiateSliceService. " + ex.getMessage()
240             logger.info(msg)
241             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
242         }
243         Map<String, Object> nssiMap = new HashMap<>()
244         List<ServiceProxy> serviceProxyList = serviceDecomposition.getServiceProxy()
245         List<String> nsstModelInfoList = new ArrayList<>()
246         for(ServiceProxy serviceProxy : serviceProxyList)
247         {
248             //String nsstModelUuid = serviceProxy.getModelInfo().getModelUuid()
249             String nsstModelUuid = serviceProxy.getSourceModelUuid()
250             //String nsstModelInvariantUuid = serviceProxy.getModelInfo().getModelInvariantUuid()
251             String nsstServiceModelInfo = """{
252             "modelInvariantUuid":"",
253             "modelUuid":"${nsstModelUuid}",
254             "modelVersion":""
255              }"""
256             nsstModelInfoList.add(nsstServiceModelInfo)
257         }
258         int currentIndex=0
259         int maxIndex=nsstModelInfoList.size()
260         if(maxIndex < 1)
261         {
262             msg = "Exception in DoAllocateNSIandNSSI. There is no NSST associated with NST "
263             logger.info(msg)
264             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
265         }
266         execution.setVariable("nsstModelInfoList",nsstModelInfoList)
267         execution.setVariable("currentIndex",currentIndex)
268         execution.setVariable("maxIndex",maxIndex)
269         execution.setVariable('nsiServiceInstanceId',sliceInstanceId)
270         execution.setVariable("nsiServiceInstanceName",sliceInstanceName)
271         logger.debug("Exit CreateNSIinAAI in DoAllocateNSIandNSSI()")
272     }
273
274     void getOneNsstInfo(DelegateExecution execution){
275         List<String> nsstModelInfoList = new ArrayList<>()
276         nsstModelInfoList = execution.getVariable("nsstModelInfoList")
277         int currentIndex = execution.getVariable("currentIndex")
278         int maxIndex = execution.getVariable("maxIndex")
279         boolean isMoreNSSTtoProcess = true
280         String nsstServiceModelInfo = nsstModelInfoList.get(currentIndex)
281         execution.setVariable("serviceModelInfo", nsstServiceModelInfo)
282         execution.setVariable("currentIndex", currentIndex)
283         currentIndex = currentIndex+1
284         if(currentIndex <= maxIndex )
285             isMoreNSSTtoProcess = false
286         execution.setVariable("isMoreNSSTtoProcess", isMoreNSSTtoProcess)
287     }
288
289     void createNSSTMap(DelegateExecution execution){
290         ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
291         String modelUuid= serviceDecomposition.getModelInfo().getModelUuid()
292         String content = serviceDecomposition.getServiceInfo().getServiceArtifact().get(0).getContent()
293         //String nsstID = jsonUtil.getJsonValue(content, "metadata.id")
294         //String vendor = jsonUtil.getJsonValue(content, "metadata.vendor")
295         //String type = jsonUtil.getJsonValue(content, "metadata.type")
296         String domain = jsonUtil.getJsonValue(content, "metadata.domainType")
297
298         Map<String, Object> nssiMap = execution.getVariable("nssiMap")
299         String servicename = execution.getVariable("sliceServiceInstanceName")
300         String nsiname = "nsi_"+servicename
301         nssiMap.put(domain,"""{
302                     "serviceInstanceId":"",
303                     "modelUuid":"${modelUuid}"
304                      }""")
305         execution.setVariable("nssiMap",nssiMap)
306     }
307
308     void prepareNSSIList(DelegateExecution execution){
309         logger.trace("Enter prepareNSSIList in DoAllocateNSIandNSSI()")
310         Map<String, Object> nssiMap = new HashMap<>()
311         Boolean isMoreNSSI = false
312         nssiMap = execution.getVariable("nssiMap")
313         List<String> keys=new ArrayList<String>(nssiMap.values())
314         List<String> nsstSequence = execution.getVariable("nsstSequence")
315         Integer currentIndex=0;
316         execution.setVariable("currentNssiIndex",currentIndex)
317         Integer maxIndex=keys.size()
318         execution.setVariable("maxIndex",maxIndex)
319         if(maxIndex>0)
320             isMoreNSSI=true
321         execution.setVariable("isMoreNSSI",isMoreNSSI)
322         logger.trace("Exit prepareNSSIList in DoAllocateNSIandNSSI()")
323     }
324
325
326     void getOneNSSIInfo(DelegateExecution execution){
327         logger.trace("Enter getOneNSSIInfo in DoAllocateNSIandNSSI()")
328
329         //ServiceDecomposition serviceDecompositionObj = execution.getVariable("serviceDecompositionObj")
330         Map<String, Object> nssiMap=execution.getVariable("nssiMap")
331         List<String> nsstSequence = execution.getVariable("nsstSequence")
332         String currentNSST= nsstSequence.get(execution.getVariable("currentNssiIndex"))
333         boolean isNSSIOptionAvailable = false
334         String nsstInput=nssiMap.get(currentNSST)
335         execution.setVariable("nsstInput",nsstInput)
336         String modelUuid = jsonUtil.getJsonValue(nsstInput, "modelUuid")
337         String nssiInstanceId = jsonUtil.getJsonValue(nsstInput, "serviceInstanceId")
338         String nssiserviceModelInfo = """{
339             "modelInvariantUuid":"",
340             "modelUuid":"${modelUuid}",
341             "modelVersion":""
342              }"""
343         Integer currentIndex = execution.getVariable("currentNssiIndex")
344         currentIndex=currentIndex+1;
345         execution.setVariable("currentNssiIndex",currentIndex)
346         execution.setVariable("nssiserviceModelInfo",nssiserviceModelInfo)
347         execution.setVariable("nssiInstanceId",nssiInstanceId)
348         logger.trace("Exit getOneNSSIInfo in DoAllocateNSIandNSSI()")
349     }
350
351     void updateCurrentIndex(DelegateExecution execution){
352
353         logger.trace("Enter updateCurrentIndex in DoAllocateNSIandNSSI()")
354         Integer currentIndex = execution.getVariable("currentNssiIndex")
355         Integer maxIndex = execution.getVariable("maxIndex")
356         if(currentIndex>=maxIndex)
357         {
358             Boolean isMoreNSSI=false
359             execution.setVariable("isMoreNSSI",isMoreNSSI)
360         }
361         logger.trace("Exit updateCurrentIndex in DoAllocateNSIandNSSI()")
362     }
363 }