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