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