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