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