logging changes
[ccsdk/sli/core.git] / sli / common / src / main / java / org / onap / ccsdk / sli / core / sli / SvcLogicDblibStore.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : CCSDK
4  * ================================================================================
5  * Copyright (C) 2017 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 package org.onap.ccsdk.sli.core.sli;
23
24 import java.io.ByteArrayInputStream;
25 import java.io.ByteArrayOutputStream;
26 import java.io.File;
27 import java.io.FileInputStream;
28 import java.io.ObjectInputStream;
29 import java.io.ObjectOutputStream;
30 import java.sql.Blob;
31 import java.sql.Connection;
32 import java.sql.PreparedStatement;
33 import java.sql.ResultSet;
34 import java.sql.SQLException;
35 import java.util.ArrayList;
36 import java.util.Properties;
37 import javax.sql.rowset.CachedRowSet;
38 import org.onap.ccsdk.sli.core.dblib.DBResourceManager;
39 import org.onap.ccsdk.sli.core.dblib.DbLibService;
40 import org.osgi.framework.Bundle;
41 import org.osgi.framework.BundleContext;
42 import org.osgi.framework.FrameworkUtil;
43 import org.osgi.framework.ServiceReference;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 public class SvcLogicDblibStore implements SvcLogicStore {
48
49         private static final String SDNC_CONFIG_DIR = "SDNC_CONFIG_DIR";
50
51         private static final Logger LOG = LoggerFactory.getLogger(SvcLogicDblibStore.class);
52
53         private static final String DBLIB_SERVICE = "org.onap.ccsdk.sli.core.dblib.DbLibService";
54
55         private DbLibService dbSvc;
56
57         public SvcLogicDblibStore()
58         {
59                 // Does nothing, but needed so that argumentless constructor
60                 // still works.
61         }
62
63         public SvcLogicDblibStore(DbLibService dbsvc) {
64                 this.dbSvc = dbsvc;
65         }
66
67         public SvcLogicDblibStore(Properties props) {
68         try {
69             dbSvc = new DBResourceManager(props);
70             JavaSingleton.setInstance(dbSvc);
71         } catch (Exception e) {
72             LOG.warn("Caught exception trying to create DBResourceManager", e);
73         }
74         }
75
76         public Connection getConnection() throws SQLException {
77             return(dbSvc.getConnection());
78         }
79
80         @Override
81         public void init(Properties props) throws ConfigurationException {
82
83                 dbSvc = getDbLibService();
84                 if(dbSvc == null) {
85                         LOG.error("SvcLogic cannot acquire DBLIB_SERVICE");
86                         return;
87                 }
88                 try {
89                         dbSvc.getData("select 1 from DUAL", new ArrayList<String>(), null);
90                         LOG.debug("SQL test was successful");
91                 } catch (SQLException e) {
92                         LOG.error("Failed SQL test", e);
93                 }
94         }
95
96         @Override
97         public boolean hasGraph(String module, String rpc, String version,
98                         String mode) throws SvcLogicException {
99                 boolean retval = false;
100                 CachedRowSet results = null;
101                 String hasVersionGraphSql = "SELECT count(*) FROM SVC_LOGIC"
102                                 + " WHERE module = ? AND rpc = ? AND mode = ? AND version = ?";
103
104                 String hasActiveGraphSql = "SELECT count(*) FROM SVC_LOGIC"
105                                 + " WHERE module = ? AND rpc = ? AND mode = ? AND active = 'Y'";
106
107                 ArrayList<String> args = new ArrayList<>();
108                 args.add(module);
109                 args.add(rpc);
110                 args.add(mode);
111
112                 try {
113
114                         if (version == null) {
115                                 results = dbSvc.getData(hasActiveGraphSql, args, null);
116                         } else {
117                                 args.add(version);
118                                 results = dbSvc.getData(hasVersionGraphSql, args, null);
119                         }
120
121                         if (results.next()) {
122                                 int cnt = results.getInt(1);
123
124                                 if (cnt > 0) {
125                                         retval = true;
126                                 }
127                         }
128                 } catch (Exception e) {
129                         throw new ConfigurationException("SQL query failed", e);
130                 } finally {
131                         if (results != null) {
132                                 try {
133                                         results.close();
134                                 } catch (SQLException x) {
135                                         LOG.error("Failed to close CachedRowSet", x);
136                                 }
137                         }
138
139                 }
140
141                 return retval;
142         }
143
144         public SvcLogicGraph fetch(String module, String rpc, String version,
145                         String mode) throws SvcLogicException {
146
147                 PreparedStatement fetchGraphStmt = null;
148                 Connection dbConn = null;
149                 SvcLogicGraph retval = null;
150                 ResultSet results = null;
151
152                 String fetchVersionGraphSql = "SELECT graph FROM SVC_LOGIC"
153                                 + " WHERE module = ? AND rpc = ? AND mode = ? AND version = ?";
154
155                 String fetchActiveGraphSql = "SELECT graph FROM SVC_LOGIC"
156                                 + " WHERE module = ? AND rpc = ? AND mode = ? AND active = 'Y'";
157
158
159                 try {
160                         dbConn = dbSvc.getConnection();
161
162                         if (version == null) {
163                                 fetchGraphStmt = dbConn.prepareStatement(fetchActiveGraphSql);
164                         } else {
165                                 fetchGraphStmt = dbConn.prepareStatement(fetchVersionGraphSql);
166                         }
167
168                         fetchGraphStmt.setString(1, module);
169                         fetchGraphStmt.setString(2,  rpc);
170                         fetchGraphStmt.setString(3, mode);
171                         if (version != null) {
172                                 fetchGraphStmt.setString(4,version);
173                         }
174
175                         results = fetchGraphStmt.executeQuery();
176
177                         if (results.next()) {
178                                 Blob graphBlob = results.getBlob("graph");
179
180                                 ObjectInputStream gStream = new ObjectInputStream(graphBlob.getBinaryStream());
181
182                                 Object graphObj = gStream.readObject();
183                                 gStream.close();
184
185                                 if (graphObj instanceof SvcLogicGraph) {
186                                         retval = (SvcLogicGraph) graphObj;
187                                 } else {
188                                         throw new ConfigurationException("invalid type for graph ("
189                                                         + graphObj.getClass().getName());
190
191                                 }
192
193                         } else {
194                                 return null;
195                         }
196                 } catch (Exception e) {
197                     LOG.error("Graph processing failed", e);
198                         throw new ConfigurationException("Graph processing failed: " + e.getMessage());
199                 } finally {
200                         try {
201                                 if (fetchGraphStmt != null) {
202                                         fetchGraphStmt.close();
203                                 }
204                         } catch (SQLException e) {
205                                 LOG.error("PreparedStatement close error", e);
206                         }
207                         if (results != null) {
208                                 try {
209                                         results.close();
210                                 } catch (SQLException x) {
211                                         LOG.error("ResultSet close error", x);
212                                 }
213                         }
214                         try {
215                                 if (dbConn != null && !dbConn.isClosed()) {
216                                         dbConn.close();
217                                 }
218                         } catch (Exception exc) {
219                                 LOG.error("dbConn close error", exc);
220                         } finally {
221                                 dbConn = null;
222                         }
223
224                 }
225
226                 return retval;
227         }
228
229         public void store(SvcLogicGraph graph) throws SvcLogicException {
230
231
232
233                 String storeGraphSql = "INSERT INTO SVC_LOGIC (module, rpc, version, mode, active, graph, md5sum)"
234                                 + " VALUES(?, ?, ?, ?, ?, ?, ?)";
235
236                 if (graph == null) {
237                         throw new SvcLogicException("graph cannot be null");
238                 }
239
240                 byte[] graphBytes = null;
241
242                 try (ByteArrayOutputStream byteStr = new ByteArrayOutputStream();
243                         ObjectOutputStream goutStr = new ObjectOutputStream(byteStr)) {
244
245                         goutStr.writeObject(graph);
246
247                         graphBytes = byteStr.toByteArray();
248
249                 } catch (Exception e) {
250                         throw new SvcLogicException("could not serialize graph", e);
251                 }
252
253                 // If object already stored in database, delete it
254                 if (hasGraph(graph.getModule(), graph.getRpc(), graph.getVersion(),
255                                 graph.getMode())) {
256                         delete(graph.getModule(), graph.getRpc(), graph.getVersion(),
257                                         graph.getMode());
258                 }
259
260                 Connection dbConn = null;
261         PreparedStatement storeGraphStmt = null;
262                 try {
263             dbConn = dbSvc.getConnection();
264             boolean oldAutoCommit = dbConn.getAutoCommit();
265                         dbConn.setAutoCommit(false);
266             storeGraphStmt = dbConn.prepareStatement(storeGraphSql);
267                         storeGraphStmt.setString(1, graph.getModule());
268                         storeGraphStmt.setString(2, graph.getRpc());
269                         storeGraphStmt.setString(3, graph.getVersion());
270                         storeGraphStmt.setString(4, graph.getMode());
271                         storeGraphStmt.setString(5, "N");
272                         storeGraphStmt.setBlob(6, new ByteArrayInputStream(graphBytes));
273                         storeGraphStmt.setString(7, graph.getMd5sum());
274                         storeGraphStmt.executeUpdate();
275                         dbConn.commit();
276             dbConn.setAutoCommit(oldAutoCommit);
277                 } catch (Exception e) {
278                         throw new SvcLogicException("Could not write object to database", e);
279                 } finally {
280                         try {
281                                 if (storeGraphStmt != null) {
282                                         storeGraphStmt.close();
283                                 }
284                         } catch (SQLException e) {
285                                 LOG.error("PreparedStatement close error", e);
286                         }
287                         try {
288                                 if (dbConn != null && !dbConn.isClosed()) {
289                                         dbConn.close();
290                                 }
291                         } catch (Exception exc) {
292                                 LOG.error("dbConn close error", exc);
293                         } finally {
294                                 dbConn = null;
295                         }
296
297                 }
298         }
299
300         public void delete(String module, String rpc, String version, String mode)
301                         throws SvcLogicException {
302                 String deleteGraphSql = "DELETE FROM SVC_LOGIC WHERE module = ? AND rpc = ? AND version = ? AND mode = ?";
303
304                 ArrayList<String> args = new ArrayList<>();
305
306                 args.add(module);
307                 args.add(rpc);
308                 args.add(version);
309                 args.add(mode);
310
311                 try {
312                         dbSvc.writeData(deleteGraphSql, args, null);
313                 } catch (Exception e) {
314                         throw new SvcLogicException("Could not delete object from database", e);
315                 }
316         }
317
318         public void activate(SvcLogicGraph graph) throws SvcLogicException {
319                 String deactivateSql = "UPDATE SVC_LOGIC SET active = 'N' WHERE module = ? AND rpc = ? AND mode = ?";
320                 String activateSql = "UPDATE SVC_LOGIC SET active = 'Y' WHERE module = ? AND rpc = ? AND mode = ? AND version = ?";
321
322                 ArrayList<String> args = new ArrayList<>();
323
324                 args.add(graph.getModule());
325                 args.add(graph.getRpc());
326                 args.add(graph.getMode());
327
328                 try {
329                         dbSvc.writeData(deactivateSql, args, null);
330                         args.add(graph.getVersion());
331                         dbSvc.writeData(activateSql, args, null);
332                 } catch (Exception e) {
333                         throw new SvcLogicException("Could not activate graph", e);
334                 }
335         }
336
337         private DbLibService getDbLibService() {
338
339                 if (dbSvc != null) {
340                         return dbSvc;
341                 }
342
343                 // Get DbLibService interface object.
344                 ServiceReference sref = null;
345                 BundleContext bctx = null;
346
347                 Bundle bundle = FrameworkUtil.getBundle(SvcLogicDblibStore.class);
348
349                 if (bundle != null) {
350                         bctx = bundle.getBundleContext();
351
352                         if (bctx != null) {
353                                 sref = bctx.getServiceReference(DBLIB_SERVICE);
354                         }
355
356                         if (sref == null) {
357                                 LOG.warn("Could not find service reference for DBLIB service ({})", DBLIB_SERVICE);
358                         } else {
359                                 dbSvc = (DbLibService) bctx.getService(sref);
360                                 if (dbSvc == null) {
361
362                                         LOG.warn("Could not find service reference for DBLIB service ({})", DBLIB_SERVICE);
363                                 }
364                         }
365                 }
366
367                 // initialize a stand-alone instance of dblib resource
368                 else {
369                         // Try to create a DbLibService object from dblib properties
370                         if(JavaSingleton.getInstance() == null){
371                                 Properties dblibProps = new Properties();
372
373                                 String propDir = System.getenv(SDNC_CONFIG_DIR);
374                                 if (propDir == null) {
375
376                                         propDir = "/opt/sdnc/data/properties";
377                                 }
378                                 String propPath = propDir + "/dblib.properties";
379
380                                 File propFile = new File(propPath);
381
382                                 if (!propFile.exists()) {
383
384                                         LOG.warn("Missing configuration properties file : {}", propFile);
385                                         return null;
386                                 }
387
388                                 try {
389
390                                         dblibProps.load(new FileInputStream(propFile));
391                                 } catch (Exception e) {
392                                         LOG.warn(
393                                                         "Could not load properties file " + propPath, e);
394                                         return null;
395
396                                 }
397
398                                 try {
399                                         dbSvc = new DBResourceManager(dblibProps);
400                                         JavaSingleton.setInstance(dbSvc);
401                                 } catch (Exception e) {
402                                         LOG.warn("Caught exception trying to create DBResourceManager", e);
403                                 }
404                         } else {
405                                 dbSvc = JavaSingleton.getInstance();
406                         }
407                 }
408                 return dbSvc;
409         }
410
411
412         static class JavaSingleton {
413              /* Private constructor     */
414              private JavaSingleton() {
415                 /* the body of the constructor here */
416              }
417
418              /* instance of the singleton declaration */
419              private static volatile  DbLibService INSTANCE ;
420
421              /* Access point to the unique instance of the singleton */
422              public static DbLibService getInstance() {
423                 return INSTANCE;
424              }
425
426              public static void setInstance(DbLibService dbresource) {
427                         INSTANCE = dbresource;
428                      }
429         }
430
431
432     @Override
433     public void activate(String module, String rpc, String version, String mode) throws SvcLogicException {
434
435         String deactivateSql = "UPDATE SVC_LOGIC SET active = 'N' WHERE module = ? AND rpc = ? AND mode = ?";
436
437         String activateSql = "UPDATE SVC_LOGIC SET active = 'Y' WHERE module = ? AND rpc = ? AND mode = ? AND version = ?";
438
439         ArrayList<String> args = new ArrayList<>();
440
441         args.add(module);
442         args.add(rpc);
443         args.add(mode);
444
445         try {
446
447             dbSvc.writeData(deactivateSql, args, null);
448
449             args.add(version);
450             dbSvc.writeData(activateSql, args, null);
451
452         } catch (Exception e) {
453             throw new SvcLogicException("Could not activate graph", e);
454         }        
455     }
456
457 }