Merge "Fix UI behavior"
[clamp.git] / src / main / java / org / onap / clamp / clds / client / DcaeInventoryServices.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  * Modifications copyright (c) 2018 Nokia\r
21  * ===================================================================\r
22  * \r
23  */\r
24 \r
25 package org.onap.clamp.clds.client;\r
26 \r
27 import com.att.eelf.configuration.EELFLogger;\r
28 import com.att.eelf.configuration.EELFManager;\r
29 import com.fasterxml.jackson.core.JsonProcessingException;\r
30 import com.fasterxml.jackson.databind.node.ObjectNode;\r
31 \r
32 import java.io.IOException;\r
33 import java.util.Date;\r
34 import java.util.List;\r
35 \r
36 import javax.ws.rs.BadRequestException;\r
37 \r
38 import org.json.simple.JSONArray;\r
39 import org.json.simple.JSONObject;\r
40 import org.json.simple.parser.JSONParser;\r
41 import org.json.simple.parser.ParseException;\r
42 import org.onap.clamp.clds.config.ClampProperties;\r
43 import org.onap.clamp.clds.dao.CldsDao;\r
44 import org.onap.clamp.clds.model.CldsEvent;\r
45 import org.onap.clamp.clds.model.CldsModel;\r
46 import org.onap.clamp.clds.model.DcaeEvent;\r
47 import org.onap.clamp.clds.model.dcae.DcaeInventoryResponse;\r
48 import org.onap.clamp.clds.model.properties.Global;\r
49 import org.onap.clamp.clds.model.properties.ModelProperties;\r
50 import org.onap.clamp.clds.util.JacksonUtils;\r
51 import org.onap.clamp.clds.util.LoggingUtils;\r
52 import org.springframework.beans.factory.annotation.Autowired;\r
53 import org.springframework.stereotype.Component;\r
54 \r
55 /**\r
56  * This class implements the communication with DCAE for the service inventory.\r
57  */\r
58 @Component\r
59 public class DcaeInventoryServices {\r
60 \r
61     protected static final EELFLogger logger = EELFManager.getInstance().getLogger(DcaeInventoryServices.class);\r
62     protected static final EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger();\r
63     protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();\r
64     private static final String DCAE_INVENTORY_URL = "dcae.inventory.url";\r
65     private static final String DCAE_INVENTORY_RETRY_INTERVAL = "dcae.intentory.retry.interval";\r
66     private static final String DCAE_INVENTORY_RETRY_LIMIT = "dcae.intentory.retry.limit";\r
67     public static final String DCAE_TYPE_NAME = "typeName";\r
68     public static final String DCAE_TYPE_ID = "typeId";\r
69     private final ClampProperties refProp;\r
70     private final CldsDao cldsDao;\r
71     private final DcaeHttpConnectionManager dcaeHttpConnectionManager;\r
72 \r
73     @Autowired\r
74     public DcaeInventoryServices(ClampProperties refProp, CldsDao cldsDao, DcaeHttpConnectionManager dcaeHttpConnectionManager) {\r
75         this.refProp = refProp;\r
76         this.cldsDao = cldsDao;\r
77         this.dcaeHttpConnectionManager = dcaeHttpConnectionManager;\r
78     }\r
79 \r
80 \r
81     /**\r
82      * Set the event inventory.\r
83      * \r
84      * @param cldsModel\r
85      *            The CldsModel\r
86      * @param userId\r
87      *            The user ID\r
88      * @throws ParseException\r
89      *             In case of DCAE Json parse exception\r
90      */\r
91     public void setEventInventory(CldsModel cldsModel, String userId) throws ParseException, InterruptedException {\r
92         String artifactName = cldsModel.getControlName();\r
93         DcaeEvent dcaeEvent = new DcaeEvent();\r
94         DcaeInventoryResponse dcaeResponse = null;\r
95         Date startTime = new Date();\r
96         LoggingUtils.setTargetContext("DCAE", "setEventInventory");\r
97         if (artifactName != null) {\r
98             artifactName = artifactName + ".yml";\r
99         }\r
100         try {\r
101             // Below are the properties required for calling the dcae inventory\r
102             ModelProperties prop = new ModelProperties(cldsModel.getName(), cldsModel.getControlName(), null, false,\r
103                     "{}", cldsModel.getPropText());\r
104             Global global = prop.getGlobal();\r
105             String invariantServiceUuid = global.getService();\r
106             List<String> resourceUuidList = global.getResourceVf();\r
107             String resourceUuid = "";\r
108             if (resourceUuidList != null && !resourceUuidList.isEmpty()) {\r
109                 resourceUuid = resourceUuidList.get(0);\r
110             }\r
111             /* Inventory service url is called in this method */\r
112             dcaeResponse = getDcaeInformation(artifactName, invariantServiceUuid, resourceUuid);\r
113             /* set dcae events */\r
114             dcaeEvent.setArtifactName(artifactName);\r
115             dcaeEvent.setEvent(DcaeEvent.EVENT_DISTRIBUTION);\r
116             LoggingUtils.setResponseContext("0", "Set inventory success", this.getClass().getName());\r
117         } catch (JsonProcessingException e) {\r
118             LoggingUtils.setResponseContext("900", "Set inventory failed", this.getClass().getName());\r
119             LoggingUtils.setErrorContext("900", "Set inventory error");\r
120             logger.error("Error during JSON decoding", e);\r
121         } catch (IOException ex) {\r
122             LoggingUtils.setResponseContext("900", "Set inventory failed", this.getClass().getName());\r
123             LoggingUtils.setErrorContext("900", "Set inventory error");\r
124             logger.error("Error during DCAE communication", ex);\r
125         } finally {\r
126             LoggingUtils.setTimeContext(startTime, new Date());\r
127             metricsLogger.info("setEventInventory complete");\r
128         }\r
129         this.analyzeAndSaveDcaeResponse(dcaeResponse, cldsModel, dcaeEvent, userId);\r
130     }\r
131 \r
132     private void analyzeAndSaveDcaeResponse(DcaeInventoryResponse dcaeResponse, CldsModel cldsModel,\r
133             DcaeEvent dcaeEvent, String userId) {\r
134         if (dcaeResponse != null) {\r
135             logger.info("Dcae Response for query on inventory: " + dcaeResponse);\r
136             String oldTypeId = cldsModel.getTypeId();\r
137             if (dcaeResponse.getTypeId() != null) {\r
138                 cldsModel.setTypeId(dcaeResponse.getTypeId());\r
139             }\r
140             if (dcaeResponse.getTypeName() != null) {\r
141                 cldsModel.setTypeName(dcaeResponse.getTypeName());\r
142             }\r
143             if (oldTypeId == null || !cldsModel.getEvent().getActionCd().equalsIgnoreCase(CldsEvent.ACTION_DISTRIBUTE)\r
144                     || cldsModel.getEvent().getActionCd().equalsIgnoreCase(CldsEvent.ACTION_SUBMITDCAE)) {\r
145                 CldsEvent.insEvent(cldsDao, dcaeEvent.getControlName(), userId, dcaeEvent.getCldsActionCd(),\r
146                         CldsEvent.ACTION_STATE_RECEIVED, null);\r
147             }\r
148             cldsModel.save(cldsDao, userId);\r
149         } else {\r
150             logger.info(cldsModel.getName() + " Model is not present in Dcae Inventory Service.");\r
151         }\r
152     }\r
153 \r
154     private int getTotalCountFromDcaeInventoryResponse(String responseStr) throws ParseException {\r
155         JSONParser parser = new JSONParser();\r
156         Object obj0 = parser.parse(responseStr);\r
157         JSONObject jsonObj = (JSONObject) obj0;\r
158         Long totalCount = (Long) jsonObj.get("totalCount");\r
159         return totalCount.intValue();\r
160     }\r
161 \r
162     private DcaeInventoryResponse getItemsFromDcaeInventoryResponse(String responseStr)\r
163             throws ParseException, IOException {\r
164         JSONParser parser = new JSONParser();\r
165         Object obj0 = parser.parse(responseStr);\r
166         JSONObject jsonObj = (JSONObject) obj0;\r
167         JSONArray itemsArray = (JSONArray) jsonObj.get("items");\r
168         JSONObject dcaeServiceType0 = (JSONObject) itemsArray.get(0);\r
169         return JacksonUtils.getObjectMapperInstance().readValue(dcaeServiceType0.toString(),\r
170                 DcaeInventoryResponse.class);\r
171     }\r
172 \r
173     /**\r
174      * DO a query to DCAE to get some Information.\r
175      * \r
176      * @param artifactName\r
177      *            The artifact Name\r
178      * @param serviceUuid\r
179      *            The service UUID\r
180      * @param resourceUuid\r
181      *            The resource UUID\r
182      * @return The DCAE inventory for the artifact in DcaeInventoryResponse\r
183      * @throws IOException\r
184      *             In case of issues with the stream\r
185      * @throws ParseException\r
186      *             In case of issues with the Json parsing\r
187      */\r
188     public DcaeInventoryResponse getDcaeInformation(String artifactName, String serviceUuid, String resourceUuid)\r
189             throws IOException, ParseException, InterruptedException {\r
190         Date startTime = new Date();\r
191         LoggingUtils.setTargetContext("DCAE", "getDcaeInformation");\r
192         String queryString = "?asdcResourceId=" + resourceUuid + "&asdcServiceId=" + serviceUuid + "&typeName="\r
193                 + artifactName;\r
194         String fullUrl = refProp.getStringValue(DCAE_INVENTORY_URL) + "/dcae-service-types" + queryString;\r
195         logger.info("Dcae Inventory Service full url - " + fullUrl);\r
196         DcaeInventoryResponse response = queryDcaeInventory(fullUrl);\r
197         LoggingUtils.setResponseContext("0", "Get Dcae Information success", this.getClass().getName());\r
198         LoggingUtils.setTimeContext(startTime, new Date());\r
199         return response;\r
200     }\r
201 \r
202     private DcaeInventoryResponse queryDcaeInventory(String fullUrl)\r
203             throws IOException, InterruptedException, ParseException {\r
204         int retryInterval = 0;\r
205         int retryLimit = 1;\r
206         if (refProp.getStringValue(DCAE_INVENTORY_RETRY_LIMIT) != null) {\r
207             retryLimit = Integer.valueOf(refProp.getStringValue(DCAE_INVENTORY_RETRY_LIMIT));\r
208         }\r
209         if (refProp.getStringValue(DCAE_INVENTORY_RETRY_INTERVAL) != null) {\r
210             retryInterval = Integer.valueOf(refProp.getStringValue(DCAE_INVENTORY_RETRY_INTERVAL));\r
211         }\r
212         for (int i = 0; i < retryLimit; i++) {\r
213             metricsLogger.info("Attempt n°" + i + " to contact DCAE inventory");\r
214             String response = dcaeHttpConnectionManager.doDcaeHttpQuery(fullUrl, "GET", null, null);\r
215             int totalCount = getTotalCountFromDcaeInventoryResponse(response);\r
216             metricsLogger.info("getDcaeInformation complete: totalCount returned=" + totalCount);\r
217             if (totalCount > 0) {\r
218                 logger.info("getDcaeInformation, answer from DCAE inventory:" + response);\r
219                 return getItemsFromDcaeInventoryResponse(response);\r
220             }\r
221             logger.info(\r
222                     "Dcae inventory totalCount returned is 0, so waiting " + retryInterval + "ms before retrying ...");\r
223             // wait for a while and try to connect to DCAE again\r
224             Thread.sleep(retryInterval);\r
225         }\r
226         logger.warn("Dcae inventory totalCount returned is still 0, after " + retryLimit + " attempts, returning NULL");\r
227         return null;\r
228     }\r
229 \r
230     /**\r
231      * Inserts a new DCAEServiceType or updates an existing instance. If the\r
232      * typeName is same second time(already exists) then the\r
233      * DCAEServiceTypeRequest is updated\r
234      * \r
235      * @param blueprintTemplate\r
236      *            blueprint content\r
237      * @param owner\r
238      *            owner of the data\r
239      * @param typeName\r
240      *            The type/artifact Name\r
241      * @param typeVersion\r
242      *            type version\r
243      * @param asdcServiceId\r
244      *            The service UUID\r
245      * @param asdcResourceId\r
246      *            The vf UUID\r
247      * @return The DCAE inventory type id\r
248      */\r
249     public String createupdateDCAEServiceType(String blueprintTemplate, String owner, String typeName, int typeVersion,\r
250             String asdcServiceId, String asdcResourceId) {\r
251         Date startTime = new Date();\r
252         LoggingUtils.setTargetContext("DCAE", "createDCAEServiceType");\r
253         String typeId = null;\r
254         try {\r
255             ObjectNode dcaeServiceTypeRequest = JacksonUtils.getObjectMapperInstance().createObjectNode();\r
256             dcaeServiceTypeRequest.put("blueprintTemplate", blueprintTemplate);\r
257             dcaeServiceTypeRequest.put("owner", owner);\r
258             dcaeServiceTypeRequest.put("typeName", typeName);\r
259             dcaeServiceTypeRequest.put("typeVersion", typeVersion);\r
260             dcaeServiceTypeRequest.put("asdcServiceId", asdcServiceId);\r
261             dcaeServiceTypeRequest.put("asdcResourceId", asdcResourceId);\r
262             String apiBodyString = dcaeServiceTypeRequest.toString();\r
263             logger.info("Dcae api Body String - " + apiBodyString);\r
264             String url = refProp.getStringValue(DCAE_INVENTORY_URL) + "/dcae-service-types";\r
265             String responseStr = dcaeHttpConnectionManager.doDcaeHttpQuery(url, "POST", apiBodyString,\r
266                     "application/json");\r
267             // If the DCAEServiceTypeRequest is created successfully it will\r
268             // return a json object responce containing a node for newly created\r
269             // "typeId"\r
270             // The newly generated DCAEServiceTypeRequest can then be accessed\r
271             // via URL: https://<DCAE_INVENTORY_URL>/dcae-service-types/<typeId>\r
272             JSONParser parser = new JSONParser();\r
273             Object obj0 = parser.parse(responseStr);\r
274             JSONObject jsonObj = (JSONObject) obj0;\r
275             typeId = (String) jsonObj.get("typeId"); // need to save this\r
276                                                      // as\r
277                                                      // service_type_id\r
278                                                      // in model table\r
279         } catch (IOException | ParseException e) {\r
280             logger.error("Exception occurred during createupdateDCAEServiceType Operation with DCAE", e);\r
281             throw new BadRequestException("Exception occurred during createupdateDCAEServiceType Operation with DCAE",\r
282                     e);\r
283         } finally {\r
284             if (typeId != null) {\r
285                 LoggingUtils.setResponseContext("0", "Create update DCAE ServiceType success",\r
286                         this.getClass().getName());\r
287             } else {\r
288                 LoggingUtils.setResponseContext("900", "Create update DCAE ServiceType failed",\r
289                         this.getClass().getName());\r
290                 LoggingUtils.setErrorContext("900", "Create update DCAE ServiceType error");\r
291             }\r
292             LoggingUtils.setTimeContext(startTime, new Date());\r
293             metricsLogger.info("createupdateDCAEServiceType complete");\r
294         }\r
295         return typeId;\r
296     }\r
297 \r
298     /**\r
299      * Method to delete blueprint from dcae inventory if it's exists.\r
300      * \r
301      * @param typeName\r
302      * @param serviceUuid\r
303      * @param resourceUuid\r
304      * @throws InterruptedException\r
305      */\r
306     public void deleteDCAEServiceType(String typeName, String serviceUuid, String resourceUuid)\r
307             throws InterruptedException {\r
308         Date startTime = new Date();\r
309         LoggingUtils.setTargetContext("DCAE", "deleteDCAEServiceType");\r
310         boolean result = false;\r
311         try {\r
312             DcaeInventoryResponse inventoryResponse = getDcaeInformation(typeName, serviceUuid, resourceUuid);\r
313             if (inventoryResponse != null && inventoryResponse.getTypeId() != null) {\r
314                 String fullUrl = refProp.getStringValue(DCAE_INVENTORY_URL) + "/dcae-service-types/"\r
315                         + inventoryResponse.getTypeId();\r
316                 dcaeHttpConnectionManager.doDcaeHttpQuery(fullUrl, "DELETE", null, null);\r
317             }\r
318             result = true;\r
319         } catch (IOException | ParseException e) {\r
320             logger.error("Exception occurred during deleteDCAEServiceType Operation with DCAE", e);\r
321             throw new BadRequestException("Exception occurred during deleteDCAEServiceType Operation with DCAE", e);\r
322         } finally {\r
323             if (result) {\r
324                 LoggingUtils.setResponseContext("0", "Delete DCAE ServiceType success", this.getClass().getName());\r
325             } else {\r
326                 LoggingUtils.setResponseContext("900", "Delete DCAE ServiceType failed", this.getClass().getName());\r
327                 LoggingUtils.setErrorContext("900", "Delete DCAE ServiceType error");\r
328             }\r
329             LoggingUtils.setTimeContext(startTime, new Date());\r
330             metricsLogger.info("deleteDCAEServiceType completed");\r
331         }\r
332     }\r
333 }\r