f7aff0eff44d3842d4938649346b948bb33d96d6
[clamp.git] / src / main / java / org / onap / clamp / clds / client / DcaeDispatcherServices.java
1 /*-\r
2  * ============LICENSE_START=======================================================\r
3  * ONAP CLAMP\r
4  * ================================================================================\r
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights\r
6  *                             reserved.\r
7  * ================================================================================\r
8  * Modifications Copyright (c) 2019 Samsung\r
9  * ================================================================================\r
10  * Licensed under the Apache License, Version 2.0 (the "License");\r
11  * you may not use this file except in compliance with the License.\r
12  * You may obtain a copy of the License at\r
13  *\r
14  * http://www.apache.org/licenses/LICENSE-2.0\r
15  *\r
16  * Unless required by applicable law or agreed to in writing, software\r
17  * distributed under the License is distributed on an "AS IS" BASIS,\r
18  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
19  * See the License for the specific language governing permissions and\r
20  * limitations under the License.\r
21  * ============LICENSE_END============================================\r
22  * ===================================================================\r
23  *\r
24  */\r
25 \r
26 package org.onap.clamp.clds.client;\r
27 \r
28 import com.att.eelf.configuration.EELFLogger;\r
29 import com.att.eelf.configuration.EELFManager;\r
30 \r
31 import com.google.gson.JsonObject;\r
32 import java.io.IOException;\r
33 import java.util.Date;\r
34 \r
35 import org.json.simple.JSONObject;\r
36 import org.json.simple.parser.JSONParser;\r
37 import org.json.simple.parser.ParseException;\r
38 import org.onap.clamp.clds.config.ClampProperties;\r
39 import org.onap.clamp.clds.exception.dcae.DcaeDeploymentException;\r
40 import org.onap.clamp.clds.util.LoggingUtils;\r
41 import org.onap.clamp.util.HttpConnectionManager;\r
42 import org.springframework.beans.factory.annotation.Autowired;\r
43 import org.springframework.stereotype.Component;\r
44 \r
45 /**\r
46  * This class implements the communication with DCAE for the service\r
47  * deployments.\r
48  */\r
49 @Component\r
50 public class DcaeDispatcherServices {\r
51 \r
52     protected static final EELFLogger logger = EELFManager.getInstance().getLogger(DcaeDispatcherServices.class);\r
53     protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();\r
54     private final ClampProperties refProp;\r
55     private final HttpConnectionManager dcaeHttpConnectionManager;\r
56     private static final String STATUS_URL_LOG = "Status URL extracted: ";\r
57     private static final String DCAE_URL_PREFIX = "/dcae-deployments/";\r
58     private static final String DCAE_URL_PROPERTY_NAME = "dcae.dispatcher.url";\r
59     private static final String DCAE_LINK_FIELD = "links";\r
60     private static final String DCAE_STATUS_FIELD = "status";\r
61 \r
62     @Autowired\r
63     public DcaeDispatcherServices(ClampProperties refProp, HttpConnectionManager dcaeHttpConnectionManager) {\r
64         this.refProp = refProp;\r
65         this.dcaeHttpConnectionManager = dcaeHttpConnectionManager;\r
66     }\r
67 \r
68     /**\r
69      * Get the Operation Status from a specified URL with retry.\r
70      * @param operationStatusUrl\r
71      *        The URL of the DCAE\r
72      * @return The status\r
73      * @throws InterruptedException Exception during the retry\r
74      */\r
75     public String getOperationStatusWithRetry(String operationStatusUrl) throws InterruptedException {\r
76         String operationStatus = "";\r
77         for (int i = 0; i < Integer.valueOf(refProp.getStringValue("dcae.dispatcher.retry.limit")); i++) {\r
78             logger.info("Trying to get Operation status on DCAE for url:" + operationStatusUrl);\r
79             operationStatus = getOperationStatus(operationStatusUrl);\r
80             logger.info("Current Status is:" + operationStatus);\r
81             if (!"processing".equalsIgnoreCase(operationStatus)) {\r
82                 return operationStatus;\r
83             } else {\r
84                 Thread.sleep(Integer.valueOf(refProp.getStringValue("dcae.dispatcher.retry.interval")));\r
85             }\r
86         }\r
87         logger.warn("Number of attempts on DCAE is over, stopping the getOperationStatus method");\r
88         return operationStatus;\r
89     }\r
90 \r
91     /**\r
92      * Get the Operation Status from a specified URL.\r
93      * @param statusUrl\r
94      *        The URL provided by a previous DCAE Query\r
95      * @return The status\r
96      */\r
97     public String getOperationStatus(String statusUrl) {\r
98         // Assigning processing status to monitor operation status further\r
99         String opStatus = "processing";\r
100         Date startTime = new Date();\r
101         LoggingUtils.setTargetContext("DCAE", "getOperationStatus");\r
102         try {\r
103             String responseStr = dcaeHttpConnectionManager.doHttpRequest(statusUrl, "GET", null,\r
104                                                                          null, "DCAE", null,\r
105                                                                          null);\r
106             JSONObject jsonObj = parseResponse(responseStr);\r
107             String operationType = (String) jsonObj.get("operationType");\r
108             String status = (String) jsonObj.get(DCAE_STATUS_FIELD);\r
109             logger.info("Operation Type - " + operationType + ", Status " + status);\r
110             LoggingUtils.setResponseContext("0", "Get operation status success", this.getClass().getName());\r
111             opStatus = status;\r
112         } catch (Exception e) {\r
113             LoggingUtils.setResponseContext("900", "Get operation status failed", this.getClass().getName());\r
114             LoggingUtils.setErrorContext("900", "Get operation status error");\r
115             logger.error("Exception occurred during getOperationStatus Operation with DCAE", e);\r
116         } finally {\r
117             LoggingUtils.setTimeContext(startTime, new Date());\r
118             metricsLogger.info("getOperationStatus complete");\r
119         }\r
120         return opStatus;\r
121     }\r
122 \r
123     /**\r
124      * Returns status URL for createNewDeployment operation.\r
125      * @param deploymentId\r
126      *        The deployment ID\r
127      * @param serviceTypeId\r
128      *        Service type ID\r
129      * @param blueprintInputJson\r
130      *        The value for each blueprint parameters in a flat JSON\r
131      * @return The status URL\r
132      */\r
133     public String createNewDeployment(String deploymentId, String serviceTypeId, JsonObject blueprintInputJson) {\r
134         Date startTime = new Date();\r
135         LoggingUtils.setTargetContext("DCAE", "createNewDeployment");\r
136         try {\r
137             JsonObject rootObject = refProp.getJsonTemplate("dcae.deployment.template").getAsJsonObject();\r
138             rootObject.addProperty("serviceTypeId", serviceTypeId);\r
139             if (blueprintInputJson != null) {\r
140                 rootObject.add("inputs", blueprintInputJson);\r
141             }\r
142             String apiBodyString = rootObject.toString();\r
143             logger.info("Dcae api Body String - " + apiBodyString);\r
144             String url = refProp.getStringValue(DCAE_URL_PROPERTY_NAME) + DCAE_URL_PREFIX + deploymentId;\r
145             String statusUrl = getDcaeResponse(url, "PUT", apiBodyString, "application/json", DCAE_LINK_FIELD,\r
146                 DCAE_STATUS_FIELD);\r
147             LoggingUtils.setResponseContext("0", "Create new deployment failed", this.getClass().getName());\r
148             return statusUrl;\r
149         } catch (Exception e) {\r
150             LoggingUtils.setResponseContext("900", "Create new deployment failed", this.getClass().getName());\r
151             LoggingUtils.setErrorContext("900", "Create new deployment error");\r
152             logger.error("Exception occurred during createNewDeployment Operation with DCAE", e);\r
153             throw new DcaeDeploymentException("Exception occurred during createNewDeployment Operation with DCAE", e);\r
154         } finally {\r
155             LoggingUtils.setTimeContext(startTime, new Date());\r
156             metricsLogger.info("createNewDeployment complete");\r
157         }\r
158     }\r
159 \r
160     /***\r
161      * Returns status URL for deleteExistingDeployment operation.\r
162      *\r
163      * @param deploymentId\r
164      *        The deployment ID\r
165      * @param serviceTypeId\r
166      *        The service Type ID\r
167      * @return The status URL\r
168      */\r
169     public String deleteExistingDeployment(String deploymentId, String serviceTypeId) {\r
170         Date startTime = new Date();\r
171         LoggingUtils.setTargetContext("DCAE", "deleteExistingDeployment");\r
172         try {\r
173             String apiBodyString = "{\"serviceTypeId\": \"" + serviceTypeId + "\"}";\r
174             logger.info("Dcae api Body String - " + apiBodyString);\r
175             String url = refProp.getStringValue(DCAE_URL_PROPERTY_NAME) + DCAE_URL_PREFIX + deploymentId;\r
176             String statusUrl = getDcaeResponse(url, "DELETE", apiBodyString, "application/json", DCAE_LINK_FIELD,\r
177                 DCAE_STATUS_FIELD);\r
178             LoggingUtils.setResponseContext("0", "Delete existing deployment success", this.getClass().getName());\r
179             return statusUrl;\r
180 \r
181         } catch (Exception e) {\r
182             LoggingUtils.setResponseContext("900", "Delete existing deployment failed", this.getClass().getName());\r
183             LoggingUtils.setErrorContext("900", "Delete existing deployment error");\r
184             logger.error("Exception occurred during deleteExistingDeployment Operation with DCAE", e);\r
185             throw new DcaeDeploymentException("Exception occurred during deleteExistingDeployment Operation with DCAE",\r
186                 e);\r
187         } finally {\r
188             LoggingUtils.setTimeContext(startTime, new Date());\r
189             metricsLogger.info("deleteExistingDeployment complete");\r
190         }\r
191     }\r
192 \r
193     private String getDcaeResponse(String url, String requestMethod, String payload, String contentType, String node,\r
194         String nodeAttr) throws IOException, ParseException {\r
195         Date startTime = new Date();\r
196         try {\r
197             String responseStr = dcaeHttpConnectionManager.doHttpRequest(url, requestMethod, payload, contentType, "DCAE", null, null);\r
198             JSONObject jsonObj = parseResponse(responseStr);\r
199             JSONObject linksObj = (JSONObject) jsonObj.get(node);\r
200             String statusUrl = (String) linksObj.get(nodeAttr);\r
201             logger.info(STATUS_URL_LOG + statusUrl);\r
202             return statusUrl;\r
203         } catch (IOException | ParseException e) {\r
204             logger.error("Exception occurred getting response from DCAE", e);\r
205             throw e;\r
206         } finally {\r
207             LoggingUtils.setTimeContext(startTime, new Date());\r
208             metricsLogger.info("getDcaeResponse complete");\r
209         }\r
210     }\r
211 \r
212     private JSONObject parseResponse(String responseStr) throws ParseException {\r
213         JSONParser parser = new JSONParser();\r
214         Object obj0 = parser.parse(responseStr);\r
215         JSONObject jsonObj = (JSONObject) obj0;\r
216         return jsonObj;\r
217     }\r
218 }