d0967cc327abbe9e444768c2853ecca7c3ba721c
[so.git] / bpmn / MSOCommonBPMN / src / main / groovy / org / onap / so / bpmn / common / scripts / AllottedResourceUtils.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Modifications Copyright (c) 2019 Samsung
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.so.bpmn.common.scripts
24
25 import org.onap.so.client.aai.entities.AAIResultWrapper
26
27 import static org.apache.commons.lang3.StringUtils.isBlank;
28
29 import javax.ws.rs.NotFoundException
30 import javax.ws.rs.core.UriBuilder
31
32 import org.apache.commons.lang.StringUtils
33 import org.camunda.bpm.engine.delegate.BpmnError
34 import org.camunda.bpm.engine.delegate.DelegateExecution
35 import org.onap.aai.domain.yang.AllottedResource
36 import org.onap.so.bpmn.core.WorkflowException
37 import org.onap.so.client.PreconditionFailedException
38 import org.onap.so.client.aai.AAIObjectType
39 import org.onap.so.client.aai.AAIResourcesClient
40 import org.onap.so.client.aai.entities.uri.AAIResourceUri
41 import org.onap.so.client.aai.entities.uri.AAIUriFactory
42 import org.onap.so.logger.MessageEnum
43 import org.onap.so.logger.MsoLogger
44 import org.slf4j.Logger
45 import org.slf4j.LoggerFactory
46
47
48
49 class AllottedResourceUtils {
50     private static final Logger logger = LoggerFactory.getLogger( AllottedResourceUtils.class);
51
52
53         private AbstractServiceTaskProcessor taskProcessor
54         ExceptionUtil exceptionUtil = new ExceptionUtil()
55         MsoUtils utils;
56
57         public AllottedResourceUtils(AbstractServiceTaskProcessor taskProcessor) {
58                 this.taskProcessor = taskProcessor
59                 this.utils = taskProcessor.utils
60         }
61
62         /*Used on Create - called from DoCreate
63         * Using Consuming ServiceInstanceId get related Allotted Resources Orchestration status from AAI
64         * 1) get related AR links for CSI 2) get AR from AR links
65         * return: null -> AR Not found
66         * return: " " -> AR found with empty orchStatus
67         * return: orchStatus - > AR found with this orchStatus
68         * setsVariable aaiARGetResponse
69         */
70         public String getAROrchStatus (DelegateExecution execution) {
71
72                 logger.trace("getAROrchStatus ")
73                 String msg = ""
74                 String serviceInstanceId = execution.getVariable("serviceInstanceId")
75                 String arType = execution.getVariable("allottedResourceType")
76                 String arRole = execution.getVariable("allottedResourceRole")
77                 String siXml = execution.getVariable("CSI_service")
78                 String orchStatus = null
79                 XmlParser xmlParser = new XmlParser()
80                 logger.debug("getAROrchStatus siXml:" + siXml)
81                 try {
82                         if (!isBlank(siXml)) {
83                                 def groovy.util.Node siNode = xmlParser.parseText(siXml)
84                                 def groovy.util.Node relationshipList = utils.getChildNode(siNode, 'relationship-list')
85                                 if (relationshipList != null) {
86                                         def groovy.util.NodeList relationships = utils.getIdenticalChildren(relationshipList, 'relationship')
87                                         for (groovy.util.Node relationship in relationships) {
88                                                 def groovy.util.Node relatedTo = utils.getChildNode(relationship, 'related-to')
89                                                 if ((relatedTo != null) && (relatedTo.text().equals('allotted-resource'))) {
90                                                         logger.debug("getARORchStatus AR found")
91                                                         def groovy.util.Node relatedLink = utils.getChildNode(relationship, 'related-link')
92                                                         if (relatedLink != null){
93                                                                 Optional<AllottedResource> ar = getARbyLink(execution, relatedLink.text(), arRole)
94                                                                 if (ar.isPresent()){
95                                                                         orchStatus = execution.getVariable("aaiAROrchStatus")
96                                                                         break
97                                                                 }
98                                                         }
99                                                 }
100                                         }
101                                 }
102                         }
103                 }catch(Exception e){
104                         logger.debug(" Error encountered in getAROrchStatus" + e.getMessage())
105                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error in getAROrchStatus" + e.getMessage())
106                 }
107                 logger.trace(" Exit getAROrchStatus - OrchStatus:" + orchStatus)
108                 return orchStatus
109         }
110
111         // get Allotted Resource by AllottedResourceId
112         // used on Delete - called from doDeleteAR
113         // setsVariable aaiARGetResponse
114         public boolean ifExistsAR(DelegateExecution execution, String allottedResourceId) {
115                 logger.trace("ifExistsAR ")
116                 try {
117                         AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.ALLOTTED_RESOURCE, allottedResourceId)
118             AAIResultWrapper wrapper = getAAIClient().get(resourceUri)
119             Optional<AllottedResource> allottedResource = wrapper.asBean(AllottedResource.class)
120             if(allottedResource.isPresent()) {
121                 setExecutionVariables(execution , allottedResource.get(),resourceUri)
122                 return true
123             }else {
124                 return false
125             }
126                 }catch(Exception e){
127                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error in ifExistsAR" + e.getMessage())
128                 }
129         }
130
131         public String getPSIFmARLink(DelegateExecution execution, String arLink)
132         {
133                 // Path: /aai/{version}/business/customers/customer/{cust}/service-subscriptions/service-subscription/{subs}/service-instances/service-instance/{psiid}/allotted-resources/allotted-resource/{arid}
134                 logger.trace(" getPSIFmARLink - path:" + arLink)
135                 String[] split = arLink.split("/service-instance/")
136                 String[] splitB =  split[1].split("/allotted-resources/")
137                 String siId = splitB[0]
138                 logger.trace(" Exit getPSIFmARLink - parentServiceInstanceId:" + siId )
139                 return siId
140         }
141
142         // get Allotted resource using Link
143         // used on Create called from getARORchStatus
144         // used on Delete called from ifExistsAR
145         // setsVariable aaiARPath - used for Patch in create
146
147         public Optional<AllottedResource> getARbyLink (DelegateExecution execution, String link, String role) {
148                 logger.trace("getARbyLink ")
149                 Optional<AllottedResource> allottedResource = Optional.empty()
150                 try {
151                         logger.debug("GET AR Aai Path is: \n" + link)
152                         AAIResourceUri uri = AAIUriFactory.createResourceFromExistingURI(AAIObjectType.ALLOTTED_RESOURCE, UriBuilder.fromPath(link).build())
153                         allottedResource = getAAIClient().get(AllottedResource.class,uri);
154                         if(allottedResource.isPresent()) {
155                                 if (!isBlank(role)) {
156                                         if (role == allottedResource.get().getRole()) {
157                                                 setExecutionVariables(execution,allottedResource.get(),uri)
158                                         } else {
159                                                 logger.debug("AAI AR does not match input role:" + role)
160                                         }
161                                 } else {
162                                         setExecutionVariables(execution,allottedResource.get(),uri)
163                                 }
164                         }else{
165                                 logger.debug("GET AR received a Not Found (404) Response")
166                         }
167                 }catch(Exception e){
168                         logger.debug(" Error encountered within GetAaiAR" + e.getMessage())
169                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error in GetAaiAR" + e.getMessage())
170                 }
171                 return allottedResource
172         }
173
174         public void setExecutionVariables(DelegateExecution execution, AllottedResource ar, AAIResourceUri arUrl) {
175                 execution.setVariable("aaiARGetResponse", ar)
176                 execution.setVariable("aaiARPath", arUrl.build().toString())
177                 execution.setVariable("aaiARResourceVersion", ar.getResourceVersion())
178                 if (StringUtils.isNotEmpty(ar.getOrchestrationStatus())) {
179                         execution.setVariable("aaiAROrchStatus", ar.getOrchestrationStatus())
180                 }
181                 else
182                 {
183                         execution.setVariable("aaiAROrchStatus", " ")
184                 }
185         }
186
187         public void updateAROrchStatus(DelegateExecution execution, String status, String aaiARPath){
188                 logger.trace("updaAROrchStatus ")
189                 try{
190
191                         AllottedResource allottedResource = new AllottedResource();
192                         allottedResource.setOrchestrationStatus(status)
193                         logger.debug('AAI AR URI: ' + aaiARPath)
194
195                         AAIResourceUri uri = AAIUriFactory.createResourceFromExistingURI(AAIObjectType.ALLOTTED_RESOURCE, UriBuilder.fromPath(aaiARPath).build())
196                         getAAIClient().update(uri,allottedResource)
197                 }catch(Exception e){
198                         logger.error("{} {} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
199                                         "Exception in updateAR.", "BPMN", MsoLogger.getServiceName(),
200                                         MsoLogger.ErrorCode.UnknownError.getValue(), e.getMessage());
201                         exceptionUtil.buildAndThrowWorkflowException(execution, 500, 'Internal Error in updateAROrchStatus.' + e.getMessage())
202                 }
203                 logger.trace("Exit updateAROrchStatus ")
204         }
205
206         //Sets Variable "wasDeleted"
207         public void deleteAR(DelegateExecution execution, String aaiARPath){
208                 logger.trace(" deleteAR - aaiARPath:" + aaiARPath)
209                 try {
210
211                         AAIResourceUri uri = AAIUriFactory.createResourceFromExistingURI(AAIObjectType.ALLOTTED_RESOURCE, UriBuilder.fromPath(aaiARPath).build())
212                         getAAIClient().delete(uri);
213                 }catch(NotFoundException ex){
214                         logger.debug("  Delete AR Received a Not Found (404) Response")
215                 }catch(PreconditionFailedException ex){
216                         logger.debug("Delete AR Received a Resource Version Mismatch Error: \n")
217                         exceptionUtil.buildAndThrowWorkflowException(execution, 412, "DeleteAR Received a resource-version Mismatch Error Response from AAI")
218                 }catch(Exception e){
219                         logger.debug(" Error encountered in deleteAR!" + e)
220                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured During Delete AR")
221                 }
222                 logger.debug("  Delete AR Received a Good Response")
223                 execution.setVariable("wasDeleted", "true")
224                 logger.trace("Exit deleteAR ")
225         }
226
227         public void buildAAIErrorResponse(DelegateExecution execution, String response, String errorMessage){
228                 logger.trace("BuildAAIErrorResponse")
229
230                 if((response != null) && (response.contains("Fault") || response.contains("RESTFault"))){
231                         WorkflowException workflowException = exceptionUtil.MapAAIExceptionToWorkflowException(response, execution)
232                         execution.setVariable("WorkflowException", workflowException)
233                 }else{
234                         exceptionUtil.buildWorkflowException(execution, 500, errorMessage)
235                 }
236
237                 logger.trace("Exit BuildAAIErrorResponse Process")
238                 throw new BpmnError("MSOWorkflowException")
239         }
240
241         public  AAIResourcesClient getAAIClient(){
242                 return new AAIResourcesClient()
243         }
244
245 }