6a7fa0b3623fa5d34c33870d46e2f3fa08ff7423
[clamp.git] / src / main / java / org / onap / clamp / clds / dao / CldsDao.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP CLAMP
4  * ================================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights
6  *                             reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END============================================
20  * ===================================================================
21  * 
22  */
23
24 package org.onap.clamp.clds.dao;
25
26 import com.att.eelf.configuration.EELFLogger;
27 import com.att.eelf.configuration.EELFManager;
28
29 import java.io.InputStream;
30 import java.text.SimpleDateFormat;
31 import java.util.ArrayList;
32 import java.util.HashMap;
33 import java.util.List;
34 import java.util.Map;
35
36 import javax.sql.DataSource;
37
38 import org.onap.clamp.clds.model.CldsDbServiceCache;
39 import org.onap.clamp.clds.model.CldsEvent;
40 import org.onap.clamp.clds.model.CldsModel;
41 import org.onap.clamp.clds.model.CldsModelInstance;
42 import org.onap.clamp.clds.model.CldsModelProp;
43 import org.onap.clamp.clds.model.CldsMonitoringDetails;
44 import org.onap.clamp.clds.model.CldsServiceData;
45 import org.onap.clamp.clds.model.CldsTemplate;
46 import org.onap.clamp.clds.model.ValueItem;
47 import org.springframework.dao.EmptyResultDataAccessException;
48 import org.springframework.jdbc.core.JdbcTemplate;
49 import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
50 import org.springframework.jdbc.core.namedparam.SqlParameterSource;
51 import org.springframework.jdbc.core.simple.SimpleJdbcCall;
52 import org.springframework.stereotype.Repository;
53
54 /**
55  * Data Access for CLDS Model tables.
56  */
57 @Repository("cldsDao")
58 public class CldsDao {
59
60     private static final EELFLogger logger = EELFManager.getInstance().getLogger(CldsDao.class);
61     private JdbcTemplate jdbcTemplateObject;
62     private SimpleJdbcCall procGetModel;
63     private SimpleJdbcCall procGetModelTemplate;
64     private SimpleJdbcCall procSetModel;
65     private SimpleJdbcCall procInsEvent;
66     private SimpleJdbcCall procUpdEvent;
67     private SimpleJdbcCall procSetTemplate;
68     private SimpleJdbcCall procGetTemplate;
69     private SimpleJdbcCall procDelAllModelInstances;
70     private SimpleJdbcCall procInsModelInstance;
71     private static final String HEALTHCHECK = "Select 1";
72
73     /**
74      * Log message when instantiating
75      */
76     public CldsDao() {
77         logger.info("CldsDao instantiating...");
78     }
79
80     /**
81      * When dataSource is provided, instantiate spring jdbc objects.
82      */
83     public void setDataSource(DataSource dataSource) {
84         this.jdbcTemplateObject = new JdbcTemplate(dataSource);
85         this.procGetModel = new SimpleJdbcCall(dataSource).withProcedureName("get_model");
86         this.procGetModelTemplate = new SimpleJdbcCall(dataSource).withProcedureName("get_model_template");
87         this.procSetModel = new SimpleJdbcCall(dataSource).withProcedureName("set_model");
88         this.procInsEvent = new SimpleJdbcCall(dataSource).withProcedureName("ins_event");
89         this.procUpdEvent = new SimpleJdbcCall(dataSource).withProcedureName("upd_event");
90         this.procGetTemplate = new SimpleJdbcCall(dataSource).withProcedureName("get_template");
91         this.procSetTemplate = new SimpleJdbcCall(dataSource).withProcedureName("set_template");
92         this.procInsModelInstance = new SimpleJdbcCall(dataSource).withProcedureName("ins_model_instance");
93         this.procDelAllModelInstances = new SimpleJdbcCall(dataSource).withProcedureName("del_all_model_instances");
94     }
95
96     /**
97      * Get a model from the database given the model name.
98      */
99     public CldsModel getModel(String modelName) {
100         return getModel(modelName, null);
101     }
102
103     /**
104      * Get a model from the database given the controlNameUuid.
105      */
106     public CldsModel getModelByUuid(String controlNameUuid) {
107         return getModel(null, controlNameUuid);
108     }
109
110     // Get a model from the database given the model name or a controlNameUuid.
111     private CldsModel getModel(String modelName, String controlNameUuid) {
112         CldsModel model = new CldsModel();
113         model.setName(modelName);
114         SqlParameterSource in = new MapSqlParameterSource().addValue("v_model_name", modelName)
115                 .addValue("v_control_name_uuid", controlNameUuid);
116         Map<String, Object> out = logSqlExecution(procGetModel, in);
117         model.setControlNamePrefix((String) out.get("v_control_name_prefix"));
118         model.setControlNameUuid((String) out.get("v_control_name_uuid"));
119         model.setId((String) (out.get("v_model_id")));
120         model.setTemplateId((String) (out.get("v_template_id")));
121         model.setTemplateName((String) (out.get("v_template_name")));
122         model.setBpmnText((String) out.get("v_template_bpmn_text"));
123         model.setPropText((String) out.get("v_model_prop_text"));
124         model.setImageText((String) out.get("v_template_image_text"));
125         model.setDocText((String) out.get("v_template_doc_text"));
126         model.setBlueprintText((String) out.get("v_model_blueprint_text"));
127         model.getEvent().setId((String) (out.get("v_event_id")));
128         model.getEvent().setActionCd((String) out.get("v_action_cd"));
129         model.getEvent().setActionStateCd((String) out.get("v_action_state_cd"));
130         model.getEvent().setProcessInstanceId((String) out.get("v_event_process_instance_id"));
131         model.getEvent().setUserid((String) out.get("v_event_user_id"));
132         model.setTypeId((String) out.get("v_service_type_id"));
133         model.setDeploymentId((String) out.get("v_deployment_id"));
134         return model;
135     }
136
137     /**
138      * Get a model and template information from the database given the model
139      * name.
140      *
141      * @param modelName
142      * @return model
143      */
144     public CldsModel getModelTemplate(String modelName) {
145         CldsModel model = new CldsModel();
146         model.setName(modelName);
147         SqlParameterSource in = new MapSqlParameterSource().addValue("v_model_name", modelName);
148         Map<String, Object> out = logSqlExecution(procGetModelTemplate, in);
149         // todo : rationalize
150         model.setControlNamePrefix((String) out.get("v_control_name_prefix"));
151         model.setControlNameUuid((String) out.get("v_control_name_uuid"));
152         model.setId((String) (out.get("v_model_id")));
153         model.setTemplateId((String) (out.get("v_template_id")));
154         model.setTemplateName((String) (out.get("v_template_name")));
155         model.setBpmnText((String) out.get("v_template_bpmn_text"));
156         model.setPropText((String) out.get("v_model_prop_text"));
157         model.setImageText((String) out.get("v_template_image_text"));
158         model.setDocText((String) out.get("v_template_doc_text"));
159         model.setBlueprintText((String) out.get("v_model_blueprint_text"));
160         model.getEvent().setId((String) (out.get("v_event_id")));
161         model.getEvent().setActionCd((String) out.get("v_action_cd"));
162         model.getEvent().setActionStateCd((String) out.get("v_action_state_cd"));
163         model.getEvent().setProcessInstanceId((String) out.get("v_event_process_instance_id"));
164         model.getEvent().setUserid((String) out.get("v_event_user_id"));
165         model.setTypeId((String) out.get("v_service_type_id"));
166         model.setDeploymentId((String) out.get("v_deployment_id"));
167         Map<String, Object> modelResults = logSqlExecution(procGetModel, in);
168         Object modelResultObject = modelResults.get("#result-set-1");
169         if (modelResultObject != null && modelResultObject instanceof ArrayList) {
170             List<Object> modelInstanceRs = (List<Object>) modelResultObject;
171             for (Object currModelInstance : modelInstanceRs) {
172                 if (currModelInstance != null && currModelInstance instanceof HashMap) {
173                     HashMap<String, String> modelInstanceMap = (HashMap<String, String>) currModelInstance;
174                     CldsModelInstance modelInstance = new CldsModelInstance();
175                     modelInstance.setModelInstanceId(modelInstanceMap.get("model_instance_id"));
176                     modelInstance.setVmName(modelInstanceMap.get("vm_name"));
177                     modelInstance.setLocation(modelInstanceMap.get("location"));
178                     model.getCldsModelInstanceList().add(modelInstance);
179                     logger.info("value of currModel: {}", currModelInstance);
180                 }
181             }
182         }
183         return model;
184     }
185
186     /**
187      * Update model in the database using parameter values and return updated
188      * model object.
189      *
190      * @param model
191      * @param userid
192      * @return
193      */
194     public CldsModel setModel(CldsModel model, String userid) {
195         SqlParameterSource in = new MapSqlParameterSource().addValue("v_model_name", model.getName())
196                 .addValue("v_template_id", model.getTemplateId()).addValue("v_user_id", userid)
197                 .addValue("v_model_prop_text", model.getPropText())
198                 .addValue("v_model_blueprint_text", model.getBlueprintText())
199                 .addValue("v_service_type_id", model.getTypeId()).addValue("v_deployment_id", model.getDeploymentId())
200                 .addValue("v_control_name_prefix", model.getControlNamePrefix())
201                 .addValue("v_control_name_uuid", model.getControlNameUuid());
202         Map<String, Object> out = logSqlExecution(procSetModel, in);
203         model.setControlNamePrefix((String) out.get("v_control_name_prefix"));
204         model.setControlNameUuid((String) out.get("v_control_name_uuid"));
205         model.setId((String) (out.get("v_model_id")));
206         model.getEvent().setId((String) (out.get("v_event_id")));
207         model.getEvent().setActionCd((String) out.get("v_action_cd"));
208         model.getEvent().setActionStateCd((String) out.get("v_action_state_cd"));
209         model.getEvent().setProcessInstanceId((String) out.get("v_event_process_instance_id"));
210         model.getEvent().setUserid((String) out.get("v_event_user_id"));
211         return model;
212     }
213
214     /**
215      * Inserts new modelInstance in the database using parameter values and
216      * return updated model object.
217      *
218      * @param model
219      * @param modelInstancesList
220      * @return
221      */
222     public void insModelInstance(CldsModel model, List<CldsModelInstance> modelInstancesList) {
223         // Delete all existing model instances for given controlNameUUID
224         logger.debug("deleting instances for: {}", model.getControlNameUuid());
225         delAllModelInstances(model.getControlNameUuid());
226         if (modelInstancesList == null) {
227             logger.debug("modelInstancesList == null");
228         } else {
229             for (CldsModelInstance currModelInstance : modelInstancesList) {
230                 logger.debug("v_control_name_uuid={}", model.getControlNameUuid());
231                 logger.debug("v_vm_name={}", currModelInstance.getVmName());
232                 logger.debug("v_location={}", currModelInstance.getLocation());
233                 SqlParameterSource in = new MapSqlParameterSource()
234                         .addValue("v_control_name_uuid", model.getControlNameUuid())
235                         .addValue("v_vm_name", currModelInstance.getVmName())
236                         .addValue("v_location", currModelInstance.getLocation());
237                 Map<String, Object> out = logSqlExecution(procInsModelInstance, in);
238                 model.setId((String) (out.get("v_model_id")));
239                 CldsModelInstance modelInstance = new CldsModelInstance();
240                 modelInstance.setLocation(currModelInstance.getLocation());
241                 modelInstance.setVmName(currModelInstance.getVmName());
242                 modelInstance.setModelInstanceId((String) (out.get("v_model_instance_id")));
243                 model.getCldsModelInstanceList().add(modelInstance);
244             }
245         }
246     }
247
248     /**
249      * Insert an event in the database - require either modelName or
250      * controlNamePrefix/controlNameUuid.
251      *
252      * @param modelName
253      * @param controlNamePrefix
254      * @param controlNameUuid
255      * @param cldsEvent
256      * @return
257      */
258     public CldsEvent insEvent(String modelName, String controlNamePrefix, String controlNameUuid, CldsEvent cldsEvent) {
259         CldsEvent event = new CldsEvent();
260         SqlParameterSource in = new MapSqlParameterSource().addValue("v_model_name", modelName)
261                 .addValue("v_control_name_prefix", controlNamePrefix).addValue("v_control_name_uuid", controlNameUuid)
262                 .addValue("v_user_id", cldsEvent.getUserid()).addValue("v_action_cd", cldsEvent.getActionCd())
263                 .addValue("v_action_state_cd", cldsEvent.getActionStateCd())
264                 .addValue("v_process_instance_id", cldsEvent.getProcessInstanceId());
265         Map<String, Object> out = logSqlExecution(procInsEvent, in);
266         event.setId((String) (out.get("v_event_id")));
267         return event;
268     }
269
270     private String delAllModelInstances(String controlNameUUid) {
271         SqlParameterSource in = new MapSqlParameterSource().addValue("v_control_name_uuid", controlNameUUid);
272         Map<String, Object> out = logSqlExecution(procDelAllModelInstances, in);
273         return (String) (out.get("v_model_id"));
274     }
275
276     /**
277      * Update event with process instance id.
278      *
279      * @param eventId
280      * @param processInstanceId
281      */
282     public void updEvent(String eventId, String processInstanceId) {
283         SqlParameterSource in = new MapSqlParameterSource().addValue("v_event_id", eventId)
284                 .addValue("v_process_instance_id", processInstanceId);
285         logSqlExecution(procUpdEvent, in);
286     }
287
288     /**
289      * Return list of model names
290      *
291      * @return model names
292      */
293     public List<ValueItem> getBpmnNames() {
294         String sql = "SELECT model_name FROM model ORDER BY 1;";
295         return jdbcTemplateObject.query(sql, new ValueItemMapper());
296     }
297
298     /**
299      * Update template in the database using parameter values and return updated
300      * template object.
301      *
302      * @param template
303      * @param userid
304      */
305     public void setTemplate(CldsTemplate template, String userid) {
306         SqlParameterSource in = new MapSqlParameterSource().addValue("v_template_name", template.getName())
307                 .addValue("v_user_id", userid).addValue("v_template_bpmn_text", template.getBpmnText())
308                 .addValue("v_template_image_text", template.getImageText())
309                 .addValue("v_template_doc_text", template.getPropText());
310         Map<String, Object> out = logSqlExecution(procSetTemplate, in);
311         template.setId((String) (out.get("v_template_id")));
312         template.setBpmnUserid((String) (out.get("v_template_bpmn_user_id")));
313         template.setBpmnId((String) (out.get("v_template_bpmn_id")));
314         template.setImageId((String) (out.get("v_template_image_id")));
315         template.setImageUserid((String) out.get("v_template_image_user_id"));
316         template.setPropId((String) (out.get("v_template_doc_id")));
317         template.setPropUserid((String) out.get("v_template_doc_user_id"));
318     }
319
320     /**
321      * Return list of template names
322      *
323      * @return template names
324      */
325     public List<ValueItem> getTemplateNames() {
326         String sql = "SELECT template_name FROM template ORDER BY 1;";
327         return jdbcTemplateObject.query(sql, new ValueItemMapper());
328     }
329
330     /**
331      * Get a template from the database given the model name.
332      *
333      * @param templateName
334      * @return model
335      */
336     public CldsTemplate getTemplate(String templateName) {
337         CldsTemplate template = new CldsTemplate();
338         template.setName(templateName);
339         SqlParameterSource in = new MapSqlParameterSource().addValue("v_template_name", templateName);
340         Map<String, Object> out = logSqlExecution(procGetTemplate, in);
341         template.setId((String) (out.get("v_template_id")));
342         template.setBpmnUserid((String) (out.get("v_template_bpmn_user_id")));
343         template.setBpmnId((String) (out.get("v_template_bpmn_id")));
344         template.setBpmnText((String) (out.get("v_template_bpmn_text")));
345         template.setImageId((String) (out.get("v_template_image_id")));
346         template.setImageUserid((String) out.get("v_template_image_user_id"));
347         template.setImageText((String) out.get("v_template_image_text"));
348         template.setPropId((String) (out.get("v_template_doc_id")));
349         template.setPropUserid((String) out.get("v_template_doc_user_id"));
350         template.setPropText((String) out.get("v_template_doc_text"));
351         return template;
352     }
353
354     public void clearServiceCache() {
355         String clearCldsServiceCacheSql = "TRUNCATE clds_service_cache";
356         jdbcTemplateObject.execute(clearCldsServiceCacheSql);
357     }
358
359     public CldsServiceData getCldsServiceCache(String invariantUUID) {
360         CldsServiceData cldsServiceData = null;
361         try {
362             String getCldsServiceSQL = "SELECT * , TIMESTAMPDIFF(SECOND, timestamp, CURRENT_TIMESTAMP()) FROM clds_service_cache where invariant_service_id  = ? ";
363             cldsServiceData = jdbcTemplateObject.queryForObject(getCldsServiceSQL, new Object[] {
364                     invariantUUID
365             }, new CldsServiceDataMapper());
366             if (cldsServiceData != null) {
367                 logger.info("CldsServiceData found in cache for Service Invariant ID:"
368                         + cldsServiceData.getServiceInvariantUUID());
369                 return cldsServiceData;
370             } else {
371                 logger.warn("CldsServiceData not found in cache for Service Invariant ID:" + invariantUUID);
372                 return null;
373             }
374         } catch (EmptyResultDataAccessException e) {
375             logger.info("CldsServiceData not found in cache for Service Invariant ID: " + invariantUUID);
376             logger.debug("CldsServiceData not found in cache for Service Invariant ID: " + invariantUUID, e);
377             return null;
378         }
379     }
380
381     public void setCldsServiceCache(CldsDbServiceCache cldsDBServiceCache) {
382         if (cldsDBServiceCache != null && cldsDBServiceCache.getInvariantId() != null
383                 && cldsDBServiceCache.getServiceId() != null) {
384             String invariantUuid = cldsDBServiceCache.getInvariantId();
385             String serviceUuid = cldsDBServiceCache.getServiceId();
386             InputStream is = cldsDBServiceCache.getCldsDataInstream();
387             String insertCldsServiceCacheSql = "INSERT INTO clds_service_cache"
388                     + "(invariant_service_id,service_id,timestamp,object_data) VALUES"
389                     + "(?,?,CURRENT_TIMESTAMP,?) ON DUPLICATE KEY UPDATE invariant_service_id = VALUES(invariant_service_id) , timestamp = CURRENT_TIMESTAMP , object_data = VALUES(object_data) ";
390             jdbcTemplateObject.update(insertCldsServiceCacheSql, invariantUuid, serviceUuid, is);
391         }
392     }
393
394     private static Map<String, Object> logSqlExecution(SimpleJdbcCall call, SqlParameterSource source) {
395         try {
396             return call.execute(source);
397         } catch (Exception e) {
398             logger.error("Exception occured in " + source.getClass().getCanonicalName() + ": " + e);
399             throw e;
400         }
401     }
402
403     public void doHealthCheck() {
404         jdbcTemplateObject.execute(HEALTHCHECK);
405     }
406
407     /**
408      * Method to get deployed/active models with model properties.
409      * 
410      * @return list of CldsModelProp
411      */
412     public List<CldsModelProp> getDeployedModelProperties() {
413         List<CldsModelProp> cldsModelPropList = new ArrayList<>();
414         String modelsSql = "select m.model_id, m.model_name, mp.model_prop_id, mp.model_prop_text FROM model m, model_properties mp, event e "
415                 + "WHERE m.model_prop_id = mp.model_prop_id and m.event_id = e.event_id and e.action_cd = 'DEPLOY'";
416         List<Map<String, Object>> rows = jdbcTemplateObject.queryForList(modelsSql);
417         CldsModelProp cldsModelProp = null;
418         for (Map<String, Object> row : rows) {
419             cldsModelProp = new CldsModelProp();
420             cldsModelProp.setId((String) row.get("model_id"));
421             cldsModelProp.setName((String) row.get("model_name"));
422             cldsModelProp.setPropId((String) row.get("model_prop_id"));
423             cldsModelProp.setPropText((String) row.get("model_prop_text"));
424             cldsModelPropList.add(cldsModelProp);
425         }
426         return cldsModelPropList;
427     }
428
429     /**
430      * Method to get deployed/active models with model properties.
431      * 
432      * @return list of CLDS-Monitoring-Details: CLOSELOOP_NAME | Close loop name
433      *         used in the CLDS application (prefix: ClosedLoop- + unique
434      *         ClosedLoop ID) MODEL_NAME | Model Name in CLDS application
435      *         SERVICE_TYPE_ID | TypeId returned from the DCAE application when
436      *         the ClosedLoop is submitted (DCAEServiceTypeRequest generated in
437      *         DCAE application). DEPLOYMENT_ID | Id generated when the
438      *         ClosedLoop is deployed in DCAE. TEMPLATE_NAME | Template used to
439      *         generate the ClosedLoop model. ACTION_CD | Current state of the
440      *         ClosedLoop in CLDS application.
441      */
442     public List<CldsMonitoringDetails> getCLDSMonitoringDetails() {
443         SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");
444         List<CldsMonitoringDetails> cldsMonitoringDetailsList = new ArrayList<CldsMonitoringDetails>();
445         String modelsSql = "SELECT CONCAT(M.CONTROL_NAME_PREFIX, M.CONTROL_NAME_UUID) AS CLOSELOOP_NAME , M.MODEL_NAME, M.SERVICE_TYPE_ID, M.DEPLOYMENT_ID, T.TEMPLATE_NAME, E.ACTION_CD, E.USER_ID, E.TIMESTAMP "
446                 + "FROM MODEL M, TEMPLATE T, EVENT E "
447                 + "WHERE M.TEMPLATE_ID = T.TEMPLATE_ID AND M.EVENT_ID = E.EVENT_ID " + "ORDER BY ACTION_CD";
448         List<Map<String, Object>> rows = jdbcTemplateObject.queryForList(modelsSql);
449         CldsMonitoringDetails cldsMonitoringDetails = null;
450         for (Map<String, Object> row : rows) {
451             cldsMonitoringDetails = new CldsMonitoringDetails();
452             cldsMonitoringDetails.setCloseloopName((String) row.get("CLOSELOOP_NAME"));
453             cldsMonitoringDetails.setModelName((String) row.get("MODEL_NAME"));
454             cldsMonitoringDetails.setServiceTypeId((String) row.get("SERVICE_TYPE_ID"));
455             cldsMonitoringDetails.setDeploymentId((String) row.get("DEPLOYMENT_ID"));
456             cldsMonitoringDetails.setTemplateName((String) row.get("TEMPLATE_NAME"));
457             cldsMonitoringDetails.setAction((String) row.get("ACTION_CD"));
458             cldsMonitoringDetails.setUserid((String) row.get("USER_ID"));
459             cldsMonitoringDetails.setTimestamp(sdf.format(row.get("TIMESTAMP")));
460             cldsMonitoringDetailsList.add(cldsMonitoringDetails);
461         }
462         return cldsMonitoringDetailsList;
463     }
464 }