remove multiline strings with A&AI client
[so.git] / bpmn / MSOCommonBPMN / src / main / groovy / org / onap / so / bpmn / common / scripts / SniroHomingV1.groovy
1 /*
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. 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.common.scripts
22
23 import org.camunda.bpm.engine.delegate.BpmnError
24 import org.camunda.bpm.engine.delegate.DelegateExecution
25
26 import org.onap.so.bpmn.common.scripts.AaiUtil
27 import org.onap.so.bpmn.common.scripts.ExceptionUtil
28 import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils
29 import org.onap.so.bpmn.core.UrnPropertiesReader
30 import org.onap.so.bpmn.core.domain.InventoryType
31 import org.onap.so.bpmn.core.domain.Resource
32 import org.onap.so.bpmn.core.domain.ServiceDecomposition
33 import org.onap.so.bpmn.core.domain.Subscriber
34 import org.onap.so.bpmn.core.domain.VnfResource
35 import org.onap.so.bpmn.core.json.JsonUtils
36 import org.onap.so.client.HttpClient
37 import org.onap.so.utils.TargetEntity
38 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
39
40 import org.json.JSONArray
41 import org.json.JSONObject
42
43 import static org.onap.so.bpmn.common.scripts.GenericUtils.*;
44
45 import java.net.URL
46
47 import javax.ws.rs.core.Response
48 import org.onap.so.logger.MessageEnum
49 import org.onap.so.logger.MsoLogger
50
51
52 /**
53  * This class is contains the scripts used
54  * by the Homing Subflow building block. The
55  * subflow attempts to home the provided
56  * resources by calling sniro.
57  *
58  * @author cb645j
59  *
60  */
61 class SniroHomingV1 extends AbstractServiceTaskProcessor{
62
63         private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, SniroHomingV1.class);
64         ExceptionUtil exceptionUtil = new ExceptionUtil()
65         JsonUtils jsonUtil = new JsonUtils()
66         SniroUtils sniroUtils = new SniroUtils(this)
67
68         /**
69          * This method validates the incoming variables.
70          * The method then prepares the sniro request
71          * and posts it to sniro's rest api.
72          *
73          * @param execution
74          *
75          * @author cb645j
76          */
77         public void callSniro(DelegateExecution execution){
78                 execution.setVariable("prefix","HOME_")
79                 msoLogger.trace("Started Sniro Homing Call Sniro ")
80                 try{
81                         execution.setVariable("rollbackData", null)
82                         execution.setVariable("rolledBack", false)
83
84                         String requestId = execution.getVariable("msoRequestId")
85                         msoLogger.debug("Incoming Request Id is: "  + requestId)
86                         String serviceInstanceId = execution.getVariable("serviceInstanceId")
87                         msoLogger.debug("Incoming Service Instance Id is: "  + serviceInstanceId)
88                         ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
89                         msoLogger.debug("Incoming Service Decomposition is: "  + serviceDecomposition)
90                         String subscriberInfo = execution.getVariable("subscriberInfo")
91                         msoLogger.debug("Incoming Subscriber Information is: "  + subscriberInfo)
92
93                         if(isBlank(requestId) || isBlank(serviceInstanceId) || isBlank(serviceDecomposition.toString()) || isBlank(subscriberInfo)){
94                                 exceptionUtil.buildAndThrowWorkflowException(execution, 4000, "A required input variable is missing or null")
95                         }else{
96                                 String subId = jsonUtil.getJsonValue(subscriberInfo, "globalSubscriberId")
97                                 String subName = jsonUtil.getJsonValue(subscriberInfo, "subscriberName")
98                                 String subCommonSiteId = ""
99                                 if(jsonUtil.jsonElementExist(subscriberInfo, "subscriberCommonSiteId")){
100                                         subCommonSiteId = jsonUtil.getJsonValue(subscriberInfo, "subscriberCommonSiteId")
101                                 }
102                                 Subscriber subscriber = new Subscriber(subId, subName, subCommonSiteId)
103
104                                 String cloudConfiguration = execution.getVariable("cloudConfiguration") // TODO Currently not being used
105                                 String homingParameters = execution.getVariable("homingParameters") // (aka. request parameters) Should be json format. TODO confirm its json format
106
107                                 //Authentication
108                                 String authHeader = UrnPropertiesReader.getVariable("sniro.manager.headers.auth", execution)
109                                 execution.setVariable("BasicAuthHeaderValue", authHeader)
110
111                                 //Prepare Callback
112                                 String timeout = execution.getVariable("timeout")
113                                 if(isBlank(timeout)){
114                                         timeout = UrnPropertiesReader.getVariable("sniro.manager.timeout", execution)
115                                         if(isBlank(timeout)) {
116                                                 timeout = "PT30M";
117                                         }
118                                 }
119                                 msoLogger.debug("Async Callback Timeout will be: " + timeout)
120
121                                 execution.setVariable("timeout", timeout);
122                                 execution.setVariable("correlator", requestId);
123                                 execution.setVariable("messageType", "SNIROResponse");
124
125                                 //Build Request & Call Sniro
126                                 String sniroRequest = sniroUtils.buildRequest(execution, requestId, serviceDecomposition, subscriber, homingParameters)
127                                 execution.setVariable("sniroRequest", sniroRequest)
128                                 msoLogger.debug("SNIRO Request is: " + sniroRequest)
129
130                                 String endpoint = UrnPropertiesReader.getVariable("sniro.manager.uri.v1", execution)
131                                 String host = UrnPropertiesReader.getVariable("sniro.manager.host", execution)
132                                 String urlString = host + endpoint
133                                 msoLogger.debug("Sniro Url is: " + urlString)
134
135                                 URL url = new URL(urlString);
136                                 HttpClient httpClient = new HttpClient(url, "application/json", TargetEntity.SNIRO)
137                                 httpClient.addAdditionalHeader("Authorization", authHeader)
138                                 Response httpResponse = httpClient.post(sniroRequest)
139
140                                 int responseCode = httpResponse.getStatus()
141
142                                 msoLogger.debug("Sniro sync response code is: " + responseCode)
143                                 if(httpResponse.hasEntity()){
144                                         msoLogger.debug("Sniro sync response is: " + httpResponse.readEntity(String.class))
145                                 }
146
147                                 if(responseCode != 202){
148                                         exceptionUtil.buildAndThrowWorkflowException(execution, responseCode, "Received a Bad Sync Response from Sniro.")
149                                 }
150
151                                 msoLogger.trace("Completed Sniro Homing Call Sniro")
152                         }
153                 }catch(BpmnError b){
154                         throw b
155                 }catch(Exception e){
156                         msoLogger.debug("Error encountered within Homing CallSniro method: " + e)
157                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in Homing CallSniro: " + e.getMessage())
158                 }
159         }
160
161         /**
162          * This method processes the callback response
163          * and the contained homing solution. It sets
164          * homing solution assignment and license
165          * information to the corresponding resources
166          *
167          * @param execution
168          *
169          * @author cb645j
170          */
171         public void processHomingSolution(DelegateExecution execution){
172                 msoLogger.trace("Started Sniro Homing Process Homing Solution")
173                 try{
174                         String response = execution.getVariable("asyncCallbackResponse")
175                         msoLogger.debug("Sniro Async Callback Response is: " + response)
176
177                         sniroUtils.validateCallbackResponse(execution, response)
178
179                         ServiceDecomposition decomposition = execution.getVariable("serviceDecomposition")
180                         List<Resource> resourceList = decomposition.getServiceResources()
181
182                         if(JsonUtils.jsonElementExist(response, "solutionInfo.placementInfo")){
183                                 String placements = jsonUtil.getJsonValue(response, "solutionInfo.placementInfo")
184                                 JSONArray arr = new JSONArray(placements)
185                                 for(int i = 0; i < arr.length(); i++){
186                                         JSONObject placement = arr.getJSONObject(i)
187                                         String jsonServiceResourceId = placement.getString("serviceResourceId")
188                                         for(Resource resource:resourceList){
189                                                 String serviceResourceId = resource.getResourceId()
190                                                 if(serviceResourceId.equalsIgnoreCase(jsonServiceResourceId)){
191                                                         //match
192                                                         String inventoryType = placement.getString("inventoryType")
193                                                         resource.getHomingSolution().setInventoryType(InventoryType.valueOf(inventoryType))
194                                                         resource.getHomingSolution().setCloudRegionId(placement.getString("cloudRegionId"))
195                                                         resource.getHomingSolution().setRehome(placement.getBoolean("isRehome"))
196                                                         JSONArray assignmentArr = placement.getJSONArray("assignmentInfo")
197                                                         Map<String, String> assignmentMap = jsonUtil.entryArrayToMap(execution, assignmentArr.toString(), "variableName", "variableValue")
198                                                         resource.getHomingSolution().setCloudOwner(assignmentMap.get("cloudOwner"))
199                                                         resource.getHomingSolution().setAicClli(assignmentMap.get("aicClli"))
200                                                         resource.getHomingSolution().setAicVersion(assignmentMap.get("aicVersion"))
201                                                         if(inventoryType.equalsIgnoreCase("service")){
202                                                                 VnfResource vnf = new VnfResource()
203                                                                 vnf.setVnfHostname(assignmentMap.get("vnfHostName"))
204                                                                 resource.getHomingSolution().setVnf(vnf)
205                                                                 resource.getHomingSolution().setServiceInstanceId(placement.getString("serviceInstanceId"))
206                                                         }
207                                                 }
208                                         }
209                                 }
210                         }
211
212                         if(JsonUtils.jsonElementExist(response, "solutionInfo.licenseInfo")){
213                                 String licenseInfo = jsonUtil.getJsonValue(response, "solutionInfo.licenseInfo")
214                                 JSONArray licenseArr = new JSONArray(licenseInfo)
215                                 for(int l = 0; l < licenseArr.length(); l++){
216                                         JSONObject license = licenseArr.getJSONObject(l)
217                                         String jsonServiceResourceId = license.getString("serviceResourceId")
218                                         for(Resource resource:resourceList){
219                                                 String serviceResourceId = resource.getResourceId()
220                                                 if(serviceResourceId.equalsIgnoreCase(jsonServiceResourceId)){
221                                                         //match
222                                                         String jsonEntitlementPoolList = jsonUtil.getJsonValue(license.toString(), "entitlementPoolList")
223                                                         List<String> entitlementPoolList = jsonUtil.StringArrayToList(execution, jsonEntitlementPoolList)
224                                                         resource.getHomingSolution().getLicense().setEntitlementPoolList(entitlementPoolList)
225
226                                                         String jsonLicenseKeyGroupList = jsonUtil.getJsonValue(license.toString(), "licenseKeyGroupList")
227                                                         List<String> licenseKeyGroupList = jsonUtil.StringArrayToList(execution, jsonLicenseKeyGroupList)
228                                                         resource.getHomingSolution().getLicense().setLicenseKeyGroupList(licenseKeyGroupList)
229                                                 }
230                                         }
231                                 }
232                         }
233                         execution.setVariable("serviceDecomposition", decomposition)
234
235                         msoLogger.trace("Completed Sniro Homing Process Homing Solution")
236                 }catch(BpmnError b){
237                         throw b
238                 }catch(Exception e){
239                         msoLogger.debug("Error encountered within Homing ProcessHomingSolution method: " + e)
240                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in Sniro Homing Process Solution")
241                 }
242         }
243
244         /**
245          * This method logs the start of DHVCreateService
246          * to make debugging easier.
247          *
248          * @param - execution
249          * @author cb645j
250          */
251         public String logStart(DelegateExecution execution){
252                 String requestId = execution.getVariable("testReqId")
253                 if(isBlank(requestId)){
254                         requestId = execution.getVariable("msoRequestId")
255                 }
256                 execution.setVariable("DHVCS_requestId", requestId)
257                 msoLogger.trace("STARTED Homing Subflow for request: "  + requestId + " ")
258                 msoLogger.debug("****** Homing Subflow Global Debug Enabled: " + execution.getVariable("isDebugLogEnabled")  + " *****")
259                 msoLogger.trace("STARTED Homing Subflow for request: "  + requestId + " ")
260         }
261
262
263         /**
264          * Auto-generated method stub
265          */
266         public void preProcessRequest(DelegateExecution execution){}
267
268 }