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