5354d52fce8642ab229fb663560c46d3ec845934
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / DoDeleteSliceService.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  # Copyright (c) 2019, CMCC Technologies Co., Ltd.
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 package org.onap.so.bpmn.infrastructure.scripts
21
22 import org.camunda.bpm.engine.delegate.BpmnError
23 import org.camunda.bpm.engine.delegate.DelegateExecution
24 import org.onap.aai.domain.yang.AllottedResource
25 import org.onap.aai.domain.yang.AllottedResources
26 import org.onap.aai.domain.yang.Relationship
27 import org.onap.aai.domain.yang.ServiceInstance
28 import org.onap.aai.domain.yang.SliceProfiles
29 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
30 import org.onap.so.bpmn.common.scripts.ExceptionUtil
31 import org.onap.aaiclient.client.aai.AAIObjectType
32 import org.onap.aaiclient.client.aai.entities.AAIResultWrapper
33 import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
34 import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
35 import org.slf4j.Logger
36 import org.slf4j.LoggerFactory
37
38 import javax.ws.rs.NotFoundException
39
40 import static org.apache.commons.lang3.StringUtils.isBlank
41
42 /**
43  * This groovy class supports the <class>DoDeleteSliceService.bpmn</class> process.
44  *
45  * Inputs:
46  * @param - msoRequestId
47  * @param - globalSubscriberId - O
48  * @param - subscriptionServiceType - O
49  * @param - serviceInstanceId
50  *
51  */
52 class DoDeleteSliceService extends AbstractServiceTaskProcessor {
53     private final String PREFIX ="DoDeleteSliceService"
54     ExceptionUtil exceptionUtil = new ExceptionUtil()
55     private static final Logger LOGGER = LoggerFactory.getLogger( DoDeleteSliceService.class)
56
57     @Override
58     void preProcessRequest(DelegateExecution execution) {
59         LOGGER.debug(" *****${PREFIX} preProcessRequest *****")
60         String msg = ""
61
62         try {
63             //String requestId = execution.getVariable("msoRequestId")
64             execution.setVariable("prefix",PREFIX)
65
66             //Inputs
67             //requestDetails.subscriberInfo. for AAI GET & PUT
68              execution.getVariable("globalSubscriberId") ?: execution.setVariable("globalSubscriberId", "")
69
70             //requestDetails.requestParameters. for AAI PUT
71             execution.getVariable("serviceType") ?: execution.setVariable("serviceType", "")
72
73             //Generated in parent for AAI PUT
74             String serviceInstanceId = execution.getVariable("serviceInstanceId")
75             if (isBlank(serviceInstanceId)){
76                 msg = "Input serviceInstanceId is null"
77                 LOGGER.info(msg)
78                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
79             }
80         } catch (BpmnError e) {
81             throw e
82         } catch (Exception ex){
83             msg = "Exception in preProcessRequest " + ex.getMessage()
84             LOGGER.error(msg)
85             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
86         }
87         LOGGER.debug("*****${PREFIX} Exit preProcessRequest *****")
88     }
89
90     /**
91      * query E2ESliceService from AAI
92      * save snssai
93      * @param execution
94      */
95     void queryE2ESliceSeriveFromAAI(DelegateExecution execution)
96     {
97         LOGGER.trace(" *****${PREFIX} Start queryE2ESliceSeriveFromAAI *****")
98         String serviceInstanceId = execution.getVariable("serviceInstanceId")
99
100         String errorMsg = "query e2e slice service from aai failed"
101         AAIResultWrapper wrapper = queryAAI(execution, AAIObjectType.SERVICE_INSTANCE, serviceInstanceId, errorMsg)
102         Optional<ServiceInstance> si =wrapper.asBean(ServiceInstance.class)
103         if(si.isPresent())
104         {
105             String snssai = si.get()?.getEnvironmentContext()
106             execution.setVariable("snssai", snssai ?: "")
107             LOGGER.info("serviceInstanceId: ${serviceInstanceId}, snssai: ${snssai}")
108         }
109         LOGGER.trace(" *****${PREFIX} Exit queryE2ESliceSeriveFromAAI *****")
110     }
111
112     /**
113      * get allotted resource from AAI
114      * save nsi id
115      * @param execution
116      */
117     void getAllottedResFromAAI(DelegateExecution execution)
118     {
119         LOGGER.trace(" *****${PREFIX} Start getAllottedResFromAAI *****")
120         String serviceInstanceId = execution.getVariable("serviceInstanceId")
121         try
122         {
123             String errorMsg = "query allotted resource from aai failed."
124             AAIResultWrapper wrapper = queryAAI(execution, AAIObjectType.ALLOTTED_RESOURCE_ALL, serviceInstanceId, errorMsg)
125             Optional<AllottedResources> ars = wrapper?.asBean(AllottedResources.class)
126             if(ars.isPresent() && ars.get().getAllottedResource())
127             {
128                 List<AllottedResource> allottedResourceList = ars.get().getAllottedResource()
129                 AllottedResource ar = allottedResourceList.first()
130                 String relatedLink = ar?.getRelationshipList()?.getRelationship()?.first()?.getRelatedLink()
131                 String nsiId = relatedLink ? relatedLink.substring(relatedLink.lastIndexOf("/") + 1,relatedLink.length()) : ""
132                 execution.setVariable("nsiId", nsiId)
133                 LOGGER.info("serviceInstanceId: ${serviceInstanceId}, nsiId:${nsiId}")
134             }
135         }
136         catch(BpmnError e){
137             throw e
138         }
139         catch (Exception ex){
140             String msg = "Exception in getAllottedResFromAAI " + ex.getMessage()
141             LOGGER.error(msg)
142             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
143         }
144         LOGGER.trace(" *****${PREFIX} Exit getAllottedResFromAAI *****")
145     }
146
147     /**
148      * get nsi service instance from aai
149      * save nssi id
150      * @param execution
151      */
152     void getNSIFromAAI(DelegateExecution execution)
153     {
154         LOGGER.trace(" *****${PREFIX} Start getNSIFromAAI *****")
155         String nsiId = execution.getVariable("nsiId")
156         try
157         {
158             String errorMsg = "query nsi from aai failed."
159             AAIResultWrapper wrapper = queryAAI(execution, AAIObjectType.SERVICE_INSTANCE, nsiId, errorMsg)
160             Optional<ServiceInstance> si =wrapper.asBean(ServiceInstance.class)
161             List<String> nssiIdList = []
162             String msg = "nsiId:${nsiId},nssiIdList:"
163             if(si.isPresent())
164             {
165                 List<Relationship> relationshipList = si.get().getRelationshipList()?.getRelationship()
166                 for (Relationship relationship : relationshipList)
167                 {
168                     String relatedTo = relationship.getRelatedTo()
169                     if (relatedTo == "service-instance")
170                     {
171                         String relatedLink = relationship.getRelatedLink()?:""
172                         String nssiId = relatedLink ? relatedLink.substring(relatedLink.lastIndexOf("/") + 1,relatedLink.length()) : ""
173                         nssiIdList.add(nssiId)
174                         msg+="${nssiId}, "
175                     }
176                 }
177             }
178             LOGGER.info(msg)
179             execution.setVariable("nssiIdList", nssiIdList)
180         }
181         catch(BpmnError e){
182             throw e
183         }
184         catch (Exception ex){
185             String msg = "Exception in getNSIFromAAI " + ex.getMessage()
186             LOGGER.error(msg)
187             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
188         }
189         LOGGER.trace(" *****${PREFIX} Exit getNSIFromAAI *****")
190     }
191
192     /**
193      * get nssi service from AAI
194      * prepare list
195      * @param execution
196      */
197     void getNSSIListFromAAI(DelegateExecution execution)
198     {
199         LOGGER.trace("*****${PREFIX} Start getNSSIListFromAAI *****")
200         List<String> nssiIdList = execution.getVariable("nssiIdList")
201         List<ServiceInstance> nssiInstanceList = []
202         String errorMsg = "query nssi list from aai failed"
203         for(String nssiId : nssiIdList)
204         {
205             AAIResultWrapper wrapper = queryAAI(execution, AAIObjectType.SERVICE_INSTANCE, nssiId, errorMsg)
206             Optional<ServiceInstance> si =wrapper.asBean(ServiceInstance.class)
207             if(si.isPresent())
208             {
209                 nssiInstanceList.add(si.get())
210             }
211         }
212         int size = nssiInstanceList.size()
213         int proportion = size >0 ?((90/size) as int) : 90
214         execution.setVariable("nssiInstanceList", nssiInstanceList)
215         execution.setVariable("currentNSSIIndex", 0)
216         execution.setVariable("proportion", proportion)
217         String msg ="nssiInstanceList size: ${nssiInstanceList.size()}, proportion:${proportion}"
218         LOGGER.info(msg)
219         LOGGER.trace(" *****${PREFIX} Exit getNSSIListFromAAI *****")
220     }
221
222     /**
223      * get current NSSI
224      * @param execution
225      */
226     void getCurrentNSSI(DelegateExecution execution)
227     {
228         LOGGER.trace(" *****${PREFIX} Start getCurrentNSSI *****")
229         List<ServiceInstance> nssiInstanceList = execution.getVariable("nssiInstanceList")
230         int currentIndex = execution.getVariable("currentNSSIIndex") as int
231         ServiceInstance nssi = nssiInstanceList?.get(currentIndex)
232         def currentNSSI = [:]
233         currentNSSI['nssiServiceInstanceId'] = nssi?.getServiceInstanceId()
234         currentNSSI['modelInvariantId'] = nssi?.getModelInvariantId()
235         currentNSSI['modelVersionId'] = nssi?.getModelVersionId()
236         currentNSSI['snssai'] = execution.getVariable("snssai") ?: ""
237         currentNSSI['nsiServiceInstanceId'] = execution.getVariable("nsiId") ?: ""
238         currentNSSI['operationId'] = execution.getVariable("operationId") ?: ""
239         currentNSSI['e2eServiceInstanceId'] = execution.getVariable("serviceInstanceId") ?: ""
240         currentNSSI['msoRequestId'] = execution.getVariable("msoRequestId") ?: ""
241         currentNSSI['globalSubscriberId'] = execution.getVariable("globalSubscriberId") ?: ""
242         currentNSSI['serviceType'] = execution.getVariable("serviceType") ?: ""
243         currentNSSI['serviceModelInfo'] = execution.getVariable("serviceModelInfo") ?: ""
244         currentNSSI['proportion'] = (execution.getVariable("proportion") as int)*(currentIndex+1)
245         execution.setVariable("currentNSSI", currentNSSI)
246         String msg = "Now we deal with nssiServiceInstanceId: ${currentNSSI['nssiServiceInstanceId']}, current Index: ${currentIndex}, current proportion:${currentNSSI['proportion']}"
247         LOGGER.info(msg)
248         LOGGER.trace(" *****${PREFIX} Exit getCurrentNSSI *****")
249     }
250
251     /**
252      * parse next nssi
253      * @param execution
254      */
255     void parseNextNSSI(DelegateExecution execution)
256     {
257         LOGGER.trace(" *****${PREFIX} Start parseNextNSSI *****")
258         if(execution.getVariable("WorkflowException") != null){
259             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "current job failure!")
260         }
261         def currentIndex = execution.getVariable("currentNSSIIndex")
262         List<ServiceInstance> nssiInstanceList = execution.getVariable("nssiInstanceList")
263         def nextIndex = ++currentIndex
264         LOGGER.info("nextIndex: ${nextIndex}")
265         if(nextIndex >= nssiInstanceList.size()){
266             execution.setVariable("isAllNSSIFinished", "true")
267         }else{
268             execution.setVariable("isAllNSSIFinished", "false")
269             execution.setVariable("currentNSSIIndex", nextIndex)
270         }
271         LOGGER.trace(" *****${PREFIX} Exit parseNextNSSI *****")
272     }
273
274
275     /**
276      * query sliceProfile from AAI
277      * save profileId
278      * @param execution
279      */
280     void querySliceProfileFromAAI(DelegateExecution execution)
281     {
282         LOGGER.trace(" *****${PREFIX} Start querySliceProfileFromAAI *****")
283         def currentNSSI = execution.getVariable("currentNSSI")
284         String nssiId = currentNSSI['nssiServiceInstanceId']
285         String errorMsg = "query slice profile failed"
286         AAIResultWrapper wrapper = queryAAI(execution, AAIObjectType.SLICE_PROFILE_ALL, nssiId, errorMsg)
287         Optional<SliceProfiles> sliceProfiles =wrapper.asBean(SliceProfiles.class)
288         if(sliceProfiles.isPresent())
289         {
290             String profileId = sliceProfiles.get().getSliceProfile()?.get(0)?.getProfileId()
291             currentNSSI['profileId'] =  profileId ?: ""
292             LOGGER.info("nssiId: ${nssiId}, profileId: ${profileId}")
293         }
294         execution.setVariable("currentNSSI", currentNSSI)
295         LOGGER.trace(" *****${PREFIX} Exit querySliceProfileFromAAI *****")
296     }
297
298     /**
299      * query AAI
300      * @param execution
301      * @param aaiObjectType
302      * @param instanceId
303      * @return AAIResultWrapper
304      */
305     private AAIResultWrapper queryAAI(DelegateExecution execution, AAIObjectType aaiObjectType, String instanceId, String errorMsg)
306     {
307         LOGGER.trace(" *****${PREFIX} Start queryAAI *****")
308         String globalSubscriberId = execution.getVariable("globalSubscriberId")
309         String serviceType = execution.getVariable("serviceType")
310
311         AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(aaiObjectType, globalSubscriberId, serviceType, instanceId)
312         if (!getAAIClient().exists(resourceUri)) {
313             exceptionUtil.buildAndThrowWorkflowException(execution, 2500, errorMsg)
314         }
315         AAIResultWrapper wrapper = getAAIClient().get(resourceUri, NotFoundException.class)
316         LOGGER.trace(" *****${PREFIX} Exit queryAAI *****")
317         return wrapper
318     }
319
320 }