4a8469cc8df746fa751b5099479055b5004039ba
[so.git] /
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.debug("Enter update relationship in DoAllocateNSIandNSSI()")
115         String allottedResourceId = execution.getVariable("allottedResourceId")
116         //Need to check whether nsi exist : Begin
117         org.onap.aai.domain.yang.ServiceInstance nsiServiceInstance = new org.onap.aai.domain.yang.ServiceInstance()
118         SliceTaskParams sliceParams = execution.getVariable("sliceParams")
119         String nsiServiceInstanceID = sliceParams.getSuggestNsiId()
120
121         AAIResourcesClient resourceClient = new AAIResourcesClient()
122         AAIResourceUri nsiServiceuri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, execution.getVariable("globalSubscriberId"), execution.getVariable("subscriptionServiceType"), nsiServiceInstanceID)
123         //AAIResourceUri nsiServiceuri = AAIUriFactory.createResourceUri(AAIObjectType.QUERY_ALLOTTED_RESOURCE, execution.getVariable("globalSubscriberId"), execution.getVariable("serviceType"), nsiServiceInstanceID)
124
125         try {
126             AAIResultWrapper wrapper = resourceClient.get(nsiServiceuri, NotFoundException.class)
127             Optional<org.onap.aai.domain.yang.ServiceInstance> si = wrapper.asBean(org.onap.aai.domain.yang.ServiceInstance.class)
128             nsiServiceInstance = si.get()
129             //allottedResourceId=nsiServiceInstance.getAllottedResources().getAllottedResource().get(0).getId()
130
131 //            if(resourceClient.exists(nsiServiceuri)){
132 //                execution.setVariable("nsi_resourceLink", nsiServiceuri.build().toString())
133 //            }else{
134 //                exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Service instance was not found in aai to " +
135 //                        "associate for service :"+serviceInstanceId)
136 //            }
137
138         AAIResourceUri allottedResourceUri = AAIUriFactory.createResourceUri(AAIObjectType.ALLOTTED_RESOURCE, execution.getVariable("globalSubscriberId"), execution.getVariable("subscriptionServiceType"), execution.getVariable("sliceServiceInstanceId"), allottedResourceId)
139         getAAIClient().connect(allottedResourceUri,nsiServiceuri)
140
141         List<String> nssiAssociated = new ArrayList<>()
142         RelationshipList relationshipList = nsiServiceInstance.getRelationshipList()
143         List<Relationship> relationships = relationshipList.getRelationship()
144         for(Relationship relationship in relationships)
145         {
146             if(relationship.getRelatedTo().equalsIgnoreCase("service-instance"))
147             {
148                 String NSSIassociated = relationship.getRelatedLink().substring(relationship.getRelatedLink().lastIndexOf("/") + 1);
149                 if(!NSSIassociated.equals(nsiServiceInstanceID))
150                     nssiAssociated.add(NSSIassociated)
151             }
152         }
153         execution.setVariable("nssiAssociated",nssiAssociated)
154         execution.setVariable("nsiServiceInstanceName",nsiServiceInstance.getServiceInstanceName())
155         }catch(BpmnError e) {
156             throw e
157         }catch (Exception ex){
158             String msg = "NSI suggested in the option doesn't exist. " + nsiServiceInstanceID
159             logger.debug(msg)
160             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
161         }
162         logger.debug("Exit update relationship in DoAllocateNSIandNSSI()")
163     }
164
165     void prepareNssiModelInfo(DelegateExecution execution){
166         logger.trace("Enter prepareNssiModelInfo in DoAllocateNSIandNSSI()")
167         List<String> nssiAssociated = new ArrayList<>()
168         Map<String, Object> nssiMap = new HashMap<>()
169         nssiAssociated=execution.getVariable("nssiAssociated")
170         for(String nssiID in nssiAssociated)
171         {
172             try {
173                 AAIResourcesClient resourceClient = new AAIResourcesClient()
174                 AAIResourceUri serviceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, execution.getVariable("globalSubscriberId"), execution.getVariable("subscriptionServiceType"), nssiID)
175                 AAIResultWrapper wrapper = resourceClient.get(serviceInstanceUri, NotFoundException.class)
176                 Optional<org.onap.aai.domain.yang.ServiceInstance> si = wrapper.asBean(org.onap.aai.domain.yang.ServiceInstance.class)
177                 org.onap.aai.domain.yang.ServiceInstance nssi = si.get()
178                 nssiMap.put(nssi.getEnvironmentContext(),"""{
179                     "serviceInstanceId":"${nssi.getServiceInstanceId()}",
180                     "modelUuid":"${nssi.getModelVersionId()}"
181                      }""")
182
183             }catch(NotFoundException e)
184             {
185                 logger.debug("NSSI Service Instance not found in AAI: " + nssiID)
186             }catch(Exception e)
187             {
188                 logger.debug("NSSI Service Instance not found in AAI: " + nssiID)
189             }
190             execution.setVariable("nssiMap",nssiMap)
191
192         }
193         logger.trace("Exit prepareNssiModelInfo in DoAllocateNSIandNSSI()")
194     }
195
196     void createNSIinAAI(DelegateExecution execution) {
197         logger.debug("Enter CreateNSIinAAI in DoAllocateNSIandNSSI()")
198         ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
199         org.onap.aai.domain.yang.ServiceInstance nsi = new ServiceInstance();
200         String sliceInstanceId = UUID.randomUUID().toString()
201         execution.setVariable("sliceInstanceId",sliceInstanceId)
202         nsi.setServiceInstanceId(sliceInstanceId)
203         String sliceInstanceName = "nsi_"+execution.getVariable("sliceServiceInstanceName")
204         nsi.setServiceInstanceName(sliceInstanceName)
205         String serviceType = execution.getVariable("serviceType")
206         nsi.setServiceType(serviceType)
207         String serviceStatus = "deactivated"
208         nsi.setOrchestrationStatus(serviceStatus)
209         String modelInvariantUuid = serviceDecomposition.getModelInfo().getModelInvariantUuid()
210         String modelUuid = serviceDecomposition.getModelInfo().getModelUuid()
211         nsi.setModelInvariantId(modelInvariantUuid)
212         nsi.setModelVersionId(modelUuid)
213         String uuiRequest = execution.getVariable("uuiRequest")
214         String serviceInstanceLocationid = jsonUtil.getJsonValue(uuiRequest, "service.parameters.requestInputs.plmnIdList")
215         nsi.setServiceInstanceLocationId(serviceInstanceLocationid)
216         //String snssai = jsonUtil.getJsonValue(uuiRequest, "service.requestInputs.snssai")
217         //nsi.setEnvironmentContext(snssai)
218         String serviceRole = "nsi"
219         nsi.setServiceRole(serviceRole)
220         String msg = ""
221         try {
222
223             AAIResourcesClient client = new AAIResourcesClient()
224             AAIResourceUri nsiServiceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, execution.getVariable("globalSubscriberId"), execution.getVariable("subscriptionServiceType"), sliceInstanceId)
225             client.create(nsiServiceUri, nsi)
226
227             Relationship relationship = new Relationship()
228             logger.info("Creating Allotted resource relationship, nsiServiceUri: " + nsiServiceUri.build().toString())
229             relationship.setRelatedLink(nsiServiceUri.build().toString())
230             AAIResourceUri allottedResourceUri = AAIUriFactory.createResourceUri(AAIObjectType.ALLOTTED_RESOURCE,
231                     execution.getVariable("globalSubscriberId"),execution.getVariable("subscriptionServiceType"),
232                     execution.getVariable("sliceServiceInstanceId"), execution.getVariable("allottedResourceId")).relationshipAPI()
233             client.create(allottedResourceUri, relationship)
234
235         } catch (BpmnError e) {
236             throw e
237         } catch (Exception ex) {
238             msg = "Exception in DoCreateSliceServiceInstance.instantiateSliceService. " + ex.getMessage()
239             logger.info(msg)
240             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
241         }
242         Map<String, Object> nssiMap = new HashMap<>()
243         List<ServiceProxy> serviceProxyList = serviceDecomposition.getServiceProxy()
244         List<String> nsstModelInfoList = new ArrayList<>()
245         for(ServiceProxy serviceProxy : serviceProxyList)
246         {
247             //String nsstModelUuid = serviceProxy.getModelInfo().getModelUuid()
248             String nsstModelUuid = serviceProxy.getSourceModelUuid()
249             //String nsstModelInvariantUuid = serviceProxy.getModelInfo().getModelInvariantUuid()
250             String nsstServiceModelInfo = """{
251             "modelInvariantUuid":"",
252             "modelUuid":"${nsstModelUuid}",
253             "modelVersion":""
254              }"""
255             nsstModelInfoList.add(nsstServiceModelInfo)
256         }
257         int currentIndex=0
258         int maxIndex=nsstModelInfoList.size()
259         if(maxIndex < 1)
260         {
261             msg = "Exception in DoAllocateNSIandNSSI. There is no NSST associated with NST "
262             logger.info(msg)
263             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
264         }
265         execution.setVariable("nsstModelInfoList",nsstModelInfoList)
266         execution.setVariable("currentIndex",currentIndex)
267         execution.setVariable("maxIndex",maxIndex)
268         execution.setVariable('nsiServiceInstanceId',sliceInstanceId)
269         execution.setVariable("nsiServiceInstanceName",sliceInstanceName)
270         logger.debug("Exit CreateNSIinAAI in DoAllocateNSIandNSSI()")
271     }
272
273     void getOneNsstInfo(DelegateExecution execution){
274         List<String> nsstModelInfoList = new ArrayList<>()
275         nsstModelInfoList = execution.getVariable("nsstModelInfoList")
276         int currentIndex = execution.getVariable("currentIndex")
277         int maxIndex = execution.getVariable("maxIndex")
278         boolean isMoreNSSTtoProcess = true
279         String nsstServiceModelInfo = nsstModelInfoList.get(currentIndex)
280         execution.setVariable("serviceModelInfo", nsstServiceModelInfo)
281         execution.setVariable("currentIndex", currentIndex)
282         currentIndex = currentIndex+1
283         if(currentIndex <= maxIndex )
284             isMoreNSSTtoProcess = false
285         execution.setVariable("isMoreNSSTtoProcess", isMoreNSSTtoProcess)
286     }
287
288     void createNSSTMap(DelegateExecution execution){
289         ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
290         String modelUuid= serviceDecomposition.getModelInfo().getModelUuid()
291         String content = serviceDecomposition.getServiceInfo().getServiceArtifact().get(0).getContent()
292         //String nsstID = jsonUtil.getJsonValue(content, "metadata.id")
293         //String vendor = jsonUtil.getJsonValue(content, "metadata.vendor")
294         //String type = jsonUtil.getJsonValue(content, "metadata.type")
295         String domain = jsonUtil.getJsonValue(content, "metadata.domainType")
296
297         Map<String, Object> nssiMap = execution.getVariable("nssiMap")
298         String servicename = execution.getVariable("sliceServiceInstanceName")
299         String nsiname = "nsi_"+servicename
300         nssiMap.put(domain,"""{
301                     "serviceInstanceId":"",
302                     "modelUuid":"${modelUuid}"
303                      }""")
304         execution.setVariable("nssiMap",nssiMap)
305     }
306
307     void prepareNSSIList(DelegateExecution execution){
308         logger.trace("Enter prepareNSSIList in DoAllocateNSIandNSSI()")
309         Map<String, Object> nssiMap = new HashMap<>()
310         Boolean isMoreNSSI = false
311         nssiMap = execution.getVariable("nssiMap")
312         List<String> keys=new ArrayList<String>(nssiMap.values())
313         List<String> nsstSequence = execution.getVariable("nsstSequence")
314         Integer currentIndex=0;
315         execution.setVariable("currentNssiIndex",currentIndex)
316         Integer maxIndex=keys.size()
317         execution.setVariable("maxIndex",maxIndex)
318         if(maxIndex>0)
319             isMoreNSSI=true
320         execution.setVariable("isMoreNSSI",isMoreNSSI)
321         logger.trace("Exit prepareNSSIList in DoAllocateNSIandNSSI()")
322     }
323
324
325     void getOneNSSIInfo(DelegateExecution execution){
326         logger.trace("Enter getOneNSSIInfo in DoAllocateNSIandNSSI()")
327
328         //ServiceDecomposition serviceDecompositionObj = execution.getVariable("serviceDecompositionObj")
329         Map<String, Object> nssiMap=execution.getVariable("nssiMap")
330         List<String> nsstSequence = execution.getVariable("nsstSequence")
331         String currentNSST= nsstSequence.get(execution.getVariable("currentNssiIndex"))
332         boolean isNSSIOptionAvailable = false
333         String nsstInput=nssiMap.get(currentNSST)
334         execution.setVariable("nsstInput",nsstInput)
335         String modelUuid = jsonUtil.getJsonValue(nsstInput, "modelUuid")
336         String nssiInstanceId = jsonUtil.getJsonValue(nsstInput, "serviceInstanceId")
337         String nssiserviceModelInfo = """{
338             "modelInvariantUuid":"",
339             "modelUuid":"${modelUuid}",
340             "modelVersion":""
341              }"""
342         Integer currentIndex = execution.getVariable("currentNssiIndex")
343         currentIndex=currentIndex+1;
344         execution.setVariable("currentNssiIndex",currentIndex)
345         execution.setVariable("nssiserviceModelInfo",nssiserviceModelInfo)
346         execution.setVariable("nssiInstanceId",nssiInstanceId)
347         logger.trace("Exit getOneNSSIInfo in DoAllocateNSIandNSSI()")
348     }
349
350     void updateCurrentIndex(DelegateExecution execution){
351
352         logger.trace("Enter updateCurrentIndex in DoAllocateNSIandNSSI()")
353         Integer currentIndex = execution.getVariable("currentNssiIndex")
354         Integer maxIndex = execution.getVariable("maxIndex")
355         if(currentIndex>=maxIndex)
356         {
357             Boolean isMoreNSSI=false
358             execution.setVariable("isMoreNSSI",isMoreNSSI)
359         }
360         logger.trace("Exit updateCurrentIndex in DoAllocateNSIandNSSI()")
361     }
362 }